[Day 07/30] Enforcing Deterministic Token Ceilings and Multi-Provider Failover in Tool-Calling Loops A developer published a 90-line pure-Python 3.11+ DeterministicToolRouter that enforces cumulative token and cost ceilings across tool-calling loops, rejects boolean values masquerading as integers in hallucinated JSON payloads, repairs malformed JSON with a single local retry, and fails over to a cheaper secondary model on HTTP 502/503 errors. The script simulates a 30-step agent loop where a hallucinated boolean and two gateway outages are handled before a 4,000-token ceiling halts execution cleanly. 📚 Ordered Python & AI Reliability Curriculum — Days 01 to 18 Click to Expand Full ordered archive & interactive reader: faultlessai.whop.site https://faultlessai.whop.site/ ⚡ Want all 18 verified .py modules + unit tests in one download? Grab the Complete 18-Day Python & SQLite Reliability Code Pack $6 · MIT License https://whop.com/checkout/plan xZHuNiWiiXNuQ/?utm source=devto&utm medium=curriculum nav&utm campaign=enforcing-deterministic-token-ceilings-and-multi&slug=enforcing-deterministic-token-ceilings-and-multi-provider-failover-in-tool-d368ec&sku=complete-18day-python-reliability-code-pack . Autonomous tool-calling scripts rarely fail with a clean crash during development; they fail at 03:00 UTC when an upstream schema change or cyclic prompt triggers a silent retry loop that runs until your API credit card hits its monthly hard limit. Even small scheduled workflows suffer three recurring reliability hazards when calling external LLM or JSON endpoints: max tokens parameters only cap a single HTTP call—they do nothing to stop a malfunctioning while loop from issuing 400 sequential 300-token tool calls in ten minutes. isinstance True, int Trap: bool is a subclass of int . A hallucinated JSON payload {"limit": true} passes isinstance val, int unless booleans are explicitly rejected before arithmetic or SQL binding. 502 Outages Identically: 502 Bad Gateway against the same broken primary model wastes latency, whereas failing over to a secondary model on a minor JSON syntax typo throws away context that a 1-turn REPAIR JSON hint fixes locally. In this teardown covering Preventing runaway overnight API bills with strict scalar schema validation and instant secondary-provider failover. reference: Python 3 Standard Library Docs https://docs.python.org/3/library/dataclasses.html , we implement and verify a 90-line DeterministicToolRouter in pure Python 3.11+ that enforces strict scalar validation, repairs malformed JSON in place, fails over across model tiers on 502 errors, and halts deterministically the instant a token or cent ceiling is reached. | Risk Vector | Fragile Pattern | Deterministic Guardrail | |---|---|---| | Cyclic Tool Loops | Limiting only max output tokens per single completion | Track cumulative tokens used and cost cents across every attempt and raise BudgetCeilingError pre-call | | Boolean Type Confusion | isinstance payload "limit" , int | Explicitly reject isinstance val, bool and expected type is int before accepting tool arguments | | Malformed JSON Output | Crashing the entire job on the first invalid field | Append a concise REPAIR JSON hint for at most 1 local retry before escalating | | Primary Gateway 502 / 503 | Sleeping on the broken primary provider | Break out of the primary retry loop immediately on transport errors and route to lean-secondary | For a standalone HTTP Retry-After client and SQLite cron guard you can drop into any Python script at zero cost, grab the Free Idempotent Cron & Circuit-Breaker Mini-Kit $0+ PWYW https://whop.com/checkout/plan rNDWoO6bujfMk/?utm source=devto&utm medium=tutorial&utm campaign=enforcing-deterministic-token-ceilings-and-multi&slug=enforcing-deterministic-token-ceilings-and-multi-provider-failover-in-tool-d368ec&sku=free-idempotent-cron-mini-kit . The standalone script below simulates a 30-step agent loop where step 2 emits a hallucinated boolean {"limit": true} , steps 4 and 5 hit HTTP 502 on frontier-primary routing automatically to lean-secondary at 1/6th the token cost , and the cumulative 4,000 -token ceiling halts execution cleanly before the loop can overspend: python from future import annotations import json import time from dataclasses import dataclass from pathlib import Path from typing import Callable, Mapping class BudgetCeilingError RuntimeError : pass @dataclass class ModelRoute: name: str cost per 1k tokens cents: float invoke: Callable str , tuple str, int class DeterministicToolRouter: def init self, routes: list ModelRoute , , max tokens: int, max cost cents: float - None: self.routes = routes self.max tokens = max tokens self.max cost cents = max cost cents self.tokens used = 0 self.cost cents = 0.0 def call tool step self, prompt: str, required types: Mapping str, type - tuple dict, str : if self.tokens used = self.max tokens or self.cost cents = self.max cost cents: raise BudgetCeilingError f"ceiling hit:tokens={self.tokens used},cents={self.cost cents:.3f}" for route in self.routes: for attempt in range 1, 3 : if self.tokens used = self.max tokens or self.cost cents = self.max cost cents: raise BudgetCeilingError f"ceiling hit:tokens={self.tokens used},cents={self.cost cents:.3f}" try: raw, tok = route.invoke prompt if attempt == 1 else prompt + "\nREPAIR JSON" except RuntimeError: break Transport failure - immediate secondary provider failover self.tokens used += tok self.cost cents = round self.cost cents + tok / 1000.0 route.cost per 1k tokens cents, 4 try: obj = json.loads raw for k, typ in required types.items : if k not in obj or isinstance obj k , bool and typ is int or not isinstance obj k , typ : raise ValueError f"schema:{k}" return obj, route.name except ValueError: continue raise RuntimeError "all routes exhausted" def run budget simulation - None: t0 = time.perf counter step counter = {"n": 0} def primary call p: str - tuple str, int : step counter "n" += 1 if step counter "n" in {4, 5}: raise RuntimeError "http 502 bad gateway" if "REPAIR JSON" not in p and step counter "n" == 2: return '{"tool":"search","limit":true}', 320 bool instead of int bug return '{"tool":"search","limit":5}', 310 def fallback call p: str - tuple str, int : return '{"tool":"search fallback","limit":3}', 240 routes = ModelRoute "frontier-primary", cost per 1k tokens cents=1.5, invoke=primary call , ModelRoute "lean-secondary", cost per 1k tokens cents=0.25, invoke=fallback call , router = DeterministicToolRouter routes, max tokens=4 000, max cost cents=5.0 schema = {"tool": str, "limit": int} completed steps = 0 secondary rescues = 0 halted by budget = False for in range 30 : try: , winner = router.call tool step "select next tool", schema completed steps += 1 if winner == "lean-secondary": secondary rescues += 1 except BudgetCeilingError: halted by budget = True break report = { "completed steps": completed steps, "secondary rescues": secondary rescues, "tokens consumed": router.tokens used, "token ceiling": router.max tokens, "cost cents": router.cost cents, "halted cleanly at ceiling": halted by budget, "elapsed ms": round time.perf counter - t0 1000.0, 2 , } Path "budget report.json" .write text json.dumps report, indent=2 , encoding="utf-8" print json.dumps report, indent=2 if name == " main ": run budget simulation We now verify in an isolated shell check that both 502 outages failed over without dropping steps and that cumulative spend halted cleanly at the configured budget boundary: python python3 -I -c ' import json b = json.load open "budget report.json" assert b "halted cleanly at ceiling" is True and b "secondary rescues" == 2 assert b "tokens consumed" <= b "token ceiling" + 350 and b "cost cents" < 6.5 print f"Verified hard token ceiling: halted runaway loop at {b "tokens consumed" } tokens ${b "cost cents" /100:.4f} with {b "secondary rescues" } seamless failovers." ' Both blocks above were executed inside an isolated environment before staging. Here is the exact captured output: Block 1 python, exit=0, 59.7 ms { "completed steps": 12, "secondary rescues": 2, "tokens consumed": 3900, "token ceiling": 4000, "cost cents": 5.25, "halted cleanly at ceiling": true, "elapsed ms": 0.1 } Block 2 bash, exit=0, 47.2 ms Verified hard token ceiling: halted runaway loop at 3900 tokens $0.0525 with 2 seamless failovers. Three numbers in budget report.json highlight why deterministic accounting beats complex agent middleware: http 502 bad gateway , DeterministicToolRouter skipped pointless retries on frontier-primary and completed both steps via lean-secondary secondary rescues == 2 at 0.25 cents per 1K tokens instead of 1.50 cents. BudgetCeilingError tripped as soon as tokens consumed crossed the 4,000 -token threshold halted cleanly at ceiling == True , capping total run cost around six cents. In production, persist tokens consumed and cost cents alongside each job ID in your SQLite WAL ledger so even process restarts cannot reset a runaway job's budget counter. To keep visibility sharp without pulling in heavy observability agents, log a single structured JSON summary line at the end of every tool-calling workflow containing job id , completed steps , tokens consumed , cost cents , secondary rescues , and halted cleanly at ceiling . Querying those five fields across daily logs immediately reveals whether an upstream provider upgrade silently degraded JSON schema compliance or increased average repair retries per run—before your monthly invoice ever surprises you. Want production-ready Python llm circuit breaker.py and Node/TypeScript agent guardrails.mjs + .d.ts routers paired with a transactional SQLite WAL job queue, constant-time HMAC webhook guards, double-entry SQL ledgers, and 4 GitHub Actions workflows? Pick up the Production AI Agent & Zero-Cost Backend Reliability Starter Kit $14, MIT License https://whop.com/tharusha-nuwansara/production-ai-agent-zero-cost-backend-reliability-starter-kit/?utm source=devto&utm medium=tutorial&utm campaign=enforcing-deterministic-token-ceilings-and-multi&slug=enforcing-deterministic-token-ceilings-and-multi-provider-failover-in-tool-d368ec&sku=production-agent-automation-kit . Verification & Disclosure: Published under the Zero-Cost Production Reliability column by Tharusha Nuwansara . Every Python and shell block above was executed and verified inside an isolated python3 -I sandbox returncode == 0 prior to publication.