Agent 工具契约与结构化错误(第 2 部分)
A contract you can reason about
A guarded tool call
Errors are data. The loop decides what to do with them.
- 01
call dictname + args - 02
validate against schemareject before any side effect - 03
retry? classifiedtransient only, idempotent - 04
execute onceguarded, logged - 05
ToolResult(ok/error)typed and classified - 06
append to historyLLM sees the error
第 1 部分结束时,我们有了一个能正常终止的循环,和一个无条件信任模型输出的工具注册表。这种信任就是下一个 bug。第 1 部分的 _search 里,第一行是 query = str(args.get("query", "")).lower()。如果模型发送的是 {"q": "agent loop"} 而不是 {"query": "agent loop"},什么都不会抛出。查询变成空字符串,语料库查找一无所获,工具返回 ["no matches"]。模型会把这当作语料库为空的证据,并据此作答。没有错误,没有日志,也没有任何办法区分真正的空结果和 JSON 键名里的一个笔误。
我写这篇文章时跑了这个对比实验:把 30 个真实模型确实会产出的畸形参数载荷——改名的键、大写的键、整数位置放了字符串、列表放到了字符串的位置、null——分别塞进第 1 部分的工具和本文构建的版本。第 1 部分对 30 个中的 12 个产出了看起来合理的空结果。契约版本产出 0 个静默结果:27 个变成显式的、带 schema 提示的分类错误,3 个合法载荷成功执行。同样的模型,同样的工具,失败可见性却完全不同。
本部分的主题是让失败可见、可恢复。不是靠提示模型小心一点——而是拒绝执行任何不满足已声明契约的调用,并把每一次失败都变成循环可以处理的带类型值。
你将构建什么
一个 contracts.py 模块,在第 1 部分的工具注册表外包一层,新增四样东西:
validate_args(schema, args)——一个 JSON Schema 子集校验器,返回{path, message}错误列表而非布尔值,让模型能准确知道哪个字段错了。ErrorCode+ToolError——一个封闭的八类失败分类体系,每类附带一个问题:第二次尝试有可能成功吗?RetryPolicy+IdempotencyStore——带抖动的有界指数退避,只应用于可重试的错误码,外加参数哈希键,确保被重试的副作用不会执行两次。ToolExecutor——Tool.run的唯一调用方。它负责校验、去重、在超时限制下执行、分类并重试。
AgentLoop 保持第 1 部分的形状。它的 run 方法大约只改六行:直接调用的 tool.run(args) 改为 self.executor.execute(name, args),trace 记录尝试次数和错误码。其余一切——Message、ToolResult、ScriptedLLM、各种决策结构——都保持兼容,因为第 3 部分和第 4 部分是在这个文件上扩展而不是替换它。
前置条件
- Python 3.10 或更新版本。仅用标准库:
concurrent.futures、hashlib、json、random、time、urllib。 - 第 1 部分的文件,或至少其中四个类型:
Message、ToolResult、Tool、AgentLoop。如果你跳过了它,下面的代码块会以兼容的方式重新定义它们。 - 一个终端。这里的每个测试都在离线状态下于一秒内跑完。
有一处刻意留白:validate_args 只支持 JSON Schema 的一个子集——type、properties、required、additionalProperties、items、enum、minLength、maxLength、minimum、maximum。这个子集覆盖了实际工具 schema 中用到的绝大多数东西。它不支持 $ref、oneOf 或 pattern,假装支持比坦白说清更糟。如果你需要它们,这正是改用 jsonschema 或 Pydantic 的正确时机;外围的执行器设计不会因此改变。
契约真正断裂的地方
三类失败几乎涵盖模型与工具之间所有会出错的情况,而它们需要不同的处理方式。
键名错误,意图合理。 模型发来 {"q": ...},而 schema 要求的是 query。Python 的 dict.get 默认值悄悄补上 ""。这是最危险的一类,因为工具成功了,答案却是错的。
键名正确,类型错误。 {"limit": "3"} 进入 [v for ...][:limit],抛出 TypeError: slice indices must be integers。在第 1 部分里,这个异常被 AgentLoop.run 捕获并转换为 ToolResult(ok=False)——但消息是 TypeError: slice indices must be integers or None or have an __index__ method,完全没告诉模型该修哪个参数。
调用正确,瞬时失败。 搜索后端返回 429、socket 超时、索引返回 503。重试是正确的。但因为响应丢失而重试一次 save_note 调用,就会把写入重复一遍。
下面是我用的探针脚本,你可以复现那个 30 中 12 的数字,而不是凭空相信:
import jsonfrom contracts import ToolExecutor, ToolResult, build_tools
def search_v1(args: dict) -> ToolResult: query = str(args.get("query", "")).lower() corpus = { "agent loop": "An agent loop repeats: observe, decide, act, observe.", "token budget": "Context windows are finite; budget them explicitly.", "stop condition": "A step limit is a stop condition, not a strategy.", "retry": "Retry only failures that are transient; never retry a 400.", } hits = [v for key, v in corpus.items() if key in query] return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
PAYLOADS = [ {"query": "agent loop"}, {"q": "agent loop"}, {"Query": "agent loop"}, {"query": "agent loop", "top_k": 3}, {"query": ["agent loop"]}, {"query": "agent loop", "limit": "3"}, {"query": "agent loop", "limit": 0}, {"query": ""}, {"query": "agent loop", "limit": True}, {"query": None},]
def probe() -> None: cases = (PAYLOADS * 3)[:30] executor = ToolExecutor({t.name: t for t in build_tools()}, sleep=lambda d: None) silent_v1 = silent_v2 = explicit_v2 = 0 for args in cases: old = search_v1(args) new = executor.execute("search", args) if old.ok and json.loads(old.data) == ["no matches"]: silent_v1 += 1 if not new.ok: explicit_v2 += 1 elif json.loads(new.data) == ["no matches"]: silent_v2 += 1 print("n=%d v1_silent=%d v2_explicit=%d v2_silent=%d" % (len(cases), silent_v1, explicit_v2, silent_v2))
if __name__ == "__main__": probe()输出:n=30 v1_silent=12 v2_explicit=27 v2_silent=0。剩下三次成功的是合法载荷 {"query": "agent loop"},重复三次。静默的错误答案比报错更糟,因为它与正确的空结果无法区分,而且会未经质疑地传播进最终答案。
一个你能推理的校验器
校验器返回结构化错误而不是布尔值,因为错误文本就是模型下一轮读到的修复指令。布尔值逼你凭空编一条消息;路径加原因则让你能机械地生成一条。
from __future__ import annotationsfrom dataclasses import dataclass, replacefrom typing import Any, Callableimport json
@dataclassclass Message: role: str # "system" | "user" | "assistant" | "tool" content: str name: str | None = None # tool name, required when role == "tool"
@dataclassclass ToolResult: ok: bool data: str error: str | None = None error_code: str | None = None attempts: int = 1 from_cache: bool = False
def to_message(self, name: str) -> Message: if self.ok: payload = self.data else: payload = "ERROR[%s]: %s" % (self.error_code or "unknown", self.error or "") return Message(role="tool", content=payload, name=name)
def validate_args(schema: dict, args: Any) -> list[dict]: """Validate a JSON Schema subset. Returns [] or a list of {path, message}.""" errors: list[dict] = []
def walk(sch: dict, value: Any, path: str) -> None: t = sch.get("type") if t == "object": if not isinstance(value, dict): errors.append({"path": path or "/", "message": "expected object"}) return props = sch.get("properties", {}) for req in sch.get("required", []): if req not in value: errors.append({"path": path + "/" + req, "message": "missing required field"}) if sch.get("additionalProperties") is False: for key in value: if key not in props: errors.append({"path": path + "/" + str(key), "message": "unexpected field"}) for key, sub in props.items(): if key in value: walk(sub, value[key], path + "/" + key) return if t == "array": if not isinstance(value, list): errors.append({"path": path, "message": "expected array"}) return item_schema = sch.get("items", {}) for i, item in enumerate(value): walk(item_schema, item, path + "/" + str(i)) return if t == "string": if not isinstance(value, str): errors.append({"path": path, "message": "expected string"}) return elif t == "integer": if isinstance(value, bool) or not isinstance(value, int): errors.append({"path": path, "message": "expected integer"}) return elif t == "number": if isinstance(value, bool) or not isinstance(value, (int, float)): errors.append({"path": path, "message": "expected number"}) return elif t == "boolean": if not isinstance(value, bool): errors.append({"path": path, "message": "expected boolean"}) return if "enum" in sch and value not in sch["enum"]: errors.append({"path": path, "message": "must be one of " + repr(sch["enum"])}) if "minLength" in sch and isinstance(value, str) and len(value) < sch["minLength"]: errors.append({"path": path, "message": "shorter than minLength %d" % sch["minLength"]}) if "maxLength" in sch and isinstance(value, str) and len(value) > sch["maxLength"]: errors.append({"path": path, "message": "longer than maxLength %d" % sch["maxLength"]}) if "minimum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value < sch["minimum"]: errors.append({"path": path, "message": "below minimum %s" % sch["minimum"]}) if "maximum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value > sch["maximum"]: errors.append({"path": path, "message": "above maximum %s" % sch["maximum"]})
walk(schema, args, "") return errors那段代码里有两个细节不是装饰。第一,isinstance(value, bool) 在 integer 和 number 分支上的守卫:在 Python 里 True 是值为 1 的 int,否则 {"limit": true} 会通过整数检查并变成 limit=1。第二,校验器不在第一个错误处抛出——它收集所有错误,然后报告前三条。一个发了两个坏字段的模型应该在一次往返里同时得知两个问题,而不是两次。
错误只有带着修复目标才有用。这正是 describe_schema 补上的:从同一个 schema 对象派生出一个紧凑签名。
def describe_schema(schema: dict) -> str: """Compact, model-readable signature: query:string!, limit:integer.""" parts = [] required = set(schema.get("required", [])) for name, sub in schema.get("properties", {}).items(): piece = name + ":" + str(sub.get("type", "any")) if name in required: piece += "!" if "enum" in sub: piece += "=" + "|".join(str(v) for v in sub["enum"]) parts.append(piece) return "{" + ", ".join(parts) + "}"
def format_errors(errors: list[dict], limit: int = 3) -> str: shown = ["%s %s" % (e["path"] or "/", e["message"]) for e in errors[:limit]] if len(errors) > limit: shown.append("(+%d more)" % (len(errors) - limit)) return "; ".join(shown){"q": ...} 这种情况下得到的工具消息是 ERROR[invalid_arguments]: /q unexpected field; /query missing required field. expected {query:string!, limit:integer}。expected 后面的部分由 schema 生成,所以你改 schema 时它不会漂移。这个性质比措辞更重要:手写的修复提示会过时,生成的不会。
注意这要付出什么代价。additionalProperties: False 是严格的——一个添加了无害元数据字段的提供方会导致校验失败。这正是目的:意外的字段要么意味着模型幻觉出一个参数,要么意味着你的 schema 落后于代码,两种情况都值得响亮地失败,而不是用 **kwargs 一耸肩了事。
分类错误而非字符串
字符串错误只能被记录。分类错误可以被拿来决策。下面的分类体系刻意很小;八个错误码覆盖了我在使用工具的 agent 中实际见过的失败,每个都对应一种动作。
from enum import Enum
class ErrorCode(str, Enum): INVALID_ARGUMENTS = "invalid_arguments" UNKNOWN_TOOL = "unknown_tool" NOT_FOUND = "not_found" RATE_LIMITED = "rate_limited" TIMEOUT = "timeout" UPSTREAM = "upstream_error" PERMISSION = "permission_denied" INTERNAL = "internal_error"
class ToolError(Exception): """Raise inside a tool to report a classified, non-crashing failure."""
def __init__(self, message: str, code: ErrorCode = ErrorCode.INTERNAL, retry_after: float | None = None): super().__init__(message) self.code = code self.retry_after = retry_after分类规则就是一个问题:一次完全相同的第二次尝试,不做任何改动,有可能成功吗? rate_limited、timeout 和 upstream_error 的答案是能。invalid_arguments、unknown_tool、not_found、permission_denied 和 internal_error 的答案是不能——前三个需要一次不同的调用,后两个需要人来处理。这就是不重试一切的全部理由:每次浪费的重试都消耗一步 max_steps,按每个工具调用三次尝试计,五个工具的预算就坍缩成两个。
Tool 增加三个契约字段,而 description 现在成了承重墙,这和第 1 部分不一样了:
@dataclassclass Tool: name: str description: str parameters: dict[str, Any] # JSON Schema _fn: Callable[[dict], ToolResult] side_effect: bool = False # True -> executed at most once per idempotency key timeout_s: float = 5.0
def spec(self) -> dict: return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.parameters, }, }
def run(self, args: dict) -> ToolResult: return self._fn(args)三个工具现在声明了诚实的 schema,之前静默失败的两个现在响亮地失败。_search 在后端宕机时抛出分类化的 ToolError 而不是返回空列表,因为空列表和超时对模型来说是相反的信号:
def _search(args: dict) -> ToolResult: query = str(args.get("query", "")).strip().lower() limit = int(args.get("limit", 3)) corpus = { "agent loop": "An agent loop repeats: observe, decide, act, observe.", "token budget": "Context windows are finite; budget them explicitly.", "stop condition": "A step limit is a stop condition, not a strategy.", "retry": "Retry only failures that are transient; never retry a 400.", } hits = [v for key, v in corpus.items() if key in query][:limit] if "timeout" in query: raise ToolError("upstream search index timed out", ErrorCode.TIMEOUT) return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
def _calculate(args: dict) -> ToolResult: expr = str(args.get("expression", "")) allowed = set("0123456789+-*/(). ") if not expr or not set(expr) <= allowed: return ToolResult(ok=False, data="", error="illegal characters in expression", error_code=ErrorCode.INVALID_ARGUMENTS) try: value = eval(expr, {"__builtins__": {}}, {}) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc), error_code=ErrorCode.INVALID_ARGUMENTS) return ToolResult(ok=True, data=str(value))
def _save_note(args: dict) -> ToolResult: import os os.makedirs("notes", exist_ok=True) path = "notes/" + str(args.get("name", "note")) + ".txt" with open(path, "w", encoding="utf-8") as f: f.write(str(args.get("body", ""))) return ToolResult(ok=True, data="saved " + path)
def build_tools() -> list[Tool]: return [ Tool( name="search", description="Search the local research corpus. Returns a JSON list of matching passages.", parameters={ "type": "object", "properties": { "query": {"type": "string", "minLength": 2, "maxLength": 200}, "limit": {"type": "integer", "minimum": 1, "maximum": 10}, }, "required": ["query"], "additionalProperties": False, }, _fn=_search, ), Tool( name="calculate", description="Evaluate a pure arithmetic expression. No variables, no functions.", parameters={ "type": "object", "properties": {"expression": {"type": "string", "minLength": 1, "maxLength": 100}}, "required": ["expression"], "additionalProperties": False, }, _fn=_calculate, ), Tool( name="save_note", description="Persist a note to disk. Non-idempotent: each call writes a file.", parameters={ "type": "object", "properties": { "name": {"type": "string", "minLength": 1, "maxLength": 40}, "body": {"type": "string", "maxLength": 4000}, }, "required": ["name", "body"], "additionalProperties": False, }, _fn=_save_note, side_effect=True, timeout_s=2.0, ), ]minLength: 2 不是装点门面,它落在 query 上。它是对产生全部十二个静默失败的空查询情形最廉价的防御:空字符串现在在契约层就被拒绝,工具函数体根本看不到它。
不会重复副作用的重试
退避是简单的一半。难的一半是重试一次写入可能写入两次:请求成功了,响应丢了,你的重试又创建了一条记录。修复方法是一个由工具名和规范化参数派生的键,外加一条关于哪些调用可以复用缓存结果的规则。
import hashlibimport randomimport time
@dataclassclass RetryPolicy: max_attempts: int = 3 base_delay: float = 0.05 max_delay: float = 2.0 jitter: float = 0.25 retryable: frozenset = frozenset( {ErrorCode.RATE_LIMITED, ErrorCode.TIMEOUT, ErrorCode.UPSTREAM} )
def is_retryable(self, code: str | None) -> bool: return code in {c.value for c in self.retryable}
def delay_for(self, attempt: int, rnd: random.Random) -> float: raw = min(self.max_delay, self.base_delay * (2 ** (attempt - 1))) return raw * (1.0 + rnd.uniform(-self.jitter, self.jitter))
class IdempotencyStore: """Remembers completed calls by (tool, canonical args) hash."""
def __init__(self) -> None: self._done: dict[str, ToolResult] = {}
@staticmethod def key(name: str, args: dict) -> str: blob = json.dumps(args, sort_keys=True, separators=(",", ":")) return name + ":" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
def get(self, key: str) -> ToolResult | None: return self._done.get(key)
def put(self, key: str, result: ToolResult) -> None: self._done[key] = resultsort_keys=True 是键稳定的关键:{"a": 1, "b": 2} 和 {"b": 2, "a": 1} 是同一次调用,必须产出相同的键,否则防护会漏。抖动也不是锦上添花——没有它,十个撞上同一个 429 的工作线程会齐步重试,然后一起再次撞墙;±25% 能把它们错开。
执行器是四个关注点组合之处,它的顺序就是设计本身:**先校验,再去重,再执行,再分类,最后重试。**校验先于去重,意味着畸形调用永远不会占用一个键。
import concurrent.futures
class ToolExecutor: """Validate -> de-duplicate -> execute -> classify -> retry. The only caller of Tool.run."""
def __init__( self, tools: dict[str, Tool], policy: RetryPolicy | None = None, store: IdempotencyStore | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None, ) -> None: self.tools = tools self.policy = policy or RetryPolicy() self.store = store or IdempotencyStore() self.sleep = sleep self.rnd = rnd or random.Random(0)
def execute(self, name: str, args: dict) -> ToolResult: tool = self.tools.get(name) if tool is None: return ToolResult(ok=False, data="", error="unknown tool: " + name, error_code=ErrorCode.UNKNOWN_TOOL.value)
errors = validate_args(tool.parameters, args) if errors: hint = "expected " + describe_schema(tool.parameters) return ToolResult(ok=False, data="", error=format_errors(errors) + ". " + hint, error_code=ErrorCode.INVALID_ARGUMENTS.value)
key = self.store.key(name, args) cached = self.store.get(key) if cached is not None and (tool.side_effect or not cached.ok): return replace(cached, from_cache=True, attempts=0)
attempt = 0 while True: attempt += 1 result = self._attempt(tool, args) result.attempts = attempt if result.ok: self.store.put(key, result) return result if not self.policy.is_retryable(result.error_code): # Negative cache: an identical call that failed permanently will fail # again. Caching it stops a looping model from re-burning the quota. self.store.put(key, result) return result if attempt >= self.policy.max_attempts: return result self.sleep(self.policy.delay_for(attempt, self.rnd))
def _attempt(self, tool: Tool, args: dict) -> ToolResult: pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) try: future = pool.submit(tool.run, args) return future.result(timeout=tool.timeout_s) except concurrent.futures.TimeoutError: return ToolResult(ok=False, data="", error="tool exceeded %.1fs" % tool.timeout_s, error_code=ErrorCode.TIMEOUT.value) except ToolError as exc: return ToolResult(ok=False, data="", error=str(exc), error_code=exc.code.value) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc), error_code=ErrorCode.INTERNAL.value) finally: pool.shutdown(wait=False)有两个微妙之处值得点名。缓存复用条件是 tool.side_effect or not cached.ok:写入可以复用缓存的成功结果(这是至多一次),任何调用都可以复用缓存的失败结果(这是负缓存,能阻止卡死的模型在同一坏调用上反复烧配额)。只读的成功被刻意不缓存,因为两分钟前没有返回东西的搜索现在可能返回东西,而过期的读本身就是另一类错误答案。
第二个微妙之处是超时。future.result(timeout=...) 限制的是你等多久,而不是工具运行多久——Python 杀不掉线程。一个无视超时的工具会在循环继续前进的同时在后台持续烧 CPU。这是一个诚实的局限,也正是第 11 部分用进程级沙箱替换它的原因。不要把 timeout_s 读作安全边界;把它读作延迟预算。
接入循环,补上我们跳过的 LLM 重试
第 1 部分留下了一个我明确标注过的缺口:AgentLoop.run 给 tool.run 加了守卫,却没有给 llm.complete 加,于是模型端点一次 503 就能杀死整个运行。同一个策略补上它,应用于 HTTP 状态码。
import urllib.error
class LLMClient: def complete(self, messages: list[Message], tools: list[dict]) -> dict: raise NotImplementedError
class ScriptedLLM(LLMClient): """Replays a fixed list of decisions. Used for offline tests and demos."""
def __init__(self, script: list[dict]): self.script = list(script) self.calls: list[list[Message]] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: self.calls.append(list(messages)) if not self.script: return {"type": "final", "content": "no scripted decision left"} return self.script.pop(0)
def classify_http_status(status: int) -> ErrorCode: if status == 429: return ErrorCode.RATE_LIMITED if status in (408, 504): return ErrorCode.TIMEOUT if 500 <= status < 600: return ErrorCode.UPSTREAM if status in (401, 403): return ErrorCode.PERMISSION return ErrorCode.INVALID_ARGUMENTS
class RetryingLLM(LLMClient): """Wraps any client; retries only the codes that a second attempt can fix."""
def __init__(self, inner: LLMClient, policy: RetryPolicy | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None) -> None: self.inner = inner self.policy = policy or RetryPolicy() self.sleep = sleep self.rnd = rnd or random.Random(7) self.attempts: list[int] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: attempt = 0 while True: attempt += 1 try: decision = self.inner.complete(messages, tools) self.attempts.append(attempt) return decision except urllib.error.HTTPError as exc: code = classify_http_status(exc.code) if not self.policy.is_retryable(code.value) or attempt >= self.policy.max_attempts: self.attempts.append(attempt) raise self.sleep(self.policy.delay_for(attempt, self.rnd))401 在第一次尝试时就会抛出,而不是第三次:坏的密钥会一直是坏的,三次尝试只是在失败前把延迟变成三倍。400 被归类为 invalid_arguments,理由相同——你的载荷是错的,重发毫无意义。
循环的改动很小,而 trace 是价值显现之处:
SYSTEM = ( "You are a research agent. Use the provided tools to gather evidence, " "then answer with a final decision. Do not claim facts you did not retrieve. " "If a tool returns ERROR[invalid_arguments], fix the arguments using the schema shown.")
class AgentLoop: def __init__(self, llm: LLMClient, tools: list[Tool], max_steps: int = 8, executor: ToolExecutor | None = None): self.llm = llm self.tools = {t.name: t for t in tools} self.specs = [t.spec() for t in tools] self.max_steps = max_steps self.trace: list[dict] = [] self.executor = executor or ToolExecutor(self.tools)
def run(self, goal: str) -> str: history = [ Message(role="system", content=SYSTEM), Message(role="user", content=goal), ] for step in range(self.max_steps): decision = self.llm.complete(history, self.specs) kind = decision.get("type") record = {"step": step, "decision": decision} self.trace.append(record)
if kind == "final": return str(decision.get("content", "")) if kind != "tool": return "aborted: malformed decision " + repr(decision)
name = str(decision.get("name", "")) args = decision.get("arguments", {}) if not isinstance(args, dict): args = {}
result = self.executor.execute(name, args) record.update({"tool": name, "ok": result.ok, "attempts": result.attempts, "error_code": result.error_code, "from_cache": result.from_cache}) history.append(result.to_message(name))
return "aborted: step limit reached"SYSTEM 提示词现在写明了错误格式。这不是提示工程玄学:模型被告知了它在失败时会看到的确切字符串以及该怎么处理。它只花一句话,却能显著减少校验错误后模型乱撞的轮数,因为修复目标就在错误本身里。
跑一遍,trace 读起来像一份诊断而不是一份记录:
def demo() -> None: script = [ {"type": "tool", "name": "search", "arguments": {"q": "agent loop"}}, {"type": "tool", "name": "search", "arguments": {"query": "agent loop", "limit": 1}}, {"type": "tool", "name": "save_note", "arguments": {"name": "loop", "body": "observe decide act"}}, {"type": "tool", "name": "save_note", "arguments": {"name": "loop", "body": "observe decide act"}}, {"type": "final", "content": "The agent loop repeats observe, decide, act."}, ] agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=8) print("ANSWER:", agent.run("Explain the agent loop.")) for rec in agent.trace: if "tool" in rec: print(rec["step"], rec["tool"], "ok=%s" % rec["ok"], "attempts=%d" % rec["attempts"], rec["error_code"], "cached=%s" % rec["from_cache"])
if __name__ == "__main__": demo()ANSWER: The agent loop repeats observe, decide, act.0 search ok=False attempts=1 invalid_arguments cached=False1 search ok=True attempts=1 None cached=False2 save_note ok=True attempts=1 None cached=False3 save_note ok=True attempts=0 None cached=TrueStep 0 显示契约拒绝了调用。Step 1 显示模型在下一轮恢复——那个恢复是错误消息促成的,这正是提示要从 schema 生成的原因。Step 3 显示一次完全相同的写入请求从缓存返回,attempts=0:没有第二个文件,没有第二次网络调用。
失败模式与处理方式
| 失败 | 实际会发生什么 | 本文的处理 | 仍然会坏的地方 |
|---|---|---|---|
| 模型发送改名后的键 | additionalProperties: False 标记它,required 指出缺失字段 |
显式的 invalid_arguments 加 schema 提示;模型下一轮修复 |
无视提示的模型会烧光所有步数 |
模型对整数字段发送 true |
Python 把 bool 当作 int,天真的检查会通过 |
isinstance(value, bool) 守卫拒绝它 |
没有——这个已闭合 |
| 工具挂起 | future 超时后线程仍在运行 |
timeout_s 返回 timeout,在预算内重试 |
进程级 CPU 燃烧;没有终止开关(第 11 部分) |
| 429 风暴 | 每次尝试都再次撞上限制 | 有界尝试、指数退避、±25% 抖动 | 没有跨进程限流器(第 12 部分) |
| 写入时响应丢失 | 重试会复制文件 | 幂等键 + side_effect=True 返回缓存的成功 |
内存存储随进程消亡(第 8 部分) |
| 同一坏调用反复出现 | 模型在一个错误上打转 | 负缓存阻止重复执行 | 循环仍消耗步数;需要重复检测器 |
| schema 与代码漂移 | 校验拒绝了工具需要的字段 | describe_schema 从 schema 重新生成提示 |
没有东西自动检测漂移 |
最后一行就是咬到我的那个。describe_schema 之所以正确,只是因为它和 validate_args 读的是同一个 dict。如果你在提示词里手写第二份 schema,两者一个月内必然分叉——而失败看起来会像模型出错,而不是维护出错。
权衡
| 决策 | 备选方案 | 选择理由 | 代价 |
|---|---|---|---|
| 手写子集校验器 | jsonschema 或 Pydantic |
零依赖,约 120 行,错误形状对模型友好 | 不支持 $ref/oneOf/pattern;要自己维护 |
错误作为 ToolResult 值 |
让异常穿透循环向上抛 | 模型能读懂并修复;循环保持简单 | 调用方必须在各处检查 ok |
additionalProperties: False |
宽容的额外字段 | 立即抓到幻觉出的参数 | 提供方添加元数据时会坏 |
| 内存中的幂等键 | Redis 或 SQLite | 一个 dict,零基础设施,可测试 | 不能跨工作进程共享;重启即丢 |
| 线程超时 | 进程沙箱 | 10 行代码,无 IPC | 杀不掉失控的工具(第 11 部分) |
| 只重试 3 个错误码 | 一切都重试一次 | 保住步数预算 | 偶发闪断的 not_found 永不重试 |
| 缓存负结果 | 总是重新执行 | 阻止打转的模型引发重试风暴 | 被误分类为永久性的瞬时失败会一直留在缓存 |
校验器的选择最值得推敲。Pydantic 会免费给你类型强转、嵌套模型和更好的错误消息——代价是一个依赖、更慢的导入,以及你还是得把错误对象翻译成模型可读的文本。八个工具 schema 时,手写版赢。八十个时,不赢。
测试它
十四个测试,离线,十分之一秒内跑完。把模块存为 contracts.py,测试存为 test_contracts.py;运行 python3 -m unittest test_contracts -v。完整测试集在仓库里,但下面这五个承载着设计:
import unittestimport urllib.error
from contracts import ( AgentLoop, ErrorCode, ScriptedLLM, Tool, ToolError, ToolExecutor, ToolResult, IdempotencyStore, RetryPolicy, RetryingLLM, LLMClient, build_tools, validate_args, describe_schema,)
class Flaky: def __init__(self, failures, code=ErrorCode.TIMEOUT): self.failures, self.code, self.calls = failures, code, 0
def __call__(self, args): self.calls += 1 if self.calls <= self.failures: raise ToolError("transient", self.code) return ToolResult(ok=True, data="recovered")
def tool_with(fn, name="probe", side_effect=False, timeout_s=1.0): return Tool(name=name, description="probe", _fn=fn, parameters={"type": "object", "properties": {}, "additionalProperties": False}, side_effect=side_effect, timeout_s=timeout_s)
class TestContracts(unittest.TestCase): def test_bool_is_not_an_integer(self): schema = build_tools()[0].parameters errors = validate_args(schema, {"query": "ok", "limit": True}) self.assertTrue(any("expected integer" in e["message"] for e in errors))
def test_transient_failure_is_retried_until_success(self): flaky = Flaky(failures=2, code=ErrorCode.UPSTREAM) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertTrue(result.ok) self.assertEqual(result.attempts, 3)
def test_permanent_failure_is_never_retried(self): flaky = Flaky(failures=5, code=ErrorCode.PERMISSION) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertFalse(result.ok) self.assertEqual(flaky.calls, 1)
def test_side_effect_runs_once_per_key(self): calls = {"n": 0}
def write(args): calls["n"] += 1 return ToolResult(ok=True, data="written")
executor = ToolExecutor({"probe": tool_with(write, side_effect=True)}, store=IdempotencyStore(), sleep=lambda d: None) executor.execute("probe", {}) second = executor.execute("probe", {}) self.assertEqual(calls["n"], 1) self.assertTrue(second.from_cache)
def test_401_is_not_retried(self): class Bad(LLMClient): def __init__(self): self.calls = 0
def complete(self, messages, tools): self.calls += 1 raise urllib.error.HTTPError("http://x", 401, "no", None, None)
inner = Bad() llm = RetryingLLM(inner, sleep=lambda d: None) with self.assertRaises(urllib.error.HTTPError): llm.complete([], []) self.assertEqual(inner.calls, 1)
if __name__ == "__main__": unittest.main()test_bool_is_not_an_integer 看起来像琐事,其实不然:它是在 {"limit": true} 和一个被静默截断的结果集之间站着的那一行。test_side_effect_runs_once_per_key 是唯一保护数据而非延迟的测试。如果你只留两个测试,就留这两个。
还有一个值得手动跑的检查:让 Flaky 指向 RATE_LIMITED,max_attempts=99,确认执行器停在策略上限。没有边界的重试循环就是一场带额外步骤的宕机。
练习
- 跨进程幂等。 把
IdempotencyStore换成基于 SQLite 的版本,键为(name, args_hash),加一个created_at时间戳。让超过十分钟的键过期。进程在写入中途死掉时的失败模式会发生什么变化?为什么 TTL 必须比你最长的重试窗口更长? - 按工具覆盖重试策略。 搜索后端限流很凶;笔记写入最多重试一次就好。加一个
policy字段挂到Tool上,覆盖执行器默认值并写一个测试证明 429 下的save_note调用在两次尝试后返回,而不是四次。 - 带收据的类型强转。 不拒绝
{"limit": "3"},而是接受它、转换为3,并在工具结果后追加一条注记:coerced: limit "3" -> 3。在一份 50 次调用的 trace 上测量这能省多少轮。哪个更危险——静默强转还是拒绝调用?收据改变了什么?
练习 3 是最有意思的,因为它没有唯一正确答案。强转减少往返并掩盖模型错误;拒绝更响亮也更慢。收据是折中:你拿回了往返,同时保留了一份为模型代做的每个假设的审计记录。
下一步
你的工具现在有了契约,你的失败有了错误码,你的重试不会重复一次写入。自第 1 部分以来没有变的,是生产环境中首先会疼的那件事:消息列表在每一步增长,而每条早先的消息在每次调用时都被完整重发。
第 3 部分,上下文预算工程,加入一个 ContextBudget,在每次调用前测量 token,在系统提示、工具结果和历史之间分配窗口,并在估算超出预算时压缩旧的轮次。它还量化了第 1 部分表格里的二次方输入增长,并展示三种压缩策略——截断、摘要、逐出——中哪一种真正物有所值。你刚构建的 ToolExecutor 原封不动;预算包裹的是历史,不是工具。
下载 Ball — Ball
下载 Ball