Skip to content

03-react-agent.ts

ReAct agent 示例,使用 createAgent 构建生产级 agent,支持多轮工具调用循环。

功能介绍

这个示例演示了如何使用 createAgent(langchain@1.x 推荐的 agent API)构建真正的 ReAct agent。agent 内部基于 LangGraph 自动跑 think-act-observe 循环,能多轮调用工具直到得出最终答案。与 02-tool-calling 的单轮演示形成对比。

使用场景

  • 需要多步推理的复杂任务
  • 需要结合多个工具的任务(agent 自主决定调用顺序)
  • 自动问答系统
  • 智能助手应用

学习要点

  1. 使用 createAgent from langchain 创建 agent(langchain@1.x 推荐写法;./agents 子路径未在 exports 暴露)
  2. CreateAgentParamsmodel: 而非 llm:
  3. agent 内部基于 LangGraph,自动跑 think-act-observe 循环
  4. agent.invoke({ messages: [...] }) 调用,返回包含完整消息历史的 state
  5. result.messages.at(-1)?.content 是最终答案(.at(-1) 在 strict 模式下可能返回 undefined,需要 ?.
  6. 打印 result.messages 可看到 think-act-observe 完整轨迹(HumanMessage -> AIMessage(tool_calls) -> ToolMessage -> AIMessage(最终答案))
  7. 多工具场景下 agent 会自主决定调用顺序和次数

源码

typescript
import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
import { createAgent } from "langchain";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

if (!process.env.ZHIPUAI_API_KEY) {
  throw new Error("ZHIPUAI_API_KEY is not set in environment variables");
}

// 复用 01-tools 的天气工具定义
const weatherTool = tool(
  async ({ city, unit }) => {
    const weatherData: Record<string, { temp: number; condition: string }> = {
      "北京": { temp: 25, condition: "晴天" },
      "上海": { temp: 22, condition: "多云" },
      "广州": { temp: 28, condition: "小雨" },
    };
    const data = weatherData[city] || { temp: 20, condition: "未知" };
    const temp = unit === "fahrenheit" ? Math.round(data.temp * 9/5 + 32) : data.temp;
    return `${city} 的天气: ${data.condition},${temp}°${unit === "celsius" ? "C" : "F"}`;
  },
  {
    name: "get_current_weather",
    description: "获取指定城市的当前天气",
    schema: z.object({
      city: z.string().describe("城市名称"),
      unit: z.enum(["celsius", "fahrenheit"]).default("celsius").describe("温度单位"),
    }),
  }
);

async function main() {
  try {
    console.log("=== ReAct Agent 示例(createAgent)===\n");

    const model = new ChatOpenAI({
      model: "deepseek-v3-1",
      temperature: 0,
      configuration: {
        baseURL: "https://ark.cn-beijing.volces.com/api/coding/v3/",
        apiKey: process.env.ZHIPUAI_API_KEY,
      },
    });

    // createAgent 是 langchain@1.x 推荐的 ReAct agent API
    // 内部基于 LangGraph,自动跑 think-act-observe 循环
    const agent = createAgent({
      model,
      tools: [weatherTool],
    });

    const question = "北京和上海天气怎么样?";
    console.log("问题:", question);
    console.log("\n---\n");

    const result = await agent.invoke({
      messages: [{ role: "user", content: question }],
    });

    // 打印消息历史,让 think-act-observe 循环可见
    // 应该能看到:HumanMessage -> AIMessage(tool_calls) -> ToolMessage × 2 -> AIMessage(最终答案)
    console.log("消息历史(共", result.messages.length, "条):");
    for (const msg of result.messages) {
      console.log(`  [${msg._getType()}]`, msg.content);
    }
    console.log("\n---\n");

    console.log("最终回答:", result.messages.at(-1)?.content);
  } catch (error) {
    console.error("Error during react agent example:", error);
    process.exit(1);
  }
}

main().catch(console.error);

运行方式

bash
npm run dev src/05-agents/03-react-agent.ts