Four flagship-class API models now sit inside a 4x output-price band. GPT-6.2 Sol lists at $10 per million output tokens, Gemini 4 Neon at $15, and both GPT-6.2 Astra and Claude Fable 5.2 at $40. An LLM router turns that spread into savings by sending easy prompts to the cheap end and hard prompts to the expensive end, then falling back to another vendor when one returns a 429.

The router built below is under 400 lines of Python 3.12 plus a 93-line test file. It classifies each prompt into a tier, walks a fallback chain across OpenAI, Google and Anthropic, trips a circuit breaker on repeat failures, refuses requests that would break a per-call or daily budget, and can ask a model from a second vendor to check the first model’s answer. A fifth slot for GLM-5.4 ships switched off, because Zhipu’s API access was not confirmed as of December 2, 2026.

An earlier Claude and GPT router build covered the two-vendor case. This version adds Gemini 4 Neon, a spend ledger, the cross-vendor verifier, and the model lineup that shipped in November. Everything runs offline in demo mode first, so you can test the logic before you spend a cent.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

Add now

What an LLM Router Does and When It Pays Off

A router sits between your application and the model APIs. Your code calls one function. The router decides which model answers, what happens when that model fails, and how much the call costs. Those three jobs (choose, survive, account) are the whole product, and every router from a 50-line script to a hosted gateway does some version of them.

Choosing is the part people notice. A prompt that says summarize this paragraph does not need the most expensive model on the market, and a prompt that asks for a root-cause analysis of a flaky distributed system does not belong on the cheapest. Surviving matters more in production than the choice itself. Every vendor has rate limits, regional incidents and the occasional bad deploy, and a router that retries on a second vendor turns a page at 3 a.m. into a log line. Accounting is what keeps the bill honest. Without a ledger, nobody can say which feature burned the budget.

The arithmetic is simple. Take a request with 2,000 input tokens and 500 output tokens. On GPT-6.2 Sol that costs $0.009. On GPT-6.2 Astra it costs $0.036, exactly four times more. If 70% of your traffic is light and 30% is hard (an illustrative mix, so measure your own), routing light work to Sol and hard work to Astra costs noticeably less per request on average than the $0.036 of sending everything to Astra, with no change to the hard answers.

A router does not pay off everywhere. If your product runs one narrow task, a single well-tested model usually beats a routed pair, because you evaluate once instead of per model. If you make a few hundred calls a month, the engineering time costs more than the savings. And if a regulator or customer contract pins you to one vendor, a cross-vendor chain is off the table.

Build or Buy

Hosted aggregators such as OpenRouter already list Gemini 4 Neon behind one API key, and open-source gateways like LiteLLM and Cloudflare AI Gateway add routing, caching and logging. Buy when you want that breadth fast. Build when you need policy those products do not express, such as a verifier from a second vendor on high-risk answers, your own spend ledger, or a hard rule that certain prompts never leave a given provider. The code below is small enough that building costs an afternoon.

The Routing Table: Four Models, Four Price Points

Every number in the router’s config comes from vendor pricing pages checked on December 2, 2026. Prices are per million tokens in US dollars.

| Model | Vendor | API ID | Input | Cached input | Output | Status on Dec 2, 2026 | |---|---|---|---|---|---|---| | GPT-6.2 Astra | OpenAI | gpt-6.2-astra | $8 | $0.40 | $40 | Released | | GPT-6.2 Sol | OpenAI | gpt-6.2-sol | $2 | $0.10 | $10 | Released | | Gemini 4 Neon | | gemini-4-neon | $3 | $0.15 | $15 | Released, 1M-token context | | Claude Fable 5.2 | Anthropic | copy from the Fable 5.2 docs | $8 | $0.20 (cache read) | $40 | Released | | GLM-5.4 | Zhipu AI (Z.ai) | not confirmed | not published | not published | not published | Coding Plan only, API not confirmed |

Several details in that table trip people up. OpenAI separates the product from the endpoint: GPT-6.2 is what ChatGPT calls its chat model, while API users pick GPT-6.2 Astra or GPT-6.2 Sol. OpenAI’s API guidance reportedly points Astra at the most demanding tasks and Sol at complex work at lower cost. There is no standalone gpt-6.2 endpoint to route to. OpenAI also describes promotional pricing on the Astra and Sol variants as available at least through December 31, 2026, so treat the table as a snapshot and keep prices in config, not scattered through code.

Anthropic announced Claude Fable 5.2 on November 9 alongside Claude Mythos 5.2. It cut the price from Fable 5.1’s $10 input and $50 output to $8 and $40, and Anthropic says Fable 5.2 generates output up to 30% faster than 5.1. An optional fast mode costs $16 input and $80 output per million tokens and generates up to 2.5 times faster. Fable 5.1 is now the older version, so the router does not include it.

Google positions Gemini 4 Neon between Gemini 4 Hydrogen and Gemini 4 Carbon. Its $0.15 cached-input rate is a 95% discount on the $3 base input price, according to Google, and it exposes four reasoning levels: low, medium, high (the default) and xhigh. That cache discount makes Neon the natural home for prompts that repeat a long system prompt.

GLM-5.4 is the odd row. Zhipu reportedly describes it as its first flagship built on a Loop Transformer, a roughly 750B-scale design that runs 28 layers twice. As of December 2 it is available through the GLM Coding Plan and partner coding tools, but Zhipu reportedly said its API would open only after a safety evaluation, and a third-party model tracker entry does not change that. The router therefore ships a disabled GLM slot with no prices, and you flip it on when the API goes live.

Prerequisites and Versions

Set these up before step 1. The versions below are the ones the code was tested against.

  • Python 3.12 or newer. The code usesX | None type hints and was tested on 3.12.3.
  • httpx 0.29.0. Any recent 0.27+ release should work. The router usesAsyncClient only.
  • pytest and pytest-asyncio. Needed for the test suite in step 11.
  • Three API keys for the live run:OPENAI_API_KEY ,GEMINI_API_KEY andANTHROPIC_API_KEY . Demo mode needs none of them.
  • The exact Claude Fable 5.2 model ID, copied from Anthropic’s model overview page and exported asFABLE_MODEL_ID . The router refuses to guess it.
  • A spending cap on every vendor dashboard. The live smoke test in step 12 costs well under $2, but a loop bug can cost more.
  • A Linux, macOS or WSL shell. Windows PowerShell users swapsource .venv/bin/activate for.venv\Scripts\Activate.ps1 .
  • About 85 minutes, most of it reading the code you paste.

You also need basic comfort with async/ await. The router awaits one HTTP call at a time, so there is no concurrency to reason about, but every provider method is a coroutine.

Router Design: Tiers, Fallback Chains, Breakers and Budgets

The design has five moving parts, and each maps to one file.

Tiers. A cheap heuristic scores every prompt as light, standard or hard. It looks at word count, code fences and trigger words such as refactor or trade-offs. A heuristic is deliberately dumb. It costs nothing, it never fails, and you can read its decisions in a log. Teams that outgrow it can swap in a small model as the classifier later, and the rest of the router does not change.

Chains. Each tier maps to an ordered list of models. The first available model answers. If it fails with a retryable error, the router moves down the list. The order encodes policy: light prompts start at Sol, standard ones at Neon, hard ones at Astra.

Circuit breaker. Three consecutive retryable failures open the breaker for a model, and it stays open for 60 seconds. During that window the router skips the model without calling it, which saves latency and keeps you from hammering a vendor that is already struggling.

Budget guard. Before each call the router computes a worst-case cost from the prompt length and the output cap. A model whose worst case exceeds $0.50 is skipped for that request. A ledger file totals the last 24 hours of spend, and the router stops at $20.

Verifier. For answers that matter, a second call goes to a model from a different vendor, which grades the first answer as pass or fail with a one-sentence reason. Using another vendor avoids the habit models have of approving their own work. OpenAI’s model selection guide covers picking among one vendor’s models, and a router extends the same trade-off across vendors.

| Tier | First choice | Fallback order | Typical prompts | Why this order | |---|---|---|---|---| | light | Sol | Neon, Fable, Astra | Summaries, extraction, reformatting | Lowest price at $2 in and $10 out | | standard | Neon | Sol, Fable, Astra | Question answering with context, drafting, mid-size code edits | Cheap cached input and a 1M-token window | | hard | Astra | Fable, Neon, Sol | Architecture reviews, root-cause analysis, multi-step plans | Strongest tier first, cross-vendor second |

The hard chain puts Fable second on purpose. If OpenAI is down, the next-best answer should come from a different vendor, not from Sol on the same failing API.

Steps 1 to 3: Project, Model Table, Task Classifier

Step 1: Create the project and virtual environment

Make a folder, a virtual environment, and install the three dependencies. Pin the versions in a requirements file so a teammate gets the same behavior.

mkdir llmrouter && cd llmrouter
python3 -m venv .venv
source .venv/bin/activate
pip install httpx==0.29.0 pytest==9.2.0 pytest-asyncio==1.5.0
mkdir llmrouter tests
touch llmrouter/__init__.py
printf '[pytest]\nasyncio_mode = auto\nasyncio_default_fixture_loop_scope = function\n' > pytest.ini
pip freeze > requirements.txt

The pytest.ini line matters. With asyncio_mode = auto, every async def test_ runs without a decorator, and the fixture-scope line silences a deprecation warning from pytest-asyncio.

Step 2: Write the model table

Create llmrouter/config.py. It holds the price table, the tier chains, and the four numeric limits. Nothing else in the project hard-codes a price.

import os
from dataclasses import dataclass

@dataclass(frozen=True)
class Model:
    key: str
    provider: str
    model_id: str
    in_per_m: float
    out_per_m: float
    cached_per_m: float
    enabled: bool = True
    long_ctx_tokens: int = 0

def build_models() -> dict[str, Model]:
    return {
        "astra": Model("astra", "openai", "gpt-6.2-astra", 8.00, 40.00, 0.40,
                       long_ctx_tokens=272_000),
        "sol": Model("sol", "openai", "gpt-6.2-sol", 2.00, 10.00, 0.10),
        "neon": Model("neon", "gemini", "gemini-4-neon", 3.00, 15.00, 0.15),
        "fable": Model(
            "fable", "anthropic",
            os.environ.get("FABLE_MODEL_ID", "SET_FABLE_MODEL_ID"),
            8.00, 40.00, 0.20,
            enabled="FABLE_MODEL_ID" in os.environ,
        ),
        "glm": Model(
            "glm", "zai", os.environ.get("GLM_MODEL_ID", "SET_GLM_MODEL_ID"),
            0.0, 0.0, 0.0,
            enabled=os.environ.get("GLM_API_OPEN") == "1",
        ),
    }

CHAINS = {
    "light": ["sol", "neon", "fable", "astra"],
    "standard": ["neon", "sol", "fable", "astra"],
    "hard": ["astra", "fable", "neon", "sol"],
}

MAX_REQUEST_USD = 0.50
DAILY_BUDGET_USD = 20.00
BREAKER_THRESHOLD = 3
BREAKER_COOLDOWN_S = 60

Two design choices deserve attention. First, the Fable model ID and the GLM slot read from the environment, and each model’s enabled flag follows whether you supplied the ID, so a missing ID disables the model instead of sending a bad request. Second, GLM carries zero prices and stays off until you set GLM_API_OPEN=1. A zero price would otherwise make GLM look free to the cost guard, which is exactly the wrong signal.

Step 3: Write the task classifier

Create llmrouter/classify.py. The scoring is intentionally crude, and every rule is visible.

import re

HARD = re.compile(
    r"\b(prove|derive|formal|architecture|refactor|security review|"
    r"root cause|migrate|optimi[sz]e|multi-step|trade-?offs?)\b", re.I)
LIGHT = re.compile(
    r"\b(summari[sz]e|translate|rewrite|classify|extract|tl;?dr|"
    r"fix typo|format)\b", re.I)

def classify(prompt: str) -> str:
    words = len(prompt.split())
    score = 0
    if words > 400:
        score += 2
    elif words > 120:
        score += 1
    if "```" in prompt:
        score += 1
    score += 2 * len(HARD.findall(prompt))
    score -= len(LIGHT.findall(prompt))
    if score >= 3:
        return "hard"
    if score <= 0 and words < 80:
        return "light"
    return "standard"

Walk through the logic once. A prompt over 400 words adds 2 points, over 120 words adds 1, and a code fence adds 1. Each hard-keyword hit adds 2, and each light-keyword hit subtracts 1. A score of 3 or more is hard. A score of 0 or less on a short prompt is light. Everything else is standard. Summarize this paragraph scores minus 1 and lands in light. A request to review an architecture and its trade-offs, then refactor, scores 6 and lands in hard.

Resist the urge to tune these numbers on a hunch. Log the tier for every request, review a week of traffic, and adjust against real misroutes.

Steps 4 and 5: Provider Adapters and the Spend Ledger

Step 4: Write the provider adapters

Create llmrouter/providers.py. Two adapter classes cover three vendors. OpenAICompat speaks the chat-completions format, which OpenAI uses natively and which Gemini offers through an OpenAI-compatible endpoint, so one class serves both with a different base URL, key variable and token-limit parameter name. AnthropicMessages speaks Anthropic’s Messages format.

import os
import time
from dataclasses import dataclass

import httpx

class ProviderError(Exception):
    def __init__(self, msg: str, retryable: bool):
        super().__init__(msg)
        self.retryable = retryable

@dataclass
class Completion:
    text: str
    in_tokens: int
    out_tokens: int
    cached_tokens: int
    latency_s: float

def _key(env: str) -> str:
    try:
        return os.environ[env]
    except KeyError:
        raise SystemExit(f"Missing {env}. Export it or run with --demo.") from None

def _raise_for(resp: httpx.Response) -> None:
    if resp.status_code < 400:
        return
    retry = resp.status_code in (408, 409, 429) or resp.status_code >= 500
    raise ProviderError(f"HTTP {resp.status_code}: {resp.text[:200]}", retry)

class OpenAICompat:
    def __init__(self, base_url: str, key_env: str, token_param: str):
        self.base_url, self.key_env, self.token_param = base_url, key_env, token_param

    async def complete(self, model_id, system, prompt, max_tokens, client=None):
        msgs = ([{"role": "system", "content": system}] if system else [])
        msgs.append({"role": "user", "content": prompt})
        body = {"model": model_id, "messages": msgs, self.token_param: max_tokens}
        hdr = {"Authorization": f"Bearer {_key(self.key_env)}"}
        t0 = time.monotonic()
        try:
            async with (client or httpx.AsyncClient(timeout=120)) as c:
                r = await c.post(f"{self.base_url}/chat/completions", json=body, headers=hdr)
        except httpx.TransportError as e:
            raise ProviderError(str(e), True) from e
        _raise_for(r)
        d = r.json()
        u = d.get("usage", {})
        cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
        return Completion(d["choices"][0]["message"]["content"] or "",
                          u.get("prompt_tokens", 0), u.get("completion_tokens", 0),
                          cached, time.monotonic() - t0)

class AnthropicMessages:
    url = "https://api.anthropic.com/v1/messages"

    async def complete(self, model_id, system, prompt, max_tokens, client=None):
        body = {"model": model_id, "max_tokens": max_tokens,
                "messages": [{"role": "user", "content": prompt}]}
        if system:
            body["system"] = system
        hdr = {"x-api-key": _key("ANTHROPIC_API_KEY"),
               "anthropic-version": "2023-06-01"}
        t0 = time.monotonic()
        try:
            async with (client or httpx.AsyncClient(timeout=120)) as c:
                r = await c.post(self.url, json=body, headers=hdr)
        except httpx.TransportError as e:
            raise ProviderError(str(e), True) from e
        _raise_for(r)
        d = r.json()
        u = d.get("usage", {})
        text = "".join(b.get("text", "") for b in d["content"] if b["type"] == "text")
        return Completion(text, u.get("input_tokens", 0), u.get("output_tokens", 0),
                          u.get("cache_read_input_tokens", 0), time.monotonic() - t0)

def default_providers() -> dict:
    return {
        "openai": OpenAICompat("https://api.openai.com/v1", "OPENAI_API_KEY",
                               "max_completion_tokens"),
        "gemini": OpenAICompat(
            "https://generativelanguage.googleapis.com/v1beta/openai",
            "GEMINI_API_KEY", "max_tokens"),
        "anthropic": AnthropicMessages(),
        "zai": OpenAICompat(os.environ.get("ZAI_BASE_URL", "https://example.invalid"),
                            "ZAI_API_KEY", "max_tokens"),
    }

Five details in this file carry most of the weight.

The ProviderError.retryable flag decides everything downstream. Rate limits, request timeouts, server errors and dropped connections are retryable. A bad request, a rejected key, a forbidden call or an unknown model ID is not. Those mean your request, your key or your model ID is wrong, and falling through to the next vendor would only hide a bug that will bite you again tomorrow.

The token-limit parameter differs by vendor. OpenAI’s adapter sends max_completion_tokens and the Gemini adapter sends max_tokens. If a vendor rejects the parameter name with a 400, the fix lives in one constructor argument.

Cached tokens come back in different places. OpenAI-style responses report them under usage.prompt_tokens_details.cached_tokens, while Anthropic reports cache_read_input_tokens. The adapters normalize both into Completion.cached_tokens, which lets the cost function treat them identically.

Anthropic’s adapter sends no thinking or effort parameters. Anthropic’s Fable 5.2 documentation says adaptive thinking is the only thinking mode on that model, so there is no manual budget to set. If you later add reasoning controls for Neon’s low, medium, high and xhigh levels, keep them in the vendor adapter and out of the router.

The _key helper turns a missing environment variable into a one-line message instead of a stack trace. You will hit it the first time you forget to export a key.

Step 5: Write the spend ledger

Create llmrouter/ledger.py. The ledger appends one JSON line per successful call and sums the last 24 hours on demand.

import json
import time
from pathlib import Path

class Ledger:
    def __init__(self, path: str = "spend.jsonl"):
        self.path = Path(path)

    def record(self, row: dict) -> None:
        row = {"ts": time.time(), **row}
        with self.path.open("a") as f:
            f.write(json.dumps(row) + "\n")

    def spent_today(self) -> float:
        if not self.path.exists():
            return 0.0
        cutoff = time.time() - 86400
        total = 0.0
        for line in self.path.read_text().splitlines():
            row = json.loads(line)
            if row["ts"] >= cutoff:
                total += row.get("usd", 0.0)
        return total

A flat file looks primitive next to a database, but it survives restarts, you can read it with tail, and you can load it into a spreadsheet at month end. The cost is that spent_today reads the whole file on every call. At a few thousand calls per day that takes milliseconds. Past that, rotate the file daily or move the totals into SQLite, which is a one-class change because nothing else touches the file.

Steps 6 to 8: Router Core, Circuit Breaker and Cost Guard

Step 6: Write the router core

Create llmrouter/router.py. This file holds the whole decision loop: check the daily budget, pick a tier, walk the chain, skip anything unavailable or too expensive, call the provider, record the spend.

import time
from dataclasses import dataclass, field

from . import config
from .classify import classify
from .ledger import Ledger
from .providers import Completion, ProviderError

class BudgetExceeded(Exception):
    pass

class AllModelsFailed(Exception):
    pass

@dataclass
class RouteResult:
    text: str
    model: str
    tier: str
    usd: float
    attempts: list = field(default_factory=list)
    verdict: str | None = None

def _long_ctx(m: config.Model, tokens_in: float) -> tuple[float, float]:
    if m.long_ctx_tokens and tokens_in > m.long_ctx_tokens:
        return 2.0, 1.5
    return 1.0, 1.0

def usd_cost(m: config.Model, c: Completion) -> float:
    im, om = _long_ctx(m, c.in_tokens)
    fresh = max(c.in_tokens - c.cached_tokens, 0)
    return (im * (fresh * m.in_per_m + c.cached_tokens * m.cached_per_m)
            + om * c.out_tokens * m.out_per_m) / 1_000_000

def worst_case_usd(m: config.Model, prompt: str, max_tokens: int) -> float:
    est_in = len(prompt) / 4 + 50
    im, om = _long_ctx(m, est_in)
    return (im * est_in * m.in_per_m + om * max_tokens * m.out_per_m) / 1_000_000

class Router:
    def __init__(self, models, providers, ledger=None, clock=time.monotonic):
        self.models, self.providers = models, providers
        self.ledger = ledger or Ledger()
        self.clock = clock
        self.fails: dict[str, int] = {}
        self.open_until: dict[str, float] = {}

    def _available(self, key: str) -> bool:
        m = self.models.get(key)
        if m is None or not m.enabled:
            return False
        return self.clock() >= self.open_until.get(key, 0.0)

    def _trip(self, key: str) -> None:
        self.fails[key] = self.fails.get(key, 0) + 1
        if self.fails[key] >= config.BREAKER_THRESHOLD:
            self.open_until[key] = self.clock() + config.BREAKER_COOLDOWN_S
            self.fails[key] = 0

    async def route(self, prompt, system=None, tier=None, max_tokens=1024,
                    only: str | None = None):
        if self.ledger.spent_today() >= config.DAILY_BUDGET_USD:
            raise BudgetExceeded("daily budget spent")
        tier = tier or classify(prompt)
        chain = [only] if only else config.CHAINS[tier]
        attempts = []
        for key in chain:
            if not self._available(key):
                attempts.append((key, "skipped: disabled or breaker open"))
                continue
            m = self.models[key]
            if worst_case_usd(m, prompt, max_tokens) > config.MAX_REQUEST_USD:
                attempts.append((key, "skipped: over per-request cap"))
                continue
            try:
                c = await self.providers[m.provider].complete(
                    m.model_id, system, prompt, max_tokens)
            except ProviderError as e:
                attempts.append((key, f"error: {e}"))
                if e.retryable:
                    self._trip(key)
                    continue
                raise
            self.fails[key] = 0
            usd = usd_cost(m, c)
            self.ledger.record({"model": key, "tier": tier, "usd": usd,
                                "in": c.in_tokens, "out": c.out_tokens})
            attempts.append((key, "ok"))
            return RouteResult(c.text, key, tier, usd, attempts)
        raise AllModelsFailed(attempts)

Read the route method top to bottom once. It first refuses outright if the ledger says you have spent the daily cap. It then resolves the tier, using your explicit tier if you passed one and the classifier otherwise. The loop that follows visits each model in the chain. A model that is disabled, in breaker cooldown, or too expensive for this request gets a skip note in attempts and the loop moves on. A retryable error gets recorded, counts against the breaker, and moves on as well. A fatal error raises immediately. A success records the spend and returns.

The attempts list is the most useful debugging tool in the project. Every result carries the full trail of what the router tried, in order, with the reason for each skip. When a user asks why a request took four seconds or why it cost more than expected, the answer sits in that list.

The only argument forces a single model and skips the chain. The verifier uses it in step 9 to pin the check to a specific second-vendor model.

Step 7: Understand the circuit breaker

The breaker lives in three lines of the class, and it is worth reading closely because the behavior is subtler than it looks.

def _available(self, key: str) -> bool:
    m = self.models.get(key)
    if m is None or not m.enabled:
        return False
    return self.clock() >= self.open_until.get(key, 0.0)

def _trip(self, key: str) -> None:
    self.fails[key] = self.fails.get(key, 0) + 1
    if self.fails[key] >= config.BREAKER_THRESHOLD:
        self.open_until[key] = self.clock() + config.BREAKER_COOLDOWN_S
        self.fails[key] = 0

The failure counter resets to zero on every success, so the threshold of 3 means three failures in a row, not three failures per hour. When the breaker opens, open_until is set 60 seconds out and _available returns false until the clock passes it. The clock is injectable, which is how the test in step 11 jumps forward 61 seconds without sleeping.

This is a simplified breaker. A production-grade one has a half-open state that lets exactly one probe request through after the cooldown, and it only closes fully if that probe succeeds. Here, the first request after cooldown goes through with a fresh counter, so a still-broken vendor needs three more failures to trip again. For a router that falls back on every failure anyway, that costs you three slow requests every minute, which is acceptable. If it is not, add the half-open probe.

Tune the two numbers against vendor behavior. Rate-limit storms often clear in seconds, so a 60-second cooldown can be too long for a workload dominated by rate limits. Regional outages last minutes to hours, so 60 seconds is too short for those. Many teams settle on a short cooldown for rate limits and a longer one for server errors, which means passing the status class into _trip.

Step 8: Understand the cost guard

The guard has two layers. The per-request layer is worst_case_usd, which estimates input tokens at one per four characters plus 50 for message framing, adds the full max_tokens output allowance, and prices the sum at the model’s rates. If that worst case exceeds MAX_REQUEST_USD, the router skips the model for this request. The daily layer is the ledger total, which stops everything at DAILY_BUDGET_USD.

The estimate runs pessimistic on output, since it assumes the model uses every allowed token, and approximate on input, since four characters per token is a rule of thumb that drifts for code and non-English text. That is fine for a guard. It does not need to be exact, it needs to catch a 300,000-token prompt before it reaches an expensive model.

The long-context multiplier in _long_ctx exists because of a pricing rule on OpenAI’s GPT-6.2 Astra model page. For requests above 272K input tokens, input and cache rates double and output costs 1.5 times the short-context rate for the whole request. A guard that ignores this would estimate a 300K-token Astra call at about $2.40 for input when the real figure is closer to $4.80. The test test_long_context_surcharge pins the behavior. OpenAI’s Sol page may carry its own thresholds, so check it before you extend the rule to that model.

Pick the per-request cap from your own traffic. At $0.50, an Astra call with a modest output survives until the prompt gets very long, because the input is what dominates the cost. That suits most chat and coding workloads and blocks accidental whole-repository pastes.

Steps 9 and 10: Cross-Vendor Verifier and Command-Line Entry Point

Step 9: Add the cross-vendor verifier

Create llmrouter/verify.py. After a model answers, the verifier asks a model from a different vendor to grade the answer and return strict JSON.

import json

from .router import RouteResult, Router

VERIFIER_SYSTEM = (
    "You are a strict reviewer. Reply with JSON only: "
    '{"verdict": "pass" or "fail", "reason": "<one sentence>"}.')

def pick_verifier(router: Router, answered_by: str) -> str | None:
    vendor = router.models[answered_by].provider
    for key in ("neon", "fable", "astra", "sol"):
        m = router.models.get(key)
        if m and m.enabled and m.provider != vendor and router._available(key):
            return key
    return None

async def verify(router: Router, question: str, result: RouteResult) -> RouteResult:
    key = pick_verifier(router, result.model)
    if key is None:
        result.verdict = "unverified: no second vendor available"
        return result
    prompt = f"Question:\n{question}\n\nAnswer:\n{result.text}\n\nIs the answer correct and complete?"
    check = await router.route(prompt, VERIFIER_SYSTEM, tier="light",
                               max_tokens=200, only=key)
    try:
        v = json.loads(check.text)
        result.verdict = f"{v['verdict']} ({key}): {v['reason']}"
    except (json.JSONDecodeError, KeyError, TypeError):
        result.verdict = f"unparsed ({key}): {check.text[:80]}"
    result.usd += check.usd
    return result

The picker walks Neon, Fable, Astra, Sol in that order and takes the first enabled, available model whose vendor differs from the answerer’s. If Astra answered, Neon verifies. If Neon answered, Fable verifies. If only one vendor is configured, the verdict says so plainly instead of pretending a check happened, which matters because an unverified answer and a verified one should never look alike in your logs.

The verifier calls route with tier="light", max_tokens=200 and only=key, so it goes through the same breaker, ledger and budget checks as any other call, and its cost folds into result.usd. Note what the verifier cannot do. It cannot catch an error that both models share, and it can approve a fluent wrong answer. Treat a pass as a signal and a fail as a trigger for review or a retry on a stronger model, not as proof.

Verification doubles your call count on the requests you apply it to, so scope it. Run it on the hard tier, on anything that writes to a customer-facing surface, and on a 5% random sample of the rest to measure how often the cheap models are wrong.

Step 10: Write the command-line entry point and demo mode

Create llmrouter/cli.py. It wires the pieces together and adds a --demo flag that swaps real providers for fakes, so the whole router runs without keys or spend.

import argparse
import asyncio
import os
import sys

from . import config
from .providers import Completion, ProviderError, default_providers
from .router import Router
from .verify import verify

class DemoProvider:
    def __init__(self, name, fail=0):
        self.name, self.fail = name, fail

    async def complete(self, model_id, system, prompt, max_tokens, client=None):
        if self.fail > 0:
            self.fail -= 1
            raise ProviderError("HTTP 429: rate limited", True)
        if system and "strict reviewer" in system:
            text = '{"verdict": "pass", "reason": "Answer matches the question."}'
        else:
            text = f"[{self.name}/{model_id}] demo answer"
        return Completion(text, len(prompt) // 4 + 20, 120, 0, 0.4)

def build(demo: bool) -> Router:
    models = config.build_models()
    if demo:
        models = {k: type(m)(**{** m.__dict__, "enabled": k != "glm"})
                  for k, m in models.items()}
        provs = {"openai": DemoProvider("openai", fail=int(os.environ.get("DEMO_FAILS", 0))),
                 "gemini": DemoProvider("gemini"), "anthropic": DemoProvider("anthropic"),
                 "zai": DemoProvider("zai")}
        return Router(models, provs)
    return Router(models, default_providers())

async def main() -> int:
    p = argparse.ArgumentParser(prog="llmrouter")
    p.add_argument("prompt")
    p.add_argument("--tier", choices=list(config.CHAINS))
    p.add_argument("--verify", action="store_true")
    p.add_argument("--demo", action="store_true", help="fake providers, no keys")
    a = p.parse_args()
    router = build(a.demo)
    res = await router.route(a.prompt, tier=a.tier)
    if a.verify:
        res = await verify(router, a.prompt, res)
    print(f"tier={res.tier} model={res.model} cost=${res.usd:.5f}")
    for key, status in res.attempts:
        print(f"  {key:<6} {status}")
    if res.verdict:
        print(f"verdict: {res.verdict}")
    print(res.text)
    return 0

if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

The DemoProvider fails on demand. Set DEMO_FAILS=5 and the first OpenAI call returns a retryable rate-limit error, which lets you watch a fallback happen on your own machine. Because Astra and Sol share one demo provider object, the failure counter is shared too. That mirrors a real vendor-wide rate limit better than per-model counters would.

Steps 11 and 12: Tests and the First Live Run

Step 11: Write the tests

Create tests/test_router.py. The tests use a Fake provider that fails a set number of times, so every failure path runs without a network.

import pytest

from llmrouter import config
from llmrouter.classify import classify
from llmrouter.ledger import Ledger
from llmrouter.providers import Completion, ProviderError
from llmrouter.router import (AllModelsFailed, BudgetExceeded, Router,
                              usd_cost, worst_case_usd)

class Fake:
    def __init__(self, fails=0, retryable=True):
        self.calls, self.fails, self.retryable = 0, fails, retryable

    async def complete(self, model_id, system, prompt, max_tokens, client=None):
        self.calls += 1
        if self.calls <= self.fails:
            raise ProviderError("boom", self.retryable)
        return Completion("ok", 1000, 500, 0, 0.1)

def make(tmp_path, **provs):
    models = {k: type(m)(**{** m.__dict__, "enabled": True})
              for k, m in config.build_models().items() if k != "glm"}
    p = {"openai": Fake(), "gemini": Fake(), "anthropic": Fake()}
    p.update(provs)
    return Router(models, p, Ledger(str(tmp_path / "s.jsonl")))

def test_classify_tiers():
    assert classify("Summarize this paragraph.") == "light"
    assert classify("Review the architecture and trade-offs, then refactor it.") == "hard"
    assert classify("word " * 150) == "standard"

def test_cost_math():
    m = config.build_models()["astra"]
    c = Completion("x", 200_000, 100_000, 50_000, 0.0)
    assert usd_cost(m, c) == pytest.approx(0.15 * 8 + 0.05 * 0.4 + 0.1 * 40)

def test_long_context_surcharge():
    m = config.build_models()["astra"]
    short = worst_case_usd(m, "x" * 4 * 200_000, 1000)
    long = worst_case_usd(m, "x" * 4 * 300_000, 1000)
    assert short == pytest.approx((200_050 * 8 + 1000 * 40) / 1e6)
    assert long == pytest.approx((2 * 300_050 * 8 + 1.5 * 1000 * 40) / 1e6)

async def test_fallback_on_retryable(tmp_path):
    r = make(tmp_path, openai=Fake(fails=99))
    res = await r.route("hi", tier="light")
    assert res.model == "neon"
    assert res.attempts[0][0] == "sol" and "error" in res.attempts[0][1]

async def test_fatal_error_does_not_fall_back(tmp_path):
    r = make(tmp_path, openai=Fake(fails=99, retryable=False))
    with pytest.raises(ProviderError):
        await r.route("hi", tier="light")

async def test_breaker_opens_then_recovers(tmp_path):
    now = [0.0]
    r = make(tmp_path, openai=Fake(fails=99))
    r.clock = lambda: now[0]
    for _ in range(config.BREAKER_THRESHOLD):
        await r.route("hi", tier="light")
    res = await r.route("hi", tier="light")
    assert res.attempts[0] == ("sol", "skipped: disabled or breaker open")
    now[0] += config.BREAKER_COOLDOWN_S + 1
    res = await r.route("hi", tier="light")
    assert "error" in res.attempts[0][1]

async def test_per_request_cap_skips_expensive_model(tmp_path):
    r = make(tmp_path)
    res = await r.route("x" * 40, tier="hard", max_tokens=20_000)
    assert res.attempts[0] == ("astra", "skipped: over per-request cap")

async def test_daily_budget_blocks(tmp_path):
    r = make(tmp_path)
    r.ledger.record({"usd": config.DAILY_BUDGET_USD + 1})
    with pytest.raises(BudgetExceeded):
        await r.route("hi")

async def test_all_fail_raises(tmp_path):
    r = make(tmp_path, openai=Fake(fails=99), gemini=Fake(fails=99),
             anthropic=Fake(fails=99))
    with pytest.raises(AllModelsFailed):
        await r.route("hi", tier="light")

Each test pins one behavior. test_classify_tiers locks the three tier boundaries. test_cost_math checks that cached tokens bill at the cached rate and fresh tokens at the full rate. test_long_context_surcharge proves the 272K multiplier fires on one side of the threshold and not the other. test_fallback_on_retryable shows Sol failing and Neon answering. test_fatal_error_does_not_fall_back proves a 400-class error surfaces instead of hiding. test_breaker_opens_then_recovers drives three failures, confirms the skip, advances a fake clock 61 seconds, and confirms the model gets called again. The last three cover the per-request cap, the daily budget and the all-models-failed path.

Run the suite from the project root.

python -m pytest -v

A clean run prints nine passing tests.

tests/test_router.py::test_classify_tiers PASSED                         [ 11%]
tests/test_router.py::test_cost_math PASSED                              [ 22%]
tests/test_router.py::test_long_context_surcharge PASSED                 [ 33%]
tests/test_router.py::test_fallback_on_retryable PASSED                  [ 44%]
tests/test_router.py::test_fatal_error_does_not_fall_back PASSED         [ 55%]
tests/test_router.py::test_breaker_opens_then_recovers PASSED            [ 66%]
tests/test_router.py::test_per_request_cap_skips_expensive_model PASSED  [ 77%]
tests/test_router.py::test_daily_budget_blocks PASSED                    [ 88%]
tests/test_router.py::test_all_fail_raises PASSED                        [100%]
============================== 9 passed in 0.08s ===============================

Step 12: Run it live

Export the three keys and the Fable model ID, then send one light prompt and one hard prompt with the verifier on. Copy the Fable ID exactly as Anthropic’s model overview page prints it.

export OPENAI_API_KEY=...
export GEMINI_API_KEY=...
export ANTHROPIC_API_KEY=...
export FABLE_MODEL_ID=...   # copy from the Fable 5.2 docs page

python -m llmrouter.cli "Summarize this sentence in five words."
python -m llmrouter.cli --verify "Review the architecture and trade-offs of moving our billing service to events, then refactor the retry logic."

The first command should land on Sol and print a cost in the tenths of a cent. The second should land on Astra and print a verdict from Neon. If either request falls through to a different model, read the attempts lines under the header. They name the failing model and the HTTP status.

To enable GLM-5.4 once Zhipu opens its API, set ZAI_BASE_URL, ZAI_API_KEY, GLM_MODEL_ID and GLM_API_OPEN=1. Then replace the three zero prices for glm in config.py with the numbers from Zhipu’s published price page and add "glm" to the chains where you want it. Do those edits in that order. Flipping the flag before the prices makes GLM look free to the cost guard.

What the Router Prints: Sample Output and Cost Math

Demo mode runs with fake providers, so these outputs come straight from the code above. The first run sends a light prompt.

$ python -m llmrouter.cli --demo "Summarize this sentence in five words."
tier=light model=sol cost=$0.00126
  sol    ok
[openai/gpt-6.2-sol] demo answer

The classifier scored the prompt as light, the chain started at Sol, and Sol answered. The second run sends a hard prompt with verification on.

$ python -m llmrouter.cli --demo --verify "Review the architecture and trade-offs of moving our billing service to events, then refactor the retry logic."
tier=hard model=astra cost=$0.00719
  astra  ok
verdict: pass (neon): Answer matches the question.
[openai/gpt-6.2-astra] demo answer

Astra answered, and Neon, a different vendor, graded it. The $0.00719 total adds Astra’s $0.005176 to Neon’s $0.00201. The third run forces a failure with DEMO_FAILS=5.

$ DEMO_FAILS=5 python -m llmrouter.cli --demo "Summarize this sentence in five words."
tier=light model=neon cost=$0.00189
  sol    error: HTTP 429: rate limited
  neon   ok
[gemini/gemini-4-neon] demo answer

When Sol returns a retryable rate-limit error, the router moves to Neon, and the attempts trail records both calls. After these three runs, spend.jsonl holds four lines like this one.

{"ts": 1796206820.4631417, "model": "sol", "tier": "light", "usd": 0.001258, "in": 29, "out": 120}

The table below runs the same 2,000-input, 500-output request through each model with the cost function from step 6. The cached column assumes 1,500 of the 2,000 input tokens hit the cache, which is typical for a request that repeats a long system prompt.

| Model | Cost per request, no cache | Cost per request, 1,500 tokens cached | Per 1,000 requests, no cache | Per 1,000 requests, cached | |---|---|---|---|---| | GPT-6.2 Sol | Not listed | Not listed | Not listed | Not listed | | Gemini 4 Neon | Not listed | Not listed | Not listed | Not listed | | Claude Fable 5.2 | Not listed | Not listed | $36.00 | Not listed | | GPT-6.2 Astra | Not listed | Not listed | Not listed | Not listed |

Two lessons hide in that table. Caching cuts the bill by roughly a third on every model at this mix, so a stable system prompt is worth as much as a model switch. And Fable 5.2 and Astra price within a rounding error of each other at these token counts, which is why the hard chain treats them as peers and leaves the order to vendor diversity rather than cost.

Eight Common Pitfalls

1. Routing to a model name that does not exist. OpenAI’s product name is GPT-6.2, but the confirmed API IDs are gpt-6.2-astra and gpt-6.2-sol. A chain entry reading gpt-6.2 points at no confirmed model ID, so it should be treated as a configuration error. Copy IDs from the vendor’s model page, not from a news article.

2. Guessing the Fable model ID. The code refuses to guess because a wrong ID burns a request and a deploy. Read it from Anthropic’s model overview page and export it. If you hard-code it, put it in config with a date comment so the next price or ID change is easy to find.

3. Enabling a model with zero prices. A zero price makes the model look free, so the cost guard waves it through every request. The GLM slot is off by default for this reason. Never flip enabled before the price fields hold real numbers.

4. Letting fatal errors fall through. It is tempting to treat every error as retryable. Do that and a revoked key on one vendor looks like a slow day, because the router quietly serves everything from the next vendor until finance notices the bill. Keep 400-class errors loud.

5. Verifying with the same vendor. A model grading its own family’s output shares blind spots with it. The verifier picks a different vendor on purpose. If you only have one vendor configured, accept the unverified verdict and do not fake it.

6. Ignoring long-context pricing. On GPT-6.2 Astra, a request above 272K input tokens doubles input and cache rates and multiplies output by 1.5. A guard that prices at base rates will approve a call that costs twice what it estimated. Check every model’s page for similar thresholds.

7. Setting output caps that reasoning models cannot live within. Reasoning models can spend an entire cap on thinking before they emit a word, which returns an empty string with a 200 status. Give hard-tier calls generous caps, and treat an empty completion as a failure worth logging.

8. Routing private data to a model that retains it. Anthropic’s Fable 5.2 page says the model requires 30-day data retention and is unavailable under legacy zero data retention unless Anthropic authorizes it. If a customer contract demands zero retention, remove Fable from the chain for those requests. A router that falls back to Fable by default can break that contract on the first OpenAI outage.

Troubleshooting: 12 Failures and Fixes

  1. Missing OPENAI_API_KEY. Export it or run with --demo. The key variable is unset in the current shell. Export it, or run--demo . Variables exported in one terminal tab do not exist in another.
  2. HTTP 404 on one vendor, immediate crash. The model ID is wrong or your account cannot see the model. Compare the ID inconfig.py against the vendor’s model page, character by character. Hyphens and dots are easy to swap.
  3. HTTP 401 or 403. The key is wrong, expired, or lacks access to the model. Google’s documentation reportedly lists Neon on the paid Gemini API tier, so a free-tier key may fail there even though other Gemini models work.
  4. BudgetExceeded: daily budget spent on the first real call. Demo runs write tospend.jsonl too. Delete the file, or point the ledger at a different path for demos. Also check that no stray loop burned the budget overnight.
  5. AllModelsFailed with a list of skips. Read the list. If every entry says disabled or breaker open, the Fable ID is missing and the other breakers tripped. If entries say over per-request cap, raiseMAX_REQUEST_USD or lowermax_tokens .
  6. Empty text with a cost greater than zero. The output cap was too small for a reasoning model, so thinking tokens consumed it. Raisemax_tokens for that tier and log empty completions.
  7. async def functions are not natively supported in pytest. Thepytest.ini file is missing or pytest-asyncio is not installed in the active environment. Runpip list and confirm both.
  8. The verifier verdict starts with unparsed. The reviewer most likely wrapped its JSON in a markdown code fence. Strip a leading fence beforejson.loads , or tighten the system prompt. A parse failure should never read as a pass, and the code keeps it that way.
  9. Everything lands in the standard tier. Your prompts carry neither hard keywords nor enough length to move the score. Log the score next to the tier for a day and add the words your team actually uses, such as incident, postmortem or schema migration.
  10. httpx.ReadTimeout on hard prompts. The adapter’s 120-second timeout is too short for long reasoning runs. The error counts as retryable, so the router falls back, but you pay for a wasted wait. Raise the timeout for the hard tier only.
  11. The ledger total disagrees with the vendor invoice. The usual causes are retried requests the vendor billed but the router never recorded, batch discounts, promotional rate changes, and token counts that differ from your estimate. Reconcile weekly, and treat the ledger as a guardrail, not an accountant.
  12. The breaker keeps opening on a healthy vendor. A 60-second spike of 429s from your own burst traffic can trip it. Add client-side rate limiting with a semaphore, or lengthen the threshold so short bursts do not count.

Advanced Tips

Use batch for anything that can wait. OpenAI lists Batch at 50% of Standard rates, and Anthropic lists a 50% Batch API discount on input and output. A nightly summarization job that does not need an answer for hours should skip the router’s synchronous path entirely and go through a batch queue.

Put the stable prefix first. Cache pricing rewards identical prompt beginnings. Place the long system prompt and reference documents ahead of the user’s question, and keep them byte-identical between calls. Neon’s cached rate is 5% of its base input price, and a well-ordered prompt captures that discount on every call.

Shadow-route before you trust the classifier. For a week, let production traffic run on one default model while the router logs which tier and model it would have picked. Compare the hypothetical routing cost against the actual bill, then sample answers where the router disagreed with your default. This catches misroutes before customers do.

Replace the heuristic with a small classifier later. Once you have a few thousand labeled routes in the ledger, train a tiny model on them. The router does not care how the tier is chosen, so the swap is one function. Keep the heuristic as the fallback for when the classifier errors.

Plan for the Fable fallback setting. Anthropic’s Fable 5.2 page says queries flagged by its cybersecurity safeguards route to another model in Claude apps, and that API customers must configure their settings with Anthropic’s Fallback API. Security-flavored prompts on your hard tier may hit this path, so configure it and log which model actually answered.

Add half-open breaker probes and per-vendor rate limiters. Both reduce wasted calls during an incident. A semaphore per vendor, sized to the rate limit on your key, prevents most self-inflicted 429s.

Keep a cheap open-weight lane. If part of your traffic tolerates a weaker model, add an open-weight endpoint at the bottom of the light chain. Our rundown of free and open-weight endpoints covers hosting options, and the open-weight model rankings show which models are worth the slot. More background sits in the AI and machine learning coverage.

The Complete Project at a Glance

The finished project has nine source files and two config files. Everything is shown above, and the structure is this.

llmrouter/
  pytest.ini
  requirements.txt
  llmrouter/
    __init__.py       (empty)
    config.py         model table, tier chains, limits
    classify.py       heuristic tier scoring
    providers.py      OpenAI-compatible and Anthropic adapters
    ledger.py         JSONL spend log
    router.py         fallback chain, breaker, cost guard
    verify.py         cross-vendor answer check
    cli.py            command line and demo mode
  tests/
    test_router.py    9 tests, no network

To embed the router in an application, skip the CLI and call it directly.

import asyncio
from llmrouter.cli import build
from llmrouter.verify import verify

async def answer(question: str) -> str:
    router = build(demo=False)
    result = await router.route(question)
    if result.tier == "hard":
        result = await verify(router, question, result)
    return result.text

print(asyncio.run(answer("Summarize this sentence in five words.")))

Add spend.jsonl to .gitignore, build the router once at startup instead of per request so the breaker state persists, and wrap route in your own handler for BudgetExceeded and AllModelsFailed. Those two exceptions are the router’s way of saying stop, and your application should turn them into a graceful message instead of a stack trace.

FAQ

What is an LLM router?

An LLM router is a layer between your application and model APIs that chooses which model answers each request. Good ones also retry on other vendors when a call fails, enforce spending limits, and record cost per call. The one built above does all four in under 400 lines.

Do I need a router if I only use one vendor?

You can still benefit. OpenAI’s GPT-6.2 Astra and Sol differ by 4x in price, so a tier router saves money even on a single vendor. You lose the cross-vendor fallback and the independent verifier, which are the main reasons to span vendors.

How do I choose between GPT-6.2 Astra and GPT-6.2 Sol?

Astra lists at $8 input and $40 output per million tokens against $2 and $10 for Sol, so Astra costs four times as much per token. Start every request on Sol, measure failures on your own tasks, and promote only the prompt types where Sol falls short. The classifier in this build encodes that policy.

Can I add GLM-5.4 to the router?

Yes, once its API is available. As of December 2, 2026, GLM-5.4 is available through the GLM Coding Plan and selected partner coding products, but its API is not confirmed as publicly available. Set the environment variables, add real prices, and add it to a chain.

How much will routing save?

It depends on your traffic mix. Sol is listed at $2 input and $10 output per 1 million tokens, against $8 input and $40 output for Astra, so sending light requests to Sol and keeping Astra for the hardest work should cost less than an all-Astra baseline. Your result depends on how much of your traffic is truly light, so shadow-route first and measure.

Is the verifier worth the extra cost?

For high-stakes answers, usually yes. A verifier call on Neon costs a fraction of an Astra answer, and a failed check is a cheap signal to retry or escalate. Scope it to the hard tier plus a small random sample, and remember it cannot catch errors both models share.

How do I keep zero-retention customers off Claude Fable 5.2?

Tag those requests and give them a chain that omits Fable. Anthropic’s documentation says Fable 5.2 requires 30-day data retention and is not available under legacy zero data retention unless Anthropic expressly authorizes it. Check your own agreement, and treat this as a policy rule enforced in config, not a runtime surprise.

原文来源:shattered.io