Back to Llama Index

Setup OpenAI Agent

llama-index-integrations/tools/llama-index-tools-graphql/examples/graphql.ipynb

0.14.212.2 KB
Original Source

GraphQL Agent Tool

This example walks through two examples of connecting an Agent to a GraphQL server, one unauthenticated endpoint and one authenticated. To start, we initialize the OpenAI package with our api key.

python
# Setup OpenAI Agent
import os

os.environ["OPENAI_API_KEY"] = "sk-your-key"

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI

Unauthenticated server

Our first example is connecting to a server provided by Apollo as an introduction to GraphQL. It provides some data about SpaceX rockets and launches.

To get started, we setup the url we want to query and some basic headers, then we ask the agent to execute a query against the server.

python
from llama_index.tools.graphql.base import GraphQLToolSpec

# Unauthenticated example against a public server
url = "https://spacex-production.up.railway.app/"
headers = {
    "content-type": "application/json",
}

graphql_spec = GraphQLToolSpec(url=url, headers=headers)
agent = FunctionAgent(
    tools=graphql_spec.to_tool_list(),
    llm=OpenAI(model="gpt-4.1"),
)

print(await agent.run("get the id, name and type of the Ships from the graphql endpoint"))

The Agent was able to form the GraphQL based on our instructions, and additionally provided some extra parsing and formatting for the data. Nice!

Authenticated Server

The next example shows setting up authentication headers to hit a private server, representing a Shopify store that has opened up GraphQL access based on an admin API token. To get started with an example similar to this, see the shopify.ipynb notebook. You will also find a more detailed example of using the Schema Definition Language file to fully unlock the GraphQL API.

python
# Authenticated example against a Shopify store

url = "https://your-store.myshopify.com/admin/api/2023-07/graphql.json"
headers = {
    "accept-language": "en-US,en;q=0.9",
    "content-type": "application/json",
    "X-Shopify-Access-Token": "your-admin-key",
}

graphql_spec = GraphQLToolSpec(url=url, headers=headers)
agent = FunctionAgent(
    tools=graphql_spec.to_tool_list(),
    llm=OpenAI(model="gpt-4.1"),
)

print(
    await agent.run("get the id and title of the first 3 products from the graphql server")
)