Prerequisites

To use the Helicone AI GraphQL API, make sure that you have the gql and aiohttp libraries installed in your Python environment. You can install these packages with the following commands:

pip install gql
pip install aiohttp

Setting up a GraphQL Client

Here’s how to setup a GraphQL client to communicate with the Helicone API:

from gql.transport.aiohttp import AIOHTTPTransport
from gql import gql, Client

url = "https://www.helicone.ai/api/graphql"

# Replace <KEY> with your personal access key
transport = AIOHTTPTransport(url=url, headers={
    "Authorization": "Bearer sk-<KEY>"
})

client = Client(transport=transport, fetch_schema_from_transport=True)

In this code:

  • url is the endpoint of the Helicone AI GraphQL API.
  • AIOHTTPTransport establishes the connection to the API endpoint.
  • Client is a GraphQL client that communicates with the API using the provided transport.

Fetching Data from the API

Here’s how to fetch data from the Helicone AI API using GraphQL:

MAX_LOOPS = 10
SIZE = 100
for i in range(MAX_LOOPS):
    query = gql(
        """
        query getData($limit: Int, $offset: Int) {
            heliconeRequest(
                limit: $limit
                offset: $offset
                filters: []
            ) {
                prompt
                properties{
                    name
                }
                responseBody
                response
            }
        }
    """
    )
    result = client.execute(query,
                            variable_values={
                                "limit": SIZE,
                                "offset": i * SIZE
                            }
                            )
    if (len(result["heliconeRequest"]) == 0):
        print("No more results")
        break
    print(len(result["heliconeRequest"]))
    print(result)

In this code:

  • MAX_LOOPS is the maximum number of requests the client will make to the API.
  • SIZE is the number of records fetched per request.
  • gql parses the GraphQL query.
  • client.execute runs the query and returns the result. The variable_values parameter is used to set the limit and offset in the GraphQL query.

The response contains a list of heliconeRequest objects. Each object includes the prompt, a list of properties with their name, the responseBody, and the response.

The loop continues to fetch data until there are no more records (when result["heliconeRequest"] is an empty list), at which point it prints “No more results” and stops.