高级功能

工具调用

让 LangGraph 代理具备调用外部 API 和执行操作的能力

📚 学习目标

学完这篇文章后,你将能够:

  • 定义可被 LLM 识别的工具(基于 Zod Schema)
  • 将工具绑定到 LLM 模型
  • 使用 ToolNode 和条件边自动执行工具调用

前置知识

在开始学习之前,建议先阅读:


1️⃣ 什么是工具调用?

工具调用(Function Calling)是现代 LLM(如 GPT-4, Claude 3)的核心能力。它允许模型:

  1. 识别用户意图需要使用工具。
  2. 生成符合工具 Schema 的参数。
  3. 暂停生成,等待外部运行工具。
  4. 接收工具运行结果,由于 Context 得到增强,模型能生成最终回答。

在 LangGraph 中,这对应 ReAct 循环。


2️⃣ 定义工具

我们使用 @langchain/core/tools 中的 tool 函数。

import { tool } from "@langchain/core/tools";
import { z } from "zod";

const weatherTool = tool(
  async ({ city }) => {
    // 模拟 API 调用
    if (city === "Shanghai") return "Sunny, 25°C";
    return "Unknown city";
  },
  {
    name: "get_weather",
    description: "Get current weather for a city",
    schema: z.object({
      city: z.string().describe("The city name, e.g. Shanghai"),
    }),
  }
);

3️⃣ 绑定到 LLM

模型必须知道有哪些工具可用。

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({ model: "gpt-4o" });
const llmWithTools = llm.bindTools([weatherTool]);

4️⃣ 构建 Graph

LangGraph 提供了内置的 ToolNode 来简化工具执行。

import { ToolNode } from "@langchain/langgraph/prebuilt";
import { StateGraph } from "@langchain/langgraph";

// 1. 定义节点
const agentNode = async (state) => {
  const { messages } = state;
  // 调用绑定了工具的 LLM
  const response = await llmWithTools.invoke(messages);
  return { messages: [response] };
};

const toolNode = new ToolNode([weatherTool]);

// 2. 定义条件路由
const shouldContinue = (state) => {
  const lastMessage = state.messages.at(-1);
  // 如果 LLM 想要调用工具,转到 'tools' 节点
  if (lastMessage.tool_calls?.length) {
    return "tools";
  }
  return "__end__";
};

// 3. 组装 Graph
const app = new StateGraph(MessagesAnnotation)
  .addNode("agent", agentNode)
  .addNode("tools", toolNode)
  .addEdge("__start__", "agent")
  .addConditionalEdges("agent", shouldContinue)
  .addEdge("tools", "agent") // 工具执行后回到 agent
  .compile();

5️⃣ MCP (Model Context Protocol)

MCP 是 Anthropic 提出的一个开放标准,旨在标准化工具的定义和连接。LangGraph 支持通过适配器连接 MCP 服务器。

// 伪代码示例
import { MultiServerMCPClient } from "@langchain/mcp-adapters";

const client = new MultiServerMCPClient({ ... });
const mcpTools = await client.getTools();
// 像普通工具一样使用
const llmWithMCP = llm.bindTools(mcpTools);

💡 练习题

  1. 实战题:编写一个 calculator 工具,支持加减乘除。将其集成到一个 Agent 中,测试问它是 "33 * 44 等于多少"。

📚 参考资源

官方文档


✅ 总结

本章要点

  • Schema:清晰的 Zod 定义是 LLM 正确调用工具的关键。
  • ToolNode:LangGraph 内置的 ToolNode 帮你处理了参数解析和结果回传。
  • Cycle:Agent -> Tools -> Agent 是最经典的循环。

下一步:如何保存应用状态,实现“断点续传”?学习持久化

登录以继续阅读

解锁完整文档、代码示例及更多高级功能。

立即登录

On this page