Lab: Choosing and Routing Models Behind an Evaluation
Filter closed and open-weight, reasoning and standard candidates on context, licence and data-handling terms, compare the rest on one evaluation set for quality, cost and latency, estimate when self-hosting an open-weight model breaks even, then route between a small and a large model and confirm on a held-out split that quality stays within a set threshold.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Candidate cards and hard requirements
- Step 2: Quality, cost and latency on one evaluation set
- Step 3: When does self-hosting break even?
- Step 4: Route between a small and a large model
- Step 5: Confirm on the held-out split
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Cost Control
- Where LLM Money Goes Concept · 15 min
- A Cost Report from Usage Logs Worked example · 20 min
- Lab: Prompt and Response Caching Lab · 25 min
- Lab: Choosing and Routing Models Behind an Evaluation Lab · 30 min
- Batch Jobs, Budgets and Limits Concept · 15 min
- Check: Cut Cost Without Breaking Quality Knowledge check · 10 questions
What you will learn
- Select a model for a feature by comparing closed and open-weight, reasoning and non-reasoning candidates on an evaluation set, cost, latency, context limits, licence and data-handling terms, including a self-hosting break-even estimate.
- Route requests between a smaller and a larger model and confirm with an evaluation that quality stays within a set threshold.
01. Goal and setup
Lesson 2 showed that Lumen's answer feature runs every question on a large reasoning model. Most questions are easy. In this lab you make two decisions with evidence instead of impressions: which models may serve the feature at all, and which requests can go to a cheaper one. The method is the same in both: hard requirements first, then one evaluation set, cost and latency for every candidate, and a quality threshold agreed before you look at the results.
Calling five real models on an evaluation set costs money and needs keys, so this lab uses deterministic fake models. Each candidate has a card with example terms and prices, and its answers pass or fail with fixed chances on easy and hard questions, so every run gives the same numbers. In the practice project you replace run() with real calls, as in lesson 2 of the AI Evaluation skill.
You need: Python 3.12 or later and pandas (tested with pandas 3.1). All prices, licences, terms, speeds and pass chances below are invented for the lab.
model-lab/
├── evalset.py 80 labelled questions with dev and test splits
├── candidates.py candidate cards and fake models
├── step1_cards.py step 1: hard requirements
├── step2_eval.py step 2: quality, cost and latency per candidate
├── step3_breakeven.py step 3: self-hosting versus a hosted API
├── router.py step 4: rules, validator and cascade
├── step4_router.py step 4: routing strategies on the dev split
└── step5_gate.py step 5: the quality gate on the test splitmkdir model-lab && cd model-lab
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install pandas02. Step 1: Candidate cards and hard requirements
The evaluation set has 80 questions: 48 easy and 32 hard, in four slices, with the hard billing questions marked must pass because a wrong answer about refunds costs real money. Even cases form the dev split, which you may look at while tuning; odd cases form the test split, which you use once, at the end. Each question text appears in several cases, which keeps the file short; a real set has distinct questions.
"""80 labelled Lumen questions: a stand-in for your versioned evaluation set."""
EASY = [
("How do I reset my password?", "account"),
("Where do I download an invoice?", "billing"),
("How do I add a teammate?", "account"),
("Can I change my billing date?", "billing"),
("How do I export my data?", "how-to"),
("Which file types can I upload?", "how-to"),
("How do I turn on two-step login?", "account"),
("Where is the API key page?", "how-to"),
]
HARD = [ # (question, slice, must pass)
("I changed plan mid-month and added seats, so why was I charged twice and "
"which charge gets refunded?", "billing", True),
("SSO works for admins but members get error 403 since the domain change; "
"what should we check first?", "troubleshooting", False),
("Exports stopped after we moved workspaces and renamed the project; how do "
"we recover the missing files?", "troubleshooting", False),
("Can two workspaces be merged?", "account", False),
("Why does the invoice total differ from seats times the plan price after "
"a downgrade?", "billing", True),
("Why is my usage zero?", "troubleshooting", False),
("Webhook retries fail with 429 and then succeed hours later; how do we "
"change the retry policy?", "how-to", False),
("Is a refund possible after the window?", "billing", True),
]
def build_cases() -> list[dict]:
cases = []
for n in range(80):
hard = n % 5 in (0, 3) # 32 hard cases, 48 easy ones
if hard:
question, slice_, must_pass = HARD[n % len(HARD)]
else:
(question, slice_), must_pass = EASY[n % len(EASY)], False
cases.append({"id": f"case-{n:03d}", "question": question,
"slice": slice_, "hard": hard, "must_pass": must_pass,
"split": "dev" if n % 2 == 0 else "test"})
return casesA candidate card records what you learn before running anything. Four distinctions matter:
- Closed or open-weight. A closed model is only available through its provider's API, on the provider's terms. An open-weight model can be downloaded and run on your own hardware or called through a hosting provider, and the choice between them is the break-even in step 3.
- Reasoning or standard. Reasoning models think before answering, which helps on multi-step questions and costs output tokens and seconds on every request.
- Context limit. The largest prompt plus output the model accepts; it must cover your longest real request with room to spare.
- Licence and data handling. Open-weight licences range from permissive ones such as Apache-2.0 to custom licences with use policies and other conditions. For a hosted API, read whether your inputs may be used for training, how long they are retained, and where they are processed.
Hard requirements are pass or fail, and they come first: no score on the evaluation can make up for terms your customers' contracts forbid.
"""Candidate cards plus deterministic fake models. Every number is an example."""
import hashlib
from dataclasses import dataclass
@dataclass(frozen=True)
class Candidate:
name: str
weights: str # "closed" or "open"
reasoning: bool
context_tokens: int
licence: str # what you found when you read it
trains_on_inputs: bool # under the terms you would actually sign
eu_region: bool
price_in: float # US dollars per million tokens through a hosted API
price_out: float
skill: tuple[float, float] # FAKE behaviour: pass chance on easy, hard cases
out_tokens: int # FAKE: answer plus reasoning tokens per request
ttft_s: float # FAKE: time to first token
tokens_per_s: float # FAKE: output speed
CANDIDATES = [
Candidate("closed-large-r", "closed", True, 1_000_000, "provider terms",
False, True, 2.00, 10.00, (0.98, 0.93), 900, 0.9, 80),
Candidate("closed-small", "closed", False, 200_000, "provider terms",
False, True, 0.20, 1.00, (0.95, 0.60), 220, 0.35, 150),
Candidate("closed-mini-preview", "closed", False, 128_000, "preview terms",
True, False, 0.05, 0.25, (0.90, 0.50), 200, 0.3, 160),
Candidate("open-medium", "open", False, 128_000, "Apache-2.0",
False, True, 0.30, 1.20, (0.94, 0.74), 260, 0.4, 110),
Candidate("open-large-r", "open", True, 128_000, "custom, use policy",
False, True, 0.90, 3.60, (0.97, 0.86), 1_100, 0.8, 60),
]
PROMPT_TOKENS = 3_000 # instructions, passages and question, per request
def unit(*parts: str) -> float:
"""A stable pseudo-random number in [0, 1) for the given parts."""
digest = hashlib.sha256(":".join(parts).encode()).hexdigest()
return int(digest[:8], 16) / 2**32
def run(model: Candidate, case: dict) -> dict:
"""FAKE model call: deterministic pass/fail, tokens, latency and cost."""
passed = unit(model.name, case["id"]) < model.skill[case["hard"]]
out = round(model.out_tokens * (0.8 + 0.4 * unit("len", model.name, case["id"])))
cost = (PROMPT_TOKENS * model.price_in + out * model.price_out) / 1e6
return {"passed": passed, "out_tokens": out, "cost": cost,
"latency_s": model.ttft_s + out / model.tokens_per_s}from candidates import CANDIDATES
NEEDS = { # hard requirements for Lumen's answer feature
"context of 32k tokens": lambda c: c.context_tokens >= 32_000,
"no training on our data": lambda c: not c.trains_on_inputs,
"EU processing available": lambda c: c.eu_region,
}
ELIGIBLE = [c for c in CANDIDATES if all(ok(c) for ok in NEEDS.values())]
if __name__ == "__main__":
for c in CANDIDATES:
failed = [need for need, ok in NEEDS.items() if not ok(c)]
kind = f"{c.weights}, {'reasoning' if c.reasoning else 'standard'}"
print(f"{c.name:<20} {kind:<18} {c.licence:<19}",
"excluded" if failed else "eligible")
for need in failed:
print(f"{'':<20} fails: {need}")python step1_cards.pyclosed-large-r closed, reasoning provider terms eligible
closed-small closed, standard provider terms eligible
closed-mini-preview closed, standard preview terms excluded
fails: no training on our data
fails: EU processing available
open-medium open, standard Apache-2.0 eligible
open-large-r open, reasoning custom, use policy eligibleThe cheapest candidate is out before it is evaluated: under its preview terms the provider may train on your inputs, and it cannot process data in the EU. open-large-r passes the automatic checks, but its custom licence still needs someone to read the use policy against your product before you rely on it. Record that as an open item on the card.
03. Step 2: Quality, cost and latency on one evaluation set
Run every eligible candidate on the same 80 cases and report, side by side: the pass rate, the pass rate on hard cases, failures on must-pass cases, cost per 1,000 queries at the candidate's hosted price, and latency percentiles. For the open-weight models, the hosted price is what a third-party inference provider would charge; step 3 asks whether running them yourself is cheaper.
import pandas as pd
from candidates import run
from evalset import build_cases
from step1_cards import ELIGIBLE
cases = build_cases()
rows = [{"model": m.name, **case, **run(m, case)} for m in ELIGIBLE for case in cases]
df = pd.DataFrame(rows)
table = df.groupby("model", sort=False).agg(
pass_rate=("passed", "mean"),
hard_pass=("passed", lambda p: p[df.loc[p.index, "hard"]].mean()),
must_fail=("passed", lambda p: (~p[df.loc[p.index, "must_pass"]]).sum()),
per_1k=("cost", lambda c: 1000 * c.mean()),
p50_s=("latency_s", "median"),
p95_s=("latency_s", lambda s: s.quantile(0.95)),
)
print(table.round(3).to_string())python step2_eval.py pass_rate hard_pass must_fail per_1k p50_s p95_s
model
closed-large-r 0.988 0.969 0 15.019 12.425 13.989
closed-small 0.838 0.625 3 0.821 1.820 2.070
open-medium 0.788 0.656 4 1.207 2.659 3.200
open-large-r 0.938 0.844 3 6.653 19.308 21.809The large reasoning model is the only one with no must-pass failures, and it costs 18 times as much as closed-small and takes nearly seven times as long. The two standard models are close to each other: on 80 cases one case is 1.25 points, so a 5-point gap between them is within the noise that the AI Evaluation skill taught you to measure. The open reasoning model sits in between on quality and cost, and is the slowest. No single model wins on every column, which is the usual result and the reason to route.
04. Step 3: When does self-hosting break even?
Self-hosting open-medium turns a price per token into a fixed monthly cost: GPUs that are paid for by the hour whether or not requests arrive, plus the people and tools that keep them running. The estimate needs four inputs:
- GPU price per hour and GPUs per replica, from your cloud or hardware quote.
- Throughput: the tokens per second one replica serves at your latency target, measured with a load test using your own prompt lengths (vLLM's
vllm bench serveis one such tool). - Utilisation: the average share of that capacity real traffic uses. Traffic peaks in office hours and you must provision for the peak, so the average is often far below 100%.
- Operations cost: monitoring, upgrades, security patches and on-call time.
"""Self-hosting open-medium versus calling it through a hosted API."""
import math
HOURS = 730 # per month
api_per_request = (3_000 * 0.30 + 260 * 1.20) / 1e6 # hosted price, example figures
# Inputs you measure or look up. These are examples, not quotes.
gpu_hourly = 2.50 # US dollars per GPU-hour, always on
gpus_per_replica = 2
throughput = 30_000 # tokens per second per replica (prompt plus output), measured
tokens_per_request = 3_260 # at your latency target
ops_monthly = 1_500.0 # monitoring, upgrades, on-call share
def self_hosted(volume: int, utilisation: float) -> tuple[int, float]:
"""Replicas needed and monthly cost. Utilisation is the average share of
capacity that real traffic uses, after peaks and quiet nights."""
usable = throughput / tokens_per_request * 3600 * HOURS * utilisation
replicas = max(1, math.ceil(volume / usable))
return replicas, replicas * gpus_per_replica * gpu_hourly * HOURS + ops_monthly
print(f"hosted API: ${1000 * api_per_request:.2f} per 1,000 requests")
fixed = self_hosted(1, 1.0)[1]
print(f"one replica: ${fixed:,.0f} a month; break-even at "
f"{fixed / api_per_request / 1e6:.2f}M requests a month\n")
print("self-hosted cost per 1,000 requests (replicas) at two utilisation levels")
print("requests/month API/1k 25% use 60% use")
for volume in (600_000, 4_000_000, 8_000_000, 20_000_000):
cells = []
for utilisation in (0.25, 0.6):
replicas, monthly = self_hosted(volume, utilisation)
cells.append(f"{1000 * monthly / volume:.2f} ({replicas})")
print(f"{volume:>14,} {1000 * api_per_request:>6.2f} {cells[0]:>10}"
f" {cells[1]:>10}")python step3_breakeven.pyhosted API: $1.21 per 1,000 requests
one replica: $5,150 a month; break-even at 4.25M requests a month
self-hosted cost per 1,000 requests (replicas) at two utilisation levels
requests/month API/1k 25% use 60% use
600,000 1.21 8.58 (1) 8.58 (1)
4,000,000 1.21 1.29 (1) 1.29 (1)
8,000,000 1.21 1.10 (2) 0.64 (1)
20,000,000 1.21 0.81 (4) 0.44 (2)Even at 600,000 questions a month, about a hundred times Lumen's current volume, the hosted API is about seven times cheaper: most of the replica would sit idle. Self-hosting breaks even at about 4.25 million requests a month, and becomes clearly cheaper only at volumes where utilisation decides how many replicas you need. Treat the result as a range, not a number: halve the throughput or double the operations cost and the break-even moves a long way. Cost is also not the only reason to host a model yourself. Data that may not leave your network, a fine-tuned model or a hard latency budget can justify it below break-even, as long as the decision record says so.
05. Step 4: Route between a small and a large model
Routing keeps the large model for the requests that need it. router.py implements two signals and their combination:
- Rules look at the question alone: length, a second question mark, words such as why or refund. They are free, fast and easy to explain, and they only see what you thought of.
- A cascade sends every request to the small model first, checks the answer, and escalates to the large model when the check fails. The FrugalGPT paper calls this an LLM cascade. It pays twice, in money and in time, for every escalated request, and it is only as good as its validator.
The validator here is fake: it stands in for real checks such as a schema check, cited passage ids that exist, and an entailment or judge check that the passages support the answer.
"""Two ways to send a request to the small or the large model."""
import re
from candidates import CANDIDATES, run, unit
SMALL, LARGE = (next(c for c in CANDIDATES if c.name == name)
for name in ("closed-small", "closed-large-r"))
HARD_WORDS = re.compile(r"\b(why|refund\w*|charged|error|after)\b", re.I)
def rules(case: dict) -> dict:
"""Route by cheap features of the question alone."""
q = case["question"]
hard = len(q.split()) > 14 or bool(HARD_WORDS.search(q)) or q.count("?") > 1
result = run(LARGE if hard else SMALL, case)
return {**result, "escalated": hard}
def validate(case: dict, result: dict) -> bool:
"""FAKE validator standing in for real checks (schema, citations present,
cited passages support the answer). It catches 80% of bad answers and
wrongly rejects 5% of good ones."""
u = unit("grader", case["id"])
return u < 0.95 if result["passed"] else u >= 0.80
def cascade(case: dict) -> dict:
"""Try the small model; escalate when its answer fails validation."""
small = run(SMALL, case)
if validate(case, small):
return {**small, "escalated": False}
large = run(LARGE, case)
return {**large, "cost": small["cost"] + large["cost"], "escalated": True,
"latency_s": small["latency_s"] + large["latency_s"]}
def rules_then_cascade(case: dict) -> dict:
"""Obviously hard questions go straight to the large model; the rest cascade."""
routed = rules(case)
return routed if routed["escalated"] else cascade(case)
STRATEGIES = {
"large_only": lambda case: {**run(LARGE, case), "escalated": True},
"small_only": lambda case: {**run(SMALL, case), "escalated": False},
"rules": rules,
"cascade": cascade,
"rules_then_cascade": rules_then_cascade,
}import pandas as pd
from evalset import build_cases
from router import STRATEGIES
dev = [c for c in build_cases() if c["split"] == "dev"]
rows = [{"strategy": name, **case, **route(case)}
for name, route in STRATEGIES.items() for case in dev]
df = pd.DataFrame(rows)
table = df.groupby("strategy", sort=False).agg(
pass_rate=("passed", "mean"),
must_fail=("passed", lambda p: (~p[df.loc[p.index, "must_pass"]]).sum()),
to_large=("escalated", "mean"),
per_1k=("cost", lambda c: 1000 * c.mean()),
p95_s=("latency_s", lambda s: s.quantile(0.95)),
)
print(f"dev split: {len(dev)} cases")
print(table.round(3).to_string())python step4_router.pydev split: 40 cases
pass_rate must_fail to_large per_1k p95_s
strategy
large_only 1.000 0 1.000 15.027 13.870
small_only 0.875 2 0.000 0.824 2.059
rules 1.000 0 0.400 6.460 13.204
cascade 1.000 0 0.175 3.364 14.197
rules_then_cascade 1.000 0 0.425 6.848 13.281On the dev split, every routed strategy matches the large model's perfect score at a fraction of its cost: the rules send 40% of requests to the large model, the cascade 17.5%. Note the cascade's p95 latency, higher than large-only, because an escalated request waits for both models. If you stopped here, the rules would look as good as anything. That is exactly the trap the next step is for: you wrote the rules while looking at these 40 questions.
06. Step 5: Confirm on the held-out split
Agree the bar before you run: a routed strategy may lose at most 3 points of pass rate against large-only on the test split, and no must-pass case may fail. The comparison is paired, case by case, so the script also counts the cases large-only passed and the router lost, and shows the change per slice.
"""Confirm on the held-out test split that routing keeps quality within the bar."""
import pandas as pd
from evalset import build_cases
from router import STRATEGIES
MAX_DROP = 0.03 # largest pass-rate drop versus large_only you accept
test = [c for c in build_cases() if c["split"] == "test"]
def evaluate(name: str) -> pd.DataFrame:
return pd.DataFrame([{**case, **STRATEGIES[name](case)} for case in test])
base = evaluate("large_only")
print(f"test split: {len(test)} cases; baseline large_only "
f"{base['passed'].mean():.3f} pass, ${1000 * base['cost'].mean():.2f}/1k")
for name in ("rules", "cascade", "rules_then_cascade"):
cand = evaluate(name)
drop = base["passed"].mean() - cand["passed"].mean()
lost = (base["passed"] & ~cand["passed"]).sum() # paired: same cases
must = (~cand.loc[cand["must_pass"], "passed"]).sum()
by_slice = cand.groupby("slice")["passed"].mean() - base.groupby("slice")[
"passed"].mean()
ok = drop <= MAX_DROP and must == 0
print(f"\n{name}: pass {cand['passed'].mean():.3f} (drop {drop:+.3f}),"
f" ${1000 * cand['cost'].mean():.2f}/1k")
print(f" cases lost {lost}, must-pass failures {must}")
print(" change by slice: " + ", ".join(f"{s} {d:+.2f}" for s, d in
by_slice.items()))
print(f" gate: {'PASS' if ok else 'FAIL'}")python step5_gate.pytest split: 40 cases; baseline large_only 0.975 pass, $15.01/1k
rules: pass 0.850 (drop +0.125), $5.11/1k
cases lost 5, must-pass failures 0
change by slice: account -1.00, billing -0.06, how-to +0.00, troubleshooting +0.00
gate: FAIL
cascade: pass 0.950 (drop +0.025), $3.04/1k
cases lost 1, must-pass failures 0
change by slice: account +0.00, billing +0.00, how-to +0.00, troubleshooting -0.12
gate: PASS
rules_then_cascade: pass 0.975 (drop +0.000), $6.96/1k
cases lost 0, must-pass failures 0
change by slice: account +0.00, billing +0.00, how-to +0.00, troubleshooting +0.00
gate: PASSThe rules fail. The test split contains short hard questions such as "Can two workspaces be merged?", which have no keyword and were not in the dev split, so the rules send them to the small model. The cascade passes: it lost one troubleshooting case and no must-pass case, at $3.04 per 1,000 queries instead of $15.01, an 80% saving. Combining rules with the cascade loses nothing and costs more than twice as much as the cascade alone.
Lumen ships the cascade, and the decision record states the bar, both results, the cost before and after, and the limits of the evidence. With 40 test cases, one case is 2.5 points, so this gate can only detect large drops; grow the set, compare with a paired bootstrap as in the AI Evaluation skill, and keep watching the escalation rate and online quality signals after release. If the escalation rate drifts up, the cascade is quietly getting more expensive.
07. Check your understanding
08. Apply it: stretch tasks
- The practice project. Replace
run()with real calls for one closed and one open-weight model on your RAG evaluation set (an OpenAI-compatible server such as vLLM or a hosted endpoint for the open model). Fill in their cards from the actual licence and data-handling terms, compute the break-even with your own GPU quote and a measured throughput, and write the choice down with the numbers. - A cheap classifier. Replace the keyword rules with a small classifier (for example logistic regression on question embeddings) trained on dev cases labelled by whether the small model passed them, and put it through the same gate.
- Lower effort before a second model. Many providers let you lower a reasoning model's effort or thinking. Add the large model at a lower effort as one more candidate, and compare it with the cascade on cost, latency and the gate.
09. Review prompt
Without looking back:
- Which requirements did you check before running any evaluation, and why do they come first?
- Which four inputs drive the self-hosting estimate, and which of them is hardest to know in advance?
- How does a cascade differ from rule-based routing in cost, latency and what it can catch?
- Why did the rules pass on dev and fail on test, and what does the gate need besides an overall pass rate?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.