返回全部文章AI 與智能體

代理工具契約與結構化錯誤(第二部分)

A contract you can reason about

Typed contractvalidate args before execution
Classified errorsenum, not error strings
Idempotent retryno duplicated side effects
LLM retryfeed the error back as a message

A guarded tool call

Errors are data. The loop decides what to do with them.

  1. 01
    call dictname + args
  2. 02
    validate against schemareject before any side effect
  3. 03
    retry? classifiedtransient only, idempotent
  4. 04
    execute onceguarded, logged
  5. 05
    ToolResult(ok/error)typed and classified
  6. 06
    append to historyLLM sees the error

第一部分結束時,有一個知道如何終止的迴圈,和一個完全相信模型所說一切的工具註冊表。那份信任就是下一個 bug。在第一部分的 _search 裡,第一行是 query = str(args.get("query", "")).lower()。如果模型送出的是 {"q": "agent loop"} 而不是 {"query": "agent loop"},什麼都不會拋出。查詢變成空字串,語料庫查詢找不到任何東西,工具回傳 ["no matches"]。模型把這解讀為語料庫是空的,並據此回答。沒有錯誤,沒有日誌行,也沒有任何辦法分辨真正的空結果與 JSON 鍵的打字錯誤。

我寫這篇文章時確實跑了這個比較:三十個真實模型確實會產生的格式錯誤引數酬載——被改名的鍵、大寫的鍵、該放整數的位置放了字串、用清單代替字串、null——分別推過第一部分的工具與我們在這裡建出的版本。第一部分對 30 個中的 12 個產生了看起來合理的空結果。契約版本產生了 0 個無聲結果:27 個變成帶有 schema 提示的明確分類錯誤,3 個合法酬載成功。同一個模型、同一組工具,只有失敗的能見度不同。

這一部分要讓失敗變得可見且可復原。不是靠提示模型小心——而是拒絕執行不符合已宣告契約的呼叫,並把每個失敗變成迴圈能據以行動的帶型別值。

你將建構什麼

一個 contracts.py 模組,以四項新增包裝第一部分的工具註冊表:

  • validate_args(schema, args)——一個 JSON Schema 子集驗證器,回傳 {path, message} 錯誤清單而非布林值,讓模型能被確切告知是哪個欄位錯了。
  • ErrorCode + ToolError——一個封閉式的八類失敗分類法,每一類都附帶一個問題:第二次嘗試有可能成功嗎?
  • RetryPolicy + IdempotencyStore——帶抖動的有限指數退避,只套用於可重試的代碼,再加上引數雜湊鍵,讓被重試的副作用無法執行兩次。
  • ToolExecutor——Tool.run 的唯一呼叫者。它驗證、去重、在逾時內執行、分類,然後重試。

AgentLoop 保持第一部分的形狀。它的 run 方法改動約六行:直接的 tool.run(args) 變成 self.executor.execute(name, args),而軌跡記錄嘗試次數與錯誤代碼。其他一切——Message、ToolResult、ScriptedLLM、決策形狀——都保持相容,因為第三與第四部分是擴充這個檔案,而不是取代它。

前置需求

  • Python 3.10 或更新。只用標準函式庫:concurrent.futures、hashlib、json、random、time、urllib。
  • 第一部分的檔案,或至少它的四個型別:Message、ToolResult、Tool、AgentLoop。如果你跳過了,下面的區塊會以相容的方式重新定義它們。
  • 一個終端機。這裡的每個測試都在一秒內離線執行完畢。

一個刻意的省略:validate_args 支援 JSON Schema 的子集——type、properties、required、additionalProperties、items、enum、minLength、maxLength、minimum、maximum。這個子集涵蓋了實務上真實工具 schema 的用法。它不支援 $ref、oneOf 或 pattern,而假裝支援比坦白承認更糟。如果你需要它們,這正是改用 jsonschema 或 Pydantic 的正確時機;周圍的 executor 設計不變。

契約實際上在哪裡失效

三類失敗幾乎涵蓋了模型與工具之間所有可能出錯的事情,而它們需要不同的處理方式。

鍵錯了,意圖合理。 {"q": ...} 對上要求 query 的 schema。Python 的 dict.get 預設值無聲地補上 ""。這是最危險的一種,因為工具成功了,答案卻是錯的。

鍵對了,型別錯了。 {"limit": "3"} 一路走到 [v for ...][:limit] 並拋出 TypeError: slice indices must be integers。在第一部分,這個例外被 AgentLoop.run 捕獲並轉成 ToolResult(ok=False)——但訊息是 TypeError: slice indices must be integers or None or have an __index__ method,完全沒告訴模型該修哪個引數。

呼叫正確,暫時性失敗。 搜尋後端回傳 429、socket 逾時、索引回傳 503。重試是對的。但只因為回應丟失就重試 save_note 呼叫,會讓寫入重複。

這是我使用的探針,讓你能重現 12-of-30 這個數字,而不是憑信心接受:

import json
from 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 annotations
from dataclasses import dataclass, replace
from typing import Any, Callable
import json
@dataclass
class Message:
role: str # "system" | "user" | "assistant" | "tool"
content: str
name: str | None = None # tool name, required when role == "tool"
@dataclass
class 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 是嚴格的——提供者加了一個無害的 metadata 欄位就會驗證失敗。這正是重點:意外的欄位代表模型幻覺出參數,或你的 schema 落後於你的程式碼,兩者都值得大聲失敗,而不是聳聳肩接受 **kwargs。

分類錯誤而非字串

字串錯誤只能被記錄。分類錯誤可以被據以決策。下面的分類法刻意很小;八個代碼涵蓋了我在使用工具的代理中實際見過的失敗,而且每個都對應到一個行動。

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 增加了三個契約欄位,而描述現在成了承重結構,不像第一部分那樣可有可無:

@dataclass
class 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 hashlib
import random
import time
@dataclass
class 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] = result

sort_keys=True 是讓鍵穩定的關鍵:{"a": 1, "b": 2} 與 {"b": 2, "a": 1} 是同一個呼叫,必須產生同一個鍵,否則防護會漏。抖動也不是可有可無——沒有它,十個撞上同一個 429 的 worker 會齊步重試並再次一起撞上;±25% 把它們錯開。

executor 是四個關注點組合的地方,而它的順序就是設計:**驗證,然後去重,然後執行,然後分類,然後重試。**驗證在去重之前,意味著格式錯誤的呼叫永遠不會占住一個鍵。

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:寫入可以重用快取的成功(這是 at-most-once),任何呼叫都可以重用快取的失敗(這是負快取,阻止卡住的模型在同一個壞呼叫上重新燒配額)。唯讀的成功刻意不快取,因為兩分鐘前沒回傳任何東西的搜尋現在可能回傳東西,而過期的讀取本身就是另一種錯誤答案。

第二個微妙之處是逾時。future.result(timeout=...) 限制的是你等多久,不是工具跑多久——Python 殺不掉執行緒。忽略逾時的工具會在背景持續燒 CPU,而迴圈已經繼續往前走。這是一個誠實的侷限,也正是第十一部分用行程層級沙盒取代它的原因。不要把 timeout_s 當成安全邊界;把它當成延遲預算。

把它接進迴圈,補上我們跳過的 LLM 重試

第一部分留了一個我明確標記過的缺口: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 基於同樣的理由——你的酬載是錯的,重送毫無意義。

迴圈的改動很小,而軌跡正是價值顯現的地方:

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 提示現在指明了錯誤格式。這不是提示工程的玄學:模型被告知失敗時會看到的確切字串,以及該拿它做什麼。這只花一句話,卻能測量地減少驗證錯誤之後慌亂亂試的輪數,因為修復目標就在錯誤本身裡。

執行它,軌跡讀起來像一份診斷報告,而不是逐字稿:

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=False
1 search ok=True attempts=1 None cached=False
2 save_note ok=True attempts=1 None cached=False
3 save_note ok=True attempts=0 None cached=True

步驟 0 顯示契約拒絕了呼叫。步驟 1 顯示模型在下一輪復原——那次復原就是錯誤訊息造成的,這正是提示由 schema 產生的原因。步驟 3 顯示一個一模一樣的寫入請求由快取服務,attempts=0:沒有第二個檔案,沒有第二次網路呼叫。

失敗模式與應對方式

失敗 實際上發生什麼 這裡的處理方式 什麼仍會壞掉
模型送出被改名的鍵 additionalProperties: False 標記它,required 指出缺少的欄位 帶 schema 提示的明確 invalid_arguments;模型下一輪自行修復 忽視提示的模型會燒光所有步驟
模型為整數送出 true Python 把 bool 當 int,天真的檢查會通過 isinstance(value, bool) 防護拒絕它 沒有——這個案例已關閉
工具卡死 future 逾時後執行緒仍持續執行 timeout_s 回傳 timeout,重試至預算上限 行程層級的 CPU 消耗;沒有中止開關(第十一部分)
429 風暴 每次嘗試都再撞上限制 有限嘗試次數、指數退避、±25% 抖動 沒有跨行程的速率限制器(第十二部分)
寫入時回應丟失 重試會重複該檔案 冪等鍵 + side_effect=True 回傳快取的成功 記憶體內儲存隨行程消亡(第八部分)
同一個壞呼叫重複出現 模型在同一個錯誤上打轉 負快取阻止重新執行 迴圈仍耗費步驟;需要重複偵測器
Schema 與程式碼漂移 驗證拒絕了工具需要的欄位 describe_schema 從 schema 重新產生提示 沒有任何東西自動偵測漂移

最後一行是咬過我的那一行。describe_schema 之所以正確,只因為它與 validate_args 讀的是同一個 dict。如果你在提示裡手寫第二份 schema,兩者會在一個月內分歧——而失敗看起來會像模型錯誤,而不是維護錯誤。

權衡

決策 替代方案 我們為何選它 代價
自製的子集驗證器 jsonschema 或 Pydantic 零相依、約 120 行、錯誤格式為模型量身打造 沒有 $ref/oneOf/pattern;要自己維護
錯誤作為 ToolResult 值 在迴圈中拋出例外 模型能讀並修復;迴圈保持簡單 呼叫方處處都要檢查 ok
additionalProperties: False 寬容的額外欄位 立刻抓到幻覺出來的參數 提供者加 metadata 時會壞
記憶體內的冪等鍵 Redis 或 SQLite 一個 dict、零基礎設施、可測試 不跨 worker 共享;重啟即失效
執行緒逾時 行程沙盒 10 行、不需要 IPC 殺不了失控的工具(第十一部分)
只重試 3 個代碼 全部重試一次 保留步驟預算 不穩定的 not_found 永遠不被重試
快取否定結果 永遠重新執行 阻止打轉模型的重試風暴 被誤判為永久性的暫時失敗會留在快取裡

驗證器的選擇最值得細究。Pydantic 會免費給你強制轉型、巢狀模型與更好的錯誤訊息——代價是一個相依、較慢的匯入,以及你反正還得翻譯成模型可讀文字的錯誤物件。在八個工具 schema 的規模,自製版本贏。在八十個,就不贏了。

測試它

十四個測試、離線、十分之一秒以內。把模組存成 contracts.py、測試存成 test_contracts.py;執行 python3 -m unittest test_contracts -v。完整測試套件在儲存庫裡,但承載設計的是這五個:

import unittest
import 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,確認 executor 在政策上限處停止。沒有上限的重試迴圈,就是一場多了幾道手續的當機。

練習

  1. 跨行程的冪等性。 把 IdempotencyStore 換成以 (name, args_hash) 為鍵、帶 created_at 時間戳的 SQLite 版本。使十分鐘以上的鍵過期。行程在寫入中途死掉的失敗模式會有何改變,以及為什麼 TTL 必須比你最長的重試窗口更長?
  2. 每工具的重試覆寫。 搜尋後端的速率限制很兇;筆記寫入最多重試一次。加一個 policy 欄位到 Tool 來覆寫 executor 的預設值,並寫一個測試證明 429 情境下的 save_note 呼叫在兩次嘗試後返回,而不是四次。
  3. 附收據的強制轉型。 不拒絕 {"limit": "3"},而是接受它、轉成 3,並在工具結果附加一則備註:coerced: limit "3" -> 3。測量這在 50 次呼叫的軌跡上省下幾輪。哪個更危險——無聲的轉型還是被拒絕的呼叫——而收據改變了什麼?

練習 3 有趣之處在於它沒有單一正確答案。轉型減少往返次數並掩蓋模型錯誤;拒絕比較大聲也比較慢。收據是折衷:你拿回往返次數,並保留一份你替模型做的每個假設的稽核紀錄。

下一步

你的工具現在有契約了,你的失敗有代碼了,你的重試不會重複寫入了。自第一部分以來還沒變的、也是上線後最先讓你痛的,是訊息清單每一步都在增長,而每一則先前的訊息在每次呼叫時都被完整重送。

第三部分,上下文預算工程,加入一個 ContextBudget,在每次呼叫前測量 token、把窗口分配給系統提示、工具結果與歷史,並在估計值超出預算時壓縮舊輪次。它也量化了第一部分表格中的輸入平方增長,並展示三種壓縮策略——截斷、摘要、淘汰——哪一種真的值得。你剛建好的 ToolExecutor 保持原樣;預算包的是歷史,不是工具。

下載 Ball — Ball

下載 Ball

正在閱讀英文?可在選單中切換語言。