共计 2286 个字符,预计需要花费 6 分钟才能阅读完成。
背景痛点:为什么工具调用 Prompt 容易翻车?
在构建 Agent 系统时,工具调用是核心能力之一。但实践中我们常遇到这些问题:

- 上下文丢失 :Agent 在处理多步骤任务时,容易忘记之前的工具调用结果
- 工具选择错误 :当多个工具功能相似时(如 search 与 vector_search),Agent 容易选错
- 参数解析失败 :自然语言生成的参数常出现格式错误或类型不匹配
- 错误传播 :单个工具调用失败可能导致整个任务链崩溃
这些问题的本质,在于传统 Prompt 设计缺乏对工具调用的系统性约束。
架构设计:两种模式的对比
直接调用模式
# 典型反模式
def run_agent(prompt):
tool = llm("选择工具:" + prompt)
return eval(tool + "(" + prompt + ")") # 危险操作!
问题:
– 完全依赖 LLM 的自由发挥
– 存在代码注入风险
– 没有错误处理机制
中介模式(推荐)
graph TD
A[Agent] --> B{ToolRouter}
B -->| 工具列表 | C[ContextManager]
B -->| 参数校验 | D[ToolExecutor]
D --> E[外部 API]
关键组件:
1. ToolRouter:根据当前上下文选择最佳工具
2. ContextManager:维护会话状态和工具历史
3. ToolExecutor:处理参数转换和错误重试
核心实现:生产级 Prompt 模板
基础模板结构
tool_prompt = """
你是一个专业助理,请根据当前上下文选择工具:可用工具:{工具描述列表}
当前上下文:{会话历史}
请严格按以下格式响应:```json
{
"tool": "工具名",
"params": {
"参数 1": "值 1",
...
},
"reason": "选择理由"
}
```"""
增强版设计技巧
-
工具描述规范
tool_descriptions = [ { "name": "google_search", "description": "通用搜索引擎,适合查找最新公开信息", "parameters": {"query": {"type": "string", "max_length": 128} }, "examples": [{"input": "找 2023 年 GDP 数据", "output": {"tool": "google_search", "params": {"query": "2023 年全球 GDP 排名"}}} ] } ] -
错误处理逻辑
def safe_parse(response): try: data = json.loads(response.strip('```json').strip('```')) assert isinstance(data['tool'], str) assert isinstance(data['params'], dict) return data except Exception as e: return { "tool": "error_handler", "params": {"error": str(e)} } -
Few-shot 学习示例
examples = """ 示例 1: 用户输入:预订明天北京的酒店 输出: ```json {"tool": "hotel_booking", "params": {"city": "北京", "date": "2023-11-21"}}
示例 2:
用户输入:周杰伦的最新专辑
输出:
{"tool": "music_search", "params": {"artist": "周杰伦", "sort": "newest"}}
“””
## 生产环境考量
### 性能优化
- ** 批量调用 **:在对话开始时预加载工具列表,避免每次请求都重新获取
- ** 缓存策略 **:对工具描述和示例使用 LRU 缓存
- ** 超时控制 **:设置工具调用的超时时间(推荐 500-1000ms)### 安全防护
1. ** 输入过滤 **
```python
import re
def sanitize_input(text):
return re.sub(r'[^\w\s.,?!@#$%^&*()-+=]', '', text)
- 权限控制
TOOL_PERMISSIONS = {"admin": ["db_write", "file_delete"], "user": ["search", "calculator"] }
监控指标
| 指标名称 | 类型 | 告警阈值 |
|---|---|---|
| tool_choice_error | counter | >5/min |
| param_parse_time | gauge | >200ms |
| tool_success_rate | ratio | <95% |
避坑指南
三大常见误区
- 过度依赖 LLM 选择工具
-
解决方案:建立工具优先级评分表
-
忽略参数类型校验
-
解决方案:使用 JSON Schema 验证
from jsonschema import validate schema = {"type": "object", "properties": {"query": {"type": "string"}}} validate(instance=params, schema=schema) -
未处理工具不可用情况
- 解决方案:实现 fallback 机制
def get_tool(tool_name): return TOOLS.get(tool_name) or TOOLS["default_search"]
性能优化技巧
- 对高频工具进行预热
- 使用异步 IO 处理网络调用
- 压缩工具描述文本(但保留关键信息)
开放式问题
- 当工具数量超过 100 个时,如何保持选择准确性而不增加延迟?
- 在多租户场景下,如何平衡工具调用的通用性和个性化需求?
希望这些实践能帮助你构建更健壮的 Agent 系统。在实际项目中,建议先从核心工具开始验证,再逐步扩展复杂场景。
正文完
