工具与函数调用
web search、REPL、API、文件系统工具。
35 分钟
工具与函数调用
agt-tools 讲了往返与 schema;本课扩展 web search、REPL、API、文件系统 四类常见工具在 Agent 里的 设计、沙箱与组合——对应 ai-agents 路线图 的工具集成节点。
学习目标
- 为四类工具写清 description 与权限边界
- 设计工具组合顺序与最大调用预算
- 处理大结果、超时与副作用
四类工具速览
| 类型 | 典型用途 | 风险 |
|---|---|---|
| Web search | 实时信息、文档 | 不可信网页、间接注入 |
| REPL / 代码执行 | 算数、数据处理 | 任意代码执行 |
| HTTP API | 业务系统读写 | 越权、重试造成重复写 |
| 文件系统 | 读 repo、写报告 | 路径穿越、删改生产文件 |
原则:模型只产出 调用意图;执行、鉴权、限流在你的 Agent 运行时。
工具描述与组合
TOOLS = [
{"name": "web_search", "description": "查公开网页;站内 FAQ 优先用 search_docs"},
{"name": "search_docs", "description": "检索已索引知识库;回答课程/track 必先用"},
{"name": "read_file", "description": "读 allowlist 内路径;禁止读 .env"},
{"name": "run_python", "description": "沙箱内执行;无 network;超时 5s"},
]
MAX_TOOL_CALLS = 8
组合模式:
调研 Agent:search_docs →(不足)web_search → read_file 片段 → 汇总
代码 Agent:list_dir → read_file → run_python 验证 → 输出 diff 建议
避免工具 职责重叠;重叠时模型随机选一个,错误率上升。
大结果与错误回传
def read_file(path: str, offset: int = 0, limit: int = 200):
content = fs.read(path)
chunk = content[offset : offset + limit]
return {
"content": chunk,
"truncated": len(content) > offset + limit,
"hint": "用 offset 续读" if truncated else None,
}
错误应 结构化,便于模型自纠:
{"error": "timeout", "tool": "web_search", "retry_after_sec": 30}
与入门课衔接
副作用操作仍遵循 agt-safety:写 API、写文件、发消息 需审批 gate,不能仅靠 prompt 禁止。
练习
- 为「站内问答 + 必要时查官网」设计工具调用顺序