Memory, routing, orchestration, cost — every piece in daily use, with the measurements attached.
← all explainers
· Yasaswy Nagavolu

Model-Router: Cut the Bill of the Same Subagent Fleet with a LiteLLM Gateway — Part 2

Swapping the aggregator behind the same Model-Router proxy for a local LiteLLM gateway cuts the open-weight side of the bill to wholesale provider rates — and the four integration landmines hit on the way (a dialect default that 404s, a token-expired that isn't, catalog holes, and the temptation to keep a dead backend) are the actual lesson.

developer-toolscliautomationai-agentscost-optimization

The routing layer leaks the bill twice, invisibly per-request, and the leak only became visible when the prepaid credits ran out. Part 1 of this series built a hand-rolled reverse proxy that routes Claude Code subagent traffic by model name — Claude requests bypass everything untouched, open-weight requests get rerouted — and coded the Claude-bypass as a first-checked invariant instead of a convention. That design routes all non-Claude traffic to a single aggregator, and it works. It also wastes money two ways. The first leak is a deposit fee: every prepaid top-up on the aggregator carries roughly a 5.5% card fee, a tax on the whole spend, not just the margin. The second leak sits on the exact tier the fleet was moved to in order to save money — the open-weight tier — where the aggregator passes flagships through at cost but carries an estimated 5–15% margin on the niche models, so the routing layer claws back part of the savings it was supposed to create. When the credits died, the real choice was either top up forever, or make the router talk to every provider directly at list price. Direct APIs exist for all of them; the only missing piece was one process that speaks OpenAI/Anthropic dialect in front of N provider dialects. That’s precisely what LiteLLM is. This is Part 2 of the series — the same Model-Router pattern, the same bypass invariant from Part 1 carried over unchanged, with the aggregator swapped out for a local gateway.

Architecture: the same bypass, a different backend

The proxy’s role is unchanged from Part 1 — read the model field first, Claude-bypass unconditionally, then route. What changed is everything behind the non-Claude branch: the aggregator adapter and the backend toggle are gone, replaced by a local LiteLLM gateway that fans out to providers directly. Click through one turn that fans two subagents to two backends.

Model-Router · LiteLLM
Reverse Proxy (LiteLLM variant)
STEP 1/9▸type
Σ 0 tok·$0.00z-ai/glm-5.2 (direct, wholesale)
Model-Router · companion repo (pt2)
route
lookup
dispatch
debug
route
bypass
reply

Both dispatches hit the same proxy. coder’s request falls through the Claude-bypass (no claude-/anthropic/ prefix), gets translated by a small alias map from z-ai/glm-5.2 to the gateway’s own alias, and is forwarded to LiteLLM on localhost:4000 with the gateway’s master-key auth — that’s the one metered step, priced here at Z.ai’s direct wholesale GLM-5.2 output rate ($4.40 per million tokens, $1.40 per million input). reviewer’s request hits the same proxy a moment later, matches the Claude-bypass immediately, and is forwarded to Anthropic with its real credentials untouched — no alias lookup, no swapped auth, no metered tick, because it never leaves the flat Claude subscription. The browser box in the diagram carries the real debugging beat from the cutover: a 401 reading “token expired or incorrect” whose actual cause was a launcher that never exported the key into the gateway’s environment — landmine 2, below.

This is what the same mixed turn looks like in the router’s own log — worth knowing before you run it, because the log is where both invariants become something you can literally watch:

[router] main→Anthropic(claude-fable-5)                                POST /v1/messages  -> 200
[router] subagent→LiteLLM(glm-5.2) agent=coder-a1b2@session-9f         POST /v1/messages  -> 200
[router] SUBAGENT-CLAUDE-OK(claude-sonnet-5) agent=reviewer-c3d4@sess  POST /v1/messages  -> 200
[router] subagent→LiteLLM(glm-5.2) agent=coder-a1b2@session-9f         POST /v1/messages  -> 200
[router] subagent→LiteLLM(deepseek-chat) agent=docs-writer-e5f6@sess   POST /v1/messages  -> 200
[router] main→Anthropic(claude-fable-5)                                POST /v1/messages  -> 429
[router] CREDIT-SUSPECT backend=anthropic model='claude-fable-5' status=429
[router] main→Anthropic(claude-fable-5)                                POST /v1/messages  -> 200
[router] NO-ALIAS(mistral/mistral-large) agent=coder-a1b2@session-9f   POST /v1/messages  -> 502 (no route)

Four things to read off it. Every line names the resolved backend and the model, so a misroute would be visible at a glance rather than buried in a provider invoice. Every subagent line also carries an agent= fragment naming which dispatch is calling — the harness attaches a per-agent id header to subagent traffic, and if you name your dispatches (or have the router’s dispatch hook inject a name derived from the agent type when the caller doesn’t), that id is a readable name instead of an opaque hex string; main- session lines carry no fragment, which is itself information. The 429 + CREDIT-SUSPECT pair shows the router tagging a suspect upstream response (a rate limit on the Anthropic side here) — and note the very next Claude request still goes to Anthropic: the bypass is an invariant, not a fallback, so Claude traffic never spills to the gateway even when Anthropic is throttling. And the last line is landmine 4 doing its job — an unmapped model dies loudly as a 502 in plain sight instead of silently riding to the wrong provider.

Four stages to the 2-way collapse

This cutover wasn’t the first design for the gateway path — it was the third, arrived at through a forcing event. Click through the arc: what was tried, what broke, what it led to.

Stage 0 — Aggregator-only
Tried

Pt1's steady state: every non-Claude request forwarded to an aggregator that speaks both dialects. One backend, one key, works.

Broke

The bill leaks twice per request: a ~5.5% deposit fee on every prepaid top-up (a tax on the whole spend), and an estimated 5–15% margin on the open-weight tier — exactly the tier the fleet routes to. You moved to cheap models to save money and the routing layer claws part of it back.

Learned

The aggregator was the right first step and the wrong steady state. Once the fleet's traffic is 100% open-weight-tier, the aggregator's markup is a recurring tax on the tier you deliberately moved to.

The most instructive mistake is stage two — the hedge. Adding a backend toggle between the aggregator and the gateway, driven by a runtime override file, felt like engineering discipline at the time. It was actually deferred deletion: once the aggregator’s credits died, the toggle was between “the path we left” and “the only path that works” — which is not a toggle. The collapse to a 2-way direct path deleted the toggle, the override file, and the old adapter, and shipped strictly less code than Part 1 started with, at a strictly cheaper bill. The teaching generalizes: when the fallback can never be chosen again, delete it.

What the cutover actually saves

The savings here are honest and bounded. The cutover removes two costs only: the ~5.5% deposit fee on every prepaid top-up, and the aggregator’s estimated 5–15% margin on the open-weight tier. Claude spend is unchanged — it’s a flat subscription, bypassed first, exactly as in Part 1. If your aggregator’s margin on your specific open-weight tier is 0%, your savings are the deposit fee alone.

flagships are passthrough — margin applies to the open-weight tier only

via aggregator$511
wholesale × (1 + 10%) × (1 + 5.5% deposit)
direct via LiteLLM$440
wholesale · 4.40/1M out
delta saved / month (direct vs aggregator)$71 · 13.8%
  • Claude spend unchanged — flat subscription, bypassed first (pt1's point).
  • Margin applies to the open-weight tier only; flagships are passthrough.
  • At 0% margin, savings = the deposit fee alone (~5.5%).
  • Wholesale anchor: z-ai/glm-5.2 — output $4.40/1M, input $1.40/1M (public list prices).

The anchor price is Z.ai’s public list rate for GLM-5.2: $4.40 per million output tokens, $1.40 per million input. Via the aggregator that same token cost the list price plus the tier margin, paid for with credits that cost an extra 5.5% to load. Direct, it’s just the list price.

Four landmines on the way in

The architecture is conceptually trivial. The integration is not. Four landmines hit on the way in, and they’re the actual lesson — each one is a place where the gateway’s defaults disagreed with the docs, the catalog, or the shell it was launched from.

1. A dialect default that 404s

LiteLLM translates Anthropic /v1/messages requests to OpenAI dialect before forwarding them. By default, for OpenAI-compatible custom providers, it targets OpenAI’s newer Responses API (/responses). Most OpenAI-compatible providers — Z.ai included — only implement /chat/completions, so every request 404s. The fix is a single environment variable:

export LITELLM_USE_CHAT_COMPLETIONS_URL_FOR_ANTHROPIC_MESSAGES=true

The catch: the published docs say to set this under general_settings in the YAML config. In the actually-installed version, the YAML placement is silently ignored — it’s read as an import-time module attribute from the environment, not from the config file. The lesson, repeated by every landmine below: when the docs and the behavior disagree, read the installed source. The installed source is the truth; the docs are a hope.

2. “Token expired” that isn’t

The gateway resolves os.environ/KEY references in its config at process start. Launch it from a shell that doesn’t have the provider keys exported, and the provider returns “token expired or incorrect” for a key that was never present in the gateway’s environment in the first place — not expired, absent. The 401 reads like an auth problem and is actually a bootstrapping problem. The fix is a launcher that parses the key file into env before spawning the gateway, setting only the variables that are missing so an explicitly-exported one always wins:

# launch_gateway.py — bootstrap keys, then spawn litellm (stdlib only)
import os, subprocess

for line in open(".env"):
    line = line.strip()
    if line and not line.startswith("#") and "=" in line:
        key, _, value = line.partition("=")
        os.environ.setdefault(key.strip(), value.strip())   # explicit env always wins

subprocess.run(["litellm", "--config", "config.yaml", "--port", "4000"])

A running process holds its environment snapshot from spawn time, so key rotation is invisible to it until restart — the launcher has to be the discipline, not the runtime.

3. Catalog is not availability

A model listed in a provider’s catalog is not a model that answers on the serverless tier. Two failure modes hide here. Some models are streaming-only — the provider rejects non-streaming requests outright, and harness traffic streams anyway, so the issue never surfaces until a smoke test tries a non-streaming call and fails. Vision models can be entirely absent from a provider’s serverless tier while still listed in the catalog, available only on a dedicated endpoint. Test every alias end-to-end with the actual request shape the harness sends, and delete the aliases that can’t serve.

4. Keep the loud-fail

Part 1’s invariant was: unmapped model → 502, never a silent fallback. An aggregator swap is exactly when “just send unknowns to the old backend” sneaks back in as a hedge. Resist it. The 502 is a feature — it’s the only way an unmapped model string surfaces at all. A silent fallback to the gateway would turn a misconfigured alias into a slow drift of traffic to the wrong provider at the wrong price, billed quietly until the next invoice. The loud-fail is the alarm; deleting it during a cutover is how regressions hide.

The evolved 2-way router

The router itself is simpler than Part 1’s. The Claude-bypass is unchanged — first check, unconditional, real auth passes through. The secondary-backend branch lost the adapter swap and the backend toggle, replaced by one alias lookup and one forward. The subagent-facing model IDs keep the provider/model shape from Part 1’s routes.json; only the router translates.

// aliases.json — provider/model (subagent-facing) → gateway alias
{
  "z-ai/glm-5.2": "glm-5.2",
  "deepseek/deepseek-chat": "deepseek-chat",
  "together-ai/llama-3.3-70b": "llama-70b"
}
# model_router.py — the evolved 2-way route()
CLAUDE_PREFIX = ("claude-", "anthropic/")
GATEWAY = "http://localhost:4000"          # LiteLLM's public default port

def route(request):
    model = request["model"]
    if model.startswith(CLAUDE_PREFIX):
        # bypass first, unconditional — unchanged from pt1
        return forward_to_anthropic(request)
    alias = ALIASES.get(model)              # provider/model → gateway alias
    if alias is None:
        return http_502(f"unmapped model: {model}")   # loud-fail, carried over
    request["model"] = alias
    return forward_to(GATEWAY, request, auth=MASTER_KEY)

Contrast with Part 1’s route(): the secondary-backend branch there had to swap auth to the aggregator’s key and forward to a swappable backend. Here it’s one map lookup and one forward to a fixed local port with the gateway’s own master key. Less code, fewer moving parts, strictly cheaper per token.

The shape of it

A thin 2-way router in front of LiteLLM: an alias map translates each subagent’s provider/model frontmatter (same shape as Part 1) to a gateway alias, launch_gateway.py bootstraps the LiteLLM config and spawns it, and every request fans out to the provider directly at list price — no aggregator, no deposit fee, no tier margin.

Technicals

  • Agentic harness: Claude Code
  • Skill/pattern name: Model-Router (LiteLLM variant)
  • Memory / RAG: None

Part 1’s variant is the right choice when you want to own the routing logic end-to-end with zero dependencies — one Python file, no gateway process, no second config dialect. Part 2’s variant is the right choice when you’d rather lean on a gateway that already speaks N provider dialects and get wholesale rates without writing an adapter per provider. The Model-Router pattern is identical in both: bypass Claude first and unconditionally, route by the model name in the request, and fail loudly on anything unmapped. The bypass is the invariant; the backend is the swap.