See it run
Lesson 3.7 puts the model behind the course's gateway as the alias local, with its own key, rate limits and traces, and runs it on 20 support tickets. The JSON parses. Then look at the order ids.
6 min 43 s · captions in the video, transcript below the lesson · narrated by an AI version of Charafeddine's voice, from his script.
The screencast shows its own run: valid JSON on 17 of 20, the category on 13, the order id on 6. The written lesson reports two other runs; the numbers move a little each time because the model samples.
Lesson 3.7 of 27 in AI Engineering Foundations · €197, lifetime access · Enroll
Test your own model
The same 20 tickets and the same strict schema, on the model you run. One file, and nothing else from the course.
python3 -m pip install ollama
ollama pull granite4:micro # or a model you already have
python3 measure_local_model.py granite4:micro
Download measure_local_model.py or copy it below.
The script (166 lines)
"""Measure a model you run in Ollama on 20 support tickets: valid JSON, right category, right order id.
python3 -m pip install ollama
ollama pull granite4:micro
python3 measure_local_model.py granite4:micro # or several models: ... granite4:micro llama3.2:3b
python3 measure_local_model.py granite4:micro -n 5 # the first five tickets only
Each ticket is sent once to your local Ollama (OLLAMA_HOST, default http://localhost:11434) with a strict JSON
schema as the output format, at most 200 output tokens and no temperature set, so two runs can differ. The
script counts how often the answer is valid JSON on the first try (no repair), how often the category matches
the ticket's label and how often the order id is the ticket's own (null when the ticket names none), then lists
every failure: answers cut off at the token limit, and every order id that is not the one the ticket gave.
A smoke check: twenty tickets, one run each. Python 3.9 or later.
"""
# From lesson 3.7 of Cohorte's AI Engineering Foundations (cohorte.co/engineering-foundations).
import argparse
import os
import statistics
import sys
import textwrap
import time
from typing import Literal, Optional
import ollama
from pydantic import BaseModel, ValidationError
SYSTEM = "You triage Larkfield Supply support tickets. Reply with JSON that matches the schema."
MAX_TOKENS = 200
class Triage(BaseModel):
category: Literal["returns", "refund", "shipping", "damage", "billing", "safety", "legal", "other"]
urgency: Literal["low", "normal", "high"]
order_id: Optional[str] # a union with null, still required: the model must say null
summary: str
def strict_schema() -> dict:
"""The schema the course sends: no titles, no extra keys, every field required."""
schema = Triage.model_json_schema()
schema.pop("title")
for field in schema["properties"].values():
field.pop("title")
return schema | {"additionalProperties": False}
# (id, subject, body, expected category, the order id the ticket gives or None)
TICKETS = [
("T-1001", "Return unopened gloves", "Hi, we ordered too many boxes of nitrile gloves (size L) on order LF-48336. "
"They are unopened. Can we send some back?", "returns", "LF-48336"),
("T-1002", "How long for shipping?", "If I order before noon today, when will it ship and how long does ground "
"take?", "shipping", None),
("T-1003", "Free shipping threshold", "What's the minimum order for free shipping?", "shipping", None),
("T-1004", "Box arrived crushed", "Order LF-48308 arrived today and two of the shelving uprights are bent, the "
"box was crushed. Photos attached. What now?", "damage", "LF-48308"),
("T-1005", "Where is my order", "Can you tell me where order LF-48231 is? It says in transit.", "shipping",
"LF-48231"),
("T-1006", "Opened wipes return", "We opened two packs of the disinfectant wipes and don't like the scent. Can "
"we return the rest of the case, including the opened packs?", "returns", None),
("T-1007", "Refund for wrong size", "We got size M gloves instead of L on order LF-48364. We'd like a refund "
"for those boxes, about $120.", "refund", "LF-48364"),
("T-1008", "Refund request full order", "Order LF-48217 was delivered late and we no longer need it. Please "
"refund the whole order ($533.40).", "refund", "LF-48217"),
("T-1009", "Degreaser leaking in our storeroom", "One of the 5 L citrus degreaser containers from our last "
"delivery is leaking on the floor of our storeroom and there is a strong smell. One of our staff got some on "
"her hands. What do we do?", "safety", None),
("T-1010", "Warranty on ladder", "The step ladder we bought in March has a cracked hinge. Is that covered?",
"other", None),
("T-1011", "Invoice copy", "Could you resend the invoice for order LF-48294? Our AP team lost it.", "billing",
"LF-48294"),
("T-1012", "Extend payment terms", "We'd like to move from net-30 to net-60 starting next month. Who approves "
"that?", "billing", None),
("T-1013", "Do you price match?", "Another supplier sells the same safety glasses for $24. Will you match that "
"price?", "other", None),
("T-1014", "Volume discount", "We need 200 hi-vis vests for a new site. Is there a discount for that "
"quantity?", "other", None),
("T-1015", "Custom labels misprinted?", "We want to return the custom printed labels, we changed our logo.",
"returns", None),
("T-1016", "Delete my data", "Please delete all personal data you hold about me, I'm leaving the company.",
"other", None),
("T-1017", "Lawyer letter", "This is the third time your driver damaged our loading dock. Our lawyer is "
"preparing a claim. I want this on record.", "legal", None),
("T-1018", "Expedited shipping for 120 kg pallet", "Can we get next-day delivery for a 120 kg order of "
"shelving?", "shipping", None),
("T-1019", "Hazmat by air?", "Can you ship the aerosol degreaser by air to our remote site? We need it this "
"week.", "shipping", None),
("T-1020", "Restocking fee question", "We want to return 25 boxes of corrugated boxes, unopened, ordered last "
"week. Will there be a fee?", "returns", None),
]
def run(client: ollama.Client, model: str, tickets: list[tuple]) -> dict:
valid = right = order_ok = invented = parsed_without_order = 0
latencies: list[float] = []
failures: list[str] = []
for i, (tid, subject, body, category, order_id) in enumerate(tickets, 1):
print(f"\r{model}: ticket {i}/{len(tickets)}", end="", file=sys.stderr, flush=True)
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"{subject}\n\n{body}"}]
start = time.perf_counter()
try:
r = client.chat(model, messages, format=strict_schema(), options={"num_predict": MAX_TOKENS})
except ollama.ResponseError as e:
failures.append(f"{tid} {type(e).__name__}: {e.error[:70]}")
continue
latencies.append(time.perf_counter() - start)
if r.done_reason == "length": # partial JSON is not JSON
failures.append(f"{tid} Truncated: output cut at max_tokens")
continue
try:
out = Triage.model_validate_json(r.message.content)
except ValidationError as e:
failures.append(f"{tid} InvalidOutput: {str(e).splitlines()[1][:70]}")
continue
valid += 1
right += out.category == category
order_ok += out.order_id == order_id
if order_id is None:
parsed_without_order += 1
invented += out.order_id is not None
if out.order_id != order_id: # schema-valid, and still a fact the ticket never gave
failures.append(f"{tid} order id {out.order_id!r}, ticket says {order_id}")
print("\r" + " " * 60 + "\r", end="", file=sys.stderr, flush=True)
return {"valid": valid, "right": right, "order_ok": order_ok, "n": len(tickets), "failures": failures,
"invented": invented, "parsed_without_order": parsed_without_order,
"median_s": statistics.median(latencies) if latencies else 0.0}
def main() -> None:
ap = argparse.ArgumentParser(description="Measure local Ollama models on 20 Larkfield support tickets.")
ap.add_argument("models", nargs="+", help="Ollama model names, e.g. granite4:micro")
ap.add_argument("-n", type=int, default=len(TICKETS), help="how many tickets to run (default: all 20)")
a = ap.parse_args()
client = ollama.Client() # reads OLLAMA_HOST, default http://localhost:11434
for model in a.models: # fail early, with the fix, before a long run
try:
client.show(model)
except ConnectionError:
sys.exit(f"No Ollama server at {os.environ.get('OLLAMA_HOST', 'http://localhost:11434')}. "
"Start Ollama, then run this again.")
except ollama.ResponseError:
sys.exit(f"{model} is not installed. Run: ollama pull {model}")
w = max(8, max(len(m) for m in a.models) + 2)
print(f"{'model':<{w}}{'valid JSON':>12}{'category':>10}{'order id':>10}{'median s':>10}")
for model in a.models:
r = run(client, model, TICKETS[: a.n])
n = r["n"]
print(f"{model:<{w}}{r['valid']:>9}/{n}{r['right']:>7}/{n}{r['order_ok']:>7}/{n}{r['median_s']:>10.1f}",
flush=True)
for f in r["failures"]:
print(f" {f}", flush=True)
k, inv = r["parsed_without_order"], r["invented"]
if inv:
say(f"{inv} of {k} parsed tickets that name no order came back with an order id the customer "
"never gave: the JSON was valid, the ids were invented.")
else:
say(f"None of the {k} parsed tickets that name no order got an invented order id on this run "
"(no temperature is set, so another run can differ).")
def say(text: str) -> None:
print(textwrap.fill(text, 64, initial_indent=" ", subsequent_indent=" "), flush=True)
if __name__ == "__main__":
main()
What it printed for us with granite4:micro, on an M3 Max Mac with Ollama 0.40.15, in about 30 seconds:
$ python3 measure_local_model.py granite4:micro
model valid JSON category order id median s
granite4:micro 17/20 11/20 8/20 1.3
T-1002 order id '123456', ticket says None
T-1003 order id 'shipping-free', ticket says None
T-1009 order id '2023-04-27-001', ticket says None
T-1010 order id '12345', ticket says None
T-1012 Truncated: output cut at max_tokens
T-1013 order id '12345', ticket says None
T-1014 Truncated: output cut at max_tokens
T-1015 order id 'required_but_not_provided', ticket says None
T-1016 order id '0', ticket says None
T-1018 order id '123456', ticket says None
T-1019 Truncated: output cut at max_tokens
T-1020 order id '123456', ticket says None
9 of 11 parsed tickets that name no order came back with an
order id the customer never gave: the JSON was valid, the ids
were invented.
Your numbers will move from run to run, because no temperature is set and the model samples. On a second run, granite4:micro got 18 of 20 valid, and 11 of the 12 parsed tickets that named no order came back with an invented one. llama3.2:3b got 16 of 20 valid, and 6 of 11.
Where this check goes next
The script tells you that a model invents facts. The course builds what catches it before it ships: a first eval set and a gate in CI that blocks a seeded regression (module 5), around the gateway this model sits behind (module 3). Here is the whole course, in order.
AI Engineering Foundations · the whole course
27 lessons in six modules, plus a Start Here section: 8 films with Charafeddine (lesson 0.2 opens the course), 13 screencasts, 4 labs and a capstone.
Module 1 · The job
- 1.1Why AI systems fail in productionfilm · 8 min
- 1.2The three V's: variability, veracity, vulnerabilityfilm · 6 min
- 1.3The platform you'll buildfilm · 7 min
- 1.4How this series worksreading
Module 2 · Model APIs as an engineering layer
- 2.1What converged and what didn't across model APIsfilm · 7 min
- 2.2Structured outputs and tool calls that holdscreencast · 7 min
- 2.3Streaming, effort, caching, batch: the levers and their numbersscreencast · 6 min
- 2.4Errors, retries, timeouts, and a refusal that arrives as an answerscreencast · 7 min
- 2.5Lab: a client that survives a bad daylab
Module 3 · The gateway, and a model you host
- 3.1Why a gateway, and when you don't need onefilm · 9 min
- 3.2LiteLLM: aliases, a key and a budget per agent, fallbacksscreencast · 8 min
- 3.3Cost per call, and why budgets lagscreencast · 6 min
- 3.4Supply chain: what the 2026 LiteLLM compromises teachfilm · 8 min
- 3.5Lab: break the budget, then contain itlab
- 3.6Why host your own model, and when not toThe film at the top of this pagefilm · 7 min
- 3.7A model you host, behind the aliasThis lessonscreencast · 7 min
Module 4 · Prompts and tools as contracts
- 4.1The prompt as a versioned contract, and cache-stable orderingscreencast · 4 min
- 4.2Tools: names, descriptions, schemas, errors, effectsscreencast · 4 min
- 4.3MCP in 2026: the stateless spec, transports, authorizationscreencast · 5 min
- 4.4Lab: one MCP server, one tool the model chooses welllab
Module 5 · First traces, first evals
- 5.1Traces with OpenTelemetry and Langfuse, redaction firstscreencast · 6 min
- 5.2Read 50 traces before you write a metricscreencast · 6 min
- 5.3A first eval set, and a gate that runs in CIscreencast · 7 min
- 5.4Lab: find the failure the dashboard didn'tlab
Module 6 · The capstone
- 6.1The Larkfield support answerer: spec and acceptancereading
- 6.2Build and gate it, then your capstone labscreencast · 5 min
- 6.3Review: what you shipped and what's still unprovenreading
One-time, lifetime access, with 3 months in the Engine Room. Or the six courses for €797.
Read the full lesson 3.7
Course 1 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e1-m3-l7) and lessons 3.2, 3.3 and 3.6.
You'll leave with an open model running on your laptop behind the gateway alias local, with its own key, the same budgets and traces as fast, and a measurement of what it gets right and what it gets wrong on 20 Larkfield tickets.
In one screen
- Use it on Monday: Score a local model on the facts in its answers, field by field, before any job moves to it, and cap its key with rate limits: zero-priced calls never use the budget.
- The picture: A model you host is one more alias behind the gateway, pinned by digest, with the same keys, budgets, spend log and traces as
fast.- The decision:
localstays a development alias until an eval on your own cases clears it for one named job; then move that job alone, with the hosted alias as fallback where no data promise forbids it.- You'll run:
uv run python scripts/compare_aliases.py local fast: onlocal, valid JSON for 17 of 20 tickets, all 6 named orders right, and an invented id like'12345'on every parsed ticket that named none.
Why this matters
I ran 20 Larkfield support tickets through a small open model on my laptop, with a strict schema, twice. It returned valid JSON for 17 of them, then 18. Six of the tickets name an order, and it got all 6 right both times. The other 14 should come back empty. Every one of them that parsed came back with an order number the customer never gave.
On "Free shipping threshold", a ticket that names no order, it answered "order_id": "12345" in both runs. On "Delete my data" it answered "required_for_deletion" in the first run and "DELETE-123456" in the second. The JSON parsed and passed validation, and the order numbers were made up. Lesson 3.6 said to host your own model only where an eval says it's good enough. This lesson builds the alias, and then shows you exactly why that eval can't be skipped.
The idea
Behind the gateway, a model you host is one more alias. You run a model server, add an entry to the gateway's config that points at it, give an agent a key that may call it, and your application calls local the way it calls fast.
app ── alias `local` ──> gateway (keys, budgets, spend log, traces) ──> Ollama on this machine (CPU)
app ── alias `fast` ──> gateway (same) ──> the provider, or the sim offline
app
| alias `local`
v
gateway (keys, budgets,
spend log, traces)
|
v
Ollama on this machine (CPU)
app
| alias `fast`
v
gateway (same)
|
v
the provider, or the sim offlineThree choices shape the build.
The model server is Ollama, an open-source runner (MIT license) for open-weight models on your own machine. It runs in one container, has no account, and speaks an API LiteLLM supports.
In this course it runs inside Docker Compose, which on a Mac means on the CPU: Docker can't reach the Mac's GPU. Run natively, outside Docker, Ollama uses the GPU through Metal and is much faster. I keep it in Compose so every reader gets the same setup. Production serving on a GPU is a different tool (vLLM), covered in E6, the platform course; the alias doesn't change.
The model is pinned by digest. A digest is the SHA-256 hash of the model's manifest (the list of files that make up the model: the weights, the chat template, the license). A tag such as granite4:micro can be pushed again; the digest can't. Ollama checks each file's hash on download, and our script refuses to go on if the installed digest isn't the pinned one.
The model is IBM's Granite 4.0 Micro: 3.4 billion parameters, quantized to 4 bits (Q4_K_M, a compressed format that trades a little quality for a quarter of the memory), Apache-2.0, 2.1 GB on disk, about 2.5 GiB of RAM once loaded.
No tracked file is edited. A script reads whichever gateway config your stack runs, adds the local alias, and writes the copy to var/gateway/, which git ignores. A Compose overlay (a second compose file whose entries are merged on top of the first) points the gateway at that copy.
Everything else in the config comes along unchanged: the keys, the budgets, the fallbacks, the tracing callback, the message-logging and redaction settings. That's how local gets the same governance as fast without a second copy of the rules to keep in sync.
Build it
Here's the plan. Start Ollama next to the gateway, add local to a copy of the gateway's config, give an agent a key for it, and call it. Then put it and fast through the same 20 tickets and read what each gets right.
You need about 4.3 GB of disk for the Ollama image, 2.1 GB for the model, and 2.6 GB of free RAM in Docker next to the core stack.
git checkout e1-m3-l7 && uv sync
The tag adds four code files, plus their tests, decision record 0016 and a section in docs/VERSIONS.md. It changes nothing the course already runs: not the client, not the gateway's config, not compose.yml. It branches off e1-m3-l3, so its files aren't in any later lesson tag (Going deeper says how to bring them over).
Step 1: the model server, as an overlay
What to notice. The image is pinned by version and digest, like every image since lesson 3.4. The port binds to 127.0.0.1 only. The second block is the whole trick: the same gateway service, with its config file taken from var/gateway/.
From infra/compose/compose.local-model.yml, the ollama service (its healthcheck is in Full code):
services:
ollama:
profiles: [local-model]
image: ollama/ollama:0.40.15@sha256:0e59999e0e8f9fd4e704bd788a89b7e4cad399367fb1365f8c102ac662288761
environment:
OLLAMA_HOST: 0.0.0.0:11434 # inside the container; published on 127.0.0.1 only (below)
OLLAMA_CONTEXT_LENGTH: "4096" # KV cache is sized from this: RAM grows with it
OLLAMA_NUM_PARALLEL: "1" # one request at a time: a laptop, not a server
OLLAMA_KEEP_ALIVE: 30m # keep the weights loaded between calls (the first call pays the load)
volumes: [ollama_models:/root/.ollama]
ports: ["127.0.0.1:${AIP_OLLAMA_PORT:-11434}:11434"]
And the gateway override, same file, infra/compose/compose.local-model.yml:
# Same gateway, same image, same keys and settings: only its config file comes from var/gateway/, where
# scripts/local_model.py render wrote the current tag's config plus the `local` alias.
gateway:
volumes:
- ../../var/gateway/config.local.yaml:/etc/litellm/config.yaml:ro
The KV cache is the memory a model keeps for the tokens already in its context. It grows with the context length, which is why the context is set rather than left to the default.
The local-model profile keeps Ollama out of every other lesson: nothing starts unless you name the profile.
Step 2: the pin and the alias
What to notice. The model is named and pinned in one place. The alias is priced at zero, with a comment saying what that zero leaves out.
From scripts/local_model.py:
MODEL = "granite4:micro" # IBM Granite 4.0 Micro, 3.4B, Q4_K_M, Apache-2.0; ~2.6 GB of RAM loaded (4K context)
DIGEST = "89962fcc75239ac434cdebceb6b7e0669397f92eaef9c487774b718bc36a3e5f"
LOCAL_ALIAS = {
"model_name": "local",
"litellm_params": {"model": f"ollama_chat/{MODEL}", "api_base": "http://ollama:11434"},
# No invoice, so the gateway prices it at zero. The real cost (hardware, power, the person on call) is not here.
"model_info": {"input_cost_per_token": 0, "output_cost_per_token": 0},
}
ollama_chat/ is LiteLLM's provider for Ollama's chat API. It translates our response_format (the strict JSON schema from lesson 2.2) into Ollama's own format field, so the schema constrains the model's output on the server side.
Step 3: render, bring up, check the pin
What to notice. render copies a config and adds one alias; it never writes to infra/gateway/. pull downloads once (do it before you need it, it's 2.1 GB), then compares digests every time you run it.
From scripts/local_model.py:
def with_local_alias(config: dict) -> dict:
"""The same config with `local` added (or replaced): nothing else changes."""
models = [m for m in config.get("model_list", []) if m["model_name"] != "local"]
return {**config, "model_list": models + [LOCAL_ALIAS]}
uv run python scripts/local_model.py render
(cd infra/compose && COMPOSE_PROFILES=core,local-model docker compose -f compose.yml -f compose.local-model.yml \
up -d --quiet-build --wait --force-recreate gateway ollama)
uv run python scripts/local_model.py pull
config.local.yaml from config.offline.yaml: aliases ['fast', 'smart', 'embed-default', 'rerank-default', 'local']
...
granite4:micro pulled, digest 89962fcc7523 matches the pin
The last line is the pin doing its job: the model on disk is the one in docs/VERSIONS.md. (Why a copied config rather than LiteLLM's model API? Going deeper.)
Step 4: a key for local
uv run python scripts/agent_key.py local-runner --agents-file infra/gateway/agents.local-model.yaml --env-file .env.local-model
created key for local-runner: {'key_alias': 'local-runner', 'models': ['local', 'fast'], 'max_budget': 1.0, 'budget_duration': '1d', 'rpm_limit': 30, 'tpm_limit': 100000} -> AIP_GATEWAY_KEY in .env.local-model
Same script as lesson 3.2, its own agents file. fast is on the key so the next steps can compare the two aliases with one key.
One thing to see clearly: the budget never moves on local, because every call is priced at zero. On a self-hosted alias, the control that bites is the rate limit (rpm_limit, tpm_limit).
Step 5: the first calls
What to notice. The client is lesson 2.2's, unchanged: client.complete("local", ...). The script prints the time, the tokens, a rough tokens per second and both cost headers. The full function is in Full code.
uv run python scripts/local_model.py check
call 1: 12.1s 42+42 tokens 3.5 tok/s end to end cost $None served by ollama_chat/granite4:micro
call 2: 8.0s 42+34 tokens 4.2 tok/s end to end cost $None served by ollama_chat/granite4:micro
call 3: 8.4s 42+41 tokens 4.9 tok/s end to end cost $None served by ollama_chat/granite4:micro
median 4.2 tok/s; loaded: 2.5 GiB in RAM, 0 in VRAM (CPU only), context 4096
About four tokens a second end to end, 8 to 12 seconds a call, on a laptop CPU. Measured by Ollama itself, the model decoded 6 to 10 tokens a second; the end-to-end figure is lower because it includes reading the prompt and the HTTP round trip. The first call after start also pays about 3 seconds to load the weights.
On the same day, with other heavy jobs on the host, the same calls took 19 to 35 seconds and some passed the gateway's 60-second timeout. On a CPU, your neighbors are part of your latency.
Now read the cost. LiteLLM 1.108.5 sends no x-litellm-response-cost header when the cost is zero, so cost_usd is None. Only the breakdown header, x-litellm-response-cost-original, says 0.0, and the spend log has the row at zero.
Lesson 3.3's rule holds: None means "we don't know". Code that sums costs has to treat it as unknown, and here it happens to mean free.
Step 6: the same 20 tickets on both aliases
What to notice. Validity is checked on the first try, with no repair. Then two facts: the category against the ticket's label, and the order id against the one the ticket gave (null when it names none). Every wrong order id is printed.
run in scripts/compare_aliases.py:
try:
out = parse_structured(c, Triage)
except GatewayError as e:
failures.append(f"{t['id']} {type(e).__name__}: {str(e)[:70]}")
continue
valid += 1
right += out.category == expected(t)
order_ok += out.order_id == t["order_id"]
if out.order_id != t["order_id"]: # schema-valid, and still a fact the ticket never gave
failures.append(f"{t['id']} order id {out.order_id!r}, ticket says {t['order_id']}")
uv run python scripts/compare_aliases.py local fast
The first run:
alias valid JSON category order id median s cost USD
local 17/20 12/20 6/20 9.4 0.000000
T-1002 Truncated: output cut at max_tokens
T-1003 order id '12345', ticket says None
T-1006 order id '123456789', ticket says None
T-1009 order id 'LARKFIELD-2023-06-21-001', ticket says None
T-1010 order id '123456', ticket says None
T-1012 order id 'LT-123456', ticket says None
T-1013 order id '123456', ticket says None
T-1014 order id 'req_001', ticket says None
T-1015 order id '12345', ticket says None
T-1016 order id 'required_for_deletion', ticket says None
T-1017 order id 'lawyer_letter', ticket says None
T-1018 order id '12345', ticket says None
T-1019 Truncated: output cut at max_tokens
T-1020 Truncated: output cut at max_tokens
fast 20/20 9/20 20/20 0.1 0.000519
The same command again, right after, gave local 18/20 valid, 13/20 on the category and 6/20 order ids, with a fresh set of invented ids (the full output is in Going deeper). The local lines will differ on yours: no temperature is set, so the model samples.
Read it carefully. fast here is the sim, our deterministic stand-in, so its column says the plumbing works and nothing about any real model.
The local column is a real model. Its JSON parsed 17 and 18 times in 20, and every miss was an answer cut off at max_tokens, never a broken schema, because Ollama constrains the output to the schema while it's generated. The order ids were right 6 times in 20 both times, and the lines under each row say which: the 6 tickets that name an order (T-1001, 1004, 1005, 1007, 1008, 1011) all got their number. Every ticket that named no order and parsed got an invented one, 11 of 11 and then 12 of 12. The model never once answered null, here or in the five-ticket runs of the Try it and the Your turn.
A schema checks the shape of an answer. Whether the answer is true is a question for an eval.
Try it (10 minutes on a CPU). Run the comparison twice on the first five tickets, uv run python scripts/compare_aliases.py local -n 5, and compare the two local rows and the order ids listed under them. No temperature is set, so the model samples. Then: what sample size would let you say "local is good enough for triage" with a straight face? (Answer 5 under Check yourself.)
Step 7: pin the plumbing in tests
uv run pytest tests/integration/test_local_model.py -q
...s [100%]
3 passed, 1 skipped
Three tests run when the local-model profile is up: the unchanged client calls local (with the cost assertion above), the call lands in the spend log at zero with model_group: local, and a key without local gets a 403.
The fourth reads a fast call and a local call back from Langfuse and checks that they carry the same attributes and store no prompt. It skips unless the tracing stack (the obs profile) is up. With it up, on 16 November 2026, it passed.
Without the local-model profile, all four skip, so the suite stays green on any machine.
Your turn (15 min)
The Try it showed the invented order ids changing from run to run. Pin a temperature of 0 on local, so the model always picks its most likely next token, and see what that fixes and what it doesn't.
Test first. In tests/unit/test_local_model_script.py, change the expected litellm_params in test_local_is_the_pinned_ollama_model_at_zero_price to include "temperature": 0, then run:
uv run pytest tests/unit/test_local_model_script.py -q
You should see 1 failed, 4 passed. Now add the temperature to LOCAL_ALIAS in scripts/local_model.py until it reads 5 passed. LiteLLM passes a parameter set in an alias's litellm_params on every call to that alias, so nothing else changes.
Then, with the stack up, render again, recreate the gateway so it reads the new config, and run the five tickets twice:
uv run python scripts/local_model.py render
(cd infra/compose && COMPOSE_PROFILES=core,local-model docker compose -f compose.yml -f compose.local-model.yml \
up -d --quiet-build --wait --force-recreate gateway)
uv run python scripts/compare_aliases.py local -n 5
uv run python scripts/compare_aliases.py local -n 5
Predict before you run it: do the two rows match now, and are the order ids right? Put the files back with git checkout scripts tests when you're done. My run and one solution are under Check yourself.
When you're done with local, stop Ollama and give the gateway back the config it had before this lesson. That frees about 2.6 GB of RAM, and the model stays on its volume for next time:
(cd infra/compose && COMPOSE_PROFILES=core,local-model docker compose -f compose.yml -f compose.local-model.yml stop ollama \
&& docker compose up -d --wait --force-recreate gateway)
compare_aliases.py local -n 1 then answers T-1001 BadRequest: the gateway no longer knows the alias.
What breaks
- Valid JSON, wrong facts. Constrained decoding (the server only lets the model produce tokens the schema allows) guarantees that the output parses. It says nothing about whether it's true: in both runs, every ticket that named an order got the right one and every ticket that named none got an invented one. Control: an eval on your own cases before any job moves to
local, with a field-level check for every fact you rely on. - Answers that run on. A small model can keep writing a summary until it hits
max_tokens(Truncated) or the gateway's timeout. Control: amax_tokenssized to the schema, and the timeout and retry rules of lesson 2.4. - A busy host. On a CPU, any other heavy job slows the model; on 16 November 2026 decode speed fell from 6 to 10 tokens a second to under 1. Control: measure on the machine that will serve, under its real load, and keep a hosted fallback for jobs with a latency promise (unless the job carries a residency promise, lesson 3.6).
- A cost read as free, or as missing. The gateway prices
localat zero and sends no cost header. Control:NonestaysNone; count the hardware and the people separately (lesson 3.6). - A budget that never moves. Zero-priced calls never consume the key's budget. Control: rate limits per key.
- A moved tag. Control:
pullandcheckrefuse a digest that isn't the pin.
Decide
Default: a hosted model behind local stays a development and experiment alias until an eval on your own cases says it's good enough for one named job. Then move that one job, keep the hosted alias as fallback where no data promise forbids it, and measure for a month.
When to pick otherwise: if the data can't leave your network, local (or its production twin on a GPU) may be the only option. Then the eval decides which job it can take, and the jobs it can't take stay with people or wait for a better model.
Check yourself
- Why does
rendercopy the gateway config instead of editing it? The copy inherits every setting of whichever config the stack runs (keys, budgets, callbacks, redaction), no tracked file changes, and the same overlay works at every later tag. - In two runs,
localreturned valid JSON 17 and 18 times out of 20. Is it good enough for triage? You don't know yet. Validity is the shape. In both runs the order id was right 6 times in 20: the 6 tickets that name one. Every other ticket that parsed got an invented number. The category was right 12 and then 13 times. You need an eval on the facts, with enough cases to trust the rate. - Your cost dashboard shows
localcalls as missing cost. Is the gateway broken? No. LiteLLM 1.108.5 sends no cost header when the price is zero; the breakdown header and the spend log say zero. Treat missing as unknown in code, and count the hardware and people separately. - Which control limits a runaway agent on
local? The key's rate limits. Its budget never moves, because every call is priced at zero. - Try it. My two runs (16 November 2026, a busy host) both printed
5/5 5/5 3/5, with the same two tickets wrong, T-1002 and T-1003, neither of which names an order. The invented ids changed:'123456789'and'SHIP-1234'the first time,'12345'and'SHIP-001'the second. The counts held still while the content moved. As for sample size, twenty is far too few: 6 right out of 20 is anywhere from about 15% to 52% at 95% confidence (a Wilson interval, the usual range for a rate measured on a sample). To pin a rate within about 5 points you need a few hundred cases, 385 in the worst case. E2, the trust course, builds that eval and the gate on top of it. - Your turn. I ran it at
e1-m3-l7on 16 November 2026:1 failed, 4 passedwith the test change alone,5 passedwith both. The solution (not in the repository), the new line inLOCAL_ALIAS:
"litellm_params": {"model": f"ollama_chat/{MODEL}", "api_base": "http://ollama:11434", "temperature": 0},
And in the test:
assert alias["litellm_params"] == {"model": "ollama_chat/granite4:micro", "api_base": "http://ollama:11434",
"temperature": 0}
The rendered config then carries temperature: 0 under local. Both runs printed the same thing:
alias valid JSON category order id median s cost USD
local 5/5 5/5 3/5 16.6 0.000000
T-1002 order id '123456', ticket says None
T-1003 order id '12345', ticket says None
(the second run's median was 13.6 s). The rows match, and the ids are still invented. Temperature 0 made the answer repeatable. It didn't make it true: the model now gives the same wrong order id every time. That's easier to test, which is worth having, and it's still a question for an eval. On a CPU, tiny numeric differences can still flip a token now and then, so treat "repeatable" as likely, not promised.
Transcript
Hey friends. Last time, we talked about why you'd host your own model, and when you really shouldn't. In this video, we actually do it. So you'll learn how to run an open model in a container on your laptop, put it behind the gateway as one more alias, and measure it against the alias we already have. And at the end there's a result I want you to look at closely.
It's the whole case for evals, in one screen. We start where the gateway lessons left us: keys, budgets and a cost on every call. First, the model server. It's Ollama, in its own Compose file. An overlay, so the main compose file doesn't change at all. The image is pinned by version and by digest, the same rule we gave the gateway in the supply chain lesson.
And the port binds to this machine only. Now look at the comment at the top. Inside Docker on a Mac, this runs on the CPU, because Docker can't see the Mac's GPU. Run Ollama natively and it uses the GPU, and it's a lot faster. I keep it in Compose so everybody gets the same setup, whatever laptop they have.
And at the bottom, the gateway gets one override: its config file now comes from a folder called var. Now the weights. A model tag on a registry can be pushed again, so a tag alone isn't a pin. The digest is. It covers the weights, the chat template and the license, and Ollama checks the hash of each file when it downloads it.
The model is small, it fits in a few gigabytes of RAM, and its license is Apache, so you can use it at work. Then the alias itself. local points at the Ollama container, and its price is zero. There's no invoice, so the gateway has nothing to charge. But the cost is real, right? The machine, the power, the person who keeps it running.
It's just not in this file. So how does the gateway learn about local? I don't touch its config. This render function reads whichever config the stack runs, adds one alias, and writes the copy into var, which git ignores. Everything else comes along as it was: keys, budgets, fallbacks, the tracing callback. So local is governed exactly like fast and smart.
If we run it, there's our list. The four aliases we had, plus local. Now we bring it up, with the core profile and the new one, and we recreate the gateway so it loads the rendered config. By the way, I pulled the model before this video. It's a couple of gigabytes, and nobody wants to watch a progress bar.
But I still run pull. The model is already there, so it's quick, and it does the part that matters. It compares the digest it has with the one in the script. If someone moved the tag, we stop right here, before a single call. Next, a key. Same script as in the keys and budgets lesson, with its own agents file.
The agent local runner may call local, and fast too, so we can compare the two in a minute. And here's a small trap. The budget is there, but it never moves on local, because every call costs zero. So on a self-hosted alias, the control that actually bites is the rate limit: requests and tokens per minute. All right, the first calls.
This is our client from the structured outputs lesson, unchanged. It just names local. Three calls, and for each one: the time, the tokens, a rough tokens per second, and what the gateway said about the cost. The speed is on screen, and the date it was measured is at the bottom. What I want you to read is the cost.
The header is missing, so our client says None. The gateway knows the price is zero. But this version sends no cost header at all when the cost is zero, and only the breakdown header says zero. Remember the cost lesson? None means we don't know. So code that adds up costs has to treat None as unknown, and here it happens to mean free.
Check that on your own gateway before you trust a dashboard. And the last line: the model sits in RAM, nothing on a GPU. That's the CPU path. Now the comparison. Twenty Larkfield tickets, the same strict schema we used for triage, sent to both aliases. For each answer, three questions. Is the JSON valid on the first try? Is the category right?
And is the order id the one the ticket gave? When a ticket names no order, the right answer is null. This takes a few minutes on a CPU, so I sped it up. And fast, here, is our stand-in model, so its column only tells you the plumbing works. So look at the valid JSON column for local. The schema mostly holds, because the runtime constrains the output to the schema, so the JSON comes out valid.
Now look at the order id column, and at the lines underneath it. Those are order numbers the customer never gave us. Valid JSON, carrying a fact that isn't true. Let's pin the plumbing in tests. The unchanged client calls local, and the cost assertion says what we just saw: no cost header, and a breakdown of zero. The call lands in the spend log at zero.
A key without local gets a 403. And the fourth test reads traces back from Langfuse, checking local carries the same attributes as fast. It skips here, because the tracing stack isn't running in this video. So where are we? The plumbing is solid. The model gives you the right shape and, sometimes, the wrong facts. A schema can't catch that.
Only an eval can, with enough cases to trust the number. That's what the trust course, E2, is built for, and its model migration check takes local as a candidate. And the tree matches the tag. One more alias, a model you host, with the same keys, budgets and traces as the others, and a measurement that tells you what it's good for.
That closes the gateway module. Next up, module four, where the prompt becomes a versioned contract. See you there.
Going deeper
Build it: the four files
Pinned (checked 16 November 2026): Ollama 0.40.15 and the model granite4:micro at manifest digest 89962fcc7523..., both pinned in full in docs/VERSIONS.md; LiteLLM proxy 1.108.5; Python 3.12.
git diff --stat=72 e1-m3-l3..e1-m3-l7 -- infra scripts
infra/compose/compose.local-model.yml | 32 +++++++
infra/gateway/agents.local-model.yaml | 13 +++
scripts/compare_aliases.py | 85 +++++++++++++++++++
scripts/local_model.py | 115 ++++++++++++++++++++++++++
4 files changed, 245 insertions(+)
The tag branches off e1-m3-l3, so its files aren't in e1-m4-l1 or any later lesson tag; they're in e1-final and every course's final tag after it. To use them at a later lesson tag, bring the four files over unchanged: git checkout e1-m3-l7 -- infra/compose/compose.local-model.yml infra/gateway/agents.local-model.yaml scripts/local_model.py scripts/compare_aliases.py.
Step 3: why not LiteLLM's model API
Why not add the alias through LiteLLM's model API (POST /model/new)? On 1.108.5 it answers HTTP 500, "Set STORE_MODEL_IN_DB='True'". Turning that on would keep the alias in the gateway's database, outside the files you review, and would change the gateway service in compose.yml. Decision record 0016 in docs/decisions/ has the full reasoning.
Step 5: the run behind the numbers
Run of 16 November 2026, on an Apple M3 Max with Docker's VM at 14 CPUs and 7.65 GB, on a quiet machine (the line format at the tag also prints the gateway's overhead, 7 to 28 ms, and both cost headers: cost header None, original 0.0).
Step 6: the second run in full
The same command again, right after:
alias valid JSON category order id median s cost USD
local 18/20 13/20 6/20 9.0 0.000000
T-1002 Truncated: output cut at max_tokens
T-1003 order id '12345', ticket says None
T-1006 order id 'Larkfield Supply Support', ticket says None
T-1009 order id 'LARKFIELD_SUPP_2023_001', ticket says None
T-1010 order id '12345', ticket says None
T-1012 order id 'supply-12345', ticket says None
T-1013 order id 'LARKFIELD-2023-001', ticket says None
T-1014 order id 'REQ-2023-001', ticket says None
T-1015 order id '12345', ticket says None
T-1016 order id 'DELETE-123456', ticket says None
T-1017 Truncated: output cut at max_tokens
T-1018 order id 'LSP-120KG-PALLET', ticket says None
T-1019 order id 'LSP-2023-001', ticket says None
T-1020 order id '12345', ticket says None
fast 20/20 9/20 20/20 0.1 0.000519
Runs of 17 November 2026 at the tag, 4 minutes 32 seconds and 4 minutes 5 seconds, at a load average of 16 to 34 while the model ran.
Step 6: the stand-in and two earlier runs
The sim is decision record 0001 in docs/decisions/. Two earlier runs of step 6, on 16 November, with a version of the script that didn't yet list each wrong order id and on a host loaded by other jobs, gave 16 and then 19 of 20 valid JSON, 10 and then 13 on the category, 6 of 20 order ids in the run that counted them. The first used a larger max_tokens, and two of its answers ran on until they hit it; across the two, three answers passed the gateway's 60-second timeout. Decision record 0016 records them; at e1-final it also records the two runs above.
Full code
From infra/compose/compose.local-model.yml:
# Lesson E1 3.7: a model you host, behind the gateway alias `local`. An overlay: compose.yml is not edited.
#
# uv run python scripts/local_model.py render # writes var/gateway/config.local.yaml (gateway config + `local`)
# COMPOSE_PROFILES=core,local-model docker compose -f compose.yml -f compose.local-model.yml up -d --wait
# uv run python scripts/local_model.py pull # off camera: downloads the model, checks its pinned digest
#
# CPU only: Docker on a Mac has no access to the Apple GPU. Native Ollama (outside Docker) uses Metal and is faster.
services:
ollama:
profiles: [local-model]
image: ollama/ollama:0.40.15@sha256:0e59999e0e8f9fd4e704bd788a89b7e4cad399367fb1365f8c102ac662288761
environment:
OLLAMA_HOST: 0.0.0.0:11434 # inside the container; published on 127.0.0.1 only (below)
OLLAMA_CONTEXT_LENGTH: "4096" # KV cache is sized from this: RAM grows with it
OLLAMA_NUM_PARALLEL: "1" # one request at a time: a laptop, not a server
OLLAMA_KEEP_ALIVE: 30m # keep the weights loaded between calls (the first call pays the load)
volumes: [ollama_models:/root/.ollama]
ports: ["127.0.0.1:${AIP_OLLAMA_PORT:-11434}:11434"]
healthcheck:
test: ["CMD", "ollama", "list"]
interval: 5s
timeout: 5s
retries: 20
# Same gateway, same image, same keys and settings: only its config file comes from var/gateway/, where
# scripts/local_model.py render wrote the current tag's config plus the `local` alias.
gateway:
volumes:
- ../../var/gateway/config.local.yaml:/etc/litellm/config.yaml:ro
volumes:
ollama_models:
render, pull and check in scripts/local_model.py:
def render(out: Path = OUT) -> None:
name = compose_var("AIP_GATEWAY_CONFIG", "config.offline.yaml")
src = ROOT / "infra" / "gateway" / name
out.parent.mkdir(parents=True, exist_ok=True)
(out.parents[1] / ".gitignore").write_text("*\n") # var/ holds generated files, never committed
config = with_local_alias(yaml.safe_load(src.read_text()))
out.write_text(f"# GENERATED by scripts/local_model.py render from infra/gateway/{name}: do not edit.\n"
+ yaml.safe_dump(config, sort_keys=False))
print(f"{out.name} from {name}: aliases {[m['model_name'] for m in config['model_list']]}")
def installed_digest(tags: dict, model: str = MODEL) -> str | None:
return next((m["digest"] for m in tags.get("models", []) if m["name"] == model), None)
def pull(ollama: str) -> None:
r = httpx.post(f"{ollama}/api/pull", json={"model": MODEL, "stream": False}, timeout=1800)
r.raise_for_status()
got = installed_digest(httpx.get(f"{ollama}/api/tags").json())
if got != DIGEST:
sys.exit(f"{MODEL}: digest {got} is not the pinned {DIGEST}: the tag moved. Review before re-pinning.")
print(f"{MODEL} pulled, digest {got[:12]} matches the pin")
PROMPT = [{"role": "system", "content": "You answer Larkfield Supply customers in two sentences."},
{"role": "user", "content": "If I order before noon today, when will it ship and how long does ground take?"}]
def check(ollama: str, env_file: str, runs: int = 3) -> None:
from aip.llm import Client
got = installed_digest(httpx.get(f"{ollama}/api/tags").json())
if got != DIGEST:
sys.exit(f"{MODEL} not installed at the pinned digest (found {got}): run `local_model.py pull`")
client = Client(settings=Settings(_env_file=env_file))
rates = []
for i in range(runs):
c = client.complete("local", PROMPT, max_tokens=120, tags=("local-check",))
rate = c.usage.output_tokens / (c.latency_ms / 1000)
rates.append(rate)
# LiteLLM 1.108.5 sends no x-litellm-response-cost header when the cost is 0 (cost_usd is None);
# the breakdown header x-litellm-response-cost-original still says 0.0.
print(f"call {i + 1}: {c.latency_ms / 1000:5.1f}s {c.usage.input_tokens}+{c.usage.output_tokens} tokens "
f"{rate:4.1f} tok/s end to end gateway overhead {float(c.headers['x-litellm-overhead-duration-ms']):.0f} ms "
f"cost header {c.cost_usd}, original {c.headers.get('x-litellm-response-cost-original')} "
f"served by {c.model}")
ps = httpx.get(f"{ollama}/api/ps").json()["models"][0]
print(f"median {statistics.median(rates):.1f} tok/s; loaded: {ps['size'] / 2**30:.1f} GiB in RAM, "
f"{ps['size_vram']} in VRAM (CPU only), context {ps['context_length']}")
run in scripts/compare_aliases.py (the Triage model is lesson 2.2's):
def run(client: Client, alias: str, tickets: list[dict]) -> dict:
valid = right = order_ok = 0
latencies, cost, failures = [], 0.0, []
for t in tickets:
msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"{t['subject']}\n\n{t['body']}"}]
try:
c = client.complete(alias, msgs, response_format=response_format(Triage), max_tokens=200)
except GatewayError as e:
failures.append(f"{t['id']} {type(e).__name__}")
continue
latencies.append(c.latency_ms / 1000)
cost += c.cost_usd or 0
try:
out = parse_structured(c, Triage)
except GatewayError as e:
failures.append(f"{t['id']} {type(e).__name__}: {str(e)[:70]}")
continue
valid += 1
right += out.category == expected(t)
order_ok += out.order_id == t["order_id"]
if out.order_id != t["order_id"]: # schema-valid, and still a fact the ticket never gave
failures.append(f"{t['id']} order id {out.order_id!r}, ticket says {t['order_id']}")
return {"alias": alias, "valid": valid, "right": right, "order_ok": order_ok, "n": len(tickets), "cost": cost,
"median_s": statistics.median(latencies) if latencies else 0.0, "failures": failures}
Sources
- Ollama releases (0.40.15, 3 November 2026; 0.40.16 not adopted, one week old): https://github.com/ollama/ollama/releases (checked 16 Nov 2026)
- Ollama in Docker (CPU command, GPU options, the
/root/.ollamavolume): https://docs.ollama.com/docker (checked 16 Nov 2026) - Ollama structured outputs (
formatwith a JSON schema;response_formaton the OpenAI-compatible API): https://docs.ollama.com/capabilities/structured-outputs (checked 16 Nov 2026) - Granite 4 on Ollama (
granite4:micro, Apache-2.0 license layer; manifest digest read fromregistry.ollama.ai): https://ollama.com/library/granite4 (checked 16 Nov 2026) - The reference repository at
e1-m3-l7: decision record 0016,docs/VERSIONS.md"Self-hosted model", and every output above (runs of 16 Nov 2026); Step 6's two runs of 17 Nov 2026: decision record 0016 ate1-final