LangChain Tools 完全指南:从基础定义到高级用法 目录工具简介创建工具基础工具定义自定义工具属性自定义工具名称自定义工具描述高级 schema 定义保留参数名称访问上下文短期记忆State访问 State更新 State上下文Context长期记忆Store流写入器Stream WriterToolNode 用法基础使用工具返回值类型返回字符串返回对象返回 Command错误处理条件路由状态注入预构建工具服务端工具使用工具简介Tools 扩展了 智能体agents 的能力——允许它们获取实时数据、执行代码、查询外部数据库以及在现实世界中执行操作。底层逻辑是工具是带有明确定义输入输出的可调用函数这些函数会传递给 聊天模型chat model模型根据对话上下文决定何时调用工具以及提供哪些输入参数。关于模型如何处理工具调用的详细说明可参考 Tool calling。创建工具基础工具定义创建工具最简单的方式是使用tool装饰器。默认情况下函数的文档字符串docstring会成为工具的描述帮助模型理解何时使用该工具。注意类型提示Type hints是必需的用于定义工具的输入 schema。文档字符串应简洁实用帮助模型理解工具用途。工具名称建议使用snake_case如web_search避免空格和特殊字符提升跨模型提供商的兼容性。fromlangchain.toolsimporttooltooldefsearch_database(query:str,limit:int10)-str:Search the customer database for records matching the query. Args: query: Search terms to look for limit: Maximum number of results to return returnfFound{limit}results for {query}自定义工具属性自定义工具名称默认工具名称取自函数名可通过装饰器参数覆盖设置更具描述性的名称fromlangchain.toolsimporttooltool(web_search)# 自定义工具名称defsearch(query:str)-str:Search the web for information.returnfResults for:{query}print(search.name)# 输出web_search自定义工具描述可覆盖自动生成的工具描述为模型提供更清晰的指引fromlangchain.toolsimporttooltool(calculator,descriptionPerforms arithmetic calculations. Use this for any math problems.)defcalc(expression:str)-str:Evaluate mathematical expressions.returnstr(eval(expression))高级 schema 定义可通过 Pydantic 模型或 JSON Schema 定义复杂输入frompydanticimportBaseModel,FieldfromtypingimportLiteralfromlangchain.toolsimporttoolclassWeatherInput(BaseModel):Input for weather queries.location:strField(descriptionCity name or coordinates)units:Literal[celsius,fahrenheit]Field(defaultcelsius,descriptionTemperature unit preference)include_forecast:boolField(defaultFalse,descriptionInclude 5-day forecast)tool(args_schemaWeatherInput)defget_weather(location:str,units:strcelsius,include_forecast:boolFalse)-str:Get current weather and optional forecast.temp22ifunitscelsiuselse72resultfCurrent weather in{location}:{temp}degrees{units[0].upper()}ifinclude_forecast:result\nNext 5 days: Sunnyreturnresult保留参数名称以下参数名称为保留字不可用作工具参数否则会导致运行时错误Parameter namePurposeconfig用于内部向工具传递RunnableConfigruntime用于ToolRuntime参数访问状态、上下文、存储若需访问运行时信息请使用ToolRuntime参数而非自定义config或runtime命名的参数。访问上下文工具的强大之处在于能访问运行时信息如对话历史、用户数据、持久化记忆。通过ToolRuntime参数可访问以下核心组件ComponentDescriptionUse caseState短期记忆 - 会话期间的可变数据消息、计数器、自定义字段访问对话历史、跟踪工具调用次数Context不可变配置 - 调用时传递的参数用户ID、会话信息根据用户身份个性化响应Store长期记忆 - 跨会话持久化数据保存用户偏好、维护知识库Stream Writer工具执行期间实时输出更新长耗时操作的进度反馈Config执行的RunnableConfig访问回调、标签和元数据Tool Call ID当前工具调用的唯一标识符日志关联、模型调用关联短期记忆StateState 代表会话期间的短期记忆包含消息历史和自定义字段通过runtime.state访问。访问 Statefromlangchain.toolsimporttool,ToolRuntimefromlangchain.messagesimportHumanMessagetooldefget_last_user_message(runtime:ToolRuntime)-str:Get the most recent message from the user.messagesruntime.state[messages]# 查找最后一条人类消息formessageinreversed(messages):ifisinstance(message,HumanMessage):returnmessage.contentreturnNo user messages found# 访问自定义状态字段tooldefget_user_preference(pref_name:str,runtime:ToolRuntime)-str:Get a user preference value.preferencesruntime.state.get(user_preferences,{})returnpreferences.get(pref_name,Not set)更新 State通过Command可更新智能体状态适用于工具需要修改自定义字段的场景fromlanggraph.typesimportCommandfromlangchain.toolsimporttooltooldefset_user_name(new_name:str)-Command:Set the users name in the conversation state.returnCommand(update{user_name:new_name})提示若多个工具可能并行更新同一状态字段建议定义 reducer 解决冲突。上下文ContextContext 提供调用时传递的不可变配置数据如用户ID、会话详情通过runtime.context访问fromdataclassesimportdataclassfromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_agentfromlangchain.toolsimporttool,ToolRuntime# 模拟用户数据库USER_DATABASE{user123:{name:Alice Johnson,account_type:Premium,balance:5000,email:aliceexample.com},user456:{name:Bob Smith,account_type:Standard,balance:1200,email:bobexample.com}}# 定义上下文 schemadataclassclassUserContext:user_id:strtooldefget_account_info(runtime:ToolRuntime[UserContext])-str:Get the current users account information.user_idruntime.context.user_idifuser_idinUSER_DATABASE:userUSER_DATABASE[user_id]returnfAccount holder:{user[name]}\nType:{user[account_type]}\nBalance: ${user[balance]}returnUser not found# 初始化模型和智能体modelChatOpenAI(modelgpt-4.1)agentcreate_agent(model,tools[get_account_info],context_schemaUserContext,system_promptYou are a financial assistant.)# 调用智能体传递上下文resultagent.invoke({messages:[{role:user,content:Whats my current balance?}]},contextUserContext(user_iduser123))print(result)长期记忆StoreBaseStore提供跨会话的持久化存储数据会保留到未来会话中通过runtime.store访问采用 namespace/key 模式组织数据。生产环境建议使用PostgresStore等持久化存储实现而非InMemoryStore详见 memory documentation。fromtypingimportAnyfromlanggraph.store.memoryimportInMemoryStorefromlangchain.agentsimportcreate_agentfromlangchain_openaiimportChatOpenAIfromlangchain.toolsimporttool,ToolRuntime# 初始化模型modelChatOpenAI(modelgpt-4.1)# 访问长期记忆tooldefget_user_info(user_id:str,runtime:ToolRuntime)-str:Look up user info.storeruntime.store user_infostore.get((users,),user_id)returnstr(user_info.value)ifuser_infoelseUnknown user# 更新长期记忆tooldefsave_user_info(user_id:str,user_info:dict[str,Any],runtime:ToolRuntime)-str:Save user info.storeruntime.store store.put((users,),user_id,user_info)returnSuccessfully saved user info.# 初始化存储和智能体storeInMemoryStore()agentcreate_agent(model,tools[get_user_info,save_user_info],storestore)# 第一个会话保存用户信息agent.invoke({messages:[{role:user,content:Save the following user: userid: abc123, name: Foo, age: 25, email: foolangchain.dev}]})# 第二个会话查询用户信息resultagent.invoke({messages:[{role:user,content:Get user info for user with id abc123}]})print(result[messages][-1].content)流写入器Stream Writer通过runtime.stream_writer可实时输出工具执行进度适用于长耗时操作fromlangchain.toolsimporttool,ToolRuntimetooldefget_weather(city:str,runtime:ToolRuntime)-str:Get weather for a given city.writerruntime.stream_writer# 实时输出进度writer(fLooking up data for city:{city})writer(fAcquired data for city:{city})returnfIts always sunny in{city}!注意使用stream_writer时工具必须在 LangGraph 执行上下文中调用详见 Streaming。ToolNode 用法ToolNode是 LangGraph 工作流中执行工具的预构建节点自动处理并行工具执行、错误处理和状态注入。适用于需要精细控制工具执行逻辑的自定义工作流替代create_agent。基础使用fromlangchain.toolsimporttoolfromlanggraph.prebuiltimportToolNodefromlanggraph.graphimportStateGraph,MessagesState,START,ENDfromlangchain_openaiimportChatOpenAI# 初始化模型modelChatOpenAI(modelgpt-4.1)# 定义工具tooldefsearch(query:str)-str:Search for information.returnfResults for:{query}tooldefcalculator(expression:str)-str:Evaluate a math expression.returnstr(eval(expression))# 创建 ToolNodetool_nodeToolNode([search,calculator])# 构建工作流builderStateGraph(MessagesState)builder.add_node(tools,tool_node)builder.add_node(llm,model)# 添加 LLM 节点builder.add_edge(START,llm)builder.add_edge(llm,tools)builder.add_edge(tools,END)graphbuilder.compile()工具返回值类型工具支持三种返回值类型适配不同场景返回字符串适用于返回人类可读的文本结果fromlangchain.toolsimporttooltooldefget_weather(city:str)-str:Get weather for a city.returnfIt is currently sunny in{city}.行为返回值会转换为ToolMessage模型读取文本后决定后续操作不直接修改智能体状态返回对象适用于返回结构化数据方便模型解析特定字段fromlangchain.toolsimporttooltooldefget_weather_data(city:str)-dict:Get structured weather data for a city.return{city:city,temperature_c:22,conditions:sunny,}行为对象会序列化后作为工具输出模型可读取特定字段进行推理不直接修改智能体状态返回 Command适用于需要修改智能体状态的场景如设置用户偏好可附带ToolMessage告知模型结果fromlangchain.messagesimportToolMessagefromlangchain.toolsimportToolRuntime,toolfromlanggraph.typesimportCommandtooldefset_language(language:str,runtime:ToolRuntime)-Command:Set the preferred response language.returnCommand(update{preferred_language:language,messages:[ToolMessage(contentfLanguage set to{language}.,tool_call_idruntime.tool_call_id,)],})行为通过update参数修改状态更新后的状态对后续步骤可见并行更新同一字段时需使用 reducers错误处理可配置工具错误的处理方式支持捕获特定异常、自定义错误信息等fromlanggraph.prebuiltimportToolNode# 1. 默认捕获调用错误重新抛出执行错误tool_nodeToolNode(tools)# 2. 捕获所有错误并返回默认提示tool_nodeToolNode(tools,handle_tool_errorsTrue)# 3. 自定义错误提示tool_nodeToolNode(tools,handle_tool_errorsSomething went wrong, please try again.)# 4. 自定义错误处理函数defhandle_error(e:ValueError)-str:returnfInvalid input:{e}tool_nodeToolNode(tools,handle_tool_errorshandle_error)# 5. 仅捕获特定异常类型tool_nodeToolNode(tools,handle_tool_errors(ValueError,TypeError))条件路由通过tools_condition可根据 LLM 是否调用工具进行条件路由fromlanggraph.prebuiltimportToolNode,tools_conditionfromlanggraph.graphimportStateGraph,MessagesState,START,ENDfromlangchain_openaiimportChatOpenAI# 初始化模型modelChatOpenAI(modelgpt-4.1)# 定义工具和 ToolNodetooldefsearch(query:str)-str:Search for information.returnfResults for:{query}tool_nodeToolNode([search])# 构建工作流builderStateGraph(MessagesState)builder.add_node(llm,model)builder.add_node(tools,tool_node)builder.add_edge(START,llm)# 条件路由LLM 调用工具则进入 tools 节点否则直接结束builder.add_conditional_edges(llm,tools_condition)builder.add_edge(tools,llm)# 工具执行后返回 LLM 继续处理graphbuilder.compile()状态注入工具可通过ToolRuntime访问当前图状态fromlangchain.toolsimporttool,ToolRuntimefromlanggraph.prebuiltimportToolNodetooldefget_message_count(runtime:ToolRuntime)-str:Get the number of messages in the conversation.messagesruntime.state[messages]returnfThere are{len(messages)}messages.tool_nodeToolNode([get_message_count])预构建工具LangChain 提供大量预构建工具和工具包覆盖网页搜索、代码解释、数据库访问等常见场景可直接集成无需自定义开发。完整工具列表按分类整理于tools and toolkits。服务端工具使用部分聊天模型内置服务端工具如网页搜索、代码解释器无需用户定义或托管工具逻辑由模型提供商在服务端执行。详细使用方法请参考各 聊天模型集成页面Tool calling 文档