Back to all articlesAI at mga ahente

Agent Tool Contracts at Structured Errors (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

Natapos ang Part 1 na may loop na marunong huminto at may tool registry na nagtitiwala sa lahat ng sinasabi ng model. Ang tiwala na iyon ang susunod na bug. Sa _search ng Part 1, ang unang linya ay query = str(args.get("query", "")).lower(). Kung magpadala ang model ng {"q": "agent loop"} sa halip na {"query": "agent loop"}, walang mararaise. Ang query ay nagiging empty string, walang itutugma ang corpus lookup, at magbabalik ang tool ng ["no matches"]. Babasahin ng model iyon bilang ebidensya na walang laman ang corpus at sasagot nang naaayon. Walang error, walang log line, at walang paraan para makilala ang tunay na empty result mula sa typo sa isang JSON key.

Tumakbo ako ng mismong paghahambing na iyon habang isinusulat ang artikulong ito: tatlumpung malformed argument payload na talagang ginagawa ng tunay na model — binago ang pangalan ng keys, naging capitalized ang keys, string sa puwesto ng integer, list sa halip na string, null — ipinasa sa tool ng Part 1 at sa bersyong itinatayo natin dito. Nakagawa ang Part 1 ng mukhang-makatuwirang empty result sa 12 sa 30. Nakagawa ang contract version ng 0 na silent results: 27 ang naging malinaw, classified errors na may schema hint, at nagtagumpay ang 3 valid payload. Parehong model, parehong tools, magkaibang bisibilidad ng kabiguan.

Tungkol sa paggawang kitang-kita at nababawi ang kabiguan ang bahaging ito. Hindi sa paghimok sa model na mag-ingat — kundi sa pagtanggi na isagawa ang tawag na hindi tumutugma sa idineklarang contract, at sa paggawang typed value ang bawat kabiguan na kayang gawan ng aksyon ng loop.

Ano ang itatayo mo

Isang contracts.py module na binabalot ang tool registry ng Part 1 na may apat na dagdag:

  • validate_args(schema, args) — isang JSON Schema subset validator na nagbabalik ng listahan ng mga error na {path, message} sa halip na boolean, para masabi nang eksakto sa model kung aling field ang mali.
  • ErrorCode + ToolError — isang closed taxonomy ng walong klase ng kabiguan, na bawat isa ay may nakadikit na isang tanong: maaari bang umasang magtagumpay ang ikalawang pagsubok?
  • RetryPolicy + IdempotencyStore — bounded exponential backoff na may jitter, inilalapat lamang sa mga retryable code, kasama ang argument-hash keys para ang sinubukang muli na side effect ay hindi maaaring tumakbo nang dalawang beses.
  • ToolExecutor — ang nag-iisang tumatawag sa Tool.run. Nagbeberipika ito, nagde-de-duplicate, nagsasagawa sa ilalim ng timeout, nagkiklasipika, at nagre-retry.

Pinapanatili ng AgentLoop ang hugis nito mula sa Part 1. Nagbabago ang run method nito nang mga anim na linya: ang tuwirang tool.run(args) ay nagiging self.executor.execute(name, args), at nirerekord ng trace ang mga pagsubok at error code. Ang lahat ng iba pa — Message, ToolResult, ScriptedLLM, mga hugis ng desisyon — nananatiling compatible, dahil pinapalawak ng Part 3 at Part 4 ang file na ito sa halip na palitan ito.

Mga kinakailangan

  • Python 3.10 o mas bago. Standard library lamang: concurrent.futures, hashlib, json, random, time, urllib.
  • Ang file ng Part 1, o kahit man lamang ang apat nitong uri: Message, ToolResult, Tool, AgentLoop. Kinalampasan mo ito, muling tinutukoy ng blok sa ibaba ang mga ito nang compatible.
  • Isang terminal. Bawat test dito ay tumatakbo nang offline sa loob ng walong segundo pababa.

Isang sadyang pagkukulang: sumusuporta ang validate_args sa isang subset ng JSON Schema — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum. Tinatakpan ng subset na iyon ang talagang ginagamit ng mga tool schema sa praktika. Hindi nito sinusuportahan ang $ref, oneOf, o pattern, at mas masahol pa ang pagpapanggap kaysa pag-amin nito. Kung kailangan mo ang mga ito, ito ang tamang punto para lumapit sa jsonschema o Pydantic; hindi nagbabago ang napapaligid na executor design.

Kung saan talaga nabubuwag ang contract

Tatlong klase ng kabiguan ang bumubuo sa halos lahat ng maaaring masama sa pagitan ng model at ng tool, at magkaiba ang kailangan nilang paghawak.

Maling key, makatuwirang layunin. {"q": ...} laban sa schema na humihiling ng query. Ang default ng dict.get sa Python ay tahimik na nagbibigay ng "". Ito ang mapanganib, dahil tagumpay ang tool ngunit mali ang sagot.

Tamang key, maling uri. Ang {"limit": "3"} ay nakararating sa [v for ...][:limit] at nagre-raise ng TypeError: slice indices must be integers. Sa Part 1, nahuhuli ng AgentLoop.run ang exception na iyon at ginagawang ToolResult(ok=False) — ngunit ang mensahe ay TypeError: slice indices must be integers or None or have an __index__ method, na walang sinasabi sa model kung aling argument ang aayusin.

Tamang tawag, pansamantalang kabiguan. Isang 429 mula sa search backend, isang socket timeout, isang 503 mula sa index. Tama ang pag-retry. Ngunit ang pag-retry ng tawag sa save_note dahil nawala ang sagot ay nagdodoble ng pagsulat.

Narito ang probe na ginamit ko, para mai-reproduce mo ang bilang na 12-sa-30 at hindi ito pagkatiwalaan na lamang:

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

Output: n=30 v1_silent=12 v2_explicit=27 v2_silent=0. Ang tatlong natitirang tagumpay ay ang valid payload na {"query": "agent loop"}, inulit nang tatlong beses. Mas masahol ang tahimik na maling sagot kaysa sa error dahil hindi ito makikilala mula sa tamang negatibong resulta, at dumadaloy ito sa huling sagot nang walang pagtutol.

Isang validator na kayang pag-isipan

Nagbabalik ang validator ng structured errors, hindi boolean, dahil ang error text ang repair instruction na binabasa ng model sa susunod nitong turn. Pinipilit ka ng boolean na gumawa ng mensahe; ang path na may kasamang dahilan ay nagpapahintulot sa iyong buuin ito nang mekanikal.

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

Dalawang detalye sa code na iyon ang hindi palamuti. Una, ang guard na isinstance(value, bool) sa integer at number: sa Python, ang True ay int na may halagang 1, kaya walang ito, {"limit": true} ay dadaan sa integer check at magiging limit=1. Pangalawa, hindi nagre-raise ang validator sa unang error — kinokolekta nito ang lahat, saka iniuulat ang unang tatlo. Ang model na nagpadala ng dalawang sirang field ay dapat malaman ang pareho sa isang round trip, hindi dalawa.

Magiging kapaki-pakinabang lamang ang mga error kung dumarating kasama ang repair target. Iyan ang idinadagdag ng describe_schema: isang compact signature na kinukuha mula sa mismong schema object.

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)

Ang tool message na magreresulta para sa kaso ng {"q": ...} ay ERROR[invalid_arguments]: /q unexpected field; /query missing required field. expected {query:string!, limit:integer}. Ang bahagi pagkatapos ng expected ay ginagawa mula sa schema, kaya hindi ito maaaring lumayo kapag sine-edit mo ang schema. Mas mahalaga ang property na iyon kaysa sa pagkakapilato: ang manumit na repair hints ay lumaluma, ang ginagawa awtomatiko ay hindi.

Tandaan ang halaga nito. Mahigpit ang additionalProperties: False — ang provider na magdadagdag ng walang-masamang metadata field ay babagsak sa beripikasyon. Doon mismo ang punto: ang hindi inaasahang field ay nangangahulugang nag-hallucinate ang model ng parameter, o napag-iwanan ng code mo ang schema mo, at magkadapat na makakuha ng malakas na kabiguan sa halip na isang pasimplang balikat na **kwargs.

Classified errors sa halip na strings

Ang string error ay puwedeng i-log. Ang classified error ay puwedeng gawan ng desisyon. Sadyang maliit ang taxonomy sa ibaba; walong code ang bumubuo sa mga kabiguan na tunay ko nang nakita sa mga agent na gumagamit ng tools, at bawat isa ay may kinalaman sa isang aksyon.

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

Ang panuntunan ng klasipikasyon ay isang tanong: magtagumpay kaya nang makatuwiran ang tapat na ikalawang pagsubok, walang anumang pagbabago? Ang rate_limited, timeout at upstream_error ay nagsasabi ng oo. Ang invalid_arguments, unknown_tool, not_found, permission_denied at internal_error ay nagsasabi ng hindi — ang unang tatlo ay kailangan ng iba ang tawag, ang huling dalawa ay kailangan ng tao. Ang tanong na iyon ang buong dahilan kung bakit hindi dapat i-retry ang lahat: bawat sayang na retry ay isang hakbang na kinokonsumo mula sa max_steps, at sa tatlong pagsubok kada tool call, ang badyet na limang tool ay gumuguhong dalawa na lamang.

May tatlong contract field na ang Tool, at ang description ay nagiging load-bearing sa paraan na hindi ito sa 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)

Nagdedeklara na ngayon ng tapat na schema ang tatlong tool, at ang dalawang dati na tahimik na bumabagsak ay malakas nang bumabagsak. Nagre-raise ang _search ng classified ToolError sa halip na magbalik ng empty list kapag bumagsak ang backend nito, dahil magkasalungat ang ibig sabihin ng empty list at ng timeout para sa model:

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,
),
]

Hindi kotsmetiko ang minLength: 2 sa query. Ito ang pinakamurang posibleng depensa sa empty-query na kaso na nakagawa ng lahat ng labindalawang silent failure: tinatanggihan na ngayon ng contract ang empty string bago pa man makita ito ng tool body.

Retry na hindi maaaring magdoble ng side effect

Ang backoff ang madaling kalahati. Ang mahirap na kalahati ay ang pag-retry ng pagsulat ay maaaring magsulat nang dalawang beses: nagtagumpay ang request, nawala ang sagot, at lumilikha ang retry mo ng ikalawang note. Ang lunas ay isang key na kinukuha mula sa tool name at sa mga canonicalised argument, kasama ang panuntunan kung aling mga tawag ang maaaring gumamit muli ng naka-cache na resulta.

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

Ang sort_keys=True ang nagpapanatili ng key na matatag: ang {"a": 1, "b": 2} at {"b": 2, "a": 1} ay parehong tawag at dapat gumawa ng parehong key, kung hindi, may tagas ang guard. Ang jitter ay hindi rin luho — walang nito, ang sampung worker na nakatama sa iisang 429 ay nagre-retry nang sabay-sabay at magkasamang tatama muli; pinakakalat sila ng ±25%.

Ang executor ang lugar kung saan nagtatagpo ang apat na alalahanin, at ang kaayusan nito ang mismong disenyo: beripika, saka i-de-duplicate, saka isagawa, saka iklasipika, saka i-retry. Ang beripikasyon bago ang deduplication ay nangangahulugang hindi kailanman sasakop ng malformed call ang isang 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)

Dalawang kaiklian na karapat-dapat pangalanan. Ang cache-reuse na kundisyon ay tool.side_effect or not cached.ok: maaaring gumamit muli ang isang pagsulat ng naka-cache na tagumpay (iyon ang at-most-once), at maaaring gumamit muli ang anumang tawag ng naka-cache na kabiguan (iyon ang negative cache, na pumipigil sa naipit na model sa muling pagsunog ng quota sa parehong sirang tawag). Sadyang hindi naka-cache ang mga tagumpay na read-only, dahil maaari nang magbalik ng may laman ngayon ang paghahanap na walang inibalik dalawang minuto ang nakakalipas, at ang panluma ang sariling klase ng maling sagot.

Ang ikalawang kaiklian ay ang timeout. Binabatak ng future.result(timeout=...) kung gaano katagal ikaw ang maghihintay, hindi kung gaano katagal tumatakbo ang tool — hindi kayang pumatay ng thread ang Python. Tuloy-tuloy na nagliliyab ng CPU sa background ang tool na nagpapabaya sa timeout habang nagpapatuloy ang loop. Tapat na kataliyan iyan, at eksaktong dahilan kung bakit pinalalitan ito ng Part 11 ng process-level sandbox. Huwag basahin ang timeout_s bilang hangganan ng kaligtasan; basahin ito bilang badyet sa latency.

Pagsabit sa loop, kasama ang LLM retry na tinigil natin

Nag-iwan ang Part 1 ng butas na binanatan ko nang tuwiran: pinoprotektahan ng AgentLoop.run ang tool.run ngunit hindi ang llm.complete, kaya isang 503 mula sa model endpoint ang pumatay ng buong run. Sinasara ng parehong polisiya ang butas na iyon, inilalapat sa mga 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))

Nagre-raise ang 401 sa unang pagsubok, hindi sa ikatlo: mananatiling masama ang sirang key, at tatlong pagsubok ang pagpaparami lamang ng latency mo tatlong beses bago mabigo. Ikiniklasipika ang 400 bilang invalid_arguments sa parehong dahilan — mali ang payload mo at walang punto sa muling pagpapadala nito.

Maliit ang pagbabago sa loop, at sa trace nakikita ang halaga:

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"

Nebinabangunan na ngayon ng prompt na SYSTEM ang format ng error. Hindi ito mistisismo ng prompt-engineering: sinasabihan ang model ng eksaktong string na makikita nito sa kabiguan at kung ano ang gagawin dito. Naghahalaga ito ng isang pangungusap at nasusukat na nababawasan ang bilang ng mga turn na inuubos pagkatapos ng beripikasyon error, dahil nasa mismong error ang repair target.

Patakbuhin ito, at mababasa ang trace na parang diagnosis sa halip na transcript:

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

Ipinapakita ng Step 0 ang contract na tumatanggi sa tawag. Ipinapakita ng Step 1 ang model na nakababawi sa susunod na turn — dahil sa error message ang pagbabawi na iyon, kaya’t gawa mula sa schema ang hint. Ipinapakita ng Step 3 ang tapat na write request na inihatid mula sa cache na may attempts=0: walang ikalawang file, walang ikalawang network call.

Mga mode ng kabiguan at kung paano haharapin

Kabiguan Ano talaga ang nangyayari Paghawak dito Ano ang sira pa rin
Nagpadala ang model ng binagong pangalan ng key Iniiwanan ito ng additionalProperties: False, binabansagan ng required ang nawawalang field Malinaw na invalid_arguments na may schema hint; nag-aayos ang model sa susunod na turn Sisinunog ng model na nagpapabaya sa hint ang lahat ng hakbang
Nagpadala ang model ng true para sa integer Itinuturing ng Python ang bool bilang int, kaya dadaan ang naive check Tinatanggihan ito ng guard na isinstance(value, bool) Wala — sarado na ito
Nagsasanla ang tool Patuloy na tumatakbo ang thread pagkatapos lumagpas sa oras ang future Nagbabalik ang timeout_s ng timeout, inuulit hanggang sa badyet Pagliyab ng CPU sa antas ng proseso; walang kill switch (Part 11)
Bagyo ng 429 Bawat pagsubok ay tumatama muli sa limitasyon May hangganan ang mga pagsubok, exponential backoff, jitter na ±25% Walang cross-process rate limiter (Part 12)
Nawala ang sagot sa pagsulat Magdodoble ng file ang retry Idempotency key + side_effect=True na nagbabalik ng naka-cache na tagumpay Namamatay kasama ng proseso ang in-memory store (Part 8)
Paulit-ulit na parehong sirang tawag Napapadpad sa ikot ang model sa isang error Pumipigil ang negative cache sa muling pagsasagawa Patuloy na umaubos ng hakbang ang loop; kailangan ng repeat detector
Nagkakalayo ang schema at code Tinatanggihan ng beripikasyon ang field na kailangan ng tool Binubuo muli ng describe_schema ang hint mula sa schema Walang awtomatikong nakakakita ng kalayuan

Ang huling hanay ang nagpahirap sa akin. Tama ang describe_schema lamang dahil parehong dict ang binabasa nito at ng validate_args. Kung magsusulat ka nang mano-mano ng pangalawang kopya ng schema sa prompt, magkakalayo ang dalawa sa loob ng isang buwan — at mukhang error ng model ang kabiguan, hindi error ng pagpapanatili.

Mga trade-off

Desisyon Alternatibo Bakit namin pinili Ang halaga
Manumit na subset validator jsonschema o Pydantic Walong dependensiya, ~120 linya, mga error na hugis para sa model Walang $ref/oneOf/pattern; ikaw ang magpapanatili
Mga error bilang halaga ng ToolResult Pag-raise ng mga exception sa buong loop Nababasa at nababago ng model; nananatiling payak ang loop Kailangang tiyakin ng mga caller ang ok sa lahat ng dako
additionalProperties: False Pinahihintulutang dagdag na field Napupunang agad-agad ang hallucinated parameters Nabubuwag kapag nagdagdag ng metadata ang provider
In-memory idempotency keys Redis o SQLite Isang dict, walang infra, naitetest Hindi nakikibahagi sa mga worker; nawawala sa restart
Timeout sa antas ng thread Process sandbox 10 linya, walang IPC Hindi makapapatay ng ligaw na tool (Part 11)
Pag-retry lamang ng 3 code Pag-retry ng lahat minsan Pinapanatili ang badyet ng hakbang Hindi kailanman mare-retry ang palpak na not_found
Pag-cache ng negatibong resulta Palaging muling isasagawa Pumipigil ng bagyo ng retry mula sa nag-iikot na model Mananatiling naka-cache ang pansamantalang kabiguan na maling naiklasipika bilang permanente

Karapat-dapat na siyasatin nang pinakamadiin ang pagpili ng validator. Bibigyan ka ng Pydantic ng coercion, nested models, at mas mahuhusay na error message nang libre — sa halaga ng isang dependensiya, mas mabagal na import, at mga error object na kailangan mo pa ring isalin sa teksto ng model. Sa walong tool schema, panalo ang manumit na bersyon. Sa walumpu, hindi na.

Pagsubok nito

Labing-apat na test, offline, walong bahagi ng segundo pababa. I-save ang module bilang contracts.py at ang mga test bilang test_contracts.py; patakbuhin ang python3 -m unittest test_contracts -v. Nasa repository ang buong suite, ngunit nakasalalay dito ang disenyo ng limang test na ito:

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

Mukhang trivia ang test_bool_is_not_an_integer at hindi naman: iyon ang nag-iisang linya na nakatayo sa pagitan ng {"limit": true} at ng tahimik na napuputol na resulta. Ang test_side_effect_runs_once_per_key ang nag-iisang test na nagpoprotekta sa datos sa halip na latency. Kung dalawang test lang ang itatabi mo, iyong dalawa ang itatabi mo.

Isang tseke pa na karapat-dapat patakbuhin nang mano-mano: ituon ang Flaky sa RATE_LIMITED na may max_attempts=99 at kumpirmahing humihinto ang executor sa hangganan ng polisiya. Ang retry loop na walang hangganan ay isang outage na may mga dagdag na hakbang.

Mga ehersisyo

  1. Cross-process idempotency. Palitan ang IdempotencyStore ng bersyong batay sa SQLite na may key na (name, args_hash) at isang created_at timestamp. Paawasin ang mga key na mas matanda sa sampung minuto. Ano ang magbabago sa mode ng kabiguan kung sa gitna ng pagsulat namatay ang proseso, at bakit kailangang mas mahaba ng TTL kaysa sa pinakamahabang retry window mo?
  2. Per-tool na pagpalit ng retry. Napakahigpit mag-rate-limit ng isang search backend; isang beses sa marami ang dapat na retry ng pag-wa-write ng note. Magdagdag ng policy field sa Tool na pumapalit sa default ng executor, at magsulat ng test na nagpapatunay na bumabalik pagkatapos ng dalawang pagsubok, hindi apat, ang tawag sa save_note sa ilalim ng 429.
  3. Coercion na may resibo. Sa halip na tanggihan ang {"limit": "3"}, tanggapin ito, gawing 3, at magdagdag ng tala sa tool result: coerced: limit "3" -> 3. Sukatin kung ilang turn ang matitipid nito sa isang 50-call na trace. Alin ang mas mapanganib — tahimik na coercion o tinanggihang tawag — at ano ang binabago ng resibo?

Ang ehersisyong 3 ang kawili-wili dahil walang iisang tamang sagot. Binabawasan ng coercion ang mga round trip at itinatago ang mga error ng model; mas malakas at mas mabagal ang pagtanggi. Ang resibo ang kompromiso: nakakabalik ka ng round trip at napapanatili mo ang audit trail ng bawat palagay na ginawa mo nang nasa ikaw ang panig ng model.

Ano ang susunod

May mga contract na ngayon ang mga tool mo, may mga code na ang mga kabiguan mo, at hindi na maaaring magdoble ng pagsulat ang mga retry mo. Ang hindi pa nagbabago mula pa noong Part 1 ang una na sasakit sa produksiyon: lumalaki sa bawat hakbang ang listahan ng mensahe, at muling ipinapadala nang buo ang bawat mas naunang mensahe sa bawat tawag.

Nagdaragdag ang Part 3, ang Context budget engineering, ng isang ContextBudget na sumusukat ng token bago ang bawat tawag, naglalaan ng window sa pagitan ng system prompt, tool results at history, at nagkokompres ng mga lumang turn kapag lumagpas sa badyet ang tantiya. Kinukuwantifika rin nito ang quadratic na paglaki ng input mula sa talahanayan ng Part 1 at ipinapakita kung alin sa tatlong diskarte ng kompresyon — truncate, summarise, evict — ang talagang nagbabayad sa sarili. Mananatili nang eksakto ang ToolExecutor na kambubuo mo lang; ang badyet ang bumabalot sa history, hindi sa mga tool.

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.