Agent Tool Contracts and Structured Errors (Part 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
Part 1 ended with a loop that terminates and a tool registry that trusts everything the model says. That trust is the next bug. In the Part 1 _search, the first line was query = str(args.get("query", "")).lower(). If the model sends {"q": "agent loop"} instead of {"query": "agent loop"}, nothing raises. The query becomes the empty string, the corpus lookup matches nothing, and the tool returns ["no matches"]. The model reads that as evidence that the corpus is empty and answers accordingly. There is no error, no log line, and no way to tell a genuine empty result from a typo in a JSON key.
I ran that exact comparison while writing this article: thirty malformed argument payloads a real model does produce — renamed keys, capitalised keys, a string where an integer belongs, a list instead of a string, null — pushed through the Part 1 tool and through the version we build here. Part 1 produced a plausible-looking empty result for 12 of 30. The contract version produced 0 silent results: 27 became explicit, classified errors carrying a schema hint, and the 3 valid payloads succeeded. Same model, same tools, different failure visibility.
This part is about making failure visible and recoverable. Not by prompting the model to be careful — by refusing to execute a call that does not satisfy a declared contract, and by turning every failure into a typed value the loop can act on.
What you’ll build
A contracts.py module that wraps the Part 1 tool registry with four additions:
validate_args(schema, args)— a JSON Schema subset validator that returns a list of{path, message}errors instead of a boolean, so the model can be told exactly which field is wrong.ErrorCode+ToolError— a closed taxonomy of eight failure classes, with one question attached to each: can a second attempt possibly succeed?RetryPolicy+IdempotencyStore— bounded exponential backoff with jitter, applied only to retryable codes, plus argument-hash keys so a retried side effect cannot run twice.ToolExecutor— the single caller ofTool.run. It validates, de-duplicates, executes under a timeout, classifies, and retries.
AgentLoop keeps its shape from Part 1. Its run method changes by about six lines: the direct tool.run(args) becomes self.executor.execute(name, args), and the trace records attempts and error codes. Everything else — Message, ToolResult, ScriptedLLM, the decision shapes — stays compatible, because Part 3 and Part 4 extend this file rather than replacing it.
Prerequisites
- Python 3.10 or newer. Standard library only:
concurrent.futures,hashlib,json,random,time,urllib. - The Part 1 file, or at least its four types:
Message,ToolResult,Tool,AgentLoop. If you skipped it, the block below redefines them compatibly. - A terminal. Every test here runs offline in under a second.
One deliberate omission: validate_args supports a subset of JSON Schema — type, properties, required, additionalProperties, items, enum, minLength, maxLength, minimum, maximum. That subset covers what real tool schemas use in practice. It does not support $ref, oneOf, or pattern, and pretending otherwise would be worse than saying so. If you need them, this is the point where reaching for jsonschema or Pydantic is the right call; the surrounding executor design does not change.
Where the contract actually breaks
Three failure classes account for nearly everything that goes wrong between a model and a tool, and they need different handling.
Wrong key, plausible intent. {"q": ...} against a schema requiring query. Python’s dict.get default silently supplies "". This is the dangerous one, because the tool succeeds and the answer is wrong.
Right key, wrong type. {"limit": "3"} reaches [v for ...][:limit] and raises TypeError: slice indices must be integers. In Part 1 that exception is caught by AgentLoop.run and converted to ToolResult(ok=False) — but the message is TypeError: slice indices must be integers or None or have an __index__ method, which tells the model nothing about which argument to fix.
Correct call, transient failure. A 429 from a search backend, a socket timeout, a 503 from an index. Retrying is correct. But retrying a save_note call because the response was lost duplicates the write.
Here is the probe I used, so you can reproduce the 12-of-30 number rather than take it on faith:
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()Output: n=30 v1_silent=12 v2_explicit=27 v2_silent=0. The three remaining successes are the valid payload {"query": "agent loop"}, repeated three times. A silent wrong answer is worse than an error because it is indistinguishable from a correct negative result, and it propagates into the final answer unchallenged.
A validator you can reason about
The validator returns structured errors, not a boolean, because the error text is the repair instruction the model reads on its next turn. A boolean forces you to invent a message; a path plus a reason lets you generate one mechanically.
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 errorsTwo details in that code are not decorative. First, isinstance(value, bool) guards on integer and number: in Python True is an int with value 1, so {"limit": true} would otherwise pass an integer check and become limit=1. Second, the validator does not raise on the first error — it collects all of them, then reports the first three. A model that sent two bad fields should learn about both in one round trip, not two.
The errors are only useful if they arrive with a repair target. That is what describe_schema adds: a compact signature derived from the same 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)The resulting tool message for the {"q": ...} case is ERROR[invalid_arguments]: /q unexpected field; /query missing required field. expected {query:string!, limit:integer}. The part after expected is generated from the schema, so it cannot drift when you edit the schema. That property matters more than the phrasing: hand-written repair hints go stale, generated ones do not.
Note what this costs. additionalProperties: False is strict — a provider that adds a harmless metadata field will fail validation. That is the point: an unexpected field means either the model hallucinated a parameter or your schema is behind your code, and both deserve a loud failure rather than a **kwargs shrug.
Classified errors instead of strings
A string error can be logged. A classified error can be decided on. The taxonomy below is deliberately small; eight codes cover the failures I have actually seen in tool-using agents, and each maps to an action.
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_afterThe classification rule is one question: would an identical second attempt, with no changes, plausibly succeed? rate_limited, timeout and upstream_error say yes. invalid_arguments, unknown_tool, not_found, permission_denied and internal_error say no — the first three need a different call, the last two need a human. That question is the whole reason not to retry everything: every wasted retry is a step consumed from max_steps, and at three attempts per tool call, a five-tool budget collapses to two.
Tool gains three contract fields, and the description is now load-bearing in a way it was not in Part 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)The three tools now declare honest schemas, and the two that failed silently before now fail loudly. _search raises a classified ToolError instead of returning an empty list when its backend is down, because an empty list and a timeout mean opposite things to the 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, ), ]minLength: 2 on query is not cosmetic. It is the cheapest possible defence against the empty-query case that produced all twelve silent failures: an empty string is now rejected by the contract before the tool body ever sees it.
Retry that cannot duplicate a side effect
Backoff is the easy half. The hard half is that retrying a write can write twice: the request succeeded, the response was lost, and your retry creates a second note. The fix is a key derived from the tool name and the canonicalised arguments, plus a rule about which calls may reuse a cached result.
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 is what makes the key stable: {"a": 1, "b": 2} and {"b": 2, "a": 1} are the same call and must produce the same key, or the guard leaks. Jitter is not a nicety either — without it, ten workers that hit the same 429 retry in lockstep and hit it again together; ±25% spreads them.
The executor is where the four concerns compose, and its ordering is the design: validate, then de-duplicate, then execute, then classify, then retry. Validation before de-duplication means a malformed call never occupies a 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)Two subtleties worth naming. The cache-reuse condition is tool.side_effect or not cached.ok: a write may reuse a cached success (that is at-most-once), and any call may reuse a cached failure (that is a negative cache, which stops a stuck model from re-burning quota on the same broken call). Read-only successes are deliberately not cached, because a search that returned nothing two minutes ago may return something now, and stale reads are their own class of wrong answer.
The second subtlety is the timeout. future.result(timeout=...) bounds how long you wait, not how long the tool runs — Python cannot kill a thread. A tool that ignores the timeout keeps burning CPU in the background while the loop moves on. That is an honest limitation, and it is exactly why Part 11 replaces this with a process-level sandbox. Do not read timeout_s as a safety boundary; read it as a latency budget.
Wiring it into the loop, plus the LLM retry we skipped
Part 1 left a gap I flagged explicitly: AgentLoop.run guarded tool.run but not llm.complete, so a single 503 from the model endpoint killed the whole run. The same policy closes it, applied to 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))A 401 is raised on the first attempt, not the third: a bad key stays bad, and three attempts only triple your latency before failing. A 400 is classified as invalid_arguments for the same reason — your payload is wrong and resending it is pointless.
The loop change is small, and the trace is where the value shows up:
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"The SYSTEM prompt now names the error format. That is not prompt-engineering mysticism: the model is told the exact string it will see on failure and what to do with it. It costs one sentence and measurably reduces the number of turns spent flailing after a validation error, because the repair target is in the error itself.
Run it, and the trace reads like a diagnosis rather than a 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=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=TrueStep 0 shows the contract rejecting the call. Step 1 shows the model recovering on the next turn — that recovery is caused by the error message, which is why the hint is generated from the schema. Step 3 shows an identical write request served from cache with attempts=0: no second file, no second network call.
Failure modes and how to handle them
| Failure | What actually happens | Handling here | What still breaks |
|---|---|---|---|
| Model sends a renamed key | additionalProperties: False flags it, required names the missing field |
Explicit invalid_arguments with a schema hint; model repairs next turn |
A model that ignores the hint burns all steps |
Model sends true for an integer |
Python treats bool as int, so a naive check passes |
isinstance(value, bool) guard rejects it |
Nothing — this is closed |
| Tool hangs | Thread keeps running after future times out |
timeout_s returns timeout, retried up to budget |
Process-level CPU burn; no kill switch (Part 11) |
| 429 storm | Every attempt re-hits the limit | Bounded attempts, exponential backoff, ±25% jitter | No cross-process rate limiter (Part 12) |
| Lost response on a write | Retry would duplicate the file | Idempotency key + side_effect=True returns cached success |
In-memory store dies with the process (Part 8) |
| Same broken call repeated | Model loops on one error | Negative cache stops re-execution | Loop still spends steps; needs a repeat detector |
| Schema and code drift | Validation rejects a field the tool needs | describe_schema regenerates the hint from the schema |
Nothing detects drift automatically |
The last row is the one that bit me. describe_schema is correct only because both it and validate_args read the same dict. If you hand-write a second copy of the schema in the prompt, the two will diverge within a month — and the failure will look like a model error, not a maintenance error.
Trade-offs
| Decision | Alternative | Why we chose it | Cost |
|---|---|---|---|
| Hand-rolled subset validator | jsonschema or Pydantic |
Zero deps, ~120 lines, errors shaped for a model | No $ref/oneOf/pattern; you maintain it |
Errors as ToolResult values |
Raise exceptions through the loop | The model can read and repair; loop stays simple | Callers must check ok everywhere |
additionalProperties: False |
Permissive extra fields | Catches hallucinated parameters immediately | Breaks when a provider adds metadata |
| In-memory idempotency keys | Redis or SQLite | One dict, no infra, testable | Not shared across workers; lost on restart |
| Thread timeout | Process sandbox | 10 lines, no IPC | Cannot kill a runaway tool (Part 11) |
| Retry only 3 codes | Retry everything once | Preserves the step budget | A flaky not_found is never retried |
| Cache negative results | Always re-execute | Stops retry storms from a looping model | A transient failure misclassified as permanent stays cached |
The validator choice deserves the most scrutiny. Pydantic would give you coercion, nested models, and better error messages for free — at the cost of a dependency, slower import, and error objects you must translate into model-readable text anyway. At eight tool schemas, the hand-rolled version wins. At eighty, it does not.
Testing it
Fourteen tests, offline, under a tenth of a second. Save the module as contracts.py and the tests as test_contracts.py; run python3 -m unittest test_contracts -v. The full suite is in the repository, but these five carry the design:
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 looks like trivia and is not: it is the one line standing between {"limit": true} and a silently truncated result set. test_side_effect_runs_once_per_key is the only test that protects data rather than latency. If you keep two tests, keep those.
One more check worth running by hand: point Flaky at RATE_LIMITED with max_attempts=99 and confirm the executor stops at the policy bound. A retry loop without a bound is an outage with extra steps.
Exercises
- Cross-process idempotency. Replace
IdempotencyStorewith a SQLite-backed version keyed by(name, args_hash)and acreated_attimestamp. Expire keys older than ten minutes. What changes about the failure mode where a process dies mid-write, and why does the TTL need to be longer than your longest retry window? - Per-tool retry overrides. A search backend rate-limits aggressively; a note write should be retried once at most. Add a
policyfield toToolthat overrides the executor default, and write a test proving asave_notecall under a 429 returns after two attempts, not four. - Coercion with a receipt. Instead of rejecting
{"limit": "3"}, accept it, convert to3, and append a note to the tool result:coerced: limit "3" -> 3. Measure how many turns that saves on a 50-call trace. Which is more dangerous — silent coercion or a rejected call — and what does the receipt change?
Exercise 3 is the interesting one because it has no single right answer. Coercion reduces round trips and hides model errors; rejection is louder and slower. The receipt is the compromise: you get the round trip back and keep an audit trail of every assumption you made on the model’s behalf.
What’s next
Your tools now have contracts, your failures have codes, and your retries cannot duplicate a write. What has not changed since Part 1 is the thing that will hurt first in production: the message list grows on every step, and every earlier message is resent in full on every call.
Part 3, Context budget engineering, adds a ContextBudget that measures tokens before each call, allocates the window between system prompt, tool results and history, and compresses old turns when the estimate exceeds the budget. It also quantifies the quadratic input growth from Part 1’s table and shows which of the three compression strategies — truncate, summarise, evict — actually pays for itself. The ToolExecutor you just built stays exactly as it is; the budget wraps the history, not the tools.
Get Ball — Ball
Get Ball