Back to all articlesAI và các tác nhân

Hợp đồng công cụ cho Agent và lỗi có cấu trúc (Phần 2)

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

Phần 1 kết thúc với một vòng lặp biết cách kết thúc và một bộ đăng ký công cụ tin tưởng mọi thứ mà mô hình nói. Sự tin tưởng đó chính là lỗi tiếp theo. Trong _search của Phần 1, dòng đầu tiên là query = str(args.get("query", "")).lower(). Nếu mô hình gửi {"q": "agent loop"} thay vì {"query": "agent loop"}, chẳng có gì bị raise cả. Truy vấn trở thành chuỗi rỗng, việc tra cứu kho tư liệu không khớp gì, và công cụ trả về ["no matches"]. Mô hình đọc điều đó như bằng chứng rằng kho tư liệu rỗng và trả lời theo hướng đó. Không có lỗi, không có dòng log, và không có cách nào phân biệt một kết quả rỗng thực sự với một lỗi chính tả trong khóa JSON.

Tôi đã chạy đúng phép so sánh đó khi viết bài này: ba mươi payload đối số sai định dạng mà một mô hình thực sự tạo ra — khóa bị đổi tên, khóa viết hoa, một chuỗi nằm ở vị trí của số nguyên, một danh sách thay vì chuỗi, null — được đẩy qua công cụ của Phần 1 và qua phiên bản chúng ta xây dựng ở đây. Phần 1 tạo ra kết quả rỗng trông hợp lý cho 12 trên 30. Phiên bản hợp đồng tạo ra 0 kết quả âm thầm: 27 trở thành lỗi được phân loại rõ ràng kèm gợi ý schema, và 3 payload hợp lệ thành công. Cùng một mô hình, cùng các công cụ, chỉ khác mức độ hiển thị của thất bại.

Phần này nói về việc làm cho thất bại hiển thị và có thể phục hồi. Không phải bằng cách nhắc mô hình cẩn thận — mà bằng cách từ chối thực thi một lời gọi không thỏa mãn hợp đồng đã khai báo, và bằng cách biến mọi thất bại thành một giá trị có kiểu mà vòng lặp có thể hành động dựa trên đó.

Bạn sẽ xây dựng gì

Một mô-đun contracts.py bao bọc bộ đăng ký công cụ của Phần 1 với bốn phần bổ sung:

  • validate_args(schema, args) — một bộ xác thực tập con JSON Schema trả về danh sách lỗi {path, message} thay vì giá trị boolean, để mô hình được nói chính xác trường nào sai.
  • ErrorCode + ToolError — một hệ thống phân loại đóng gồm tám lớp thất bại, mỗi lớp gắn với một câu hỏi: lần thử thứ hai có khả năng thành công không?
  • RetryPolicy + IdempotencyStore — backoff luỹ thừa có giới hạn kèm jitter, chỉ áp dụng cho các mã có thể thử lại, cộng với khóa băm đối số để một tác dụng phụ được thử lại không thể chạy hai lần.
  • ToolExecutor — nơi gọi duy nhất của Tool.run. Nó xác thực, khử trùng lặp, thực thi trong giới hạn thời gian, phân loại, và thử lại.

AgentLoop giữ nguyên hình dạng từ Phần 1. Phương thức run của nó thay đổi khoảng sáu dòng: lời gọi trực tiếp tool.run(args) trở thành self.executor.execute(name, args), và trace ghi lại các lần thử cùng mã lỗi. Mọi thứ khác — Message, ToolResult, ScriptedLLM, các hình dạng quyết định — vẫn tương thích, vì Phần 3 và Phần 4 mở rộng tệp này thay vì thay thế nó.

Điều kiện tiên quyết

  • Python 3.10 trở lên. Chỉ dùng thư viện chuẩn: concurrent.futures, hashlib, json, random, time, urllib.
  • Tệp của Phần 1, hoặc ít nhất bốn kiểu của nó: Message, ToolResult, Tool, AgentLoop. Nếu bạn bỏ qua, khối bên dưới định nghĩa lại chúng một cách tương thích.
  • Một terminal. Mọi bài kiểm tra ở đây chạy ngoại tuyến trong chưa đến một giây.

Một điểm bỏ qua có chủ ý: validate_args hỗ trợ một tập con của JSON Schema — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum. Tập con này bao phủ những gì schema công cụ thực tế dùng trong thực tiễn. Nó không hỗ trợ $ref, oneOf hay pattern, và giả vờ ngược lại còn tệ hơn là nói thẳng. Nếu bạn cần chúng, đây chính là lúc nên chuyển sang jsonschema hoặc Pydantic; thiết kế executor xung quanh không thay đổi.

Nơi hợp đồng thực sự vỡ

Ba lớp thất bại chiếm gần như mọi thứ có thể sai giữa một mô hình và một công cụ, và chúng cần cách xử lý khác nhau.

Khóa sai, ý định hợp lý. {"q": ...} đối với một schema yêu cầu query. Giá trị mặc định của dict.get trong Python âm thầm cung cấp "". Đây là trường hợp nguy hiểm, vì công cụ thành công mà câu trả lời lại sai.

Khóa đúng, kiểu sai. {"limit": "3"} chạm tới [v for ...][:limit] và raise TypeError: slice indices must be integers. Ở Phần 1, ngoại lệ đó bị AgentLoop.run bắt và chuyển thành ToolResult(ok=False) — nhưng thông báo là TypeError: slice indices must be integers or None or have an __index__ method, thứ không cho mô hình biết đối số nào cần sửa.

Lời gọi đúng, thất bại tạm thời. Một 429 từ backend tìm kiếm, một socket timeout, một 503 từ chỉ mục. Thử lại là đúng. Nhưng thử lại một lời gọi save_note vì phản hồi bị mất sẽ nhân đôi thao tác ghi.

Đây là đoạn thăm dò tôi đã dùng, để bạn có thể tái hiện con số 12 trên 30 thay vì tin suông:

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()

Kết quả: n=30 v1_silent=12 v2_explicit=27 v2_silent=0. Ba thành công còn lại là payload hợp lệ {"query": "agent loop"}, lặp lại ba lần. Một câu trả lời sai một cách âm thầm còn tệ hơn một lỗi, vì nó không thể phân biệt với một kết quả âm đúng, và nó lan vào câu trả lời cuối cùng mà không bị chất vấn.

Một bộ xác thực bạn có thể suy luận được

Bộ xác thực trả về lỗi có cấu trúc, không phải boolean, vì văn bản lỗi chính là chỉ dẫn sửa lỗi mà mô hình đọc ở lượt tiếp theo. Boolean buộc bạn bịa ra một thông báo; một đường dẫn cộng với lý do cho phép bạn sinh thông báo một cách máy móc.

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

Hai chi tiết trong đoạn mã đó không phải để trang trí. Thứ nhất, phần bảo vệ isinstance(value, bool) trên integer và number: trong Python, True là một int có giá trị 1, nên nếu không có nó, {"limit": true} sẽ vượt qua kiểm tra số nguyên và trở thành limit=1. Thứ hai, bộ xác thực không raise ngay ở lỗi đầu tiên — nó thu thập tất cả, rồi báo cáo ba lỗi đầu. Một mô hình đã gửi hai trường sai nên biết cả hai trong một lượt đi-về, chứ không phải hai.

Lỗi chỉ hữu ích nếu chúng đi kèm đích sửa lỗi. Đó là điều describe_schema bổ sung: một chữ ký gọn gàng được suy ra từ chính đối tượng 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)

Thông báo công cụ thu được cho trường hợp {"q": ...} là ERROR[invalid_arguments]: /q unexpected field; /query missing required field. expected {query:string!, limit:integer}. Phần sau expected được sinh từ schema, nên nó không thể lệch khi bạn chỉnh sửa schema. Thuộc tính đó quan trọng hơn cách diễn đạt: gợi ý sửa lỗi viết tay sẽ lỗi thời, còn gợi ý được sinh ra thì không.

Hãy lưu ý cái giá của điều này. additionalProperties: False rất nghiêm ngặt — một nhà cung cấp thêm vào một trường metadata vô hại sẽ fail xác thực. Đó chính là mục đích: một trường ngoài dự kiến nghĩa là hoặc mô hình ảo tưởng ra một tham số, hoặc schema của bạn tụt lại sau mã của bạn, và cả hai đều xứng đáng với một thất bại ồn ào thay vì một cái nhún vai **kwargs.

Lỗi được phân loại thay vì chuỗi

Lỗi dạng chuỗi chỉ có thể được ghi log. Lỗi được phân loại có thể được quyết định dựa trên. Hệ thống phân loại dưới đây được cố ý giữ nhỏ; tám mã bao phủ những thất bại tôi thực sự từng thấy trong các agent dùng công cụ, và mỗi mã ánh xạ tới một hành động.

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

Quy tắc phân loại chỉ là một câu hỏi: một lần thử thứ hai giống hệt, không thay đổi gì, có khả năng thành công không? rate_limited, timeout và upstream_error trả lời là có. invalid_arguments, unknown_tool, not_found, permission_denied và internal_error trả lời là không — ba loại đầu cần một lời gọi khác, hai loại cuối cần con người. Câu hỏi đó là toàn bộ lý do không thử lại mọi thứ: mỗi lần thử lại lãng phí là một bước bị tiêu tốn từ max_steps, và với ba lần thử cho mỗi lời gọi công cụ, ngân sách năm công cụ sụp còn hai.

Tool có thêm ba trường hợp đồng, và phần mô tả giờ đây chịu lực theo cách mà nó chưa từng có ở Phần 1:

@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)

Ba công cụ giờ khai báo schema trung thực, và hai công cụ từng thất bại âm thầm nay thất bại ồn ào. _search raise một ToolError được phân loại thay vì trả về danh sách rỗng khi backend của nó sập, vì một danh sách rỗng và một timeout mang ý nghĩa trái ngược với mô hình:

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 trên query không phải để đẹp. Nó là lá chắn rẻ nhất có thể chống lại trường hợp truy vấn rỗng đã sinh ra cả mười hai thất bại âm thầm: một chuỗi rỗng giờ bị hợp đồng từ chối trước khi thân công cụ kịp nhìn thấy nó.

Thử lại không thể nhân đôi tác dụng phụ

Backoff là nửa dễ. Nửa khó là việc thử lại một thao tác ghi có thể ghi hai lần: yêu cầu thành công, phản hồi bị mất, và lần thử lại của bạn tạo ra một ghi chú thứ hai. Cách sửa là một khóa được suy ra từ tên công cụ và các đối số đã chuẩn hoá, cộng với một quy tắc về những lời gọi nào có thể tái sử dụng kết quả đã cache.

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 chính là thứ làm cho khóa ổn định: {"a": 1, "b": 2} và {"b": 2, "a": 1} là cùng một lời gọi và phải sinh ra cùng một khóa, nếu không lớp bảo vệ sẽ rò rỉ. Jitter cũng không phải thứ xa xỉ — không có nó, mười worker cùng chạm 429 sẽ thử lại đồng bộ và cùng chạm lại một lần nữa; ±25% dàn trải chúng ra.

Executor là nơi bốn mối quan tâm kết hợp với nhau, và thứ tự của nó chính là thiết kế: xác thực, rồi khử trùng lặp, rồi thực thi, rồi phân loại, rồi thử lại. Xác thực trước khử trùng lặp nghĩa là một lời gọi sai dạng không bao giờ chiếm một khóa.

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)

Hai điểm tinh tế đáng gọi tên. Điều kiện tái sử dụng cache là tool.side_effect or not cached.ok: một thao tác ghi có thể tái sử dụng một thành công đã cache (đó là at-most-once), và bất kỳ lời gọi nào cũng có thể tái sử dụng một thất bại đã cache (đó là negative cache, ngăn một mô hình bị kẹt đốt lại quota trên cùng một lời gọi hỏng). Các thành công chỉ đọc được cố ý không cache, vì một tìm kiếm không trả về gì hai phút trước có thể trả về cái gì đó bây giờ, và kết quả đọc lỗi thời là một lớp câu trả lời sai riêng.

Điểm tinh tế thứ hai là timeout. future.result(timeout=...) giới hạn thời gian bạn chờ, không phải thời gian công cụ chạy — Python không thể giết một thread. Một công cụ phớt lờ timeout sẽ tiếp tục đốt CPU ở nền trong khi vòng lặp đi tiếp. Đó là một giới hạn được thừa nhận thẳng thắn, và chính là lý do Phần 11 thay thế nó bằng sandbox cấp tiến trình. Đừng đọc timeout_s như một ranh giới an toàn; hãy đọc nó như một ngân sách độ trễ.

Gắn nó vào vòng lặp, cùng phần thử lại LLM mà ta đã bỏ qua

Phần 1 để lại một lỗ hổng mà tôi đã chỉ rõ: AgentLoop.run bảo vệ tool.run nhưng không bảo vệ llm.complete, nên chỉ một 503 từ endpoint mô hình là đủ giết cả lần chạy. Cùng chính sách đó lấp lỗ hổng này, áp dụng cho các mã trạng thái 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))

Một 401 được raise ngay ở lần thử đầu tiên, chứ không phải lần thứ ba: một khóa xấu vẫn xấu, và ba lần thử chỉ làm độ trễ của bạn gấp ba trước khi thất bại. Một 400 được phân loại là invalid_arguments vì cùng lý do — payload của bạn sai và gửi lại nó là vô ích.

Thay đổi của vòng lặp là nhỏ, và trace là nơi giá trị hiện lên:

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"

Prompt SYSTEM giờ nêu rõ định dạng lỗi. Đó không phải mê tín về prompt-engineering: mô hình được cho biết chuỗi chính xác mà nó sẽ thấy khi thất bại và phải làm gì với chuỗi đó. Nó tốn một câu và giảm đo lường được số lượt bị lãng phí sau một lỗi xác thực, vì đích sửa lỗi nằm ngay trong lỗi.

Chạy nó, và trace đọc như một bản chẩn đoán thay vì một bản ghi chép:

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

Bước 0 cho thấy hợp đồng từ chối lời gọi. Bước 1 cho thấy mô hình phục hồi ở lượt tiếp theo — sự phục hồi đó được gây ra bởi thông báo lỗi, đó là lý do gợi ý được sinh từ schema. Bước 3 cho thấy một yêu cầu ghi giống hệt được phục vụ từ cache với attempts=0: không có tệp thứ hai, không có lời gọi mạng thứ hai.

Các chế độ thất bại và cách xử lý chúng

Thất bại Điều thực sự xảy ra Cách xử lý ở đây Điều gì vẫn hỏng
Mô hình gửi một khóa bị đổi tên additionalProperties: False đánh dấu nó, required nêu tên trường còn thiếu invalid_arguments rõ ràng kèm gợi ý schema; mô hình tự sửa ở lượt tiếp theo Một mô hình phớt lờ gợi ý sẽ đốt hết các bước
Mô hình gửi true cho một số nguyên Python coi bool là int, nên một kiểm tra ngây thơ sẽ qua Phần bảo vệ isinstance(value, bool) từ chối nó Không có gì — lỗ hổng này đã đóng
Công cụ treo Thread vẫn chạy sau khi future vượt thời gian chờ timeout_s trả về timeout, được thử lại đến hết ngân sách Đốt CPU cấp tiến trình; không có kill switch (Phần 11)
Bão 429 Mỗi lần thử lại đều chạm giới hạn Số lần thử có giới hạn, backoff luỹ thừa, jitter ±25% Không có rate limiter liên tiến trình (Phần 12)
Phản hồi bị mất khi ghi Thử lại sẽ nhân đôi tệp Khóa idempotency + side_effect=True trả về thành công đã cache Kho in-memory chết cùng tiến trình (Phần 8)
Cùng một lời gọi hỏng lặp lại Mô hình kẹt trong vòng lặp trên một lỗi Negative cache ngăn thực thi lại Vòng lặp vẫn tiêu tốn bước; cần bộ phát hiện lặp lại
Schema và mã lệch nhau Xác thực từ chối một trường mà công cụ cần describe_schema sinh lại gợi ý từ schema Không gì tự động phát hiện sự lệch nhau

Dòng cuối cùng là dòng từng làm tôi đau. describe_schema chỉ đúng vì cả nó và validate_args đều đọc cùng một dict. Nếu bạn viết tay một bản sao thứ hai của schema trong prompt, hai bản sẽ lệch nhau trong vòng một tháng — và thất bại sẽ trông như một lỗi của mô hình, chứ không phải lỗi bảo trì.

Đánh đổi

Quyết định Phương án thay thế Vì sao chúng ta chọn nó Cái giá
Bộ xác thực tập con tự viết jsonschema hoặc Pydantic Không phụ thuộc, ~120 dòng, lỗi được định hình cho mô hình Không có $ref/oneOf/pattern; bạn phải tự bảo trì
Lỗi là giá trị ToolResult Raise ngoại lệ xuyên suốt vòng lặp Mô hình có thể đọc và sửa; vòng lặp giữ đơn giản Người gọi phải kiểm tra ok ở mọi nơi
additionalProperties: False Cho phép trường thừa Bắt ngay tham số bị ảo tưởng Hỏng khi một nhà cung cấp thêm metadata
Khóa idempotency in-memory Redis hoặc SQLite Một dict, không hạ tầng, dễ kiểm thử Không chia sẻ giữa các worker; mất khi khởi động lại
Timeout theo thread Sandbox theo tiến trình 10 dòng, không cần IPC Không thể giết một công cụ mất kiểm soát (Phần 11)
Chỉ thử lại 3 mã Thử lại mọi thứ một lần Bảo toàn ngân sách bước Một not_found chập chờn không bao giờ được thử lại
Cache kết quả âm Luôn thực thi lại Chặn bão thử lại từ một mô hình đang lặp Một thất bại tạm thời bị phân loại nhầm là vĩnh viễn sẽ ở lại trong cache

Lựa chọn bộ xác thực đáng được soi kỹ nhất. Pydantic sẽ cho bạn coercion, các mô hình lồng nhau, và thông báo lỗi tốt hơn miễn phí — với cái giá là một phụ thuộc, import chậm hơn, và các đối tượng lỗi mà bạn vẫn phải dịch thành văn bản mà mô hình đọc được. Với tám schema công cụ, phiên bản tự viết thắng. Với tám mươi, thì không.

Kiểm thử nó

Mười bốn bài kiểm tra, ngoại tuyến, dưới một phần mười giây. Lưu mô-đun thành contracts.py và các bài kiểm tra thành test_contracts.py; chạy python3 -m unittest test_contracts -v. Bộ kiểm tra đầy đủ nằm trong repository, nhưng năm bài sau đây mang toàn bộ thiết kế:

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 trông như một chi tiết vặt và không phải vậy: đó là dòng duy nhất đứng giữa {"limit": true} và một tập kết quả bị cắt ngắn một cách âm thầm. test_side_effect_runs_once_per_key là bài kiểm tra duy nhất bảo vệ dữ liệu thay vì độ trễ. Nếu bạn chỉ giữ lại hai bài kiểm tra, hãy giữ hai bài đó.

Một phép kiểm tra nữa đáng chạy tay: trỏ Flaky vào RATE_LIMITED với max_attempts=99 và xác nhận executor dừng ở giới hạn của chính sách. Một vòng lặp thử lại không có giới hạn là một sự cố kèm các bước thừa.

Bài tập

  1. Idempotency liên tiến trình. Thay IdempotencyStore bằng phiên bản dựa trên SQLite, khóa theo (name, args_hash) và dấu thời gian created_at. Hết hạn các khóa cũ hơn mười phút. Điều gì thay đổi ở chế độ thất bại khi một tiến trình chết giữa chừng thao tác ghi, và vì sao TTL cần dài hơn cửa sổ thử lại dài nhất của bạn?
  2. Ghi đè thử lại theo từng công cụ. Một backend tìm kiếm rate-limit rất hà khắc; một thao tác ghi ghi chú nên được thử lại nhiều nhất một lần. Thêm trường policy vào Tool để ghi đè mặc định của executor, và viết một bài kiểm tra chứng minh một lời gọi save_note dưới điều kiện 429 trả về sau hai lần thử, chứ không phải bốn.
  3. Coercion kèm biên nhận. Thay vì từ chối {"limit": "3"}, hãy chấp nhận nó, chuyển thành 3, và nối một ghi chú vào kết quả công cụ: coerced: limit "3" -> 3. Đo xem điều đó tiết kiệm bao nhiêu lượt trên một trace 50 lời gọi. Cái nào nguy hiểm hơn — coercion âm thầm hay một lời gọi bị từ chối — và biên nhận thay đổi điều gì?

Bài tập 3 là bài thú vị vì nó không có một câu trả lời đúng duy nhất. Coercion giảm số lượt đi-về và che giấu lỗi của mô hình; từ chối thì ồn ào và chậm hơn. Biên nhận là thỏa hiệp: bạn lấy lại lượt đi-về và giữ một dấu vết kiểm toán về mọi giả định bạn đã thay mặt mô hình đưa ra.

Bước tiếp theo

Các công cụ của bạn giờ có hợp đồng, các thất bại của bạn có mã, và các lần thử lại của bạn không thể nhân đôi một thao tác ghi. Điều chưa thay đổi kể từ Phần 1 là thứ sẽ đau đầu tiên trong môi trường sản xuất: danh sách tin nhắn lớn lên sau mỗi bước, và mọi tin nhắn trước đó được gửi lại toàn vẹn trong mỗi lời gọi.

Phần 3, Kỹ thuật ngân sách ngữ cảnh, bổ sung một ContextBudget đo token trước mỗi lời gọi, phân bổ cửa sổ giữa system prompt, kết quả công cụ và lịch sử, và nén các lượt cũ khi ước lượng vượt ngân sách. Nó cũng lượng hoá sự tăng trưởng bình phương của đầu vào từ bảng ở Phần 1 và cho thấy trong ba chiến lược nén — cắt ngắn, tóm tắt, loại bỏ — chiến lược nào thực sự đáng tiền. ToolExecutor bạn vừa xây giữ nguyên y như cũ; ngân sách bọc lấy lịch sử, không phải các công cụ.

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.