大模型应用开发 / 系统课时
构建多轮 Agent 循环
构建多轮 Agent 循环
学习目标
完成本课后,你将能够:
- 实现模型、工具和消息历史之间的循环
- 支持一轮中的多个工具调用
- 设置最大轮数、超时和重复调用保护
- 在最终回答与异常退出之间建立明确状态
Agent 循环的状态机
多轮 Agent 不是无限调用模型。每轮只有两种主要结果:
- 模型返回工具调用:执行工具并继续下一轮。
- 模型不再返回工具调用:把内容作为最终回答。
应用还必须处理失败、超时、用户取消和达到轮数上限。
循环流程图

完整循环示例
保存为 agent_loop.py:
python
import json
from typing import Any, Callable
from ollama import chat
MODEL = "<TOOL_CAPABLE_MODEL>"
MAX_ROUNDS = 5
def add(left: float, right: float) -> dict[str, Any]:
return {"ok": True, "value": left + right}
def multiply(left: float, right: float) -> dict[str, Any]:
return {"ok": True, "value": left * right}
FUNCTIONS: dict[str, Callable[..., dict[str, Any]]] = {
"add": add,
"multiply": multiply,
}
TOOLS = [
{
"type": "function",
"function": {
"name": "add",
"description": "计算两个数字之和。",
"parameters": {
"type": "object",
"properties": {
"left": {"type": "number"},
"right": {"type": "number"},
},
"required": ["left", "right"],
"additionalProperties": False,
},
},
},
{
"type": "function",
"function": {
"name": "multiply",
"description": "计算两个数字之积。",
"parameters": {
"type": "object",
"properties": {
"left": {"type": "number"},
"right": {"type": "number"},
},
"required": ["left", "right"],
"additionalProperties": False,
},
},
},
]
messages = [
{
"role": "user",
"content": "先计算 12 加 8,再把结果乘以 3。",
}
]
seen_calls: set[str] = set()
for round_number in range(1, MAX_ROUNDS + 1):
response = chat(
model=MODEL,
messages=messages,
tools=TOOLS,
options={"temperature": 0},
)
assistant = response["message"]
messages.append(assistant)
tool_calls = assistant.get("tool_calls", [])
if not tool_calls:
content = assistant.get("content", "").strip()
if not content:
raise SystemExit("模型没有工具调用,也没有最终回答")
print(content)
print(f"rounds={round_number}")
break
for call in tool_calls:
function = call["function"]
name = function["name"]
arguments = function.get("arguments", {})
if name not in FUNCTIONS:
raise SystemExit(f"不允许的工具: {name}")
if set(arguments) != {"left", "right"}:
raise SystemExit(f"参数字段错误: {arguments}")
signature = json.dumps(
{"name": name, "arguments": arguments},
sort_keys=True,
ensure_ascii=False,
)
if signature in seen_calls:
raise SystemExit(f"检测到重复工具调用: {signature}")
seen_calls.add(signature)
result = FUNCTIONS[name](
float(arguments["left"]),
float(arguments["right"]),
)
messages.append(
{
"role": "tool",
"tool_name": name,
"content": json.dumps(result, ensure_ascii=False),
}
)
else:
raise SystemExit(f"超过最大轮数 {MAX_ROUNDS}")将模型占位符替换后运行:
bash
python agent_loop.py预期输出结构:
text
<FINAL_RESPONSE_CONTAINING_60>
rounds=<ROUND_COUNT>多工具调用
模型可能在同一轮返回多个 tool_calls。应用应:
- 逐个验证。
- 根据工具是否独立决定串行或并行。
- 保持结果与调用的对应关系。
- 把每个结果加入消息历史。
- 再请求模型综合回答。
涉及共享状态或写操作时,不应盲目并行。
终止条件
至少设置:
- 最大模型轮数
- 最大工具调用次数
- 单工具超时
- 整体任务超时
- 重复调用检测
- 最大消息或 Token 预算
- 用户取消
- 连续工具错误阈值
达到上限时返回明确的失败状态,不要让循环继续消耗资源。
错误策略
工具失败后可以把结构化错误回传模型,让模型选择替代方案,但必须限制重试次数。错误结果示例:
json
{
"ok": false,
"error": "timeout",
"retryable": true
}模型不应看到内部堆栈、数据库连接串或密钥。
可观测性
每轮记录:
- 会话 ID
- 轮数
- 模型名称
- 工具名称
- 参数摘要
- 参数校验结果
- 工具耗时
- 工具结果状态
- Token 与模型耗时
- 终止原因
敏感参数应脱敏,写操作应记录业务审计 ID。
本课练习
练习 1:增加第三个工具
任务目标:扩展工具注册表。输入或初始条件:已有加法和乘法循环。实现要求:增加除法并处理除零。验收条件:错误结构化且循环不会崩溃。
练习 2:实现总超时
任务目标:限制 Agent 资源。输入或初始条件:某个工具模拟长时间运行。实现要求:为任务设置总超时并取消后续轮次。验收条件:最终状态明确为 timeout。
练习 3:检测重复循环
任务目标:防止模型反复调用同一工具。输入或初始条件:构造重复参数。实现要求:使用签名集合拒绝重复。验收条件:程序在上限前终止并记录原因。
按自己的节奏,确认真正理解。