AutoGPT/agbenchmark/utils/get_data_from_helicone.py

83 lines
2.3 KiB
Python
Raw Normal View History

2023-07-31 12:41:45 +00:00
import json
2023-07-31 13:02:46 +00:00
import os
from typing import Optional
import requests
from agbenchmark.agent_interface import HELICONE_GRAPHQL_LOGS
from agbenchmark.start_benchmark import BENCHMARK_START_TIME
def get_data_from_helicone(challenge: str) -> Optional[float]:
# Define the endpoint of your GraphQL server
url = "https://www.helicone.ai/api/graphql"
# Set the headers, usually you'd need to set the content type and possibly an authorization token
headers = {"authorization": f"Bearer {os.environ.get('HELICONE_API_KEY')}"}
# Define the query, variables, and operation name
query = """
2023-07-31 11:54:27 +00:00
query ExampleQuery($properties: [PropertyFilter!]){
aggregatedHeliconeRequest(properties: $properties) {
costUSD
}
}
"""
variables = {
2023-08-01 23:50:41 +00:00
"properties": [
{
2023-08-01 23:50:41 +00:00
"value": {"equals": os.environ.get("AGENT_NAME")},
"name": "agent",
},
{
2023-08-01 23:50:41 +00:00
"value": {"equals": BENCHMARK_START_TIME},
"name": "benchmark_start_time",
},
2023-08-01 23:50:41 +00:00
{"value": {"equals": challenge}, "name": "challenge"},
]
}
if HELICONE_GRAPHQL_LOGS:
print(query)
print(json.dumps(variables, indent=4))
operation_name = "ExampleQuery"
2023-08-01 23:50:41 +00:00
data = {}
2023-07-31 12:41:45 +00:00
response = None
2023-07-31 12:28:01 +00:00
2023-07-31 11:54:27 +00:00
try:
response = requests.post(
url,
headers=headers,
json={
"query": query,
"variables": variables,
"operationName": operation_name,
},
)
2023-07-31 13:02:46 +00:00
2023-07-31 11:54:27 +00:00
data = response.json()
except requests.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
return None # Re-raise the exception to stop execution
2023-07-31 12:41:45 +00:00
except json.JSONDecodeError:
print(f"Invalid JSON response: {response.text if response else 'No response'}")
return None
2023-07-31 11:54:27 +00:00
except Exception as err:
print(f"Other error occurred: {err}")
return None
2023-07-31 12:28:01 +00:00
2023-08-01 12:44:32 +00:00
try:
2023-08-01 23:50:41 +00:00
if data is None or data.get("data") is None:
print("Invalid response received from server: no data")
return None
2023-08-01 12:44:32 +00:00
return (
data.get("data", {})
.get("aggregatedHeliconeRequest", {})
.get("costUSD", None)
)
except Exception as err:
print(f"Error occurred while parsing response: {err}")
return None