Skip to main content
GraphQL 是一种用于 API 的查询语言,也是执行这些查询的运行时。GraphQL 对 API 中的数据提供完整且易于理解的描述,让客户端能够精确请求所需数据,简化 API 的演进过程,并支持强大的开发者工具。
通过在提供给智能体的工具列表中加入 BaseGraphQLTool,您可以让智能体具备从 GraphQL API 查询数据的能力。 本 Jupyter Notebook 演示了如何将 GraphQLAPIWrapper 组件与智能体配合使用。 在本示例中,我们将使用公开的 Star Wars GraphQL API,其端点为:swapi-graphql.netlify.app/graphql 首先,您需要安装 httpxgql Python 包。
pip install httpx gql > /dev/null
pip install -qU  langchain-community
现在,让我们使用指定的 Star Wars API 端点创建一个 BaseGraphQLTool 实例,并初始化带有该工具的智能体。
import os

os.environ["OPENAI_API_KEY"] = ""
from langchain_community.agent_toolkits.load_tools import load_tools

tools = load_tools(
    ["graphql"],
    graphql_endpoint="https://swapi-graphql.netlify.app/graphql",
)
from langchain.agents import create_agent


agent = create_agent("gpt-4.1-mini", tools)
接下来,我们可以使用智能体对 Star Wars GraphQL API 执行查询。下面让智能体列出所有星球大战电影及其上映日期。
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()
================================ Human Message =================================

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
          }
        }
      }
    }
  }


================================== Ai Message ==================================
Tool Calls:
  query_graphql (call_tN5A0dBbfOMewuw8Yy13bYpW)
 Call ID: call_tN5A0dBbfOMewuw8Yy13bYpW
  Args:
    tool_input: query { allFilms { films { title } } }
================================= Tool Message =================================
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}"
================================== Ai Message ==================================

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!