图形QL
GraphQL 是 API 的查询语言,也是对数据执行这些查询的运行时。
GraphQL提供 API 中数据的完整且易于理解的描述,使客户能够准确询问他们需要的东西,仅此而已,使 API 随着时间的推移而发展变得更加容易,并支持强大的开发人员工具。
通过包含BaseGraphQLTool在提供给代理的工具列表中,您可以授予代理从 GraphQL API 查询数据以用于您需要的任何目的的能力。
此 Jupyter Notebook 演示了如何使用GraphQLAPIWrapper组件。
在此示例中,我们将使用公共Star Wars GraphQL API可在以下端点使用: https://swapi-graphql.netlify.app/graphql 。
首先,您需要安装httpx和gqlPython 包。
pip install httpx gql > /dev/null
Note: you may need to restart the kernel to use updated packages.
%pip install --upgrade --quiet langchain-community
Note: you may need to restart the kernel to use updated packages.
现在,让我们使用指定的 Star Wars API 终端节点创建一个 BaseGraphQLTool 实例,并使用该工具初始化代理。
import os
os.environ["OPENAI_API_KEY"] = ""
from langchain.agents import load_tools
tools = load_tools(
["graphql"],
graphql_endpoint="https://swapi-graphql.netlify.app/graphql",
)
API 参考:load_tools
from langgraph.prebuilt import create_react_agent
agent = create_react_agent("openai:gpt-4.1-mini", tools)
API 参考:create_react_agent
现在,我们可以使用 Agent 对 Star Wars GraphQL API 运行查询。让我们让 Agent 列出所有 Star Wars 电影及其发布日期。
graphql_fields = """allFilms {
films {
title
director
releaseDate
speciesConnection {
species {
name
classification
homeworld {
name
}
}
}
}
}
"""
suffix = "Search for the titles of all the stawars films stored in the graphql database that has this schema "
input_message = {
"role": "user",
"content": suffix + graphql_fields,
}
for step in agent.stream(
{"messages": [input_message]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
Search for the titles of all the stawars films stored in the graphql database that has this schema allFilms {
films {
title
director
releaseDate
speciesConnection {
species {
name
classification
homeworld {
name
}
}
}
}
}
==================================[1m Ai Message [0m==================================
Tool Calls:
query_graphql (call_tN5A0dBbfOMewuw8Yy13bYpW)
Call ID: call_tN5A0dBbfOMewuw8Yy13bYpW
Args:
tool_input: query { allFilms { films { title } } }
=================================[1m Tool Message [0m=================================
Name: query_graphql
"{\n \"allFilms\": {\n \"films\": [\n {\n \"title\": \"A New Hope\"\n },\n {\n \"title\": \"The Empire Strikes Back\"\n },\n {\n \"title\": \"Return of the Jedi\"\n },\n {\n \"title\": \"The Phantom Menace\"\n },\n {\n \"title\": \"Attack of the Clones\"\n },\n {\n \"title\": \"Revenge of the Sith\"\n }\n ]\n }\n}"
==================================[1m Ai Message [0m==================================
The titles of all the Star Wars films stored in the database are:
1. A New Hope
2. The Empire Strikes Back
3. Return of the Jedi
4. The Phantom Menace
5. Attack of the Clones
6. Revenge of the Sith
If you would like more information about any of these films, please let me know!