-
Notifications
You must be signed in to change notification settings - Fork 29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Featuring SQ mech tool #240
Open
bgodlin
wants to merge
10
commits into
valory-xyz:main
Choose a base branch
from
subquery:subquery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4e182af
Featuring SQ mech tool
bgodlin 4e2c002
Merge branch 'valory-xyz:main' into subquery
bgodlin 41a5397
Added a test to verify the successful query response analysis
bgodlin 170a667
Merge branch 'main' into subquery
bgodlin 6c4a857
Logic was revised
bgodlin 593ac44
Comments Addressed
bgodlin f90e6b6
Merge branch 'main' into subquery
bgodlin b1d089f
fingerprint; fingerprint_ignore_patterns added
bgodlin 6ad4c8f
Merge branch 'main' into subquery
bgodlin 287a3aa
Merge branch 'main' into subquery
bgodlin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
# ------------------------------------------------------------------------------ | ||
# | ||
# Copyright 2024 Valory AG | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
# ------------------------------------------------------------------------------ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
# ------------------------------------------------------------------------------ | ||
# | ||
# Copyright 2024 Valory AG | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
# ------------------------------------------------------------------------------ |
20 changes: 20 additions & 0 deletions
20
packages/subquery/customs/graphql_response_analyser/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# -*- coding: utf-8 -*- | ||
# ------------------------------------------------------------------------------ | ||
# | ||
# Copyright 2023-2024 Valory AG | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
# ------------------------------------------------------------------------------ | ||
|
||
"""This module explains the output of the GraphQL server within a given context, including a description of the indexed data being served and the query itself.""" |
19 changes: 19 additions & 0 deletions
19
packages/subquery/customs/graphql_response_analyser/component.yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
name: graphql_response_analyser | ||
author: subquery | ||
version: 0.1.0 | ||
type: custom | ||
description: This module explains the output of the GraphQL chain data indexer within a given context, including a description of the indexed data being served and the query itself. | ||
license: Apache-2.0 | ||
aea_version: '>=1.0.0, <2.0.0' | ||
entry_point: graphql_response_analyser.py | ||
fingerprint: | ||
__init__.py: | ||
graphql_response_analyser.py: | ||
fingerprint_ignore_patterns: [] | ||
callable: run | ||
dependencies: | ||
openai: | ||
version: ==1.11.0 | ||
tiktoken: | ||
version: ==0.5.1 | ||
requests: {} |
186 changes: 186 additions & 0 deletions
186
packages/subquery/customs/graphql_response_analyser/graphql_response_analyser.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,186 @@ | ||
# -*- coding: utf-8 -*- | ||
# ------------------------------------------------------------------------------ | ||
# | ||
# Copyright 2023-2024 Valory AG | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
# ------------------------------------------------------------------------------ | ||
|
||
"""Contains the job definitions""" | ||
|
||
from typing import Any, Dict, Optional, Tuple | ||
import os | ||
from openai import OpenAI | ||
import json | ||
import requests | ||
|
||
client: Optional[OpenAI] = None | ||
|
||
|
||
def generate_graphql_query(user_request, schema, description, examples): | ||
return ( | ||
f""" | ||
You are a GraphQL query generator. Based on the following GraphQL schema and the user's natural language request, generate a valid GraphQL query. | ||
|
||
GraphQL Project Description: "{description}" | ||
|
||
User Request: "{user_request}" | ||
|
||
GraphQL Schema: {json.dumps(schema)} | ||
|
||
Example Queries: | ||
|
||
""" | ||
+ examples | ||
+ """ | ||
|
||
GraphQL Query: | ||
|
||
""" | ||
) | ||
|
||
|
||
# Analyze data and generate response using OpenAI | ||
def analyze_data_and_generate_response(data): | ||
return f""" | ||
|
||
Once the query you have given was executed, the following data was fetched: | ||
|
||
JSON Data: {json.dumps(data)} | ||
|
||
Based on the provided context, please generate a bullet-pointed summary in a machine-readable JSON format. The JSON structure should have an array object named 'analysis_result,' with each analytical conclusion represented as a separate string element within the array. | ||
""" | ||
|
||
|
||
class OpenAIClientManager: | ||
"""Client context manager for OpenAI.""" | ||
|
||
def __init__(self, api_key: str): | ||
self.api_key = api_key | ||
|
||
def __enter__(self) -> OpenAI: | ||
global client | ||
if client is None: | ||
client = OpenAI(api_key=self.api_key) | ||
return client | ||
|
||
def __exit__(self, exc_type, exc_value, traceback) -> None: | ||
global client | ||
if client is not None: | ||
client.close() | ||
client = None | ||
|
||
|
||
DEFAULT_OPENAI_SETTINGS = { | ||
"max_tokens": 500, | ||
"temperature": 0.7, | ||
} | ||
PREFIX = "openai-" | ||
ENGINES = { | ||
"chat": ["gpt-3.5-turbo", "gpt-4"], | ||
"completion": ["gpt-3.5-turbo-instruct"], | ||
} | ||
ALLOWED_TOOLS = [PREFIX + value for values in ENGINES.values() for value in values] | ||
|
||
|
||
# Fetch the GraphQL schema using introspection query | ||
def fetch_graphql_schema(endpoint): | ||
introspection_query = """ | ||
{ | ||
__schema { | ||
types { | ||
name | ||
fields { | ||
name | ||
type { | ||
kind | ||
name | ||
} | ||
} | ||
} | ||
} | ||
} | ||
""" | ||
response = requests.post(endpoint, json={"query": introspection_query}) | ||
if response.status_code == 200: | ||
return response.json() | ||
else: | ||
raise Exception( | ||
f"Failed to fetch schema: {response.status_code}, {response.text}" | ||
) | ||
|
||
|
||
def fetch_data_from_indexer(endpoint, query): | ||
response = requests.post(endpoint, json={"query": query}) | ||
if response.status_code == 200: | ||
return response.json() | ||
else: | ||
raise Exception( | ||
f"Failed to fetch schema: {response.status_code}, {response.text}" | ||
) | ||
|
||
|
||
def run(**kwargs) -> Tuple[Optional[str], Optional[Dict[str, Any]], Any, Any]: | ||
"""Run the task""" | ||
with OpenAIClientManager(kwargs["api_keys"]["openai"]): | ||
max_tokens = kwargs.get("max_tokens", DEFAULT_OPENAI_SETTINGS["max_tokens"]) | ||
temperature = kwargs.get("temperature", DEFAULT_OPENAI_SETTINGS["temperature"]) | ||
endpoint = kwargs.get("endpoint") | ||
description = kwargs.get("description") | ||
request = kwargs.get("request") | ||
examples = kwargs.get("examples") | ||
tool = kwargs["tool"] | ||
schema = fetch_graphql_schema(endpoint) | ||
prompt = generate_graphql_query(request, schema, description, examples) | ||
if tool not in ALLOWED_TOOLS: | ||
return ( | ||
f"Tool {tool} is not in the list of supported tools.", | ||
None, | ||
None, | ||
None, | ||
) | ||
engine = tool.replace(PREFIX, "") | ||
messages = [ | ||
{"role": "user", "content": prompt}, | ||
] | ||
response = client.chat.completions.create( | ||
model=engine, | ||
messages=messages, | ||
temperature=temperature, | ||
max_tokens=max_tokens, | ||
n=1, | ||
timeout=120, | ||
stop=None, | ||
) | ||
query_to_be_used = response.choices[0].message.content | ||
print(query_to_be_used) | ||
requested_data = fetch_data_from_indexer(endpoint, query_to_be_used) | ||
messages = [ | ||
{"role": "user", "content": prompt}, | ||
{"role": "user", "content": query_to_be_used}, | ||
{ | ||
"role": "user", | ||
"content": analyze_data_and_generate_response(requested_data), | ||
}, | ||
] | ||
response = client.chat.completions.create( | ||
model=engine, | ||
messages=messages, | ||
temperature=temperature, | ||
max_tokens=max_tokens, | ||
n=1, | ||
timeout=120, | ||
stop=None, | ||
) | ||
return response.choices[0].message.content, prompt, None, None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# -*- coding: utf-8 -*- | ||
# ------------------------------------------------------------------------------ | ||
# | ||
# Copyright 2024 Valory AG | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# | ||
# ------------------------------------------------------------------------------ | ||
|
||
query_examples = """ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. copyright header is missing here, which the CI complains about |
||
1. | ||
|
||
# Provide me a list of addresses that have made the highest number of transfers to a specific address | ||
|
||
query MyQuery { | ||
account(id: "0x0000000000000000000000000000000000000000") { | ||
id | ||
receivedTransfers { | ||
groupedAggregates(groupBy: FROM_ID) { | ||
keys | ||
distinctCount { | ||
id | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
2. | ||
|
||
# Please provide a list of addresses who transfered the highest amounts within the certain timeframe. | ||
|
||
query MyQuery { | ||
account(id: "0x0000000000000000000000000000000000000000") { | ||
id | ||
receivedTransfers( | ||
first: 5 | ||
filter: {and: [{timestamp: {greaterThan: "0"}}, {timestamp: {lessThan: "1000"}}]} | ||
) { | ||
groupedAggregates(groupBy: FROM_ID) { | ||
keys | ||
sum { | ||
value | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
3. | ||
|
||
# Please provide a first transfer ever indexed | ||
|
||
query MyQuery { | ||
transfers(first: 1, orderBy: TIMESTAMP_ASC) { | ||
nodes { | ||
id | ||
value | ||
} | ||
} | ||
} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there are some missing required fields here: