工具扩展了智能体 的能力——让它们能够获取实时数据、执行代码、查询外部数据库以及在现实世界中采取行动。
在底层,工具是具有明确定义输入和输出的可调用函数,它们会被传递给聊天模型 。模型根据对话上下文决定何时调用工具,以及提供哪些输入参数。
关于模型如何处理工具调用的详细信息,请参阅工具调用 。
创建工具
基础工具定义
创建工具最简单的方法是从 langchain 包中导入 tool 函数。你可以使用 zod 来定义工具的输入模式:
import * as z from "zod"
import { tool } from "langchain"
const searchDatabase = tool (
({ query , limit }) => `为 ' ${ query } ' 找到了 ${ limit } 条结果` ,
{
name : "search_database" ,
description : "在客户数据库中搜索与查询匹配的记录。" ,
schema : z . object ( {
query : z . string () . describe ( "要查找的搜索词" ) ,
limit : z . number () . describe ( "要返回的最大结果数" ) ,
} ) ,
}
) ;
服务端工具使用: 一些聊天模型内置了在模型提供商服务端执行的工具(如网络搜索、代码解释器)。详情请参阅服务端工具使用 。
工具名称建议使用 snake_case(例如,使用 web_search 而不是 Web Search)。一些模型提供商对包含空格或特殊字符的名称存在问题或会报错拒绝。坚持使用字母数字字符、下划线和连字符有助于提高跨提供商的兼容性。
访问上下文
当工具能够访问运行时信息(如对话历史、用户数据和持久化内存)时,它们的功能最为强大。本节介绍如何从工具内部访问和更新这些信息。
上下文
上下文提供了在调用时传递的不可变配置数据。用于用户ID、会话详情或不应在对话期间更改的应用程序特定设置。
工具可以通过 config 参数访问智能体的运行时上下文:
import * as z from "zod"
import { ChatOpenAI } from "@langchain/openai"
import { createAgent } from "langchain"
const getUserName = tool (
( _ , config ) => {
return config . context . user_name
},
{
name : "get_user_name" ,
description : "获取用户的名称。" ,
schema : z . object ( {} ) ,
}
) ;
const contextSchema = z . object ( {
user_name : z . string () ,
} ) ;
const agent = createAgent ( {
model : new ChatOpenAI ( { model : "gpt-4.1" } ) ,
tools : [getUserName] ,
contextSchema ,
} ) ;
const result = await agent . invoke (
{
messages : [ { role : "user" , content : "我的名字是什么?" } ]
},
{
context : { user_name : "John Smith" }
}
) ;
长期记忆(存储)
BaseStore 提供了跨对话持久存在的存储。与状态(短期记忆)不同,保存到存储的数据在未来的会话中仍然可用。
通过 config.store 访问存储。存储使用命名空间/键模式来组织数据:
import * as z from "zod" ;
import { createAgent , tool } from "langchain" ;
import { InMemoryStore } from "@langchain/langgraph" ;
import { ChatOpenAI } from "@langchain/openai" ;
const store = new InMemoryStore () ;
// 访问内存
const getUserInfo = tool (
async ({ user_id }) => {
const value = await store . get ([ "users" ] , user_id) ;
console . log ( "get_user_info" , user_id , value) ;
return value ;
},
{
name : "get_user_info" ,
description : "查找用户信息。" ,
schema : z . object ( {
user_id : z . string () ,
} ) ,
}
) ;
// 更新内存
const saveUserInfo = tool (
async ({ user_id , name , age , email }) => {
console . log ( "save_user_info" , user_id , name , age , email) ;
await store . put ([ "users" ] , user_id , { name , age , email } ) ;
return "成功保存用户信息。" ;
},
{
name : "save_user_info" ,
description : "保存用户信息。" ,
schema : z . object ( {
user_id : z . string () ,
name : z . string () ,
age : z . number () ,
email : z . string () ,
} ) ,
}
) ;
const agent = createAgent ( {
model : new ChatOpenAI ( { model : "gpt-4.1" } ) ,
tools : [getUserInfo , saveUserInfo] ,
store ,
} ) ;
// 第一个会话:保存用户信息
await agent . invoke ( {
messages : [
{
role : "user" ,
content : "保存以下用户:userid: abc123, name: Foo, age: 25, email: foo@langchain.dev" ,
},
] ,
} ) ;
// 第二个会话:获取用户信息
const result = await agent . invoke ( {
messages : [
{ role : "user" , content : "获取ID为 'abc123' 的用户信息" },
] ,
} ) ;
console . log (result) ;
// 这是ID为 "abc123" 的用户信息:
// - 名称:Foo
// - 年龄:25
// - 邮箱:foo@langchain.dev
See all 70 lines
流写入器
在工具执行期间流式传输实时更新。这对于在长时间运行的操作期间向用户提供进度反馈很有用。
使用 config.writer 发出自定义更新:
import * as z from "zod" ;
import { tool , ToolRuntime } from "langchain" ;
const getWeather = tool (
({ city }, config : ToolRuntime ) => {
const writer = config . writer ;
// 在工具执行时流式传输自定义更新
if (writer) {
writer ( `正在查找城市数据: ${ city } ` ) ;
writer ( `已获取城市数据: ${ city } ` ) ;
}
return ` ${ city } 总是阳光明媚!` ;
},
{
name : "get_weather" ,
description : "获取给定城市的天气。" ,
schema : z . object ( {
city : z . string () ,
} ) ,
}
) ;
ToolNode 是一个预构建的节点,用于在 LangGraph 工作流中执行工具。它自动处理并行工具执行、错误处理和状态注入。
基本用法
import { ToolNode } from "@langchain/langgraph/prebuilt" ;
import { tool } from "@langchain/core/tools" ;
import * as z from "zod" ;
const search = tool (
({ query }) => `结果: ${ query } ` ,
{
name : "search" ,
description : "搜索信息。" ,
schema : z . object ( { query : z . string () } ) ,
}
) ;
const calculator = tool (
({ expression }) => String ( eval (expression)) ,
{
name : "calculator" ,
description : "评估数学表达式。" ,
schema : z . object ( { expression : z . string () } ) ,
}
) ;
// 使用你的工具创建 ToolNode
const toolNode = new ToolNode ([search , calculator]) ;
工具返回值
你可以为工具选择不同的返回值:
返回 string 用于人类可读的结果。
返回 object 用于模型应解析的结构化结果。
返回带有可选消息的 Command,当你需要写入状态时。
返回字符串
当工具应为模型提供纯文本以供其读取并在下一个响应中使用时,返回字符串。
import { tool } from "langchain" ;
import * as z from "zod" ;
const getWeather = tool ( ({ city }) => `It is currently sunny in ${ city } .` , {
name : "get_weather" ,
description : "Get weather for a city." ,
schema : z . object ( { city : z . string () } ) ,
} ) ;
行为:
返回值被转换为 ToolMessage。
模型看到该文本并决定下一步做什么。
除非模型或其他工具稍后更改,否则不会更改智能体状态字段。
当结果本质上是人类可读文本时使用此方法。
返回对象
当你的工具生成结构化数据且模型应检查时,返回对象(例如 dict)。
import { tool } from "langchain" ;
import * as z from "zod" ;
const getWeatherData = tool (
({ city }) => ( {
city ,
temperature_c : 22 ,
conditions : "sunny" ,
} ) ,
{
name : "get_weather_data" ,
description : "Get structured weather data for a city." ,
schema : z . object ( { city : z . string () } ) ,
},
) ;
行为:
对象被序列化并作为工具输出发送回来。
模型可以读取特定字段并基于它们进行推理。
与字符串返回类似,这不会直接更新图状态。
当下游推理受益于显式字段而非自由格式文本时使用此方法。
返回 Command
当工具需要更新图状态时(例如,设置用户偏好或应用程序状态),返回 Command 。
你可以返回带有或不包含 ToolMessage 的 Command。
如果模型需要看到工具执行成功(例如,确认偏好更改),请在更新中包含 ToolMessage,并使用 runtime.tool_call_id 作为 tool_call_id 参数。
import { tool , ToolMessage , type ToolRuntime } from "langchain" ;
import { Command } from "@langchain/langgraph" ;
import * as z from "zod" ;
const setLanguage = tool (
async ({ language }, config : ToolRuntime ) => {
return new Command ( {
update : {
preferredLanguage : language ,
messages : [
new ToolMessage ( {
content : `Language set to ${ language } .` ,
tool_call_id : config . toolCallId ,
} ) ,
] ,
},
} ) ;
},
{
name : "set_language" ,
description : "Set the preferred response language." ,
schema : z . object ( { language : z . string () } ) ,
},
) ;
行为:
命令使用 update 更新状态。
更新后的状态在同一运行中的后续步骤中可用。
对于可能被并行工具调用更新的字段,请使用归约器。
当工具不仅仅是返回数据,还要改变智能体状态时使用此方法。
错误处理
配置如何处理工具错误。所有选项请参阅 ToolNode API 参考。
import { ToolNode } from "@langchain/langgraph/prebuilt" ;
// 默认行为
const toolNode = new ToolNode (tools) ;
// 捕获所有错误
const toolNode = new ToolNode (tools , { handleToolErrors : true } ) ;
// 自定义错误消息
const toolNode = new ToolNode (tools , {
handleToolErrors : "出错了,请重试。"
} ) ;
使用 tools_condition 根据 LLM 是否进行了工具调用来进行条件路由:
import { ToolNode , toolsCondition } from "@langchain/langgraph/prebuilt" ;
import { StateGraph , MessagesAnnotation } from "@langchain/langgraph" ;
const builder = new StateGraph (MessagesAnnotation)
. addNode ( "llm" , callLlm)
. addNode ( "tools" , new ToolNode (tools))
. addEdge ( "__start__" , "llm" )
. addConditionalEdges ( "llm" , toolsCondition) // 路由到 "tools" 或 "__end__"
. addEdge ( "tools" , "llm" ) ;
const graph = builder . compile () ;
状态注入
工具可以通过 ToolRuntime 访问当前图状态:
有关从工具访问状态、上下文和长期记忆的更多详细信息,请参阅访问上下文 。
预构建工具
LangChain 提供了大量预构建的工具和工具包,用于常见任务,如网络搜索、代码解释、数据库访问等。这些即用型工具可以直接集成到你的智能体中,无需编写自定义代码。
有关按类别组织的可用工具的完整列表,请参阅工具和工具包 集成页面。
服务端工具使用
一些聊天模型内置了由模型提供商在服务端执行的工具。这些功能包括网络搜索和代码解释器等,无需你定义或托管工具逻辑。
有关启用和使用这些内置工具的详细信息,请参阅各个聊天模型集成页面 和工具调用文档 。