{"slug": "day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in", "title": "[Day 07/30] Enforcing Deterministic Token Ceilings and Multi-Provider Failover in Tool-Calling Loops", "summary": "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.", "body_md": "**📚 Ordered Python & AI Reliability Curriculum — Days 01 to 18 (Click to Expand)**\n\nFull ordered archive & interactive reader: [faultlessai.whop.site](https://faultlessai.whop.site/)\n\n⚡ **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).\n\nAutonomous 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:\n\n`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.\nIn 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.\n\n| Risk Vector | Fragile Pattern | Deterministic Guardrail | \n|---|---|---|\n| **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 | \n| **Boolean Type Confusion** | `isinstance(payload[\"limit\"], int)` | Explicitly reject `isinstance(val, bool) and expected_type is int` before accepting tool arguments | \n| **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 | \n| **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` | \n\nFor 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).\n\nThe 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:\n\n``` python\nfrom __future__ import annotations\n\nimport json\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Callable, Mapping\n\nclass BudgetCeilingError(RuntimeError):\n    pass\n\n@dataclass\nclass ModelRoute:\n    name: str\n    cost_per_1k_tokens_cents: float\n    invoke: Callable[[str], tuple[str, int]]\n\nclass DeterministicToolRouter:\n    def __init__(self, routes: list[ModelRoute], *, max_tokens: int, max_cost_cents: float) -> None:\n        self.routes = routes\n        self.max_tokens = max_tokens\n        self.max_cost_cents = max_cost_cents\n        self.tokens_used = 0\n        self.cost_cents = 0.0\n\n    def call_tool_step(self, prompt: str, required_types: Mapping[str, type]) -> tuple[dict, str]:\n        if self.tokens_used >= self.max_tokens or self.cost_cents >= self.max_cost_cents:\n            raise BudgetCeilingError(f\"ceiling_hit:tokens={self.tokens_used},cents={self.cost_cents:.3f}\")\n\n        for route in self.routes:\n            for attempt in range(1, 3):\n                if self.tokens_used >= self.max_tokens or self.cost_cents >= self.max_cost_cents:\n                    raise BudgetCeilingError(f\"ceiling_hit:tokens={self.tokens_used},cents={self.cost_cents:.3f}\")\n                try:\n                    raw, tok = route.invoke(prompt if attempt == 1 else prompt + \"\\nREPAIR_JSON\")\n                except RuntimeError:\n                    break  # Transport failure -> immediate secondary provider failover\n                self.tokens_used += tok\n                self.cost_cents = round(self.cost_cents + (tok / 1000.0) * route.cost_per_1k_tokens_cents, 4)\n                try:\n                    obj = json.loads(raw)\n                    for k, typ in required_types.items():\n                        if k not in obj or (isinstance(obj[k], bool) and typ is int) or not isinstance(obj[k], typ):\n                            raise ValueError(f\"schema:{k}\")\n                    return obj, route.name\n                except ValueError:\n                    continue\n        raise RuntimeError(\"all_routes_exhausted\")\n\ndef run_budget_simulation() -> None:\n    t0 = time.perf_counter()\n    step_counter = {\"n\": 0}\n\n    def primary_call(p: str) -> tuple[str, int]:\n        step_counter[\"n\"] += 1\n        if step_counter[\"n\"] in {4, 5}:\n            raise RuntimeError(\"http_502_bad_gateway\")\n        if \"REPAIR_JSON\" not in p and step_counter[\"n\"] == 2:\n            return '{\"tool\":\"search\",\"limit\":true}', 320  # bool instead of int bug!\n        return '{\"tool\":\"search\",\"limit\":5}', 310\n\n    def fallback_call(_p: str) -> tuple[str, int]:\n        return '{\"tool\":\"search_fallback\",\"limit\":3}', 240\n\n    routes = [\n        ModelRoute(\"frontier-primary\", cost_per_1k_tokens_cents=1.5, invoke=primary_call),\n        ModelRoute(\"lean-secondary\", cost_per_1k_tokens_cents=0.25, invoke=fallback_call),\n    ]\n    router = DeterministicToolRouter(routes, max_tokens=4_000, max_cost_cents=5.0)\n    schema = {\"tool\": str, \"limit\": int}\n\n    completed_steps = 0\n    secondary_rescues = 0\n    halted_by_budget = False\n    for _ in range(30):\n        try:\n            _, winner = router.call_tool_step(\"select_next_tool\", schema)\n            completed_steps += 1\n            if winner == \"lean-secondary\":\n                secondary_rescues += 1\n        except BudgetCeilingError:\n            halted_by_budget = True\n            break\n\n    report = {\n        \"completed_steps\": completed_steps,\n        \"secondary_rescues\": secondary_rescues,\n        \"tokens_consumed\": router.tokens_used,\n        \"token_ceiling\": router.max_tokens,\n        \"cost_cents\": router.cost_cents,\n        \"halted_cleanly_at_ceiling\": halted_by_budget,\n        \"elapsed_ms\": round((time.perf_counter() - t0) * 1000.0, 2),\n    }\n    Path(\"budget_report.json\").write_text(json.dumps(report, indent=2), encoding=\"utf-8\")\n    print(json.dumps(report, indent=2))\n\nif __name__ == \"__main__\":\n    run_budget_simulation()\n```\n\nWe 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:\n\n``` python\npython3 -I -c '\nimport json\nb = json.load(open(\"budget_report.json\"))\nassert b[\"halted_cleanly_at_ceiling\"] is True and b[\"secondary_rescues\"] == 2\nassert b[\"tokens_consumed\"] <= b[\"token_ceiling\"] + 350 and b[\"cost_cents\"] < 6.5\nprint(f\"Verified hard token ceiling: halted runaway loop at {b[\"tokens_consumed\"]} tokens (${b[\"cost_cents\"]/100:.4f}) with {b[\"secondary_rescues\"]} seamless failovers.\")\n'\n```\n\nBoth blocks above were executed inside an isolated environment before staging. Here is the exact captured output:\n\n```\n# Block 1 (python, exit=0, 59.7 ms)\n{\n  \"completed_steps\": 12,\n  \"secondary_rescues\": 2,\n  \"tokens_consumed\": 3900,\n  \"token_ceiling\": 4000,\n  \"cost_cents\": 5.25,\n  \"halted_cleanly_at_ceiling\": true,\n  \"elapsed_ms\": 0.1\n}\n\n# Block 2 (bash, exit=0, 47.2 ms)\nVerified hard token ceiling: halted runaway loop at 3900 tokens ($0.0525) with 2 seamless failovers.\n```\n\nThree numbers in `budget_report.json` highlight why deterministic accounting beats complex agent middleware:\n\n`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.\nIn 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.\n\nTo 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.\n\nWant 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).\n\n*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.*", "url": "https://wpnews.pro/news/day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in", "canonical_source": "https://dev.to/faultlessai/day-0730-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in-tool-calling-loops-4164", "published_at": "2026-12-05 18:56:48+00:00", "updated_at": "2026-12-05 19:13:37.647565+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["DeterministicToolRouter", "Python 3.11"], "also_reported_by": [], "takeaway": "Track cumulative tokens_used and cost_cents across every attempt and raise a BudgetCeilingError before each call, since max_tokens only caps a single HTTP request and cannot stop a runaway loop from issuing hundreds of calls.", "recommendation": {"advice": "Enforce a cumulative token and cent ceiling before every model call, reject booleans where ints are expected, and fail over to a cheaper secondary model immediately on 502/503 rather than retrying the primary.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in", "markdown": "https://wpnews.pro/news/day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in.md", "text": "https://wpnews.pro/news/day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in.txt", "jsonld": "https://wpnews.pro/news/day-07-30-enforcing-deterministic-token-ceilings-and-multi-provider-failover-in.jsonld"}}