GraphQL 工具

这个 Jupyter Notebook 展示了如何在代理程序中使用 BaseGraphQLTool 组件。

GraphQL 是一种用于 API 的查询语言,也是执行这些查询的运行时。GraphQL 提供了对 API 中数据的完整和可理解的描述,使客户端能够精确地获取所需的数据,而无需多余的内容,使得随时间推移演进 API 更加容易,并且支持强大的开发者工具。

通过在提供给代理程序的工具列表中包含 BaseGraphQLTool,您可以授权代理程序从 GraphQL API 查询数据,以满足您的任何需求。

在本例中,我们将使用位于以下终点的公共 Star Wars GraphQL API:https://swapi-graphql.netlify.app/.netlify/functions/index。

首先,您需要安装 httpx 和 gql 两个 Python 包。

pip install httpx gql > /dev/null

现在,让我们创建一个具有指定 Star Wars API 终点的 BaseGraphQLTool 实例,并使用该工具初始化一个代理程序。

from langchain import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.utilities import GraphQLAPIWrapper

llm = OpenAI(temperature=0)

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

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

现在,我们可以使用代理程序来针对 Star Wars GraphQL API 运行查询。让我们要求代理程序列出所有 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.'
Last Updated:
Contributors: 刘强