先补齐必要概念
适合:学习 Agent 应用开发的后端开发者。
- Agent 循环的控制权与完成判据
- 模型输出是下一步建议,运行时才掌握执行和终态。停止只证明循环结束,成功还必须证明约定的业务条件成立;预算耗尽、取消和结果未知因此不能被同一个“完成”标签覆盖。
原理怎样一步步成立?
逐步解释原理
- 一个模型轮次产生五个工具调用,预算怎么记?
一轮并不等于一个动作,需要把抽象循环落到资源账本。
- 用户取消时远端写操作已经成功,你如何收尾?
取消信号作用于执行过程,已发生的业务事实需要单独收尾。
- 模型给出正确答案却没有执行要求的测试,算成功吗?
控制终态必须回到验收条件,而不是文本的可信程度。
进阶 · 定位故障
排错 · 复现多次运行清零预算的故障
本层目标:用事件和失败验收定位持久化预算回归,仅在隔离源码副本修复并重跑。
图解 · 模型停止与业务完成
只有匹配的商户回执才证明申请完成。模型最终回答、审批与超时分别说明不同事实;取消也不能抹去已经提交的申请。 点图可打开原图放大查看。
故障证据与准确起点
图解 · 跨次恢复必须保留计数
这是公开只读修复实验的观察结果。这里统计已提交工具结果,不能替代HTTP尝试、计费token或外部写入计数。 点图可打开原图放大查看。
循环可以在每次运行内都有限,却在多次运行间累积无限调用。不要修改 work/agent.sqlite;从解压的项目根目录开始,Python 和本地回环服务应已能按 README 运行。下面脚本把 Python 源码及 migrations 复制到临时目录,每次检查新建一对数据库。
合同桩模型始终提出同一个获授权 get_order 参数,但按 transcript 给每个候选生成新的调用 ID。这是有意的:否则重复 ID 检测会掩盖预算故障。实验不请求真实模型、不审批、不执行业务写入。注入行在每次 run 第一次认领租约之前把两个任务累计计数清零。连续三次运行,每次允许三轮。
# Run from the extracted capstone directory. Only a temporary copy is changed.
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
root = Path.cwd()
box = Path(tempfile.mkdtemp(prefix="loop-boundary-"))
for path in root.glob("*.py"):
shutil.copy2(path, box / path.name)
shutil.copytree(root / "migrations", box / "migrations")
source = (box / "agent.py").read_text()
anchor = " lease = self.store.claim(task_id, lease_seconds)"
assert source.count(anchor) == 2
# Inject only into run(), before the first lease claim; execute() stays unchanged.
bug = " self.store.update(task_id, turn_count=0, tool_count=0) # BUG_RESET_BUDGET\n"
(box / "agent.py").write_text(source.replace(anchor, bug + anchor, 1))
check = r'''
import json
import tempfile
from pathlib import Path
from agent import Agent
from common import LabError
from harness import client, merchant_process
from store import Store
class RepeatOrder:
name = "repeated-read-contract-stub"
def respond(self, request):
n = sum(i.get("type") == "function_call" for i in request["input"]) + 1
call = {"type": "function_call", "call_id": "repeat-" + str(n),
"name": "get_order", "arguments": '{"order_id":"o-100"}'}
return {"status": "completed", "output": [call]}, {"source": "contract_stub"}
with tempfile.TemporaryDirectory(prefix="loop-check-") as tmp:
work = Path(tmp)
with merchant_process(work) as service:
store = Store(work / "agent.sqlite")
try:
agent = Agent(store, client(service.url), RepeatOrder())
agent.submit("o-100", "Return my unused item.", "repeat-check")
agent.run("repeat-check", rounds=3)
agent.run("repeat-check", rounds=3)
error = None
try:
agent.run("repeat-check", rounds=3)
except LabError as exc:
error = exc.code
task = store.inspect("repeat-check")
tools = [e for e in task["events"] if e["kind"] == "tool"]
failures = [e["payload"]["reason"] for e in task["events"] if e["kind"] == "failure"]
audit = client(service.url, "admin-token").request("GET", "/v1/audit")
count = sum(r["task_id"] == "repeat-check" for r in audit["returns"])
print(json.dumps({"status": task["status"], "checkpoint_tools": task["tool_count"],
"tool_events": len(tools), "error": error, "failure_events": failures,
"business_returns": count}, sort_keys=True), flush=True)
assert error == "tool_budget_exhausted", "cross-run tool budget was reset"
assert len(tools) == 6 and task["tool_count"] == 6
assert count == 0
finally:
store.close()
'''
(box / "check_loop.py").write_text(check)
run = subprocess.run([sys.executable, "check_loop.py"], cwd=box, capture_output=True, text=True)
print(run.stdout.strip())
print("fault_exit=" + str(run.returncode))
assert run.returncode == 1 and "cross-run tool budget was reset" in run.stderr, run.stderr
assert json.loads(run.stdout)["tool_events"] == 9
print("Repair only the copied agent.py in:", box)
print("Then run:", sys.executable, str(box / "check_loop.py"))
先读失败,再修复
故障检查输出 status="queued"、checkpoint_tools=3、tool_events=9,没有 error 或 failure 事件,business_returns=0。子进程因 cross-run tool budget was reset 断言非零退出,外层复现器打印 fault_exit=1。九条已提交 tool 事件否定了断点工具数只有三的表象。沿这个不一致回查插入的 BUG_RESET_BUDGET 行;不要加大配额,也不要把循环归类为已完成。
只修脚本打印路径中的临时 agent.py:删除含 BUG_RESET_BUDGET 的一行。不要改 MAX_TOOLS、断言或重复读取桩。再次运行打印出的 check_loop.py 命令。每次检查新建数据库,因此恢复不会继承故障运行的九条回执。修复后必须零退出:status="failed"、checkpoint_tools=6、tool_events=6、error="tool_budget_exhausted"、failure_events=["tool_budget_exhausted"],业务申请数为零。第三次运行记录了候选模型响应,但未调度第七个工具。
用两份输出写事件→原因→修复的事故笔记。这是源码副本修复练习,不是只运行项目已有测试。它验证成功读取的预算边界;失败 HTTP 尝试和外部写入仍须单独处理。
代码示例
另一道守卫可能掩盖待验证故障
只关闭整批预检后,Agent.tool 内仍有逐工具预算检查。仍然看到 tool_budget_exhausted,不证明整批预检执行过。故障实验必须说明哪些独立守卫也能阻止这个输入,再看事件数判断实际覆盖。
本层验收任务
运行临时副本复现器,解释计数三与事件九的不一致,删除副本中的预算清零注入行,再运行不变的检查。提交两次输出和简短的证据→原因→修复笔记。
正在读取此浏览器记录…
收起答案,检查理解
同参数重复读取为什么每次都要使用新 call_id?
展开参考推导
复用 ID 会触发 duplicate_model_call_id 或回执复用,九次调用故障就无法出现。实验通过合法的新候选隔离任务累计预算的持久化问题。生产还可比较规范化后的动作/参数签名识别语义重复,但这个示例没有实现该检测器。
延伸原理与知识练习
遇到不熟悉的原理,先阅读实现、连续追问和迁移案例,再独立说明前提与边界。作答与笔记保存到原有账号记录。
本专题的全部关联解析与练习(1 道)
依据与验证范围
原理依据来自公开资料;数字、案例和任务是本站教学设计。离线实验验证本页注明的范围,学习效果仍需通过独立任务与反馈判断。