Cascades, rules and verifiers for multi-model apps

APIDeepSeekFreeKey · Updated 2026-11-22 · 8 min read

Envelopes being sorted into pigeonholes
Routing sends each request to the slot that suits it.

Almost everyone who builds with language models ends up asking a version of the same question. My everyday model handles most things, but when it cannot solve a problem, what should I escalate to, and how do I decide automatically? Developers describe orchestration setups where an expensive assistant delegates routine work to cheaper models to stretch a budget, and others ask which slightly pricier model to reach for when their usual low-cost choice keeps failing on hard reasoning.

This article turns those instincts into a design. It explains the three main routing patterns, how to verify an answer cheaply so you know when to escalate, how to keep the logic in one small module, and how to measure whether routing is actually saving money and time. The code uses OpenAI-compatible clients, so any provider fits, including DeepSeek's API and the keyless free-ai endpoint on this site.

This site is not affiliated with DeepSeek. free-ai is an independent open-weight model of about 35B parameters, a reasonable bottom tier in a cascade for many tasks, and clearly not the top tier for hard reasoning, where larger commercial models do better.

Frequently asked questions

What is model routing?

Routing means choosing, per request, which model should handle it, rather than sending everything to one model. The aim is to pay for strong models only when a task needs them and use cheaper or free ones for the rest.

How does a cascade differ from a rule-based router?

A rule-based router decides up front from the request type, such as 'all summaries go to the small model'. A cascade tries the cheap model first and escalates only if the answer fails a check. Rules are predictable; cascades adapt to difficulty.

Which is better: a classifier model or simple rules?

Start with rules, because they are transparent and free. Add a cheap classifier only when you have data showing that rules misroute a meaningful share of requests.

How do I know a cheap model's answer is good enough?

Use checks that are cheaper than the model: JSON schema validation, running unit tests, compiling the code, confirming required fields, or a short self-rating from a second cheap call. The best checks are deterministic.

Does escalation make responses slower?

For escalated requests, yes, since two calls run in sequence. If most requests pass on the first tier, the average latency still drops compared with sending everything to a slow, strong model.

What should I escalate to after a cheap model fails?

A stronger general model or a reasoning mode of the same model, depending on the failure. Logic and multi-step errors respond to reasoning; missing knowledge or weak code often needs a larger model.

Can a free endpoint be part of a production cascade?

As a first tier for low-stakes tasks, yes, provided you always have a paid fallback, because the free endpoint has no SLA and may return 503 when busy.

Why one model for everything is wasteful

Request difficulty in real apps is skewed. A large share of calls are easy: rephrase this, classify that, extract a date, write a short reply. A small share are genuinely hard. Sending everything to your strongest model pays premium prices for easy work; sending everything to the cheapest one disappoints on the hard tail.

Routing exploits that skew. If most traffic can be served by a cheap or free model and only the hard remainder goes to a premium one, the total bill falls sharply while the quality users see on hard tasks stays high.

Routing also improves resilience as a side effect. An app that already knows how to send requests to more than one model can keep working when one provider is slow, rate limited or temporarily unavailable.

Measure the skew first

Sample a hundred real requests and label them easy, medium or hard by hand. The proportions tell you how much routing could save before you write any code.

Pattern one: static rules by task

The simplest router maps request types to models. Your app already knows what kind of request it is sending because a specific feature produced it. Title suggestions, tag extraction and tone rewrites go to the small tier; code review and planning go to the strong tier.

Rules are easy to explain, cost nothing to evaluate and never surprise you. Their weakness is that difficulty varies within a task: most code questions might be simple, but a few are not.

Rules in configuration

Keep the task-to-model map in a config file. Moving a task between tiers should never require a deploy of application code.

Rules from user intent

Interface choices can carry routing signals for free. A 'quick answer' and a 'detailed analysis' button, or a toggle for 'careful mode', let users tell you which tier they want, and people are usually honest about it because they also care about speed.

  • Small tier: classification, extraction, short rewrites, titles, translations of short text
  • Middle tier: general chat, summaries of long text, routine code
  • Strong tier: debugging, architecture questions, multi-step plans, anything user-critical
Staircase with three landings
Tiers are landings: climb only as high as the task needs.

Pattern two: cascades with verification

A cascade sends the request to the cheapest tier, checks the result, and moves up a tier only if the check fails. Everything depends on the check. For structured output, validate the JSON. For code, run the tests or at least compile it. For extraction, confirm required fields exist and match expected formats.

The code below implements a generic cascade. Each tier is a base URL, key and model; the verifier is any function that returns true for an acceptable answer.

Failures count as escalation

Treat errors such as 503 or a timeout on the cheap tier the same as a failed check. The user gets an answer from the next tier instead of an error message.

Return which tier answered

Logging the tier index for every request is what lets you measure later whether the cascade is saving anything.

import json, os
from openai import OpenAI

TIERS = [
    ("https://api.apideepseekfreekey.com/v1", "free", "free-ai"),
    (os.environ.get("STRONG_URL", "https://api.deepseek.com"), os.environ.get("STRONG_KEY", ""), os.environ.get("STRONG_MODEL", "deepseek-chat")),
]

def cascade(messages, verify, **kw):
    last = None
    for i, (url, key, model) in enumerate(TIERS):
        if not key:
            continue
        try:
            r = OpenAI(base_url=url, api_key=key).chat.completions.create(model=model, messages=messages, **kw)
        except Exception as e:
            print("tier", i, "error:", type(e).__name__)
            continue
        last = r.choices[0].message.content
        if verify(last):
            return last, i
        print("tier", i, "failed verification, escalating")
    return last, None

def is_ticket_json(text):
    try:
        d = json.loads(text)
        return d.get("priority") in {"low", "medium", "high"} and bool(d.get("summary"))
    except (ValueError, AttributeError):
        return False

answer, tier = cascade(
    [{"role": "system", "content": "Reply with JSON only: {\"priority\": low|medium|high, \"summary\": string}"},
     {"role": "user", "content": "Checkout page returns 500 for all users since the last deploy."}],
    is_ticket_json, max_tokens=200,
)
print(tier, answer)

Verifiers that cost less than the model

A cascade is only as good as its check. The best verifiers are deterministic and cheap: parsing, schema validation, regular expressions for expected formats, compiling or linting code, running a test suite, checking that cited passages exist. These catch the most common failure, an answer in the wrong shape, with certainty.

For open-ended text, deterministic checks are harder. Options include a second short call asking a model to rate the answer against criteria, or simple heuristics such as minimum length and the presence of key terms. Both are imperfect, so use them for low-stakes features first.

Tests as verifiers

For code generation, a few unit tests written in advance are the strongest possible check. If the cheap model's code passes them, there is little reason to pay for a stronger one.

Self-rating pitfalls

Models asked to grade their own work tend to be generous. If you use a model as a judge, give it a strict rubric and, ideally, a different model from the one that answered.

Three stacked water filters over a jug
A cascade passes requests down tiers until one gives a clean result.

Pattern three: a router model

The most sophisticated approach uses a small, fast model to classify each request's difficulty before choosing a tier. It can work well, but it adds a call to every request and its own error rate. It earns its place mainly when requests are free-form, such as an open chat box, where your app cannot infer the task type.

If you try it, keep the classifier prompt short, ask for a single label, and fall back to the middle tier when the label is unclear. Measure misroutes against a hand-labelled sample.

A router model also needs maintenance. When you change tiers or add a feature, its labels may no longer match your setup, so include it in the same regression runs as everything else.

Hybrid routers

Combine rules and a classifier: rules handle every request where the feature makes the task obvious, and the classifier handles only the free-form remainder.

Delegation inside agent workflows

Coding agents offer a natural place for routing. A strong orchestrating model plans the work and hands well-defined leaf tasks to cheaper helpers: write this test, explain this error, draft this docstring. Some developers encode this in the project instruction file the agent reads, listing which kinds of tasks to delegate and to which model.

Delegation works best when the leaf task is self-contained and its result easy to check. It works poorly for tasks that need the whole picture, where the cheap helper lacks context and the orchestrator spends more effort fixing its output than it saved. The mechanics of pointing tools at different backends are covered in running a coding agent on another backend.

Pass explicit context

When delegating, include the exact files or snippets the helper needs. A cheap model given the right twenty lines beats an expensive one guessing.

Inspection bench with calipers and a metal part
Verifiers decide when an answer is good enough.

Measuring whether routing pays off

Routing adds complexity, so prove it is worth it. Track, per feature: share of requests answered at each tier, escalation rate, average latency, cost per request and user-visible quality signals such as retries, thumbs-down or support tickets. Compare with a period when everything went to one model.

Watch especially for escalation rates creeping up. If the cheap tier fails half the time, you are paying for two calls on half your traffic and may be better off moving that feature up a tier permanently.

Run the measurement for long enough to cover your normal weekly pattern, since request mix often differs between weekdays and weekends. Then review the escalated requests by hand once in a while. They are the clearest picture you will get of what your cheap tier cannot do, and they often reveal a missing instruction or a bad example in the prompt rather than a model limit.

Cost per successful answer

The metric that matters is not price per call but total spend divided by accepted answers. A cheap tier that often fails can be more expensive by this measure.

Choosing the tiers themselves

Pick tiers that differ meaningfully. Two models of similar strength at similar prices add complexity without benefit. A typical stack has a free or very cheap bottom tier, a capable mid-priced general model, and a strong reasoning-capable top tier for the few requests that need it. A reasoning flag on the same model can act as an intermediate step, as explained in chat versus reasoner modes.

Expect to revise tiers often. Models improve, prices move and providers rename things. Keeping tiers in configuration and running a small regression set when you change them, as described in catching model drift, keeps the router trustworthy.

Be honest about the top tier

For the hardest reasoning and coding tasks, the top tier should be the strongest model you can justify, typically a large commercial one. A free 35B model belongs lower in the stack.

Clipboard, hard hat and blueprints on a table
The orchestrator plans; helpers handle the leaf tasks.
Try the free API

Open the home page and send a request to the keyless endpoint straight from your browser, no account or key needed.

Read also