Find answers from the community

Updated 3 months ago

how to add graphql schema within the code in LlamaIndex

how to add graphql schema within the code in LlamaIndex
k
a
10 comments
Please stand by @andysingal as I search the knowledge base. I normally take about 20 seconds or so. :wave:
----------------------
In LlamaIndex, you can use the GraphQL schema within your code by leveraging the GraphQLToolSpec class and the OnDemandLoaderTool class. Here's a step-by-step guide on how to do it:

  1. Setup the GraphQLToolSpec: This class is used to make a GraphQL query against the server. You need to initialize it with the URL of your GraphQL server and optionally, any headers required for the request. Here's an example of how to do it:
Plain Text
from llama_index.tools.graphql.base import GraphQLToolSpec

url = "<https://your-graphql-server.com">
headers = {
    "content-type": "application/json",
    # Add any other headers if required
}

graphql_spec = GraphQLToolSpec(url=url, headers=headers)

Source ()

  1. Parse the GraphQL Schema: You can parse the GraphQL schema and extract the QueryRoot objects. These objects are critical to writing good queries. Here's an example of how to do it:
Plain Text
import json
from graphql import parse

with open("your_graphql_schema.txt", "r") as f:
    txt = f.read()

ast = parse(txt)

query_root_node = next(
    (
        defn
        for defn in ast.definitions
        if defn.kind == "object_type_definition" and defn.name.value == "QueryRoot"
    )
)
query_roots = [field.name.value for field in query_root_node.fields]
print(query_roots)

Source ()

  1. Setup the OnDemandLoaderTool: This tool is used to create an interface that your Agent can use to query and process the GraphQL schema. Here's an example of how to do it:
Plain Text
from llama_index.file.sdl.base import SDLReader
from llama_index.tools.ondemand_loader_tool import OnDemandLoaderTool

documentation_tool = OnDemandLoaderTool.from_defaults(
    SDLReader(),
    name="graphql_writer",
    description="""
        The GraphQL schema file is located at './data/shopify_graphql.txt', this is always the file argument.
        A tool for processing the Shopify GraphQL spec, and writing queries from the documentation.
    """,
)

Source ()

Please replace "your-graphql-server.com" and "your_graphql_schema.txt" with your actual GraphQL server URL and schema file path respectively.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
@kapa.ai is this the right format? query subscription {
Solana {
InstructionBalanceUpdates(limit: {count: 10}) {
Transaction {
Index
FeePayer
Fee
Signature
Result {
Success
ErrorMessage
}
}
Instruction {
InternalSeqNumber
Index
CallPath
Program {
Address
Name
Parsed
}
}
Block {
Time
Hash
Height
}
BalanceUpdate {
Account {
Address
}
Amount
Currency {
Decimals
CollectionAddress
Name
Key
IsMutable
Symbol
}
}
}
}
}
Let me check the knowledge base for you. One moment! :books:
----------------------
Yes, the format of your GraphQL query appears to be correct. It follows the standard structure of a GraphQL query, which includes nested objects and fields.

Here's a breakdown of your query:

  • Solana: This is the root query object. All the fields under this object will be queried from the Solana object in your GraphQL schema.
  • InstructionBalanceUpdates: This is a field under the Solana object. It seems to take a limit argument which is an object itself with a count field.
  • Transaction, Instruction, Block, BalanceUpdate: These are fields under the InstructionBalanceUpdates object. Each of these fields has its own nested fields that you're querying.
Please ensure that all the fields and nested fields in your query exist in your GraphQL schema and are spelled correctly. Also, make sure that the types of the arguments you're passing (like count: 10) match the types expected by your GraphQL schema.

You can use the graphql_request method from the PlaygroundsSubgraphConnectorToolSpec class in LlamaIndex to execute this query. Here's an example:

```python
from llama_index.tools.playgrounds import PlaygroundsSubgraphConnectorToolSpec

Initialize the tool spec

tool_spec = PlaygroundsSubgraphConnectorToolSpec(...)

Your GraphQL query

query = """
query subscription {
Solana {
InstructionBalanceUpdates(limit: {count: 10}) {
Transaction {
Index
FeePayer
Fee
Signature
Result {
Success
ErrorMessage
}
}
Instruction {
InternalSeqNumber
Index
CallPath
Program {
Address
Name
Parsed
}
}
Block {
Time
Hash
Height
}
BalanceUpdate {
Account {
Address
}
Amount
Currency {
Decimals
CollectionAddress
Name
Key
IsMutable
Symbol
}
}
}
}
}
"""

Execute the query

response = tool_spec.graphql_request(query)
`` Please replace the ... in PlaygroundsSubgraphConnectorToolSpec(...)` with the appropriate arguments for your use case.

Source ()
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
@kapa.ai i tried %%writefile bitquery_graphql.txt
query subscription {
Solana {
InstructionBalanceUpdates(limit: {count: 10}) {
Transaction {
Index
FeePayer
Fee
Signature
Result {
Success
ErrorMessage
}
}
Instruction {
InternalSeqNumber
Index
CallPath
Program {
Address
Name
Parsed
}
}
Block {
Time
Hash
Height
}
BalanceUpdate {
Account {
Address
}
Amount
Currency {
Decimals
CollectionAddress
Name
Key
IsMutable
Symbol
}
}
}
}
}
followed by
Plain Text
import json
from graphql import parse

with open("bitquery_graphql.txt", "r") as f:
    txt = f.read()

ast = parse(txt)

query_root_node = next(
    (
        defn
        for defn in ast.definitions
        if defn.kind == "object_type_definition" and defn.name.value == "QueryRoot"
    )
)
query_roots = [field.name.value for field in query_root_node.fields]
print(query_roots)
but get error
Let me check the knowledge base for you. One moment! :books:
----------------------
The error you're encountering might be due to the fact that the code you're using is designed to parse a GraphQL schema, not a GraphQL query.

In the code you provided, it's trying to find a QueryRoot object in the GraphQL schema. However, you're providing it with a GraphQL query, not a schema. A GraphQL schema is a server-side artifact that describes the types of data available and how they relate to each other. It's not the same as a GraphQL query, which is a client-side artifact that specifies what data to fetch.

If you want to parse a GraphQL query, you would need a different approach. You can still use the parse function from the graphql library to parse the query into an Abstract Syntax Tree (AST), but you wouldn't look for a QueryRoot object. Instead, you would navigate the AST according to the structure of your query.

Here's an example of how you might parse a GraphQL query:

Plain Text
from graphql import parse

with open("bitquery_graphql.txt", "r") as f:
    query = f.read()

ast = parse(query)

# Print the kind of the top-level AST node
print(ast.kind)

# Print the kinds of the definitions in the query
for defn in ast.definitions:
    print(defn.kind)


This will give you a sense of the structure of your query. You can then navigate the AST according to that structure.

If you want to parse a GraphQL schema, you would need to have the schema in SDL (Schema Definition Language) format. You can usually download this from your GraphQL server. Once you have the schema, you can use the code you provided to parse it and extract the QueryRoot object.

Source ()
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Add a reply
Sign up and join the conversation on Discord