工具扩展了代理 的能力——让它们能够获取实时数据、执行代码、查询外部数据库并在现实世界中采取行动。
在底层,工具是具有明确定义输入和输出的可调用函数,这些函数被传递给聊天模型 。模型根据对话上下文决定何时调用工具,以及提供哪些输入参数。
有关模型如何处理工具调用的详细信息,请参阅工具调用 。
创建工具
基本工具定义
创建工具的最简单方法是从 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-4.1" } ) ,
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-4.1" } ) ,
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 Server 上运行时,通过 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 Server 上运行时,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 }) => `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 : "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 获取实时答案。