工具扩展了代理 的能力——让它们能够获取实时数据、执行代码、查询外部数据库并在现实世界中采取行动。
在底层,工具是具有明确定义输入和输出的可调用函数,这些函数被传递给聊天模型 。模型根据对话上下文决定何时调用工具,以及提供什么输入参数。
有关模型如何处理工具调用的详细信息,请参阅工具调用 。
创建工具
基本工具定义
创建工具最简单的方法是从 langchain 包中导入 tool 函数。你可以使用 zod 来定义工具的输入模式:
import * as z from "zod"
import { tool } from "langchain"
const searchDatabase = tool (
({ query , limit }) => `Found ${ limit } results for ' ${ query } '` ,
{
name : "search_database" ,
description : "Search the customer database for records matching the query." ,
schema : z . object ( {
query : z . string () . describe ( "Search terms to look for" ) ,
limit : z . number () . describe ( "Maximum number of results to return" ) ,
} ) ,
}
) ;
服务器端工具使用: 一些聊天模型具有内置工具(网络搜索、代码解释器),这些工具在服务器端执行。详情请参阅服务器端工具使用 。
工具名称建议使用 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 : "Get the user's name." ,
schema : z . object ( {} ) ,
}
) ;
const contextSchema = z . object ( {
user_name : z . string () ,
} ) ;
const agent = createAgent ( {
model : new ChatOpenAI ( { model : "gpt-5.4" } ) ,
tools : [getUserName] ,
contextSchema ,
} ) ;
const result = await agent . invoke (
{
messages : [ { role : "user" , content : "What is my name?" } ]
},
{
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 : "Look up user info." ,
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 "Successfully saved user info." ;
},
{
name : "save_user_info" ,
description : "Save user info." ,
schema : z . object ( {
user_id : z . string () ,
name : z . string () ,
age : z . number () ,
email : z . string () ,
} ) ,
}
) ;
const agent = createAgent ( {
model : new ChatOpenAI ( { model : "gpt-5.4" } ) ,
tools : [getUserInfo , saveUserInfo] ,
store ,
} ) ;
// 第一次会话:保存用户信息
await agent . invoke ( {
messages : [
{
role : "user" ,
content : "Save the following user: userid: abc123, name: Foo, age: 25, email: foo@langchain.dev" ,
},
] ,
} ) ;
// 第二次会话:获取用户信息
const result = await agent . invoke ( {
messages : [
{ role : "user" , content : "Get user info for user with 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 ( `Looking up data for city: ${ city } ` ) ;
writer ( `Acquired data for city: ${ city } ` ) ;
}
return `It's always sunny in ${ city } !` ;
},
{
name : "get_weather" ,
description : "Get weather for a given city." ,
schema : z . object ( {
city : z . string () ,
} ) ,
}
) ;
执行信息
通过 runtime.execution_info 从工具内部访问线程ID、运行ID和重试状态:
import { tool } from "langchain" ;
import * as z from "zod" ;
const logExecutionContext = tool (
async ( _input , runtime ) => {
const info = runtime . executionInfo ;
console . log ( `Thread: ${ info . threadId } , Run: ${ info . runId } ` ) ;
console . log ( `Attempt: ${ info . nodeAttempt } ` ) ;
return "done" ;
},
{
name : "log_execution_context" ,
description : "Log execution identity information." ,
schema : z . object ( {} ) ,
}
) ;
需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。
服务器信息
当你的工具在 LangGraph 服务器上运行时,通过 runtime.server_info 访问助手ID、图ID和已认证的用户:
import { tool } from "langchain" ;
import * as z from "zod" ;
const getAssistantScopedData = tool (
async ( _input , runtime ) => {
const server = runtime . serverInfo ;
if (server != null ) {
console . log ( `Assistant: ${ server . assistantId } , Graph: ${ server . graphId } ` ) ;
if (server . user != null ) {
console . log ( `User: ${ server . user . identity } ` ) ;
}
}
return "done" ;
},
{
name : "get_assistant_scoped_data" ,
description : "Fetch data scoped to the current assistant." ,
schema : z . object ( {} ) ,
}
) ;
当工具未在 LangGraph 服务器上运行时,serverInfo 为 null。
需要 deepagents>=1.9.0(或 @langchain/langgraph>=1.2.8)。
ToolNode 是一个预构建节点,用于在 LangGraph 工作流中执行工具。它自动处理并行工具执行、错误处理和状态注入。
基本用法
import { ToolNode } from "@langchain/langgraph/prebuilt" ;
import { tool } from "@langchain/core/tools" ;
import * as z from "zod" ;
const search = tool (
({ query }) => `Results for: ${ query } ` ,
{
name : "search" ,
description : "Search for information." ,
schema : z . object ( { query : z . string () } ) ,
}
) ;
const calculator = tool (
({ expression }) => String ( eval (expression)) ,
{
name : "calculator" ,
description : "Evaluate a math expression." ,
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 }) => `目前 ${ city } 天气晴朗。` , {
name : "get_weather" ,
description : "获取城市的天气。" ,
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 : "获取城市的结构化天气数据。" ,
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 : "Something went wrong, please try again."
} ) ;
使用 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 提供了大量用于常见任务的预构建工具和工具包,如网络搜索、代码解释、数据库访问等。这些现成的工具可以直接集成到你的代理中,无需编写自定义代码。
有关按类别组织的可用工具完整列表,请参阅工具和工具包 集成页面。
服务器端工具使用
一些聊天模型具有由模型提供商在服务器端执行的内置工具。这些功能包括网络搜索和代码解释器,无需你定义或托管工具逻辑。
有关启用和使用这些内置工具的详细信息,请参阅各个聊天模型集成页面 和工具调用文档 。
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。