חוזים של כלי Agent ושגיאות מובנות (חלק 2)
A contract you can reason about
A guarded tool call
Errors are data. The loop decides what to do with them.
- 01
call dictname + args - 02
validate against schemareject before any side effect - 03
retry? classifiedtransient only, idempotent - 04
execute onceguarded, logged - 05
ToolResult(ok/error)typed and classified - 06
append to historyLLM sees the error
חלק 1 הסתיים עם לולאה שמסתיימת בזמן ורישום כלים שסומך על כל מה שהמודל אומר. האמון הזה הוא הבאג הבא. ב-_search של חלק 1, השורה הראשונה הייתה query = str(args.get("query", "")).lower(). אם המודל שולח {"q": "agent loop"} במקום {"query": "agent loop"}, שום דבר לא נזרק. השאילתה הופכת למחרוזת ריקה, חיפוש בקורפוס לא מוצא כלום, והכלי מחזיר ["no matches"]. המודל קורא את זה כהוכחה שהקורפוס ריק ועונה בהתאם. אין שגיאה, אין שורת לוג, ואין דרך להבדיל בין תוצאה ריקה אמיתית לטעות הקלדה במפתח JSON.
הרצתי בדיוק את ההשוואה הזו בזמן כתיבת המאמר: שלושים מטעני פרמטרים פגומים שמודל אמיתי מייצר בפועל — מפתחות ששונו, מפתחות באותיות רישיות, מחרוזת במקום מספר שלם, רשימה במקום מחרוזת, null — שהועברו דרך הכלי של חלק 1 ודרך הגרסה שאנחנו בונים כאן. חלק 1 הפיק תוצאה ריקה שנראתה סבירה עבור 12 מתוך 30. גרסת החוזה הפיקה 0 תוצאות שקטות: 27 הפכו לשגיאות מפורשות ומסווגות עם רמז סכמה, ו-3 המטענים התקינים הצליחו. אותו מודל, אותם כלים, נראות שגיאות שונה.
החלק הזה עוסק בהפיכת הכישלון לגלוי ולניתן להחלמה. לא על ידי בקשה מהמודל להיזהר — אלא על ידי סירוב להריץ קריאה שאינה עומדת בחוזה מוצהר, ועל ידי הפיכת כל כישלון לערך טיפוסי שהלולאה יכולה לפעול לפיו.
מה תבנו
מודול contracts.py שעוטף את רישום הכלים מחלק 1 עם ארבע תוספות:
validate_args(schema, args)— מאמת משנה של JSON Schema שמחזיר רשימת שגיאות מהצורה{path, message}במקום ערך בוליאני, כך שאפשר לומר למודל בדיוק איזה שדה שגוי.ErrorCode+ToolError— טקסונומיה סגורה של שמונה מחלקות כישלון, עם שאלה אחת המחוברת לכל אחת: האם ניסיון שני יכול בהחלט להצליח?RetryPolicy+IdempotencyStore— השהיה מעריכית חסומה עם jitter, המוחלת רק על קודים ניתנים לניסיון חוזר, ובנוסף מפתחות גיבוב של פרמטרים כדי שתופעת לוואי שנוסתה שוב לא תרוץ פעמיים.ToolExecutor— הקורא היחיד שלTool.run. הוא מאמת, מבטל כפילויות, מריץ תחת פסק זמן, מסווג ומנסה שוב.
AgentLoop שומר על הצורה שלו מחלק 1. שיטת ה-run שלו משתנה בכשש שורות: הקריאה הישירה tool.run(args) הופכת ל-self.executor.execute(name, args), והמעקב רושם ניסיונות וקודי שגיאה. כל השאר — Message, ToolResult, ScriptedLLM, צורות ההחלטה — נשאר תואם, כי חלק 3 וחלק 4 מרחיבים את הקובץ הזה במקום להחליף אותו.
דרישות מוקדמות
- Python 3.10 או חדש יותר. ספריית התקן בלבד:
concurrent.futures,hashlib,json,random,time,urllib. - קובץ חלק 1, או לפחות את ארבעת הטיפוסים שלו:
Message,ToolResult,Tool,AgentLoop. אם דילגתם עליו, הבלוק למטה מגדיר אותם מחדש בצורה תואמת. - מסוף טרמינל. כל הבדיקות כאן רצות אופליין בפחות משנייה.
השמטה מכוונת אחת: validate_args תומך בתת-קבוצה של JSON Schema — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum. תת-הקבוצה הזו מכסה את מה שסכמות כלים אמיתיות משתמשות בו בפועל. היא אינה תומכת ב-$ref, oneOf או pattern, והעמדת פנים שהיא כן תהיה גרועה מלהודות בכך. אם אתם צריכים אותן, זו בדיוק הנקודה שבה כדאי לפנות ל-jsonschema או ל-Pydantic; עיצוב המבצע סביבם לא משתנה.
היכן החוזה באמת נשבר
שלוש מחלקות כישלון מהוות כמעט את כל מה שמשתבש בין מודל לכלי, וכל אחת זקוקה לטיפול שונה.
מפתח שגוי, כוונה סבירה. {"q": ...} מול סכמה הדורשת query. ברירת המחדל של dict.get מספקת "" בשקט. זה המקרה המסוכן, כי הכלי מצליח והתשובה שגויה.
מפתח נכון, טיפוס שגוי. {"limit": "3"} מגיע אל [v for ...][:limit] וזורק TypeError: slice indices must be integers. בחלק 1 החריגה הזו נתפסת על ידי AgentLoop.run ומומרת ל-ToolResult(ok=False) — אבל ההודעה היא TypeError: slice indices must be integers or None or have an __index__ method, שלא אומרת למודל כלום על איזה פרמטר לתקן.
קריאה תקינה, כישלון חולף. 429 ממנוע החיפוש, פסק זמן של socket, 503 מאינדקס. ניסיון חוזר הוא הדבר הנכון. אבל ניסיון חוזר של קריאת save_note כי התגובה אבדה משכפל את הכתיבה.
הנה הבדיקה שהשתמשתי בה, כדי שתוכלו לשחזר את המספר 12 מתוך 30 ולא לקחת אותו על אמון:
import jsonfrom contracts import ToolExecutor, ToolResult, build_tools
def search_v1(args: dict) -> ToolResult: query = str(args.get("query", "")).lower() corpus = { "agent loop": "An agent loop repeats: observe, decide, act, observe.", "token budget": "Context windows are finite; budget them explicitly.", "stop condition": "A step limit is a stop condition, not a strategy.", "retry": "Retry only failures that are transient; never retry a 400.", } hits = [v for key, v in corpus.items() if key in query] return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
PAYLOADS = [ {"query": "agent loop"}, {"q": "agent loop"}, {"Query": "agent loop"}, {"query": "agent loop", "top_k": 3}, {"query": ["agent loop"]}, {"query": "agent loop", "limit": "3"}, {"query": "agent loop", "limit": 0}, {"query": ""}, {"query": "agent loop", "limit": True}, {"query": None},]
def probe() -> None: cases = (PAYLOADS * 3)[:30] executor = ToolExecutor({t.name: t for t in build_tools()}, sleep=lambda d: None) silent_v1 = silent_v2 = explicit_v2 = 0 for args in cases: old = search_v1(args) new = executor.execute("search", args) if old.ok and json.loads(old.data) == ["no matches"]: silent_v1 += 1 if not new.ok: explicit_v2 += 1 elif json.loads(new.data) == ["no matches"]: silent_v2 += 1 print("n=%d v1_silent=%d v2_explicit=%d v2_silent=%d" % (len(cases), silent_v1, explicit_v2, silent_v2))
if __name__ == "__main__": probe()פלט: n=30 v1_silent=12 v2_explicit=27 v2_silent=0. שלוש ההצלחות הנותרות הן המטען התקין {"query": "agent loop"}, שחוזר שלוש פעמים. תשובה שגויה שקטה גרועה משגיאה כי היא אינה ניתנת להבחנה מתוצאה שלילית נכונה, והיא מגלשת לתשובה הסופית ללא עוררין.
מאמת שאפשר לחשוב עליו
המאמת מחזיר שגיאות מובנות ולא בוליאני, כי טקסט השגיאה הוא הוראת התיקון שהמודל קורא בתור הבא שלו. בוליאני מחייב אתכם להמציא הודעה; נתיב וסיבה מאפשרים לייצר אחת באופן מכני.
from __future__ import annotationsfrom dataclasses import dataclass, replacefrom typing import Any, Callableimport json
@dataclassclass Message: role: str # "system" | "user" | "assistant" | "tool" content: str name: str | None = None # tool name, required when role == "tool"
@dataclassclass ToolResult: ok: bool data: str error: str | None = None error_code: str | None = None attempts: int = 1 from_cache: bool = False
def to_message(self, name: str) -> Message: if self.ok: payload = self.data else: payload = "ERROR[%s]: %s" % (self.error_code or "unknown", self.error or "") return Message(role="tool", content=payload, name=name)
def validate_args(schema: dict, args: Any) -> list[dict]: """Validate a JSON Schema subset. Returns [] or a list of {path, message}.""" errors: list[dict] = []
def walk(sch: dict, value: Any, path: str) -> None: t = sch.get("type") if t == "object": if not isinstance(value, dict): errors.append({"path": path or "/", "message": "expected object"}) return props = sch.get("properties", {}) for req in sch.get("required", []): if req not in value: errors.append({"path": path + "/" + req, "message": "missing required field"}) if sch.get("additionalProperties") is False: for key in value: if key not in props: errors.append({"path": path + "/" + str(key), "message": "unexpected field"}) for key, sub in props.items(): if key in value: walk(sub, value[key], path + "/" + key) return if t == "array": if not isinstance(value, list): errors.append({"path": path, "message": "expected array"}) return item_schema = sch.get("items", {}) for i, item in enumerate(value): walk(item_schema, item, path + "/" + str(i)) return if t == "string": if not isinstance(value, str): errors.append({"path": path, "message": "expected string"}) return elif t == "integer": if isinstance(value, bool) or not isinstance(value, int): errors.append({"path": path, "message": "expected integer"}) return elif t == "number": if isinstance(value, bool) or not isinstance(value, (int, float)): errors.append({"path": path, "message": "expected number"}) return elif t == "boolean": if not isinstance(value, bool): errors.append({"path": path, "message": "expected boolean"}) return if "enum" in sch and value not in sch["enum"]: errors.append({"path": path, "message": "must be one of " + repr(sch["enum"])}) if "minLength" in sch and isinstance(value, str) and len(value) < sch["minLength"]: errors.append({"path": path, "message": "shorter than minLength %d" % sch["minLength"]}) if "maxLength" in sch and isinstance(value, str) and len(value) > sch["maxLength"]: errors.append({"path": path, "message": "longer than maxLength %d" % sch["maxLength"]}) if "minimum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value < sch["minimum"]: errors.append({"path": path, "message": "below minimum %s" % sch["minimum"]}) if "maximum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool): if value > sch["maximum"]: errors.append({"path": path, "message": "above maximum %s" % sch["maximum"]})
walk(schema, args, "") return errorsשני פרטים בקוד הזה אינם דקורטיביים. ראשית, ההגנות isinstance(value, bool) ב-integer וב-number: בפייתון True הוא int עם הערך 1, ולכן {"limit": true} אחרת היה עובר בדיקת מספר שלם והופך ל-limit=1. שנית, המאמת אינו זורק על השגיאה הראשונה — הוא אוסף את כולן ומדווח על שלוש הראשונות. מודל ששלח שני שדות פגומים צריך ללמוד על שניהם במסע אחד, לא בשניים.
השגיאות שימושיות רק אם הן מגיעות עם יעד תיקון. זה בדיוק מה ש-describe_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 נוצר מהסכמה, ולכן הוא אינו יכול להתיישן כשאתם עורכים את הסכמה. התכונה הזו חשובה יותר מהניסוח: רמזי תיקון שנכתבים ידנית מתיישנים, כאלה שנוצרים אוטומטית לא.
שימו לב למה זה עולה. additionalProperties: False הוא קפדני — ספק שמוסיף שדה מטא-דאטה חף מפשע ייכשל באימות. זו המטרה: שדה בלתי צפוי משמעותו שהמודל המציא פרמטר או שהסכמה שלכם מאחורי הקוד שלכם, ושני המקרים ראויים לכישלון רועש ולא למחוות כתפיים של **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 מקבל שלושה שדות חוזה, והתיאור הוא עכשיו אלמנט נושא עומס באופן שלא היה בחלק 1:
@dataclassclass Tool: name: str description: str parameters: dict[str, Any] # JSON Schema _fn: Callable[[dict], ToolResult] side_effect: bool = False # True -> executed at most once per idempotency key timeout_s: float = 5.0
def spec(self) -> dict: return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.parameters, }, }
def run(self, args: dict) -> ToolResult: return self._fn(args)שלושת הכלים מצהירים עכשיו על סכמות כנות, והשניים שנכשלו בשקט קודם נכשלים עכשיו ברעש. _search זורק ToolError מסווג במקום להחזיר רשימה ריקה כשה-backend שלו מושבת, כי רשימה ריקה ופסק זמן מסמנים דברים הפוכים למודל:
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 אינו קוסמטי. זו ההגנה הזולה ביותר מפני מקרה השאילתה הריקה שהפיק את שנים-עשר הכישלונות השקטים: מחרוזת ריקה נדחית עכשיו על ידי החוזה לפני שגוף הכלי רואה אותה בכלל.
ניסיון חוזר שאינו יכול לשכפל תופעת לוואי
ההשהיה (backoff) היא החצי הקל. החצי הקשה הוא שניסיון חוזר של כתיבה יכול לכתוב פעמיים: הבקשה הצליחה, התגובה אבדה, והניסיון החוזר שלכם יוצר הערה שנייה. הפתרון הוא מפתח הנגזר משם הכלי ומהפרמטרים המנורמלים, ועוד כלל לגבי אילו קריאות מותר להשתמש בתוצאה ממטמון.
import hashlibimport randomimport time
@dataclassclass RetryPolicy: max_attempts: int = 3 base_delay: float = 0.05 max_delay: float = 2.0 jitter: float = 0.25 retryable: frozenset = frozenset( {ErrorCode.RATE_LIMITED, ErrorCode.TIMEOUT, ErrorCode.UPSTREAM} )
def is_retryable(self, code: str | None) -> bool: return code in {c.value for c in self.retryable}
def delay_for(self, attempt: int, rnd: random.Random) -> float: raw = min(self.max_delay, self.base_delay * (2 ** (attempt - 1))) return raw * (1.0 + rnd.uniform(-self.jitter, self.jitter))
class IdempotencyStore: """Remembers completed calls by (tool, canonical args) hash."""
def __init__(self) -> None: self._done: dict[str, ToolResult] = {}
@staticmethod def key(name: str, args: dict) -> str: blob = json.dumps(args, sort_keys=True, separators=(",", ":")) return name + ":" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
def get(self, key: str) -> ToolResult | None: return self._done.get(key)
def put(self, key: str, result: ToolResult) -> None: self._done[key] = resultsort_keys=True הוא מה שהופך את המפתח ליציב: {"a": 1, "b": 2} ו-{"b": 2, "a": 1} הן אותה קריאה וחייבות להפיק את אותו מפתח, אחרת ההגנה דולפת. ה-jitter אינו נחמדות גם כן — בלעדיו, עשרה תהליכי עבודה שנתקלו באותו 429 מנסים שוב בתזמון משותף ונתקלים בו שוב יחד; ±25% פורש אותם.
המבצע הוא המקום שבו ארבעת העניינים מתחברים, וסדר הפעולות שלו הוא העיצוב: לאמת, אז לבטל כפילויות, אז להריץ, אז לסווג, אז לנסות שוב. אימות לפני ביטול כפילויות משמעותו שקריאה פגומה לעולם לא תופסת מפתח.
import concurrent.futures
class ToolExecutor: """Validate -> de-duplicate -> execute -> classify -> retry. The only caller of Tool.run."""
def __init__( self, tools: dict[str, Tool], policy: RetryPolicy | None = None, store: IdempotencyStore | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None, ) -> None: self.tools = tools self.policy = policy or RetryPolicy() self.store = store or IdempotencyStore() self.sleep = sleep self.rnd = rnd or random.Random(0)
def execute(self, name: str, args: dict) -> ToolResult: tool = self.tools.get(name) if tool is None: return ToolResult(ok=False, data="", error="unknown tool: " + name, error_code=ErrorCode.UNKNOWN_TOOL.value)
errors = validate_args(tool.parameters, args) if errors: hint = "expected " + describe_schema(tool.parameters) return ToolResult(ok=False, data="", error=format_errors(errors) + ". " + hint, error_code=ErrorCode.INVALID_ARGUMENTS.value)
key = self.store.key(name, args) cached = self.store.get(key) if cached is not None and (tool.side_effect or not cached.ok): return replace(cached, from_cache=True, attempts=0)
attempt = 0 while True: attempt += 1 result = self._attempt(tool, args) result.attempts = attempt if result.ok: self.store.put(key, result) return result if not self.policy.is_retryable(result.error_code): # Negative cache: an identical call that failed permanently will fail # again. Caching it stops a looping model from re-burning the quota. self.store.put(key, result) return result if attempt >= self.policy.max_attempts: return result self.sleep(self.policy.delay_for(attempt, self.rnd))
def _attempt(self, tool: Tool, args: dict) -> ToolResult: pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) try: future = pool.submit(tool.run, args) return future.result(timeout=tool.timeout_s) except concurrent.futures.TimeoutError: return ToolResult(ok=False, data="", error="tool exceeded %.1fs" % tool.timeout_s, error_code=ErrorCode.TIMEOUT.value) except ToolError as exc: return ToolResult(ok=False, data="", error=str(exc), error_code=exc.code.value) except Exception as exc: return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc), error_code=ErrorCode.INTERNAL.value) finally: pool.shutdown(wait=False)שתי עדינויות שראוי לציין. תנאי השימוש מחדש במטמון הוא tool.side_effect or not cached.ok: כתיבה רשאית לעשות שימוש בהצלחה ממוחזרת (זה at-most-once), וכל קריאה רשאית לעשות שימוש בכישלון ממוחזר (זה מטמון שלילי, שעוצר מודל תקוע מלשרוף מחדש את המכסה על אותה קריאה שבורה). הצלחות של קריאה בלבד במכוון אינן ממוחזרות, כי חיפוש שלא החזיר דבר לפני שתי דקות עשוי להחזיר משהו עכשיו, וקריאות מיושנות הן מחלקה נפרדת של תשובות שגויות.
העדינות השנייה היא פסק הזמן. future.result(timeout=...) חוסם כמה זמן אתם ממתינים, לא כמה זמן הכלי רץ — פייתון אינה יכולה להרוג תהלין. כלי שמתעלם מפסק הזמן ממשיך לשרוף מעבד ברקע בזמן שהלולאה ממשיכה הלאה. זו מגבלה כנה, וזו בדיוק הסיבה שחלק 11 מחליף אותה בארגז חול ברמת תהליך. אל תקראו את timeout_s כגבול בטיחות; קראו אותו כתקציב שהיה (latency).
חיבור לתוך הלולאה, וגם ניסיון החוזר של ה-LLM שדילגנו עליו
חלק 1 השאיר פער שסימנתי במפורש: AgentLoop.run הגן על tool.run אבל לא על llm.complete, כך ש-503 יחיד מנקודת הקצה של המודל הרג את ההרצה כולה. אותה מדיניות סוגרת את הפער, ומוחלת על קודי מצב HTTP.
import urllib.error
class LLMClient: def complete(self, messages: list[Message], tools: list[dict]) -> dict: raise NotImplementedError
class ScriptedLLM(LLMClient): """Replays a fixed list of decisions. Used for offline tests and demos."""
def __init__(self, script: list[dict]): self.script = list(script) self.calls: list[list[Message]] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: self.calls.append(list(messages)) if not self.script: return {"type": "final", "content": "no scripted decision left"} return self.script.pop(0)
def classify_http_status(status: int) -> ErrorCode: if status == 429: return ErrorCode.RATE_LIMITED if status in (408, 504): return ErrorCode.TIMEOUT if 500 <= status < 600: return ErrorCode.UPSTREAM if status in (401, 403): return ErrorCode.PERMISSION return ErrorCode.INVALID_ARGUMENTS
class RetryingLLM(LLMClient): """Wraps any client; retries only the codes that a second attempt can fix."""
def __init__(self, inner: LLMClient, policy: RetryPolicy | None = None, sleep: Callable[[float], None] = time.sleep, rnd: random.Random | None = None) -> None: self.inner = inner self.policy = policy or RetryPolicy() self.sleep = sleep self.rnd = rnd or random.Random(7) self.attempts: list[int] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: attempt = 0 while True: attempt += 1 try: decision = self.inner.complete(messages, tools) self.attempts.append(attempt) return decision except urllib.error.HTTPError as exc: code = classify_http_status(exc.code) if not self.policy.is_retryable(code.value) or attempt >= self.policy.max_attempts: self.attempts.append(attempt) raise self.sleep(self.policy.delay_for(attempt, self.rnd))401 נזרק בניסיון הראשון, לא השלישי: מפתח גרוע נשאר גרוע, ושלושה ניסיונות רק משלשים את ההשהיה שלכם לפני הכישלון. 400 מסווג כ-invalid_arguments מאותה סיבה — המטען שלכם שגוי ושליחתו מחדש חסרת תועלת.
השינוי בלולאה קטן, והמעקב הוא המקום שבו הערך מופיע:
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=False1 search ok=True attempts=1 None cached=False2 save_note ok=True attempts=1 None cached=False3 save_note ok=True attempts=0 None cached=Trueצעד 0 מציג את החוזה דוחה את הקריאה. צעד 1 מציג את המודל מתאושש בתור הבא — ההתאוששות הזו נגרמת על ידי הודעת השגיאה, ולכן הרמז נוצר מהסכמה. צעד 3 מציג בקשת כתיבה זהה שמסופקת מהמטמון עם attempts=0: אין קובץ שני, אין קריאת רשת שנייה.
מצבי כישלון ואיך לטפל בהם
| כישלון | מה קורה בפועל | הטיפול כאן | מה עדיין נשבר |
|---|---|---|---|
| המודל שולח מפתח ששונה | additionalProperties: False מסמן זאת, required מציין את השדה החסר |
invalid_arguments מפורש עם רמז סכמה; המודל מתקן בתור הבא |
מודל שמתעלם מהרמז שורף את כל הצעדים |
המודל שולח true במקום מספר שלם |
פייתון מתייחסת ל-bool כאל int, ולכן בדיקה נאיבית עוברת |
ההגנה isinstance(value, bool) דוחה זאת |
כלום — זה סגור |
| כלי נתקע | התהלין ממשיך לרוץ אחרי ש-future חרג מפסק הזמן |
timeout_s מחזיר timeout, מנוסה שוב עד לתקציב |
שריפת מעבד ברמת תהליך; אין מתג עצירה (חלק 11) |
| סערת 429 | כל ניסיון פוגע שוב במגבלה | מספר ניסיונות חסום, השהיה מעריכית, jitter של ±25% | אין מגביל קצב בין-תהליכי (חלק 12) |
| תגובה שאבדה בכתיבה | ניסיון חוזר ישכפל את הקובץ | מפתח idempotency + side_effect=True מחזיר הצלחה ממוחזרת |
מחסן בזיכרון מת עם התהליך (חלק 8) |
| אותה קריאה שבורה חוזרת | המודל מסתובב סביב שגיאה אחת | מטמון שלילי עוצר הרצה חוזרת | הלולאה עדיין מבזבזת צעדים; צריך גלאי חזרתיות |
| סטייה בין סכמה לקוד | האימות דוחה שדה שהכלי צריך | describe_schema מייצר מחדש את הרמז מהסכמה |
שום דבר לא מזהה סטייה אוטומטית |
השורה האחרונה היא זו שנשכה אותי. describe_schema נכון רק כי גם הוא וגם validate_args קוראים את אותו מילון. אם אתם כותבים ביד עותק שני של הסכמה בפרומפט, השניים יפרדו בתוך חודש — והכישלון ייראה כשגיאת מודל, לא כשגיאת תחזוקה.
תמורות
| החלטה | אלטרנטיבה | למה בחרנו בה | עלות |
|---|---|---|---|
| מאמת תת-קבוצה בכתיבה עצמאית | jsonschema או Pydantic |
אפס תלות, כ-120 שורות, שגיאות בצורה מותאמת למודל | אין $ref/oneOf/pattern; אתם מתחזקים אותו |
שגיאות כערכי ToolResult |
זריקת חריגות דרך הלולאה | המודל יכול לקרוא ולתקן; הלולאה נשארת פשוטה | קוראים חייבים לבדוק ok בכל מקום |
additionalProperties: False |
שדות נוספים מתירניים | תופס פרמטרים מדומיינים מיד | נשבר כשספק מוסיף מטא-דאטה |
| מפתחות idempotency בזיכרון | Redis או SQLite | מילון אחד, אין תשתית, ניתן לבדיקה | לא משותף בין תהליכי עבודה; אובד בהפעלה מחדש |
| פסק זמן של תהלין | ארגז חול של תהליך | 10 שורות, אין IPC | לא ניתן להרוג כלי שהשתבש (חלק 11) |
| ניסיון חוזר רק ל-3 קודים | ניסיון חוזר להכול פעם אחת | שומר על תקציב הצעדים | not_found מתנדנד לעולם אינו נמנסה שוב |
| מטמון של תוצאות שליליות | הרצה מחדש תמיד | עוצר סערות ניסיון חוזר ממודל לופת | כישלון חולף שסווג שלא בצדק כקבוע נשאר במטמון |
בחירת המאמת ראויה לבחינה מדוקדקת ביותר. Pydantic היה נותן לכם coercion, מודלים מקוננים והודעות שגיאה טובות יותר בחינם — במחיר תלות, יבוא איטי יותר, ואובייקטי שגיאה שבכל מקרה עליכם לתרגם לטקסט קריא למודל. בשמונה סכמות כלים, הגרסה העצמאית מנצחת. בשמונים, היא לא.
בדיקות
ארבעה עשר בדיקות, אופליין, בפחות מעשירית השנייה. שמרו את המודול בשם contracts.py ואת הבדיקות בשם test_contracts.py; הריצו python3 -m unittest test_contracts -v. הסוויטה המלאה נמצאת במאגר, אבל חמש הבדיקות האלה נושאות את העיצוב:
import unittestimport urllib.error
from contracts import ( AgentLoop, ErrorCode, ScriptedLLM, Tool, ToolError, ToolExecutor, ToolResult, IdempotencyStore, RetryPolicy, RetryingLLM, LLMClient, build_tools, validate_args, describe_schema,)
class Flaky: def __init__(self, failures, code=ErrorCode.TIMEOUT): self.failures, self.code, self.calls = failures, code, 0
def __call__(self, args): self.calls += 1 if self.calls <= self.failures: raise ToolError("transient", self.code) return ToolResult(ok=True, data="recovered")
def tool_with(fn, name="probe", side_effect=False, timeout_s=1.0): return Tool(name=name, description="probe", _fn=fn, parameters={"type": "object", "properties": {}, "additionalProperties": False}, side_effect=side_effect, timeout_s=timeout_s)
class TestContracts(unittest.TestCase): def test_bool_is_not_an_integer(self): schema = build_tools()[0].parameters errors = validate_args(schema, {"query": "ok", "limit": True}) self.assertTrue(any("expected integer" in e["message"] for e in errors))
def test_transient_failure_is_retried_until_success(self): flaky = Flaky(failures=2, code=ErrorCode.UPSTREAM) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertTrue(result.ok) self.assertEqual(result.attempts, 3)
def test_permanent_failure_is_never_retried(self): flaky = Flaky(failures=5, code=ErrorCode.PERMISSION) executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None) result = executor.execute("probe", {}) self.assertFalse(result.ok) self.assertEqual(flaky.calls, 1)
def test_side_effect_runs_once_per_key(self): calls = {"n": 0}
def write(args): calls["n"] += 1 return ToolResult(ok=True, data="written")
executor = ToolExecutor({"probe": tool_with(write, side_effect=True)}, store=IdempotencyStore(), sleep=lambda d: None) executor.execute("probe", {}) second = executor.execute("probe", {}) self.assertEqual(calls["n"], 1) self.assertTrue(second.from_cache)
def test_401_is_not_retried(self): class Bad(LLMClient): def __init__(self): self.calls = 0
def complete(self, messages, tools): self.calls += 1 raise urllib.error.HTTPError("http://x", 401, "no", None, None)
inner = Bad() llm = RetryingLLM(inner, sleep=lambda d: None) with self.assertRaises(urllib.error.HTTPError): llm.complete([], []) self.assertEqual(inner.calls, 1)
if __name__ == "__main__": unittest.main()test_bool_is_not_an_integer נראה כמו דבר פעוט ואינו כזה: זו השורה היחידה שעומדת בין {"limit": true} לבין קבוצת תוצאות שנחתכה בשקט. test_side_effect_runs_once_per_key הוא הבדיקה היחידה שמגינה על נתונים ולא על השהיה. אם תשמרו שתי בדיקות, שמרו את אלה.
עוד בדיקה שראוי להריץ ביד: כוונו את Flaky אל RATE_LIMITED עם max_attempts=99 ווודאו שהמבצע עוצר בגבול המדיניות. לולאת ניסיון חוזר בלי חסם היא הפסקת שירות עם צעדים נוספים.
תרגילים
- Idempotency בין-תהליכית. החליפו את
IdempotencyStoreבגרסה מגובה ב-SQLite עם מפתח(name, args_hash)וחותמת זמןcreated_at. הפגו מפתחות ישנים מעשר דקות. מה משתנה במצב הכישלון שבו תהליך מת באמצע כתיבה, ומדוע ה-TTL צריך להיות ארוך יותר מחלון הניסיון החוזר הארוך ביותר שלכם? - עקיפות ניסיון חוזר לכל כלי. מנוע חיפוש מגביל קצב באגרסיביות; כתיבת הערה צריכה להינסות שוב פעם אחת לכל היותר. הוסיפו שדה
policyל-Toolשעוקף את ברירת המחדל של המבצע, וכתבו בדיקה שמוכיחה שקריאתsave_noteתחת 429 חוזרת אחרי שני ניסיונות, לא ארבעה. - Coercion עם קבלה. במקום לדחות את
{"limit": "3"}, קבלו אותו, המירו ל-3, והוסיפו הערה לתוצאת הכלי:coerced: limit "3" -> 3. מדדו כמה תורים זה חוסך במעקב של 50 קריאות. מה מסוכן יותר — coercion שקט או קריאה נדחית — ומה הקבלה משנה?
תרגיל 3 הוא המעניין כי אין לו תשובה נכונה יחידה. Coercion מקטין את מספר מסעות הקדפדפד ומסתיר שגיאות מודל; דחייה רועשת יותר ואיטית יותר. הקבלה היא הפשרה: אתם מקבלים בחזרה את מסע הקדפדפד ושומרים עקבות ביקורת של כל הנחה שביצעתם בשם המודל.
מה הלאה
הכלים שלכם עכשיו עם חוזים, הכישלונות שלכם עם קודים, והניסיונות החוזרים שלכם אינם יכולים לשכפל כתיבה. מה שלא השתנה מאז חלק 1 הוא הדבר שיכאיב ראשון בייצור: רשימת ההודעות גדלה בכל צעד, וכל הודעה קודמת נשלחת במלואה בכל קריאה.
חלק 3, הנדסת תקציב הקשר, מוסיף ContextBudget שמודד token-ים לפני כל קריאה, מקצה את החלון בין פרומפט המערכת, תוצאות כלים והיסטוריה, ודוחס תורים ישנים כשההערכה חורגת מהתקציב. הוא גם מכמת את הצמיחה הריבועית של הקלט מהטבלה של חלק 1 ומציג איזו מבין שלוש אסטרטגיות הדחיסה — חיתוך, תמצות, פינוי — באמת משתלמת. ה-ToolExecutor שבנתם כרגע נשאר בדיוק כפי שהוא; התקציב עוטף את ההיסטוריה, לא את הכלים.
Get Ball — Ball
Get Ball