Skip to content

01-tools.ts

工具定义示例,使用 tool() helper 创建结构化工具供 agent 使用。

功能介绍

这个示例演示了如何使用 tool() helper(langchain@1.x 推荐写法)定义带 zod schema 的结构化工具。工具包含名称、描述和执行函数,agent 可以根据描述理解何时以及如何使用这个工具。

使用场景

  • 为 agent 添加自定义能力(如查询天气、检索数据等)
  • 让 agent 能调用外部 API
  • 扩展 agent 的功能边界
  • 连接 AI 和真实世界的系统

学习要点

  1. 使用 tool() helper 创建工具(langchain@1.x 推荐写法,比 DynamicTool 更简洁)
  2. name 参数给工具命名
  3. description 参数描述工具用途(很重要,agent 靠这个理解)
  4. schema 参数用 zod 定义结构化输入
  5. 直接用 tool.invoke({ ... }) 调用工具

源码

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

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

    // 使用 tool() helper 定义天气工具(langchain@1.x 推荐写法)
    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("温度单位"),
        }),
      }
    );

    console.log("工具名称:", weatherTool.name);
    console.log("工具描述:", weatherTool.description);
    console.log("\n---\n");

    const result = await weatherTool.invoke({ city: "北京", unit: "celsius" });
    console.log("调用 get_current_weather({ city: '北京', unit: 'celsius' }):");
    console.log(result);
  } catch (error) {
    console.error("Error during tools example:", error);
    process.exit(1);
  }
}

main().catch(console.error);

运行方式

bash
npm run dev src/05-agents/01-tools.ts