【08】LangChain 入门:用 @tool 装饰器 5 分钟搭 Agent

📅 2026/7/29 12:00:12
【08】LangChain 入门:用 @tool 装饰器 5 分钟搭 Agent
LangChain 入门用 tool 装饰器 5 分钟搭 Agent基于 Lion-1209/AgentStudyhttps://github.com/Lion-1209/AgentStudy 仓库对应代码见stage2-langchain/task2.1_langchain_agent.py从 200 行到 100 行框架的价值上一篇你用手写了 200 行的最小 Agent。现在用 LangChain同样的功能只需要 100 行。框架不改变本质只是把重复的工作封装起来。LangChain Agent 的核心组件tool decorator define工具AgentExecutor wrap ReAct loopChatPromptTemplate prompt templateLLM model callfinal output三个组件 一个 Agent。5 分钟搭一个 Agent步骤 1定义工具用装饰器fromlangchain_core.toolsimporttooltooldefget_weather(city:str)-str:获取指定城市的天气信息。 Args: city: 城市名称如北京 weather_data{北京:晴天温度 25°C,上海:多云温度 28°C,}returnweather_data.get(city,f未找到{city}的天气数据)tooldefcalculate(expression:str)-str:计算数学表达式。 Args: expression: 数学表达式如 2 3 * 4 returnstr(eval(expression))tools[get_weather,calculate]装饰器的魔法tool自动从函数签名和 docstring 生成 JSON Schema。你不需要手写工具描述。步骤 2创建 Agentfromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_agent llmChatOpenAI(modelgpt-4o-mini)agentcreate_agent(llm,toolstools)步骤 3运行resultagent.invoke({messages:[{role:user,content:北京天气怎么样}]})print(result[messages][-1].content)就这么简单。3 个步骤一个可用的 Agent。对比纯 Python vs LangChain维度纯 PythonLangChain工具定义手写字典 描述tool装饰器自动生成 SchemaReAct 循环自己写 while 循环AgentExecutor自动封装提示词管理字符串拼接ChatPromptTemplate模板化错误处理手动 try-except内置错误处理机制调试print 语句LangSmith 集成tool 装饰器原理你写函数 docstringtool decoratorauto提取function nameauto提取参数类型auto提取docstring作为description生成JSON SchemaLLM 能理解的工具define你只写业务逻辑框架帮你生成 Schema。学习检查清单能用 tool 装饰器定义一个工具吗知道 AgentExecutor 封装了什么吗能对比出 LangChain 相比纯 Python 省掉了哪些重复代码吗延伸阅读 完整代码stage2-langchain/task2.1_langchain_agent.py API 参考LANGCHAIN_REFERENCE.md️ 上一篇[07] 4 大框架横评手册️ 下一篇[09] 多工具 Agent 错误处理