用户最常的4 类扩展需求——加 tool / 注入 prompt / 派子 agent / 隔离执行——在三家分别用4 套完全不同的 API。这一节按 4 个主题切换,每个主题三家代码并排。
建议先读《状态与控制流 / State / Reducer / 终止条件》;如果你是跳读,至少先看本章索引与本页 TL;DR。
进阶理解层,把抽象落实到真实代码与状态机。
用户最常的 4 类扩展需求 ——加 tool / 注入 prompt / 派子 agent / 隔离执行——在三家分别用 4 套完全不同的 API 。这一节按 4 个主题切换,每个主题三家代码并排。
先追 entry / state / extension points,再看 API 名字。
课程主线:源码 + 官方 docs + 版本上下文。
@function_tool + Pydantic;smolagents 强调 "@tool" + 显式 inputs/output_type 字段。step_callbacks——最简但不能短路 loop。executor_type,把"在哪跑 LLM 写的代码"做成框架级配置。def get_weather(city: str) -> str,希望 LLM 能在某种条件下调用它。差异点:①schema 怎么生成(自动推 vs 显式);② 参数校验在哪做;③ tool 拿不拿 framework 上下文;④ tool 抛异常时怎么处理。
from langchain_core.tools import tool @tool def get_weather(city: str) -> str: """Look up weather for a city.""" return _call_api(city) # 也可以传 args_schema 显式 Pydantic @tool(args_schema=WeatherInput) def get_weather2(...): ...
typing.get_type_hints + 启发式 parser)。handle_tool_error)。
from agents import function_tool, RunContextWrapper @function_tool def get_weather( ctx: RunContextWrapper, # framework 注入 city: str ) -> str: """Look up weather.""" api_key = ctx.context.api_key # 取应用上下文 return _call_api(city, api_key)
create_model),同时收集 docstring 当 description。RunContextWrapper——framework 自动注入,让 tool 拿到用户 context + 当前 trace + usage。failure_error_function,默认 wrap 成错误消息。
from smolagents import tool @tool def get_weather(city: str) -> str: """Look up weather. Args: city: City name. """ return _call_api(city) # 类形态: class WeatherTool(Tool): name = "get_weather" description = "..." inputs = {"city": {"type": "string", "description": "..."}} output_type = "string" def forward(self, city): ...
AgentError,被 step 捕获写到 action_step.error。
| 维度 | LangChain | Agents SDK | smolagents |
|---|---|---|---|
| 装饰器 | @tool | @function_tool | @tool 或 Tool 子类 |
| schema 来源 | type hint + docstring | Pydantic auto | 显式 inputs dict + docstring Args 段 |
| 第一参数注入 framework 上下文 | 无原生(需用 InjectedToolArg) | RunContextWrapper 一等公民 | 无(用 closur |