进阶 agently.cn 2026-10-08 20:14:53 · 2 阅读
第5章 Tools 兼容层与 Action 运行时映射
第5章 Tools
语言:English · 中文
Tools 工具家族是 Agently 的兼容层,让模型能够调用函数、MCP 服务器和沙箱。新代码请优先使用 action 接口——参见 Action Runtime。tool 家族仍然可用,可以平滑映射到新的运行时,这里为已在代码中使用它的用户提供文档。
Surface map
| 旧(兼容) | 新(推荐) | 用途 |
| @agent.tool_func | @agent.action_func | 标记函数并推导其 schema |
| agent.use_tool(my_func) | agent.use_actions(my_func) | 注册单个 |
| agent.use_tools([a, b]) | agent.use_actions([a, b]) | 批量注册 |
| agent.use_mcp(url) | agent.use_mcp(url) | 无变化——MCP 挂载 |
| agent.use_sandbox(...) | agent.use_sandbox(...) | 无变化——沙箱挂载 |
| extra.tool_logs | extra.action_logs | 循环产生的调用记录 |
| Agently.tool | Agently.action | 全局注册辅助 |
两列名称都路由到同一套内部 action 运行时。旧名称并非独立的 ToolManager 插件实现,只是为方便而保留的别名。
Minimal example
```python from agently import Agently agent = Agently.create_agent() @agent.tool_func def add(a: int, b: int) -> int: """Add two integers.""" return a + b agent.use_tool(add) result = agent.input("What is 3333 + 6666?").start() print(result) ``` 模型会把 add 视为可调用的工具,并自行决定是否调用它。Auto-func —— 由模型驱动的实现
@agent.auto_func 装饰器会把函数签名加 docstring 转换为由模型驱动的实现,使用 agent 已注册的 tools / actions:
```python @agent.auto_func def calculate(formula: str) -> int: """Compute {formula}. MUST USE ACTIONS to ensure the answer is correct.""" ... print(calculate("3333+6666=?")) ``` 被装饰的函数没有函数体(...)。调用时,agent 会带着已注册的工具运行模型并返回结果。该用哪个接口
全新代码:使用 action 接口(参见 Action Runtime)。所有扩展、插件类型和架构改进都发生在这里。
以下情况继续用 tool 接口:
- 你在维护使用这些名称的现有代码。
- 你要集成的库或示例使用了它们。
tool 家族不会被移除——但新功能会先出现在 action 侧。
内置 actions 和旧版 tools
一些常见能力以内置 action 包的形式提供:
- Search —— 网络搜索封装
- Browse —— 页面抓取与可读内容提取
- Cmd —— 底层受限 shell 执行
新代码请使用 action 原生导入路径:
```python from agently.builtins.actions import Browse, Search agent.use_actions(Search(timeout=15, backend="auto")) agent.use_actions(Browse()) ``` Search(...) 会注册 search、search_news、search_wikipedia 和 search_arxiv;Browse(...) 注册 browse。实现代码位于 agently.builtins.actions 下。agently.builtins.tools 只是面向既有示例和应用的轻量兼容导入门面;它可能保留旧的 tool_info_list 元数据,但不应承载内置能力的实现。agent.use_tools(...)、agent.tool_func 和 Agently.tool 仍作为兼容接口受支持。不要把 tool_info_list / BuiltInTool 作为编写内置能力的新 API。 Search 由 ddgs 包驱动。backend="auto" 使用默认策略,也可以传入具体的 ddgs 后端,如 yahoo、brave、duckduckgo、google、startpage、mojeek、wikipedia 或 yandex。后端返回 HTTP 200 并不代表能解析出搜索结果;当某个后端没有可用结果时,Search 会按配置顺序在默认的 ddgs 后端之间回退。真正无结果的搜索会以 [] 作为成功的 action 结果返回,而不是让 action 循环失败。 当前面的后端失败但后续回退返回了可用结果时,Action 结果会用 status="partial_success",success=True,并附带后端诊断信息。应把它视为可用的证据加上可观测性信息,而不是 action.failed 的终止状态。需要 shell 访问时,优先使用 agent.enable_shell(...),它会挂载一个托管的 run_bash action。Cmd 仍作为底层兼容包保留,并作为 Bash 执行的实现辅助。
当前 action 原生示例见 examples/builtin_actions/。历史内置 tool 示例位于 examples/archived/builtin_tools/,并会指向当前的替代方案。
See also
- Action Runtime —— 推荐接口,含完整架构说明
- MCP —— agent.use_mcp(...) 详情
- Coding Agents —— 面向使用内置 search/browse 和自定义 action 的项目的编码代理指南