Back to all articlesAI और एजेंट

Agent टूल कॉन्ट्रैक्ट और स्ट्रक्चर्ड एरर्स (Part 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

Part 1 एक ऐसे लूप के साथ समाप्त हुआ जो समाप्त होता है और एक टूल रजिस्ट्री जो मॉडल की हर बात पर भरोसा करती है। वह भरोसा अगला बग है। Part 1 के _search में, पहली पंक्ति query = str(args.get("query", "")).lower() थी। यदि मॉडल {"q": "agent loop"} भेजता है — {"query": "agent loop"} के बजाय — तो कुछ भी error नहीं उठता। query खाली स्ट्रिंग बन जाती है, corpus lookup कुछ भी मैच नहीं करता, और टूल ["no matches"] लौटाता है। मॉडल इसे इस बात के प्रमाण के रूप में पढ़ता है कि corpus खाली है और तदनुसार उत्तर देता है। कोई error नहीं, कोई log लाइन नहीं, और किसी JSON key की टाइपो को एक वास्तविक खाली परिणाम से अलग बताने का कोई तरीका नहीं है।

मैंने यह लेख लिखते समय यह तुलना की: तीस खराब argument payloads जो एक वास्तविक मॉडल वास्तव में उत्पन्न करता है — बदले हुए keys, capitalised keys, जहाँ integer चाहिए वहाँ string, string के बजाय list, null — Part 1 के टूल और यहाँ हमारे द्वारा बनाए गए संस्करण दोनों से डाले गए। Part 1 ने 12 of 30 के लिए एक भरोसेमंद दिखने वाला खाली परिणाम दिया। कॉन्ट्रैक्ट संस्करण ने 0 silent परिणाम दिए: 27 स्पष्ट, वर्गीकृत errors बन गए जिनमें schema hint था, और 3 वैध payloads सफल हुए। वही मॉडल, वही टूल, अलग failure दृश्यता।

यह भाग failure को दृश्यमान और वसूली योग्य बनाने के बारे में है। मॉडल को सावधान रहने के लिए prompt देकर नहीं — एक ऐसे call को निष्पादित करने से इनकार करके जो घोषित कॉन्ट्रैक्ट को पूरा नहीं करता, और हर failure को एक टाइप किए गए मान में बदलकर जिस पर लूप कार्रवाई कर सके।

आप क्या बनाएँगे

एक contracts.py मॉड्यूल जो Part 1 टूल रजिस्ट्री को चार अतिरिक्त चीज़ों से लपेटता है:

  • validate_args(schema, args) — एक JSON Schema सबसेट वैलिडेटर जो boolean के बजाय {path, message} errors की एक सूची लौटाता है, ताकि मॉडल को ठीक-ठीक बताया जा सके कि कौन-सा field गलत है।
  • ErrorCode + ToolError — आठ failure श्रेणियों की एक बंद टैक्सोनॉमी, जिसमें से प्रत्येक से एक प्रश्न जुड़ा है: क्या दूसरा प्रयास सफल हो सकता है?
  • RetryPolicy + IdempotencyStore — jitter के साथ सीमित exponential backoff, केवल retryable codes पर लागू, साथ ही argument-hash keys ताकि दोबारा किए गए side effect दो बार न चलें।
  • ToolExecutor — Tool.run का एकमात्र caller। यह मान्य करता है, डुप्लिकेट हटाता है, timeout के अंतर्गत निष्पादित करता है, वर्गीकृत करता है, और retry करता है।

AgentLoop Part 1 वाला अपना रूप बनाए रखता है। इसका run method लगभग छह पंक्तियों में बदलता है: सीधा tool.run(args) self.executor.execute(name, args) बन जाता है, और trace प्रयासों और error codes को रिकॉर्ड करता है। बाकी सब कुछ — Message, ToolResult, ScriptedLLM, निर्णय के रूप — संगत रहता है, क्योंकि Part 3 और Part 4 इस फ़ाइल को बदलने के बजाय इसका विस्तार करते हैं।

पूर्वापेक्षाएँ

  • Python 3.10 या नया। केवल मानक लाइब्रेरी: concurrent.futures, hashlib, json, random, time, urllib।
  • Part 1 की फ़ाइल, या कम से कम उसके चार प्रकार: Message, ToolResult, Tool, AgentLoop। यदि आपने उसे छोड़ा था, तो नीचे दिया गया ब्लॉक उन्हें संगत रूप में फिर से परिभाषित करता है।
  • एक टर्मिनल। यहाँ हर परीक्षण ऑफ़लाइन और एक सेकंड से कम समय में चलता है।

एक जानबूझकर किया गया omission: validate_args JSON Schema का एक सबसेट सपोर्ट करता है — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum। यह सबसेट व्यवहार में वास्तविक टूल schemas के उपयोग को कवर करता है। यह $ref, oneOf, या pattern को सपोर्ट नहीं करता, और ऐसा दिखावा करना इस बात को कहने से भी बुरा होगा। यदि आपको इनकी आवश्यकता है, तो यही वह बिंदु है जहाँ jsonschema या Pydantic तक पहुँचना सही निर्णय है; आसपास का executor डिज़ाइन नहीं बदलता।

जहाँ कॉन्ट्रैक्ट वास्तव में टूटता है

तीन failure श्रेणियाँ मॉडल और टूल के बीच होने वाली लगभग हर गड़बड़ी के लिए ज़िम्मेदार हैं, और इन्हें अलग तरह से संभालने की आवश्यकता है।

गलत key, विश्वसनीय इरादा। {"q": ...} एक ऐसे schema के विरुद्ध जिसमें query की आवश्यकता है। Python का dict.get डिफ़ॉल्ट चुपचाप "" प्रदान करता है। यह सबसे खतरनाक है, क्योंकि टूल सफल होता है और उत्तर गलत होता है।

सही key, गलत type। {"limit": "3"} [v for ...][:limit] तक पहुँचता है और TypeError: slice indices must be integers उठाता है। Part 1 में वह अपवाद AgentLoop.run द्वारा पकड़ा जाता है और ToolResult(ok=False) में बदला जाता है — लेकिन संदेश TypeError: slice indices must be integers or None or have an __index__ method होता है, जो मॉडल को यह नहीं बताता कि किस argument को ठीक करना है।

सही call, अस्थायी failure। search बैकएंड से 429, socket timeout, index से 503। retry करना सही है। लेकिन response खो जाने के कारण save_note call को दोबारा करना write को डुप्लिकेट कर देता है।

यह वह परीक्षण है जिसे मैंने उपयोग किया, ताकि आप 12-of-30 संख्या को बिना भरोसा किए खुद दोहरा सकें:

import json
from contracts import ToolExecutor, ToolResult, build_tools
def search_v1(args: dict) -> ToolResult:
query = str(args.get("query", "")).lower()
corpus = {
"agent loop": "An agent loop repeats: observe, decide, act, observe.",
"token budget": "Context windows are finite; budget them explicitly.",
"stop condition": "A step limit is a stop condition, not a strategy.",
"retry": "Retry only failures that are transient; never retry a 400.",
}
hits = [v for key, v in corpus.items() if key in query]
return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
PAYLOADS = [
{"query": "agent loop"}, {"q": "agent loop"}, {"Query": "agent loop"},
{"query": "agent loop", "top_k": 3}, {"query": ["agent loop"]},
{"query": "agent loop", "limit": "3"}, {"query": "agent loop", "limit": 0},
{"query": ""}, {"query": "agent loop", "limit": True}, {"query": None},
]
def probe() -> None:
cases = (PAYLOADS * 3)[:30]
executor = ToolExecutor({t.name: t for t in build_tools()}, sleep=lambda d: None)
silent_v1 = silent_v2 = explicit_v2 = 0
for args in cases:
old = search_v1(args)
new = executor.execute("search", args)
if old.ok and json.loads(old.data) == ["no matches"]:
silent_v1 += 1
if not new.ok:
explicit_v2 += 1
elif json.loads(new.data) == ["no matches"]:
silent_v2 += 1
print("n=%d v1_silent=%d v2_explicit=%d v2_silent=%d"
% (len(cases), silent_v1, explicit_v2, silent_v2))
if __name__ == "__main__":
probe()

आउटपुट: n=30 v1_silent=12 v2_explicit=27 v2_silent=0। शेष तीन सफलताएँ वैध payload {"query": "agent loop"} हैं, जो तीन बार दोहराया गया। चुपचाप गलत उत्तर error से भी बुरा है क्योंकि इसे एक सही नकारात्मक परिणाम से अलग नहीं किया जा सकता, और यह बिना किसी चुनौती के अंतिम उत्तर में फैल जाता है।

एक वैलिडेटर जिसे आप समझ सकते हैं

वैलिडेटर boolean नहीं, संरचित errors लौटाता है, क्योंकि error टेक्स्ट ही वह मरम्मत निर्देश है जिसे मॉडल अपने अगले चरण में पढ़ता है। boolean आपको एक संदेश गढ़ने पर मजबूर करता है; एक path और कारण आपको इसे यांत्रिक रूप से उत्पन्न करने देता है।

from __future__ import annotations
from dataclasses import dataclass, replace
from typing import Any, Callable
import json
@dataclass
class Message:
role: str # "system" | "user" | "assistant" | "tool"
content: str
name: str | None = None # tool name, required when role == "tool"
@dataclass
class ToolResult:
ok: bool
data: str
error: str | None = None
error_code: str | None = None
attempts: int = 1
from_cache: bool = False
def to_message(self, name: str) -> Message:
if self.ok:
payload = self.data
else:
payload = "ERROR[%s]: %s" % (self.error_code or "unknown", self.error or "")
return Message(role="tool", content=payload, name=name)
def validate_args(schema: dict, args: Any) -> list[dict]:
"""Validate a JSON Schema subset. Returns [] or a list of {path, message}."""
errors: list[dict] = []
def walk(sch: dict, value: Any, path: str) -> None:
t = sch.get("type")
if t == "object":
if not isinstance(value, dict):
errors.append({"path": path or "/", "message": "expected object"})
return
props = sch.get("properties", {})
for req in sch.get("required", []):
if req not in value:
errors.append({"path": path + "/" + req, "message": "missing required field"})
if sch.get("additionalProperties") is False:
for key in value:
if key not in props:
errors.append({"path": path + "/" + str(key), "message": "unexpected field"})
for key, sub in props.items():
if key in value:
walk(sub, value[key], path + "/" + key)
return
if t == "array":
if not isinstance(value, list):
errors.append({"path": path, "message": "expected array"})
return
item_schema = sch.get("items", {})
for i, item in enumerate(value):
walk(item_schema, item, path + "/" + str(i))
return
if t == "string":
if not isinstance(value, str):
errors.append({"path": path, "message": "expected string"})
return
elif t == "integer":
if isinstance(value, bool) or not isinstance(value, int):
errors.append({"path": path, "message": "expected integer"})
return
elif t == "number":
if isinstance(value, bool) or not isinstance(value, (int, float)):
errors.append({"path": path, "message": "expected number"})
return
elif t == "boolean":
if not isinstance(value, bool):
errors.append({"path": path, "message": "expected boolean"})
return
if "enum" in sch and value not in sch["enum"]:
errors.append({"path": path, "message": "must be one of " + repr(sch["enum"])})
if "minLength" in sch and isinstance(value, str) and len(value) < sch["minLength"]:
errors.append({"path": path, "message": "shorter than minLength %d" % sch["minLength"]})
if "maxLength" in sch and isinstance(value, str) and len(value) > sch["maxLength"]:
errors.append({"path": path, "message": "longer than maxLength %d" % sch["maxLength"]})
if "minimum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool):
if value < sch["minimum"]:
errors.append({"path": path, "message": "below minimum %s" % sch["minimum"]})
if "maximum" in sch and isinstance(value, (int, float)) and not isinstance(value, bool):
if value > sch["maximum"]:
errors.append({"path": path, "message": "above maximum %s" % sch["maximum"]})
walk(schema, args, "")
return errors

उस कोड की दो बातें सजावटी नहीं हैं। पहली, isinstance(value, bool) गार्ड integer और number पर लगता है: Python में True मान 1 वाला एक int है, इसलिए अन्यथा {"limit": true} integer जाँच पास कर जाता और limit=1 बन जाता। दूसरी, वैलिडेटर पहले error पर नहीं रुकता — वह सभी errors इकट्ठा करता है, फिर पहले तीन की रिपोर्ट करता है। दो गलत field भेजने वाले मॉडल को दो बार नहीं, एक ही round trip में दोनों के बारे में पता चलना चाहिए।

errors तभी उपयोगी हैं जब वे मरम्मत के लक्ष्य के साथ आएँ। यही 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 field जोड़ता है वह मान्यता में विफल हो जाएगा। यही बात है: एक अप्रत्याशित field का अर्थ है या तो मॉडल ने एक पैरामीटर की कल्पना की, या आपका schema आपके कोड से पीछे है, और दोनों ही चुपचाप **kwargs की तरह कंधे झटकने के बजाय एक ज़ोरदार failure के लायक हैं।

स्ट्रिंग्स के बजाय वर्गीकृत errors

एक स्ट्रिंग error को लॉग किया जा सकता है। एक वर्गीकृत error पर निर्णय लिया जा सकता है। नीचे दी गई टैक्सोनॉमी जानबूझकर छोटी है; आठ codes वे failure कवर करते हैं जो मैंने टूल इस्तेमाल करने वाले agents में वास्तव में देखे हैं, और प्रत्येक एक कार्रवाई से मेल खाता है।

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 नहीं कहते — पहले तीन को एक अलग call की आवश्यकता है, आखिरी दो को एक इंसान की। यही प्रश्न हर चीज़ को retry न करने का पूरा कारण है: हर बेकार retry max_steps से एक चरण खर्च करता है, और प्रति टूल call तीन प्रयासों पर, पाँच-टूल का बजट घटकर दो रह जाता है।

Tool तीन कॉन्ट्रैक्ट field प्राप्त करता है, और description अब ऐसे महत्वपूर्ण है जैसे Part 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)

तीनों टूल अब ईमानदार schemas घोषित करते हैं, और जो दो पहले चुपचाप विफल होते थे अब ज़ोर से विफल होते हैं। _search अपने बैकएंड down होने पर खाली सूची लौटाने के बजाय एक वर्गीकृत 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 पर लगाना सजावटी नहीं है। यह उन बारह silent failures को उत्पन्न करने वाले खाली-query मामले के विरुद्ध सबसे सस्ता बचाव है: अब एक खाली स्ट्रिंग को टूल बॉडी देखने से पहले ही कॉन्ट्रैक्ट द्वारा अस्वीकार कर दिया जाता है।

ऐसा retry जो side effect को डुप्लिकेट न करे

Backoff आसान आधा है। कठिन आधा यह है कि एक write को दोबारा करने से दो बार write हो सकती है: अनुरोध सफल हुआ, response खो गया, और आपके retry ने दूसरा note बना दिया। समाधान टूल नाम और मानकीकृत arguments से व्युत्पन्न एक key है, साथ ही यह नियम कि कौन-से call कैश्ड परिणाम का दोबारा उपयोग कर सकते हैं।

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 ही key को स्थिर बनाता है: {"a": 1, "b": 2} और {"b": 2, "a": 1} एक ही call हैं और उन्हें एक ही key उत्पन्न करनी चाहिए, अन्यथा गार्ड लीक हो जाता है। Jitter भी कोई लक्ज़री नहीं है — इसके बिना, दस workers जो एक ही 429 पर एक साथ retry करते हैं वे फिर एक साथ उसे ठोकते हैं; ±25% उन्हें फैला देता है।

executor वही जगह है जहाँ चारों चिंताएँ एक साथ आती हैं, और इसका क्रम ही डिज़ाइन है: पहले मान्य करें, फिर डुप्लिकेट हटाएँ, फिर निष्पादित करें, फिर वर्गीकृत करें, फिर retry करें। डुप्लिकेट हटाने से पहले मान्यता का अर्थ है कि एक खराब call कभी किसी key पर कब्ज़ा नहीं करता।

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 है: एक write कैश्ड सफलता का दोबारा उपयोग कर सकती है (यह at-most-once है), और कोई भी call कैश्ड failure का दोबारा उपयोग कर सकता है (यह एक negative cache है, जो एक अटके हुए मॉडल को उसी खराब call पर कोटा दोबारा जलाने से रोकता है)। केवल-पढ़ने वाली सफलताएँ जानबूझकर कैश नहीं की जातीं, क्योंकि दो मिनट पहले कुछ भी न लौटाने वाली search अब कुछ लौटा सकती है, और पुराने reads गलत उत्तर की अपनी श्रेणी हैं।

दूसरी सूक्ष्म बात timeout है। future.result(timeout=...) यह सीमित करता है कि आप कितनी देर प्रतीक्षा करते हैं, यह नहीं कि टूल कितनी देर चलता है — Python एक thread को मार नहीं सकता। timeout को नज़रअंदाज़ करने वाला टूल पृष्ठभूमि में CPU जलाता रहता है जबकि लूप आगे बढ़ जाता है। यह एक ईमानदार सीमा है, और यही कारण है कि Part 11 इसे process-level sandbox से बदलता है। timeout_s को सुरक्षा सीमा के रूप में न पढ़ें; इसे विलंबता बजट के रूप में पढ़ें।

इसे लूप से जोड़ना, और वह LLM retry जिसे हमने छोड़ा था

Part 1 में एक अंतर छोड़ा गया था जिसे मैंने स्पष्ट रूप से चिन्हित किया था: AgentLoop.run ने tool.run को सुरक्षित किया पर llm.complete को नहीं, इसलिए मॉडल endpoint से एक ही 503 पूरा रन खत्म कर देता था। वही नीति HTTP status codes पर लागू करके इसे बंद करती है।

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 पहले प्रयास पर उठाया जाता है, तीसरे पर नहीं: एक खराब key खराब ही रहती है, और तीन प्रयास विफल होने से पहले केवल आपकी विलंबता को तिगुना करते हैं। 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 अब error फ़ॉर्मैट को नाम देता है। यह prompt-engineering का रहस्यवाद नहीं है: मॉडल को ठीक-ठीक वह स्ट्रिंग बताई जाती है जो उसे failure पर दिखेगी और उसके साथ क्या करना है। इसकी कीमत एक वाक्य है और यह मापने योग्य रूप से उन चरणों की संख्या घटाता है जो मान्यता error के बाद हाथ-पैर मारने में बर्बाद होते हैं, क्योंकि मरम्मत का लक्ष्य स्वयं error में होता है।

इसे चलाएँ, और 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 कॉन्ट्रैक्ट को call अस्वीकार करते दिखाता है। चरण 1 मॉडल को अगले चरण में उबरते दिखाता है — वह उबरना error संदेश के कारण है, यही कारण है कि संकेत schema से उत्पन्न किया जाता है। चरण 3 एक समान write अनुरोध को attempts=0 के साथ कैश से परोसे दिखाता है: न कोई दूसरी फ़ाइल, न कोई दूसरा नेटवर्क call।

Failure के तरीके और उन्हें कैसे संभालें

Failure वास्तव में क्या होता है यहाँ संभालना क्या अब भी टूटता है
मॉडल बदला हुआ key भेजता है additionalProperties: False इसे चिन्हित करता है, required गुम field का नाम बताता है schema hint के साथ स्पष्ट invalid_arguments; मॉडल अगले चरण में मरम्मत करता है संकेत को नज़रअंदाज़ करने वाला मॉडल सभी चरण जला देता है
मॉडल integer के लिए true भेजता है Python bool को int मानता है, इसलिए साधारण जाँच पास हो जाती है isinstance(value, bool) गार्ड इसे अस्वीकार करता है कुछ नहीं — यह बंद है
टूल अटक जाता है future timeout होने के बाद भी Thread चलता रहता है timeout_s timeout लौटाता है, बजट तक retry Process-level CPU बर्न; कोई kill switch नहीं (Part 11)
429 तूफान हर प्रयास सीमा को फिर ठोकता है सीमित प्रयास, exponential backoff, ±25% jitter कोई cross-process rate limiter नहीं (Part 12)
write पर response खो गया retry फ़ाइल को डुप्लिकेट कर देगा Idempotency key + side_effect=True कैश्ड सफलता लौटाता है In-memory store प्रोसेस के साथ मर जाता है (Part 8)
वही खराब call बार-बार मॉडल एक error पर लूप करता है Negative cache दोबारा निष्पादन रोकता है लूप अभी भी चरण खर्च करता है; repeat detector की आवश्यकता
schema और कोड में बहाव मान्यता एक ऐसे field को अस्वीकार करती है जिसे टूल चाहता है describe_schema schema से संकेत फिर उत्पन्न करता है कोई भी बहाव स्वतः नहीं पकड़ता

आख़िरी पंक्ति वही है जिसने मुझे काटा। describe_schema सही इसलिए है क्योंकि यह और validate_args दोनों एक ही dict पढ़ते हैं। यदि आप prompt में schema की दूसरी प्रति हाथ से लिखें, तो दोनों एक महीने के भीतर अलग हो जाएँगे — और failure एक मॉडल error की तरह दिखेगा, रखरखाव error की तरह नहीं।

ट्रेड-ऑफ़

निर्णय विकल्प हमने इसे क्यों चुना कीमत
हाथ से बनाया सबसेट वैलिडेटर jsonschema या Pydantic शून्य निर्भरताएँ, ~120 पंक्तियाँ, मॉडल के लिए ढाले गए errors कोई $ref/oneOf/pattern नहीं; आपको इसे बनाए रखना होगा
errors को ToolResult मान के रूप में लूप से अपवाद उठाएँ मॉडल पढ़ और मरम्मत कर सकता है; लूप सरल रहता है caller को हर जगह ok जाँचना होगा
additionalProperties: False अतिरिक्त fields को उदारता से स्वीकार करें कल्पित पैरामीटर तुरंत पकड़ता है जब प्रदाता metadata जोड़े तो टूट जाता है
In-memory idempotency keys Redis या SQLite एक dict, कोई infra नहीं, परीक्षण योग्य workers में साझा नहीं; रीस्टार्ट पर खो जाता है
Thread timeout Process sandbox 10 पंक्तियाँ, कोई IPC नहीं बेकाबू टूल को मार नहीं सकता (Part 11)
केवल 3 codes retry करें हर चीज़ एक बार retry करें चरण बजट बचाता है एक अस्थिर not_found कभी retry नहीं होता
negative परिणाम कैश करें हमेशा दोबारा निष्पादित करें लूप करते मॉडल से retry तूफान रोकता है स्थायी मान ली गई अस्थायी failure कैश में रह जाती है

वैलिडेटर के चुनाव पर सबसे अधिक विचार करने की आवश्यकता है। Pydantic आपको coercion, नेस्टेड मॉडल और बेहतर error संदेश मुफ़्त देगा — एक निर्भरता, धीमा आयात, और error ऑब्जेक्टों की कीमत पर जिन्हें आपको वैसे भी मॉडल-पाठ्य टेक्स्ट में अनुवाद करना होगा। आठ टूल schemas पर, हाथ से बनाया संस्करण जीतता है। अस्सी पर, नहीं।

इसका परीक्षण

चौदह परीक्षण, ऑफ़लाइन, एक सेकंड के दसवें हिस्से से कम। मॉड्यूल को contracts.py और परीक्षणों को test_contracts.py के रूप में सहेजें; python3 -m unittest test_contracts -v चलाएँ। पूरा सूट रिपॉज़िटरी में है, लेकिन ये पाँच डिज़ाइन को ले जाते हैं:

import unittest
import urllib.error
from contracts import (
AgentLoop, ErrorCode, ScriptedLLM, Tool, ToolError, ToolExecutor, ToolResult,
IdempotencyStore, RetryPolicy, RetryingLLM, LLMClient, build_tools,
validate_args, describe_schema,
)
class Flaky:
def __init__(self, failures, code=ErrorCode.TIMEOUT):
self.failures, self.code, self.calls = failures, code, 0
def __call__(self, args):
self.calls += 1
if self.calls <= self.failures:
raise ToolError("transient", self.code)
return ToolResult(ok=True, data="recovered")
def tool_with(fn, name="probe", side_effect=False, timeout_s=1.0):
return Tool(name=name, description="probe", _fn=fn,
parameters={"type": "object", "properties": {},
"additionalProperties": False},
side_effect=side_effect, timeout_s=timeout_s)
class TestContracts(unittest.TestCase):
def test_bool_is_not_an_integer(self):
schema = build_tools()[0].parameters
errors = validate_args(schema, {"query": "ok", "limit": True})
self.assertTrue(any("expected integer" in e["message"] for e in errors))
def test_transient_failure_is_retried_until_success(self):
flaky = Flaky(failures=2, code=ErrorCode.UPSTREAM)
executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None)
result = executor.execute("probe", {})
self.assertTrue(result.ok)
self.assertEqual(result.attempts, 3)
def test_permanent_failure_is_never_retried(self):
flaky = Flaky(failures=5, code=ErrorCode.PERMISSION)
executor = ToolExecutor({"probe": tool_with(flaky)}, sleep=lambda d: None)
result = executor.execute("probe", {})
self.assertFalse(result.ok)
self.assertEqual(flaky.calls, 1)
def test_side_effect_runs_once_per_key(self):
calls = {"n": 0}
def write(args):
calls["n"] += 1
return ToolResult(ok=True, data="written")
executor = ToolExecutor({"probe": tool_with(write, side_effect=True)},
store=IdempotencyStore(), sleep=lambda d: None)
executor.execute("probe", {})
second = executor.execute("probe", {})
self.assertEqual(calls["n"], 1)
self.assertTrue(second.from_cache)
def test_401_is_not_retried(self):
class Bad(LLMClient):
def __init__(self):
self.calls = 0
def complete(self, messages, tools):
self.calls += 1
raise urllib.error.HTTPError("http://x", 401, "no", None, None)
inner = Bad()
llm = RetryingLLM(inner, sleep=lambda d: None)
with self.assertRaises(urllib.error.HTTPError):
llm.complete([], [])
self.assertEqual(inner.calls, 1)
if __name__ == "__main__":
unittest.main()

test_bool_is_not_an_integer एक मामूली बात लगता है और है नहीं: यह एक पंक्ति {"limit": true} और चुपचाप कटे हुए परिणाम सेट के बीच खड़ी है। test_side_effect_runs_once_per_key एकमात्र परीक्षण है जो विलंबता नहीं, डेटा की रक्षा करता है। यदि आप दो परीक्षण रखें, तो यही रखें।

एक और जाँच जिसे हाथ से चलाना उचित है: Flaky को RATE_LIMITED पर max_attempts=99 के साथ इंगित करें और पुष्टि करें कि executor नीति की सीमा पर रुक जाता है। बिना सीमा का retry लूप अतिरिक्त चरणों वाला आउटेज है।

अभ्यास

  1. Cross-process idempotency। IdempotencyStore को SQLite-आधारित संस्करण से बदलें जो (name, args_hash) और created_at टाइमस्टैंप द्वारा key हो। दस मिनट से पुराने keys को समाप्त करें। उस failure मोड में क्या बदलता है जहाँ प्रोसेस write के बीच मर जाता है, और TTL को आपके सबसे लंबे retry विंडो से लंबा क्यों होना चाहिए?
  2. प्रति-टूल retry ओवरराइड। एक search बैकएंड आक्रामक रूप से rate-limit करता है; एक note write को अधिकतम एक बार retry किया जाना चाहिए। एक policy field Tool में जोड़ें जो executor डिफ़ॉल्ट को ओवरराइड करे, और एक परीक्षण लिखें जो साबित करे कि 429 के तहत save_note call दो प्रयासों के बाद लौटता है, चार के बाद नहीं।
  3. रसीद के साथ coercion। {"limit": "3"} को अस्वीकार करने के बजाय, इसे स्वीकार करें, 3 में बदलें, और टूल परिणाम में एक नोट जोड़ें: coerced: limit "3" -> 3। मापें कि 50-call trace पर यह कितने चरण बचाता है। कौन अधिक खतरनाक है — चुपचाप coercion या अस्वीकृत call — और रसीद क्या बदलती है?

अभ्यास 3 सबसे रोचक है क्योंकि इसका कोई एक सही उत्तर नहीं है। Coercion round trips घटाता है और मॉडल की गलतियों को छुपाता है; अस्वीकृति अधिक ज़ोरदार और धीमी है। रसीद समझौता है: आपको round trip वापस मिलता है और मॉडल की ओर से आपने किए गए हर अनुमान का ऑडिट ट्रेल बना रहता है।

आगे क्या

आपके टूल्स को अब कॉन्ट्रैक्ट मिल गए हैं, आपकी failures के codes हैं, और आपके retry किसी write को डुप्लिकेट नहीं कर सकते। जो Part 1 से नहीं बदला है वह चीज़ प्रोडक्शन में सबसे पहले चोट पहुँचाएगी: हर चरण पर संदेश सूची बढ़ती है, और हर call पर हर पिछला संदेश पूरा का पूरा दोबारा भेजा जाता है।

Part 3, Context budget engineering, एक ContextBudget जोड़ता है जो हर call से पहले tokens मापता है, system prompt, टूल परिणामों और इतिहास के बीच विंडो आवंटित करता है, और जब अनुमान बजट से अधिक हो जाए तो पुराने चरणों को संपीड़ित करता है। यह Part 1 की तालिका से द्विघात इनपुट वृद्धि को भी मापता है और दिखाता है कि तीनों संपीड़न रणनीतियों — truncate, summarise, evict — में से कौन सी वास्तव में लाभदायक है। आपके द्वारा अभी बनाया गया ToolExecutor बिलकुल वैसा ही रहता है; बजट टूल्स को नहीं, इतिहास को लपेटता है।

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.