跳到主要內容
Open In ColabOpen on GitHub

GraphQL

GraphQL 是一種用於 API 的查詢語言,也是一個針對您的資料執行這些查詢的執行階段。GraphQL 提供了您 API 中資料的完整且易於理解的描述,讓客戶能夠準確地要求他們需要的內容,不多也不少,使 API 隨著時間的推移更容易演進,並啟用強大的開發人員工具。

透過在提供給 Agent 的工具列表中包含 BaseGraphQLTool,您可以授予您的 Agent 從 GraphQL API 查詢資料的能力,以用於您需要的任何目的。

此 Jupyter Notebook 示範如何將 GraphQLAPIWrapper 組件與 Agent 一起使用。

在此範例中,我們將使用公開的 Star Wars GraphQL API,其端點位於:https://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 列出所有星際大戰電影及其發行日期。

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.'

此頁面是否對您有幫助?