跳至主要内容

GraphQL

GraphQL 是一种用于 API 的查询语言,以及一个用于针对您的数据执行这些查询的运行时。GraphQL 提供了对 API 中数据的完整且易于理解的描述,使客户端能够准确地请求他们需要的内容,并且仅此而已,使随着时间的推移更容易发展 API,并支持强大的开发者工具。

通过在提供给 Agent 的工具列表中包含BaseGraphQLTool,您可以授予您的 Agent 查询来自 GraphQL API 的数据的能力,以满足您所需的任何目的。

此 Jupyter Notebook 演示了如何将GraphQLAPIWrapper组件与 Agent 一起使用。

在此示例中,我们将使用以下端点提供的公共Star Wars GraphQL APIhttps://swapi-graphql.netlify.app/.netlify/functions/index

首先,您需要安装httpxgql Python 包。

pip install httpx gql > /dev/null
%pip install --upgrade --quiet  langchain-community

现在,让我们使用指定的 Star Wars API 端点创建一个 BaseGraphQLTool 实例,并使用该工具初始化一个 Agent。

from langchain.agents import AgentType, initialize_agent, load_tools
from langchain_openai import OpenAI

llm = OpenAI(temperature=0)

tools = load_tools(
["graphql"],
graphql_endpoint="https://swapi-graphql.netlify.app/.netlify/functions/index",
)

agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

现在,我们可以使用 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 "


agent.run(suffix + graphql_fields)


> Entering new AgentExecutor chain...
 I need to query the graphql database to get the titles of all the star wars films
Action: query_graphql
Action Input: query { allFilms { films { title } } }
Observation: "{\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}"
Thought: I now know the titles of all the star wars films
Final Answer: The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith.

> Finished chain.
'The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith.'

此页面是否有帮助?


您也可以留下详细的反馈 在 GitHub 上.