跳到主要內容

GraphQL

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

透過將 BaseGraphQLTool 包含在提供給 Agent 的工具列表中,您可以授予您的 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 列出所有星際大戰電影及其發布日期。

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

這個頁面有幫助嗎?