Types of Models (AI Engg #5)
A finance team asks you to add an “ask your statements” feature. Legal says customer data cannot leave the company’s cloud. Procurement has budget for exactly one thing, and it is not GPUs. The obvious answer — call the biggest closed model — is off the table. The alternative — self-host a small open model — may or may not be good enough. How do you decide?
This chapter gives you the decision procedure. You will learn the three model families, what actually differs between them, how to evaluate them on your task instead of public leaderboards, and how to build a router so cheap requests stay cheap. By the end, “which model?” becomes a spreadsheet, not a vibe.
Three families
- Closed / proprietary. OpenAI (GPT, o-series), Anthropic (Claude), Google (Gemini). Weights are secret; you call an API. Best average quality, tools, and structured output; per-token pricing; data leaves your network; versions drift under you.
- Open weights. Meta Llama, Alibaba Qwen, Mistral, DeepSeek, Google Gemma. You download the weights and run them wherever you like (Ollama, vLLM, a cloud VM, your VPC). Free of per-token cost, fully controllable, fine-tunable; you pay in GPUs, ops, and eval work.
- Small / local. 1B–8B open models, usually quantized, running on a laptop or a single GPU. Private, offline, near-zero marginal cost, fast. Great for classification, extraction, drafts, and dev loops; weaker at hard reasoning.
The line between them keeps moving. Open models that were frontier two years ago now run on a laptop; closed models leap ahead on the hardest tasks. Assume you will re-decide every quarter, and build so a swap is an environment variable, not a rewrite.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=5pt, minimum width=3.0cm, minimum height=1.2cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=red!10] (c) at (-3.6,0) {closed\\GPT / Claude / Gemini\\best quality, per-token};
\node[b, fill=blue!10] (o) at (0,0) {open weights\\Llama / Qwen / Mistral\\hostable, fine-tunable};
\node[b, fill=green!12] (s) at (3.6,0) {small / local\\3–8B quantized\\private, cheap, fast};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {prototype closed $\to$ measure everything $\to$ move hot paths down this ladder};
\end{tikzpicture}
What actually differs (not just “quality”)
“Quality” is a single blurry number. In practice these dimensions decide:
| Dimension | Why it matters | Where open wins | Where closed wins |
|---|---|---|---|
| Reasoning | hard multi-step tasks | improving fast | currently ahead |
| Tool / function calling | agents (Ch. 11) | decent | most reliable |
| Structured output | parsing, schemas | varies | strong schema mode |
| Context window | long docs | up to 128K+ | up to 1M |
| Latency | UX | tunable, self-hosted | network + queue |
| Cost | scale | ~$0 marginal | per token |
| Privacy | compliance | full control | data leaves VPC |
| Licensing | legal | check each license | vendor terms |
| Version stability | regressions | you pin the weights | vendor updates |
The last two rows are the ones engineers forget and lawyers remember. A closed model can change under you overnight; your regression suite (Chapter 13) exists partly to catch that. An open model you can freeze byte-for-byte — at the cost of never improving until you choose to.
Choosing the right model: the procedure
Stop asking “what’s the best model?” Ask “what is the cheapest model that passes my evals?”
- Write the task spec. Input, output schema, and 50–200 golden examples with expected outputs. If you cannot write this, no model will save you.
- Set constraints. Data residency, max latency, max cost per 1K calls, required context length.
- Shortlist 4–6 models. One flagship closed, one small closed, two open, one local.
- Run the same evals through all of them. Score with deterministic checks + a model judge (Chapter 13).
- Pick the cheapest that clears your bar. Route the rest.
# a dead-simple bench harness — run it on YOUR goldens, not MMLU
from openai import OpenAI
CANDIDATES = [
("gpt-4o", OpenAI()),
("gpt-4o-mini", OpenAI()),
("qwen2.5:7b", OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")),
]
def score(model, client, goldens):
ok = 0
for g in goldens:
r = client.chat.completions.create(model=model, temperature=0,
messages=[{"role": "user", "content": g["prompt"]}])
out = r.choices[0].message.content
if g["must_contain"].lower() in out.lower():
ok += 1
return ok / len(goldens)
for name, c in CANDIDATES:
print(f"{name:16} {score(name, c, goldens):.2%}")
Public leaderboards (MMLU, GPQA, coding arena) are useful for shortlisting and useless for deciding. Your task is peculiar: your documents, your format, your edge cases. The only score that matters is the one on your goldens.
Benchmarks: how to read them without being fooled
- Contamination. Models are trained on the internet, which includes benchmark answers. A suspiciously high score on a famous benchmark can mean memorization, not skill.
- Saturation. When every model scores 90%+, the benchmark no longer distinguishes them. Look at the hard splits.
- Prompt sensitivity. A model that wins with one prompt format can lose with another. Benchmark harnesses standardize prompts; your app does not.
- Task mismatch. A model that tops a coding leaderboard can be mediocre at faithful RAG summarization. Match the benchmark family to your task.
- Cost-adjusted view. A model 2 points better but 10× the price is often the wrong default.
The honest use of benchmarks: filter 50 models to 5, then benchmark those 5 on your data. Never skip the second step.
The router: cheap by default, escalate on doubt
The mature architecture is not one model. It is a router that sends each request to the cheapest model likely to succeed, and escalates when confidence is low.
def classify_reasoning_needed(q: str) -> bool:
# cheap heuristic model call, or a tiny classifier
r = small.chat.completions.create(
model="gpt-4o-mini", temperature=0, max_tokens=4,
messages=[{"role": "system", "content": "Answer only SIMPLE or HARD."},
{"role": "user", "content": q}])
return "HARD" in r.choices[0].message.content.upper()
def answer(q):
if classify_reasoning_needed(q):
return flagship(q) # GPT-5 / Claude / Gemini
return cheap(q) # 4o-mini / Qwen-7B
Two more patterns worth knowing:
- Cascade / verify. Cheap model answers; a second cheap model (or a judge) verifies; only failures go to the flagship. Cuts cost dramatically on high-volume workloads.
- Gateway. Put OpenRouter (Chapter 6) or your own proxy in front, so
model=is a config value and fallbacks are automatic when a provider is down.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.7cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=gray!10] (q) at (-3.6,0) {request};
\node[b, fill=orange!15] (r) at (-1.3,0) {router\\classify};
\node[b, fill=green!12] (c) at (1.6,0.9) {cheap model\\80\% of traffic};
\node[b, fill=red!10] (f) at (1.6,-0.9) {flagship\\hard 20\%};
\draw[a] (q) -- (r); \draw[a] (r) -- (c); \draw[a] (r) -- (f);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.6) {same evals gate every branch};
\end{tikzpicture}
Fine-tuning on small open models
Once you have a high-volume, narrow task that a small model almost passes, fine-tuning can close the gap and collapse cost and latency. Use it for:
- Consistent format the model keeps fumbling.
- Domain tone (a terse legal register, a quirky internal style).
- Latency/cost wins when you have thousands of labeled examples.
Do not use it for facts (stale, cannot cite — use RAG, Chapter 10), and do not start there. The order is: prompt → context/RAG → small model → fine-tune. Teams that fine-tune first burn weeks and inherit an eval problem with an extra model to maintain.
A worked decision
Back to the finance team. The feature: answer questions over a customer’s statements.
- Spec: 300 golden Q→A pairs, must cite the statement page, must refuse if not present.
- Constraints: data cannot leave VPC ⇒ closed APIs disallowed. Latency < 3s p95. Budget ≈ one A10 GPU.
- Shortlist: Llama-3-8B, Qwen2.5-7B, Mistral-7B (all local), plus a 3B for drafts.
- Bench: measure answer correctness (judge) + citation accuracy (deterministic page check) + p95 latency.
- Outcome: Qwen2.5-7B at ~40 tok/s, 92% correctness, 95% citation accuracy meets the bar. Route simple lookups (“what was my balance in June?”) to a 3B model with a SQL tool; use 7B for synthesis.
The decision was driven by the constraint, not by the leaderboard — and the evals proved it was good enough.
Pitfalls
- Benchmark shopping. Public scores shortlist; your goldens decide. No exceptions.
- Ignoring latency. A 30s agent loop is a broken product no matter how smart. Measure p95, stream, and parallelize.
- No fallback. One provider outage should not be your outage. Gateway + a second model.
- Fine-tuning too early. Fix prompt and retrieval first; they are cheaper and usually sufficient.
- Forgetting licensing. Some “free” weights restrict commercial use. Read the license before you build a business on it.
Why can the cheapest model be the right default? When is self-hosting forced rather than chosen?
ASolution
Because most production traffic is easy, and routing easy requests to a cheap model cuts cost and latency without hurting quality; evals tell you the cheap model clears the bar. Self-hosting is forced by data-residency/compliance rules, by latency constraints, or by marginal-cost economics at very high volume — not usually by raw quality.
Next: The Open Stack (AI Engg #6) — how to actually run these models locally and route between them.