Back to all articlesAI และเอเจนต์

สัญญาเครื่องมือของ Agent และข้อผิดพลาดแบบมีโครงสร้าง (ตอนที่ 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

ตอนที่ 1 จบลงด้วยลูปที่หยุดได้และทะเบียนเครื่องมือที่เชื่อถือทุกสิ่งที่โมเดลพูด ความเชื่อถือนี้คือบั๊กถัดไป ใน _search ของตอนที่ 1 บรรทัดแรกคือ query = str(args.get("query", "")).lower() หากโมเดลส่ง {"q": "agent loop"} แทน {"query": "agent loop"} จะไม่มีอะไรถูกยกขึ้น query จะกลายเป็นสตริงว่าง การค้นหาในคลังข้อมูลไม่พบอะไร และเครื่องมือจะคืน ["no matches"] โมเดลอ่านสิ่งนี้เป็นหลักฐานว่าคลังข้อมูลว่างเปล่าแล้วตอบตามนั้น ไม่มีข้อผิดพลาด ไม่มีบรรทัด log และไม่มีวิธีแยกผลลัพธ์ที่ว่างจริงออกจากการพิมพ์คีย์ JSON ผิด

ฉันรันการเปรียบเทียบนี้พอดีขณะเขียนบทความนี้: payload อาร์กิวเมนต์ที่ผิดรูปแบบสามสิบชุดที่โมเดลจริงๆ สร้างขึ้น — คีย์ที่เปลี่ยนชื่อ, คีย์ที่ขึ้นตัวพิมพ์ใหญ่, สตริงในตำแหน่งที่ควรเป็นจำนวนเต็ม, ลิสต์แทนสตริง, null — ถูกส่งผ่านเครื่องมือในตอนที่ 1 และผ่านเวอร์ชันที่เราสร้างที่นี่ ตอนที่ 1 ให้ผลลัพธ์ว่างที่ดูน่าเชื่อถือสำหรับ 12 ใน 30 เวอร์ชันสัญญาให้ผลลัพธ์ที่เงียบ 0 ราย: 27 รายกลายเป็นข้อผิดพลาดที่ชัดเจนและจัดหมวดหมู่พร้อมคำแนะนำ schema และ payload ที่ถูกต้อง 3 รายสำเร็จ โมเดลเดียวกัน เครื่องมือเหมือนกัน ความชัดเจนของความล้มเหลวต่างกัน

ตอนนี้เกี่ยวกับการทำให้ความล้มเหลวมองเห็นได้และกู้คืนได้ ไม่ใช่ด้วยการบอกให้โมเดลระวัง — แต่ด้วยการปฏิเสธการรันคอลที่ไม่เป็นไปตามสัญญาที่ประกาศไว้ และการเปลี่ยนความล้มเหลวทุกอย่างเป็นค่าที่มีชนิดซึ่งลูปสามารถดำเนินการต่อได้

สิ่งที่คุณจะสร้าง

โมดูล contracts.py ที่ห่อทะเบียนเครื่องมือจากตอนที่ 1 ด้วยสิ่งเพิ่มเติมสี่อย่าง:

  • validate_args(schema, args) — ตัวตรวจสอบชุดย่อยของ JSON Schema ที่คืนรายการข้อผิดพลาด {path, message} แทนค่า boolean เพื่อให้บอกโมเดลได้อย่างชัดเจนว่าช่องใดผิด
  • ErrorCode + ToolError — ระบบจัดหมวดหมู่แบบปิดของความล้มเหลวแปดประเภท โดยแต่ละประเภทมีคำถามแนบอยู่: การลองครั้งที่สองอาจสำเร็จได้หรือไม่?
  • RetryPolicy + IdempotencyStore — exponential backoff แบบมีขอบเขตพร้อม jitter ใช้เฉพาะกับโค้ดที่ลองใหม่ได้ บวกด้วยคีย์จากแฮชอาร์กิวเมนต์เพื่อไม่ให้ผลข้างเคียงที่ถูกลองใหม่รันสองครั้ง
  • ToolExecutor — ผู้เรียก Tool.run เพียงรายเดียว ทำการตรวจสอบ, กำจัดซ้ำ, รันภายใต้ timeout, จัดหมวดหมู่ และลองใหม่

AgentLoop ยังคงรูปแบบจากตอนที่ 1 เมธอด run เปลี่ยนไปประมาณหกบรรทัด: tool.run(args) โดยตรงกลายเป็น self.executor.execute(name, args) และ trace บันทึกจำนวนครั้งที่ลองและโค้ดข้อผิดพลาด สิ่งอื่นทั้งหมด — Message, ToolResult, ScriptedLLM, รูปแบบของการตัดสินใจ — ยังเข้ากันได้ เพราะตอนที่ 3 และตอนที่ 4 ขยายไฟล์นี้แทนที่จะแทนที่

สิ่งที่ต้องมีก่อน

  • Python 3.10 ขึ้นไป เฉพาะ standard library: 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 เป็นทางเลือกที่ถูกต้อง การออกแบบ executor รอบๆ ไม่เปลี่ยนแปลง

จุดที่สัญญาแตกจริง

ความล้มเหลวสามประเภทคิดเป็นสัดส่วนเกือบทั้งหมดของสิ่งที่ผิดพลาดระหว่างโมเดลกับเครื่องมือ และต้องการการจัดการที่ต่างกัน

คีย์ผิดแต่ความตั้งใจดูสมเหตุสมผล {"q": ...} กับ schema ที่ต้องการ query ค่าเริ่มต้นของ dict.get ใน Python คือ "" ที่ถูกเติมเข้ามาเงียบๆ นี่คืออันตรายที่สุด เพราะเครื่องมือสำเร็จและคำตอบผิด

คีย์ถูกแต่ชนิดผิด {"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 จาก backend การค้นหา, socket timeout, หรือ 503 จากดัชนี การลองใหม่ถูกต้อง แต่การลองใหม่คอล save_note เพราะตอบหายไปจะทำให้เขียนซ้ำ

นี่คือการทดสอบที่ฉันใช้ เพื่อให้คุณสร้างเลข 12 ใน 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 ความสำเร็จที่เหลืออีกสามรายคือ payload ที่ถูกต้อง {"query": "agent loop"} ที่ถูกทำซ้ำสามครั้ง คำตอบที่ผิดแบบเงียบแย่กว่าข้อผิดพลาดเพราะแยกไม่ออกจากผลลัพธ์เชิงลบที่ถูกต้อง และมันแพร่เข้าสู่คำตอบสุดท้ายโดยไม่มีใครทักท้วง

ตัวตรวจสอบที่คุณสามารถใช้เหตุผลกับมันได้

ตัวตรวจสอบคืนข้อผิดพลาดแบบมีโครงสร้าง ไม่ใช่ค่า boolean เพราะข้อความข้อผิดพลาดคือคำสั่งซ่อมแซมที่โมเดลอ่านในเทิร์นถัดไป ค่า boolean บังคับให้คุณประดิษฐ์ข้อความขึ้นมาเอง เส้นทางและเหตุผลทำให้คุณสร้างข้อความได้โดยอัตโนมัติ

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 คือ int ที่มีค่า 1 มิฉะนั้น {"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

ข้อผิดพลาดแบบจัดหมวดหมู่แทนสตริง

ข้อผิดพลาดแบบสตริงถูกบันทึก log ได้ ข้อผิดพลาดแบบจัดหมวดหมู่สามารถ ตัดสินใจ จากมันได้ ระบบจัดหมวดหมู่ด้านล่างตั้งใจให้เล็ก โค้ดแปดตัวครอบคลุมความล้มเหลวที่ฉันเห็นจริงใน 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 ได้ฟิลด์สัญญาสามตัว และคำอธิบายตอนนี้สำคัญในแบบที่ไม่เคยเป็นในตอนที่ 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)

เครื่องมือทั้งสามตอนนี้ประกาศ schema ที่ซื่อสัตย์ และสองตัวที่เคยล้มเหลวแบบเงียบตอนนี้ล้มเหลวอย่างชัดเจน เมื่อ backend ล่ม _search จะยก ToolError แบบจัดหมวดหมู่แทนการคืนรายการว่าง เพราะรายการว่างกับ timeout มีความหมายตรงข้ามสำหรับโมเดล:

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 ไม่ใช่ของตกแต่ง เป็นการป้องกันที่ถูกที่สุดสำหรับกรณี query ว่างที่ก่อให้เกิดความล้มเหลวเงียบทั้งสิบสองราย สตริงว่างตอนนี้ถูกสัญญาปฏิเสธก่อนที่เนื้อหาของเครื่องมือจะได้เห็นมัน

การลองใหม่ที่ไม่ทำซ้ำผลข้างเคียง

backoff คือครึ่งที่ง่าย ครึ่งที่ยากคือการลองใหม่การเขียนอาจเขียนสองครั้ง: คำขอสำเร็จ แต่ตอบหายไป และการลองใหม่ของคุณสร้างโน้ตที่สอง วิธีแก้คือคีย์ที่ได้จากชื่อเครื่องมือและอาร์กิวเมนต์ที่ทำให้เป็นรูปแบบมาตรฐาน บวกกฎว่าคอลใดอาจใช้ผลลัพธ์จากแคชซ้ำได้

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} คือการเรียกเดียวกันและต้องให้คีย์เดียวกัน มิฉะนั้นการป้องกันจะรั่ว Jitter ก็ไม่ใช่เรื่องฟุ่มเฟือย — หากไม่มีมัน คนงานสิบคนที่ชน 429 เดียวกันจะลองใหม่พร้อมกันแบบ lockstep และชนอีกครั้ง ±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) และคอลใดๆ อาจใช้ ความล้มเหลว ที่แคชไว้ซ้ำได้ (นี่คือแคชเชิงลบ ซึ่งหยุดโมเดลที่ติดอยู่ไม่ให้เผยโควต้าซ้ำกับคอลที่พังเดิม) ความสำเร็จแบบอ่านอย่างเดียวตั้งใจไม่แคช เพราะการค้นหาที่ไม่พบอะไรเมื่อสองนาทีก่อนอาจพบอะไรตอนนี้ และการอ่านที่ล้าสมัยก็คือคำตอบผิดอีกประเภทหนึ่ง

รายละเอียดอ่อนที่สองคือ timeout future.result(timeout=...) จำกัดระยะเวลาที่ คุณ รอ ไม่ใช่ระยะที่เครื่องมือรัน — Python ไม่สามารถฆ่า thread ได้ เครื่องมือที่เพิกเฉยต่อ timeout จะยังเผา CPU ในพื้นหลังต่อไปแม้ลูปจะเดินหน้าแล้ว นี่คือข้อจำกัดที่ซื่อสัตย์ และเป็นเหตุผลที่ตอนที่ 11 แทนที่ด้วย sandbox ระดับ process อย่าอ่าน timeout_s เป็นขอบเขตความปลอดภัย ให้อ่านเป็นงบ latency

การเชื่อมเข้ากับลูป และการลองใหม่ LLM ที่เราข้ามไป

ตอนที่ 1 ทิ้งช่องว่างที่ฉันตั้งใจชี้ไว้: AgentLoop.run ป้องกัน tool.run แต่ไม่ป้องกัน llm.complete ดังนั้น 503 เดียวจากจุดเชื่อมต่อโมเดลจะฆ่าการรันทั้งหมด นโยบายเดียวกันปิดช่องว่างนี้ โดยใช้กับ HTTP status code

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 ด้วยเหตุผลเดียวกัน — payload ของคุณผิดและการส่งซ้ำไร้ความหมาย

การเปลี่ยนแปลงในลูปมีน้อย และคุณค่าปรากฏใน 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 ตอนนี้ระบุรูปแบบข้อผิดพลาด นี่ไม่ใช่ความลี้ลับของ prompt engineering: โมเดลได้รับบอกอย่างชัดเจนว่าสตริงไหนจะเห็นเมื่อล้มเหลวและจะทำอย่างต่อได้ ค่าใช้จ่ายคือประโยคเดียว และมันลดจำนวนเทิร์นที่ใช้ไปกับการดิ้นรนหลังข้อผิดพลาดตรวจสอบอย่างที่วัดได้ เพราะเป้าหมายการซ่อมอยู่ในข้อผิดพลาดเอง

รันมัน แล้ว 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=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 ระบุช่องที่หาย invalid_arguments ชัดเจนพร้อมคำแนะนำ schema; โมเดลซ่อมในเทิร์นถัดไป โมเดลที่เพิกเฉยคำแนะนำจะเผาขั้นตอนทั้งหมด
โมเดลส่ง true สำหรับจำนวนเต็ม Python ถือ bool เป็น int ดังนั้นการตรวจแบบธรรมดาผ่าน การป้องกัน isinstance(value, bool) ปฏิเสธ ไม่มีอะไร — ปิดแล้ว
เครื่องมือค้าง thread ยังรันต่อหลัง future หมด timeout timeout_s คืน timeout, ลองใหม่จนถึง budget เผา CPU ระดับ process; ไม่มี kill switch (ตอนที่ 11)
พายุ 429 ทุกครั้งชนขีดจำกัดซ้ำ จำนวนครั้งมีขอบ, exponential backoff, jitter ±25% ไม่มีตัวจำกัดอัตราข้าม process (ตอนที่ 12)
ตอบหายระหว่างเขียน การลองใหม่จะทำให้ไฟล์ซ้ำ คีย์ idempotency + side_effect=True คืนความสำเร็จจากแคช ที่เก็บในหน่วยความจำตายไปกับ process (ตอนที่ 8)
คอลที่พังเดิมถูกทำซ้ำ โมเดลวนอยู่กับข้อผิดพลาดเดียว แคชเชิงลบหยุดการรันซ้ำ ลูปยังใช้ขั้นตอนอยู่ ต้องการตัวตรวจจับการซ้ำ
schema กับโค้ดเบี่ยงกัน การตรวจปฏิเสธฟิลด์ที่เครื่องมือต้องการ describe_schema สร้างคำแนะนำจาก schema ใหม่ ไม่มีอะไรตรวจจับการเบี่ยงโดยอัตโนมัติ

แถวสุดท้ายคือแถวที่กัดฉัน describe_schema ถูกต้องก็เพราะมันและ validate_args อ่าน dict ตัวเดียวกัน หากคุณเขียน schema สำเนาที่สองในพรอมต์ด้วยมือ ทั้งสองจะแยกกันภายในหนึ่งเดือน — และความล้มเหลวจะดูเหมือนข้อผิดพลาดของโมเดล ไม่ใช่ข้อผิดพลาดของการบำรุงรักษา

ข้อแลกเปลี่ยน

การตัดสินใจ ทางเลือกอื่น เหตุผลที่เราเลือก ค่าใช้จ่าย
ตัวตรวจสอบชุดย่อยแบบทำเอง jsonschema หรือ Pydantic ไม่มี dependency, ~120 บรรทัด, ข้อผิดพลาดรูปแบบสำหรับโมเดล ไม่มี $ref/oneOf/pattern; คุณต้องดูแลเอง
ข้อผิดพลาดเป็นค่า ToolResult ยกข้อยกเว้นผ่านลูป โมเดลอ่านและซ่อมได้; ลูปยังง่าย ผู้เรียกต้องเช็ค ok ทุกที่
additionalProperties: False อนุญาตฟิลด์เพิ่ม จับพารามิเตอร์ที่แต่งขึ้นทันที พังเมื่อผู้ให้บริการเพิ่ม metadata
คีย์ idempotency ในหน่วยความจำ Redis หรือ SQLite dict เดียว ไม่มีโครงสร้างพื้นฐาน ทดสอบได้ ไม่แชร์ข้ามคนงาน; หายตอนรีสตาร์ท
timeout แบบ thread sandbox ระดับ process 10 บรรทัด ไม่มี IPC ฆ่าเครื่องมือที่ควบคุมไม่ได้ไม่ได้ (ตอนที่ 11)
ลองใหม่เฉพาะ 3 โค้ด ลองทุกอย่างหนึ่งครั้ง รักษางบขั้นตอน not_found ที่เสถียรไม่เคยถูกลองใหม่
แคชผลลัพธ์เชิงลบ รันใหม่เสมอ หยุดพายุลองใหม่จากโมเดลที่วน ความล้มเหลวชั่วคราวที่จัดผิดยังคงอยู่ในแคช

การเลือกตัวตรวจสอบสมควรถูกตรวจสอบมากที่สุด Pydantic จะให้ coercion, โมเดลซ้อน, และข้อความข้อผิดพลาดที่ดีกว่าฟรีๆ — ด้วยราคาของ dependency, การ import ที่ช้าลง, และออบเจกต์ข้อผิดพลาดที่คุณยังต้องแปลเป็นข้อความที่โมเดลอ่านอยู่ดี ที่ schema ของเครื่องมือแปดตัว เวอร์ชันทำเองชนะ ที่แปดสิบตัวไม่ชนะ

การทดสอบ

การทดสอบสิบสี่รายการ ออฟไลน์ ต่ำกว่าหนึ่งในสิบของวินาที บันทึกโมดูลเป็น contracts.py และการทดสอบเป็น test_contracts.py รัน python3 -m unittest test_contracts -v ชุดเต็มอยู่ใน repository แต่ห้ารายการนี้คือแกนของการออกแบบ:

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. idempotency ข้าม process แทนที่ IdempotencyStore ด้วยเวอร์ชันที่ใช้ SQLite เป็นหลัง โดยมีคีย์ (name, args_hash) และ timestamp created_at ให้หมดอายุคีย์ที่เก่ากว่าสิบนาที อะไรเปลี่ยนไปในโหมดความล้มเหลวที่ process ตายกลางการเขียน และทำไม TTL ต้องยาวกว่าช่วงลองใหม่ที่ยาวที่สุดของคุณ?
  2. การ overriding การลองใหม่ต่อเครื่องมือ backend การค้นหาจำกัดอัตราอย่างรุนแรง การเขียนโน้ตควรลองใหม่ได้มากสุดหนึ่งครั้ง เพิ่มฟิลด์ policy ใน Tool ที่ overriding ค่าเริ่มต้นของ executor และเขียนการทดสอบที่พิสูจน์ว่าคอล save_note ภายใต้ 429 คืนหลังสองครั้ง ไม่ใช่สี่ครั้ง
  3. coercion พร้อมใบรับรอง แทนการปฏิเสธ {"limit": "3"} ให้ยอมรับ แปลงเป็น 3 และเพิ่มโน้ตในผลลัพธ์ของเครื่องมือ: coerced: limit "3" -> 3 วัดว่าประหยัดเทิร์นไปกี่เทิร์นใน trace 50 คอล อันไหนอันตรายกว่ากัน — coercion แบบเงียบหรือคอลที่ถูกปฏิเสธ — และใบรับรองเปลี่ยนอะไร?

แบบฝึกหัดที่ 3 น่าสนใจเพราะไม่มีคำตอบที่ถูกต้องเพียงเดียว Coercion ลดรอบไปกลับและซ่อนข้อผิดพลาดของโมเดล การปฏิเสธดังและช้ากว่า ใบรับรองคือข้อประนีประนอม: คุณได้รอบไปกลับคืนและยังมีบันทึกตรวจสอบทุกข้อสันนิษฐานที่คุณทำแทนโมเดล

สิ่งถัดไป

เครื่องมือของคุณมีสัญญาแล้ว ความล้มเหลวมีโค้ดแล้ว และการลองใหม่ของคุณทำซ้ำการเขียนไม่ได้แล้ว สิ่งที่ไม่เปลี่ยนแปลงตั้งแต่ตอนที่ 1 คือสิ่งที่จะเจ็บก่อนใน production: รายการข้อความโตขึ้นทุกขั้นตอน และข้อความเก่าทุกข้อความถูกส่งใหม่เต็มๆ ทุกครั้งที่เรียก

ตอนที่ 3, Context budget engineering, เพิ่ม ContextBudget ที่วัด token ก่อนทุกการเรียก จัดสรรหน้าต่างระหว่าง system prompt, ผลลัพธ์เครื่องมือ และประวัติ และบีบอัดเทิร์นเก่าเมื่อการประมาณเกินงบ มันยังวัดปริมาณการเติบโตแบบ quadratic ของ input จากตารางในตอนที่ 1 และแสดงให้เห็นว่ากลยุทธ์การบีบอัดสามแบบ — truncate, summarise, evict — แบบไหนคุ้มค่าจริง ToolExecutor ที่คุณเพิ่งสร้างยังคงเหมือนเดิม งบเป็นสิ่งที่ห่อประวัติ ไม่ใช่เครื่องมือ

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.