LangChain 1.0 实战:用 @tool 装饰器5分钟搞定你的第一个AI工具函数

张开发
2026/5/19 20:34:22 15 分钟阅读
LangChain 1.0 实战:用 @tool 装饰器5分钟搞定你的第一个AI工具函数
LangChain 1.0 极简实战5分钟用tool打造你的第一个AI工具函数刚接触LangChain时最让人头疼的往往不是概念理解而是如何快速实现第一个能跑通的Demo。今天我们就用最直白的方式从零开始创建一个天气查询工具函数全程只需5分钟不绕弯子只讲实操。1. 环境准备与基础工具创建在开始之前确保你的Python环境已经安装好LangChain核心包pip install langchain-core创建一个最简单的工具函数只需要三步导入tool装饰器编写普通Python函数添加清晰的docstring来看这个查询城市温度的示例from langchain.tools import tool tool def get_temperature(city: str) - float: 获取指定城市的当前温度摄氏度 Args: city: 需要查询的城市名称如北京 # 这里应该是调用天气API的代码 # 为演示返回模拟数据 return 22.5 if city 北京 else 18.0关键点说明函数参数需要类型标注如strdocstring中的参数说明会被LangChain自动解析返回类型也要明确标注如float2. 工具属性自定义技巧默认情况下工具名称就是函数名但我们可以通过装饰器参数自定义tool(weather_checker, description查询实时天气数据包括温度、湿度和风速) def check_weather(location: str) - dict: 实际实现中可以返回更丰富的天气数据 return {temp: 22, humidity: 65, wind: 10}属性自定义的三种方式自定义项方法示例工具名称tool(自定义名称)tool(天气查询)工具描述description参数description获取实时天气参数说明docstring中的Args部分location: 城市名称或坐标提示description比docstring优先级更高两者都存在时以description为准3. 复杂参数处理方案当需要处理复杂输入时可以使用Pydantic模型定义参数结构from pydantic import BaseModel, Field from typing import Literal class WeatherQuery(BaseModel): location: str Field(description城市名称或经纬度坐标) unit: Literal[celsius, fahrenheit] Field( defaultcelsius, description温度单位摄氏度或华氏度 ) include_forecast: bool Field( defaultFalse, description是否包含三日预报 ) tool(args_schemaWeatherQuery) def get_detailed_weather(query: WeatherQuery) - str: 获取详细的天气信息 base_info f{query.location}当前温度22{query.unit[0]} if query.include_forecast: base_info \n未来三日晴转多云 return base_info这种方式的优势在于参数验证自动化生成更准确的工具调用说明支持复杂嵌套参数结构4. 实战集成到Agent测试工具创建好后最简单的测试方式是直接调用weather_tool get_detailed_weather print(weather_tool.run({location: 上海, unit: celsius}))更真实的场景是集成到Agent中from langchain.agents import AgentExecutor, create_tool_calling_agent from langchain_openai import ChatOpenAI model ChatOpenAI(modelgpt-3.5-turbo) tools [get_detailed_weather] agent create_tool_calling_agent(model, tools) agent_executor AgentExecutor(agentagent, toolstools) response agent_executor.invoke({ input: 上海明天会下雨吗用摄氏度显示温度 }) print(response[output])常见问题排查工具未被识别 → 检查docstring格式是否正确参数传递错误 → 确认参数类型标注是否准确描述不清晰 → 优化description或docstring5. 效率优化与小技巧几个提升开发效率的实用技巧代码补全配置VS Code示例{ python.analysis.typeCheckingMode: basic, python.languageServer: Pylance }调试建议先用tool.run()单独测试工具打印工具的args_schema查看参数结构对复杂工具可以先写伪代码再实现性能考量工具函数应当保持轻量耗时操作考虑添加缓存I/O操作尽量使用异步import asyncio from langchain.tools import tool tool async def async_weather_check(city: str) - str: 异步版本的天气查询 await asyncio.sleep(0.1) # 模拟网络请求 return f{city}天气晴最后分享一个真实案例曾遇到一个工具因为docstring中漏写了参数说明导致Agent始终无法正确调用。后来发现LangChain对参数描述的完整性要求很高每个参数都必须在Args部分明确说明用途。这个教训让我从此养成了写完整docstring的习惯。

更多文章