这一章正式进入 LangChain 前面我们已经把边界说清楚了:这一章只讨论一件事,单个 Agent 怎样在一轮请求里调用多个工具,把事情做完。
先不要急着记概念,先看一个最小例子。还是用「AI 电子伴侣」这个场景。
用户发来一句话:
我明天下午三点要开会,帮我记一下。顺便查一下上海明天会不会下雨。
如果我们希望这个 Agent 能处理这句话,它至少要会两件事:
用 LangChain.js v1,可以先这样写:
01import * as z from 'zod'02import { createAgent, initChatModel, tool } from 'langchain'0304const model = await initChatModel('gpt-4.1-mini', {05modelProvider: 'openai',06})0708const createReminder = tool(09async ({ title, time }) => {10return `提醒已创建:${time} ${title}`11},12{13name: 'create_reminder',14description: '创建提醒事项',15schema: z.object({16title: z.string().describe('提醒内容'),17time: z.string().describe('提醒时间'),18}),19}20)2122const getWeather = tool(23async ({ city }) => {24return `${city} 明天有小雨,出门记得带伞`25},26{27name: 'get_weather',28description: '查询城市天气',29schema: z.object({30city: z.string().describe('要查询天气的城市'),31}),32}33)3435const agent = createAgent({36model,37tools: [createReminder, getWeather],38systemPrompt: '你是一名细心、自然的生活助手。',39})4041const result = await agent.invoke({42messages: [43{44role: 'user',45content: '我明天下午三点要开会,帮我记一下。顺便查一下上海明天会不会下雨。',46},47],48})4950console.log(result.messages.at(-1)?.content)
这段代码已经把这一章最重要的几样东西都摆出来了:
initChatModel():先把模型接进来tool():把外部能力包装成工具createAgent():把模型、工具和系统设定组装成一个 Agentagent.invoke():把一轮消息交给 Agent 处理后面整章内容,基本都会围绕这四件事展开。