Agent 工具调用,写一个有预算的最小循环
771 字约 3 分钟
2026-11-23
用户问「阅读清单里有几本在读的书」。模型拿不到应用里刚更新的数据,可以请求一个只读工具。应用执行查询,将结果和那次调用的 ID 一起回传,模型据此回答。如果路径始终固定为查询再解释,直接写成工作流也可以。需要根据工具结果调整下一步时,再由模型选择后续动作。 Anthropic · Building effective agents
模型请求,应用执行
| 步骤 | 谁负责 |
|---|---|
| 决定是回复还是发起工具调用 | 模型 |
| 检查工具名称、参数、当前权限与预算 | 应用 |
| 查询数据,记录成功或业务错误 | 工具实现 |
| 按调用 ID 回传结果,决定是否再走一轮 | 应用回传,模型决定下一步 |
结构化参数有助于减少格式错误,应用仍要检查工具是否可用、用户有权读取哪些数据。工具最好描述业务动作,例如「按阅读状态统计」,让应用可以明确校验输入和授权。 OpenAI · Function calling
用假模型跑通两轮
例子假设模型适配层每轮已经规范化为「最终回复」或「一次工具调用」。业务函数只接受两个阅读状态。每次调用都会占用预算,包括参数错误的调用。
STATUSES = {"reading": 2, "finished": 3}
def execute(tool, args):
if tool != "count_books":
return {"error": "unknown_tool"}
if not isinstance(args, dict) or set(args) != {"status"}:
return {"error": "invalid_arguments"}
status = args["status"]
if not isinstance(status, str) or status not in STATUSES:
return {"error": "invalid_status"}
return {"count": STATUSES[status]}
def run(step, max_calls=2):
if max_calls < 0:
raise ValueError("调用预算应为非负数")
results = []
call_ids = set()
for _ in range(max_calls + 1):
action = step(tuple(results))
if action["type"] == "final":
return action["text"]
if action["type"] != "call":
raise ValueError("无法识别模型动作")
if len(results) >= max_calls:
raise RuntimeError("工具调用预算已用尽")
call_id = action["id"]
if call_id in call_ids:
raise RuntimeError("工具调用 ID 重复")
call_ids.add(call_id)
result = execute(action["tool"], action["arguments"])
results.append({"call_id": call_id, "output": result})
def fake_model(results):
if not results:
return {
"type": "call",
"id": "call-1",
"tool": "count_books",
"arguments": {"status": "reading"},
}
assert results[0]["call_id"] == "call-1"
return {"type": "final", "text": f"在读 {results[0]['output']['count']} 本"}
assert run(fake_model) == "在读 2 本"
assert execute("count_books", {"status": []}) == {"error": "invalid_status"}
assert execute("unknown", {}) == {"error": "unknown_tool"}
try:
run(fake_model, max_calls=0)
except RuntimeError as exc:
assert str(exc) == "工具调用预算已用尽"
else:
raise AssertionError("用尽预算后应停止")保存成 tool_loop.py 后运行 python tool_loop.py。真实模型接口可能一轮返回多个调用。接入时,要为每个调用分别校验、计数并回传对应的结果。
为异常设计明确的结束路径
先按失败原因决定由谁处理。参数错误可以回传给模型修正。服务不可用时,由应用按策略限次重试或结束。正式应用还要设置耗时预算,将超时和调用次数耗尽表述为未完成。带写入的工具应由独立的确认与执行流程处理。
