Module 03: Projects

Understand LLMs5 projects0 of 5 complete

Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.

Five projects: two starters and three stretches (the streaming gateway and the resumable batch classifier are optional). Every one runs keylessly against the free local stand-in from lesson 03.1, Part 12: Ollama on localhost:11434 serves the OpenAI and Anthropic formats. Gemini has no local stand-in (Ollama does not speak Gemini's API, lesson 03.1, 12.4), so the projects use the three Ollama routes locally. Hosted providers (OpenAI, Anthropic, Gemini, OpenRouter) are the stretch goal for each project once you have a key: you change a registry file and your .env, not the code.

What the stand-in can and cannot tell you. It is a 0.5-billion-parameter model, so its answers are often wrong or odd, and they vary from run to run. It proves your plumbing (requests, streams, retries, files, tests), not how GPT, Claude or Gemini behave. Every "expected output" below was produced on the stand-in; the exact words, token counts and timings will differ on your machine, and the text says so wherever it matters. Output from a hosted provider would differ again.

First time? Do lesson 03.1, Part 4 once (uv init llm-apis --bare --python 3.13, then uv add openai anthropic google-genai python-dotenv pydantic pyyaml httpx, with package names only, so you get the newest releases; the lessons' Setup sections say which versions their samples were checked against), then Part 12: install Ollama, ollama pull qwen2.5:0.5b, and create the model aliases (12.3). Run scripts with uv run python file.py. Keep the pinned versions while you work: google-genai 3.0.0 came out on 6 November 2026 with a different default HTTP library and Gemini API version (3.1.0, on 10 November, lists no breaking changes), and nothing in these projects was run on either (lesson 03.1, 4.5).

Three of the projects use the package from lesson 03.11, which is called provider_agnostic (not llm: the lesson explains why). Copy it into your project root with the helper files its Setup table names (cost_calc.py, prices.py, prices.yaml from 03.7; llm_errors.py, retry_after.py, check_response.py from 03.8; weather_tools.py from 03.5), using the final versions of those files. Its provider_agnostic/models.local.yaml maps the three API shapes Ollama speaks to the stand-in: local-responses, local-chat and local-anthropic (the local fallback chain holds all three). There is no local Gemini route; the Gemini routes are hosted-only and tested with mocks (03.11, Part 10). Import from the package, as in from provider_agnostic import LLMClient, Registry, Request, Message.


Starter

Starter: Multi-provider chat CLI#

Goal: Build a terminal chat that streams each answer as it arrives, lets you switch provider in the middle of a conversation with /model, and saves every conversation to disk so you can resume it later, even on a different provider.

Prerequisites: lessons 03.1 to 03.3 and 03.8, the first parts of 03.11 (the client and its types), and the stand-in running.

What you'll practise:

  • Streaming one turn and committing it only when the stream finishes (lesson 03.3, 1.1, 4.1, 8.4)
  • Keeping the provider's full reply in the history, not only its text (lesson 03.2, 3.6, 5.1)
  • Saving, reloading and continuing a conversation, and continuing it on a different provider (5.2, 5.4)
  • Using one client for several API shapes (required: the OpenAI and Anthropic adapters; the Gemini, OpenRouter and Ollama adapters are optional), with capability checks that fail before anything is sent (lesson 03.11, Part 3, 7.3)
  • Treating a failed turn as a failed turn, with typed errors (lesson 03.8, 1.1, lesson 03.11, Part 6)

Setup: the provider_agnostic package and helper files described above, and the stand-in running. Your chat CLI must work with the OpenAI and Anthropic adapters (and a fallback between them); wiring up Gemini or OpenRouter is optional. Run it as uv run python chat.py --registry provider_agnostic/models.local.yaml. Export the variables from 03.1, 12.3 in the terminal where you run the CLI. The header comment of models.local.yaml says which key variable each route reads.

Steps:

  1. Check the plumbing. Before writing the CLI, call each route once: client.complete(Request(model=route, system="Be brief.", messages=[Message.user("Say hello in three words.")])) for the three routes in the local fallback chain — local-responses, local-chat and local-anthropic — as in 03.11, Part 10's demo. Print r.text, r.finish_reason.value and r.usage. All three should answer.
  2. Stream one turn. Write chat.py with a function stream_turn(client, model, system, history) that iterates client.stream(Request(...)), prints each TextDelta with flush=True, records the time of the first one, and returns event.response when it sees Done. Wrap the loop in try/finally: stream.close() so that Ctrl-C closes the connection and the provider stops generating (03.3, 8.5).
  3. Keep the history. Append Message.user(line) before the call and response.message after it (not a new Message.assistant(text): response.message carries reasoning blocks and other provider-native parts, 03.2, 3.6). Print a footer for each turn: the route that served it, the finish reason, input and output tokens, the first-token time and the cost.
  4. Add commands. Handle /models (list registry.aliases and registry.models), /model NAME (call client.preflight(NAME) first, so a typo fails now and not in the middle of the next turn), /system TEXT, /history, /new and /quit. The history is provider-neutral, so after /model the next turn simply sends the same messages through a different adapter. A part's provider-native twin is replayed only to the provider and API that produced it (03.11, 3.1); on any other route the adapter falls back to the text.
  5. Save after every turn. Write conversations/NAME.json with {"version": 1, "model", "system", "messages": [m.model_dump(mode="json") ...]}, writing to a .tmp file and then os.replace so a crash never leaves half a file. Add --resume, which loads the file with Message.model_validate, and let an explicit --model override the saved one. Store the whole message (all parts), not just the text, for the reasons in 03.2, 5.1.
  6. Handle failure. Catch LLMError around the turn. On failure, pop the user message you just added (so the history never ends in a dangling user turn), print the error's class name and its retryable flag, and carry on. Do the same for KeyboardInterrupt: an interrupted turn is not kept.
  7. Test the store. Write test_store.py with two pytest tests (03.10, 7.1): a conversation saved and reloaded equals the original messages, and loading a missing name raises FileNotFoundError. Use pytest's tmp_path and monkeypatch so the tests never touch your real conversations/ folder.

Hints if you are stuck: get a plain client.complete loop working first and add streaming afterwards. Replay the same conversation with the printf pipe in the verify command instead of typing it, so runs are comparable. If --resume rebuilds the wrong shape, print m.model_dump(mode="json") for one saved message and compare it with what Message.model_validate expects. If a route fails, run step 1's single call on it before debugging the CLI.

Verify it, and what you should see:

bash
uv run pytest -q test_store.py                                     # 2 passed
printf 'My name is Priya. Reply in one short sentence.\n/model local-anthropic\nWhat is my name?\n/history\n/model nope\n/quit\n' | uv run python chat.py --registry provider_agnostic/models.local.yaml --name demo

Output (illustrative, trimmed from an earlier run and not re-run; your wording and timings will differ, because the model is tiny and not deterministic). The two turns below are from a run on the stand-in:

text
[model local-responses; /help for commands]
you> local-responses> Hello, my name is Priya! How can I assist you today?
[local-responses | stop | in 31 out 16 | first token 173 ms | $0.0]
you> [now using local-anthropic]
you> local-anthropic> Your name is Priya.
[local-anthropic | stop | in 61 out 7 | first token 101 ms | $0.0]

/history then lists the four messages in order (the two user lines and the two assistant replies), and /model nope prints a line starting [cannot use 'nope': unknown model alias 'nope'; known aliases: followed by the registry's alias and entry names. That last part was not re-run after the Gemini route left the local registry, so its exact text is not shown.

What to notice: the second turn, on the Anthropic route, still knows the name from a turn written on the Responses route, because the history is yours and provider-neutral. The 0.5B model may not answer every question well; that is the model, not the client. Then resume the saved conversation on a different route:

bash
printf 'Repeat my name.\n/quit\n' | uv run python chat.py --registry provider_agnostic/models.local.yaml --name demo --resume --model local-chat

It prints a [resumed demo: ...] banner with the number of saved messages, then [model local-chat; /help for commands], then the answer from the local-chat route with its footer. (The resume output was not re-run either, because the saved conversation is shorter now.)

To see the failure path, point one registry entry at a closed port (base_url: http://localhost:9/v1) and chat on it: the turn prints [ConnectionFailed: Connection error. [local]] (retryable=True) and the history is unchanged.

Done when:

  • Streaming prints text as it arrives and shows a first-token time on every turn.
  • You can switch among at least three local routes mid-conversation and the model still uses facts from earlier turns.
  • A conversation survives quitting and --resume, including on a route other than the one that wrote it, and the two store tests pass.
  • A failed or interrupted turn leaves the history and the saved file unchanged.
  • Your notes list at least two differences between the routes you saw (for example usage reported or not, response ID format) with a link to the lesson section that explains each.

Extensions: Keep the saved conversations in SQLite instead of JSON, with one row per message (03.2, 5.2). Trim old turns to a token budget before each call (5.5). Add /cost, which sums response.cost.usd for the session. Hosted, needs keys: use provider_agnostic/models.yaml instead of models.local.yaml, put your keys in .env, and chat on the fast and smart aliases (python chat.py --registry provider_agnostic/models.yaml --model fast). Check each price in your price table against the provider's pricing page first (03.7, 4.4).


Starter

Starter: Structured extractor#

Goal: Turn messy invoice text into validated Pydantic objects, retry with the exact validation errors when the model gets it wrong, and route anything that still fails to a person with the reason attached.

Prerequisites: lessons 03.4 and 03.8, the testing ideas in 03.10 Part 7, and the stand-in running.

What you'll practise:

  • Pydantic as the schema language, and the four layers of validation: parse, schema, semantic validators, business rules (lesson 03.4, Part 2, 6.1, 6.3)
  • Telling a refusal, a truncation, a safety block and an invalid reply apart before you parse (6.4, 6.5)
  • A bounded validate-and-retry loop with escalation and a typed result (7.2, 7.3)
  • Fixing the schema when retries cannot help (7.4)
  • Deciding which errors to retry and which never to (lesson 03.8, 4.1, 4.4)
  • Testing without a model, using a scripted fake (lesson 03.10, 7.2)

Setup: the stand-in running with the aliases from 03.1, 12.3 (the extractor asks for gpt-6-luna, then gpt-6.1-terra; both are names for the same local model). Copy into one folder: extractor.py (03.4, 7.3), outcomes.py (6.5), invoice_model.py (the Invoice model, built up through Parts 6 and 7), and llm_errors.py and retry_after.py (03.8, 4.4). Also uv add pytest.

Steps:

  1. Write the corpus. Make an invoices/ folder with six text files and an expected.json with the right answer for each. Five are invoices in different styles: a plain one (INV-2041: two lines, total £110.00, due date given), one with VAT and no due date (INV-2042: £100.00 plus £20.00 VAT, total £120.00), a euro invoice with a Zwischensumme and 19% VAT, a dollar invoice with a thousands separator ($1,090.00) and "Payment on receipt", and a rupee invoice with GST. The sixth is not an invoice (a shipping email), and its expected value is null: a good extractor must not invent an invoice from it.
  2. Run the extractor as written. Write run_extract.py, which reads each file and calls extract(openai_backend(client, effort=None), Invoice, text, system=..., models=["gpt-6-luna", "gpt-6.1-terra"], attempts_per_model=2) with an OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0) client. Use effort=None because the 0.5B model cannot think and rejects reasoning settings. Print one line per document: the status, the kind of each attempt, and REVIEW if result.needs_review or business_checks() raised a flag. Save every result to results.jsonl.
  3. Read the failures. Look at result.errors and result.attempts for the documents that fail. Sort each failure into the kinds from 03.4, 7.2: invalid output, refusal, truncation, call error. Note that the VAT invoice cannot pass the Invoice rule "lines add up to the total", however well the model reads it. That is a schema bug, not a model bug.
  4. Fix the schema. Add InvoiceWithTax(Invoice) with a tax field and a rule that lines plus tax equal the total (03.4, 7.4). Add a --schema plain|tax option and compare the two runs.
  5. Score it. Compare each extracted object with expected.json field by field (invoice_number, issue_date, due_date, currency, total, tax) and print the count of correct fields for the documents that extracted. Run it three times and report the spread: with sampling on, the local model gives a different result each run.
  6. Prove the repair loop without a model. The local model is too unreliable to demonstrate retries on demand, so write test_repair.py with a scripted backend: a function with the extractor's backend signature that returns canned JSON in order, built with outcomes.validate(schema, text, context) and remembering every conversation it was sent (03.10, 7.2). Assert two things. First, a bad answer followed by a good one yields status == "ok", the retry's conversation is user, assistant, user, and the last message quotes the exact validation error. Second, four bad answers across two models yield invalid_after_retries with needs_review true and no value, and the second model's first call is a fresh one-message conversation.
  7. Exercise the call-failure path. Run uv run python run_extract.py --models no-such-model on a single document. A 404 is a bad request, which classify() marks not retryable, so the status must be error after one attempt and not four (03.8, Part 4).
  8. Write up what you found: which layer caught each failure, which documents needed review and why, and what you would change about the schema, the instructions or the model.

Hints if you are stuck: build the scripted backend and test_repair.py before touching the local model, so you know the retry loop is right when the model misbehaves. Print result.attempts for every failing document before you decide whether the schema, the prompt or the model is at fault. If every document fails, run one document with attempts_per_model=1 and read the raw reply.

Verify it, and what you should see:

bash
uv run python test_repair.py
text
1. ok ['invalid', 'ok'] models: ['cheap', 'cheap']
   retry conversation roles: ['user', 'assistant', 'user']
   feedback sent: - (root): Value error, lines (100.00) plus tax (0.00) must equal total (120.00)
2. invalid_after_retries ['invalid', 'invalid', 'invalid', 'invalid'] models: ['cheap', 'cheap', 'strong', 'strong']
   first call to 'strong' had 1 message(s): a fresh conversation
   errors kept for the reviewer: ['(root): Value error, lines (100.00) plus tax (0.00) must equal total (120.00)']
all repair tests passed

This output is identical on every run. The local model's runs are not. One run on the stand-in with the plain Invoice schema:

text
inv1: ok                     attempts=invalid/ok  fields 5/5
inv2: invalid_after_retries  attempts=invalid/invalid/invalid/invalid  REVIEW
inv3: invalid_after_retries  attempts=invalid/invalid/invalid/invalid  REVIEW
inv4: ok                     attempts=ok  fields 5/5
inv5: invalid_after_retries  attempts=invalid/invalid/invalid/invalid  REVIEW
inv6: invalid_after_retries  attempts=invalid/invalid/invalid/invalid  REVIEW

and with --schema tax, four runs sent 6, 4, 5 and 5 of the six documents to review, and the documents that did extract had between 4 of 6 and all of their fields right (field accuracy 4/6, 12/12, 9/12, 10/12). Your numbers will differ. What is stable is the shape: the non-invoice (inv6) never produces a value, because the grounding check (03.4, 6.3) rejects a total that is not in the text; a model that invents the tax or the total fails the rule and is sent back with the exact message; and a document that fails four times ends as invalid_after_retries with its last errors kept. The failure path prints:

text
inv1: error                  attempts=error  REVIEW
['bad_request: Error code: 404 - model \'no-such-model\' not found']

A small model is a good place to learn this, because it fails often enough to show every branch. Do not read the field-accuracy numbers as a verdict on any hosted model.

Done when:

  • run_extract.py processes the folder, prints a status per document and writes results.jsonl with the status, attempt kinds, value, errors and review flag.
  • The VAT invoice is handled by the tax schema and not by retrying.
  • test_repair.py passes and shows the errors being fed back and the escalation with a fresh conversation.
  • The non-invoice document ends in review, never with an invented invoice.
  • Your write-up names, for each failed document, the validation layer that caught it.

Extensions: Add an explicit "not an invoice" path to the schema instead of relying on failure (03.4, 5.3, 9.5). Add a business rule that routes totals above a threshold to a second approver. Stream the object and show it filling in (Part 8). Hosted, needs keys: use anthropic_backend or gemini_backend from the same file (with the default effort="low"), keep the same corpus and compare how many documents each needs a retry for; read the schema limits of each provider first (Part 4). Treat extracted values as untrusted input (03.4, Part 6).


Stretch

Stretch: Provider benchmark#

Goal: Run a fixed set of tasks through several provider routes, repeatedly and with bounded concurrency, and report accuracy, time to first token, total latency, token use and cost for each route, in a table you could defend in a design review.

Prerequisites: lessons 03.3, 03.7, 03.8, 03.9 (bounded concurrency) and 03.11, and the stand-in running.

What you'll practise:

Setup: the provider_agnostic package and helper files, plus bounded.py (03.9, 4.4).

Steps:

  1. Fix the task set. Write tasks.jsonl with 8 to 12 tasks, each {"id", "prompt", "expect"} with a machine-checkable answer: four ticket classifications (billing, bug, account, other), two sums, two factual one-word answers. Keep the prompts and expected answers in version control; a benchmark whose tasks change is not a benchmark. Decide the scoring rule before you look at results (here, a case-insensitive exact match after stripping a trailing full stop).
  2. Call one route, streaming. Write one_call(client, route, task) that iterates client.astream(Request(model=route, messages=[...], max_output_tokens=20)), notes the time of the first TextDelta, and on Done returns a dictionary with the route, task, whether it was correct, time to first token, total time, and usage.total_input_tokens and usage.output_tokens (03.3, 12.1).
  3. Run each route with bounded concurrency. Build (key, lambda) pairs for every task × repetition (use at least 3 repetitions) and run them with run_bounded(jobs, concurrency=2). Run one route at a time, so routes do not compete for the same laptop. Keep failures: a failed call is a row with ok: false, not a missing row (03.9, 4.4).
  4. Log every call. Build the client with hooks=[JsonlCostHook("bench_calls.jsonl")] and Policy(max_attempts=2, attempt_timeout_s=60) so exactly one layer retries (03.8, 5.5). Record retries separately from first-try latency, or a retried call will make a route look slower than it is. Never log prompts or keys.
  5. Price it. The local routes are free, so also compute a shadow price: the cost of the same token counts at a hosted model's rates, with cost_calc.price(cost_calc.Usage(provider=..., model=..., input=..., output=...), PriceTable.load()). Label this "as if hosted" in the output, and print the price table's version beside it (03.7, 4.4).
  6. Report. Print one table: route, calls, failures, accuracy, median time to first token, median and 95th-percentile total latency, tokens in and out, and shadow cost per 1,000 calls. State the sample size next to every percentile, and say which differences are larger than the run-to-run spread you measured in step 3 and which are not.
  7. Make it repeatable. Cache nothing in the measured run, but add a development cache for building the report so you can iterate without calling the model again (03.10, 13.2). Write a test that feeds a hand-made bench_results.jsonl to the report code and checks the table.
  8. Write the memo. One page: what you measured, what you could not, the table, and what would change the conclusion.

Hints if you are stuck: run one task on one route and print the whole result row before you add concurrency. If a number looks wrong, open bench_calls.jsonl and read the raw record for that call. If routes disagree by a few percent, repeat the run before concluding anything: the spread between your own repeats is your noise floor.

Verify it, and what you should see:

bash
uv run python bench.py --repeat 3
wc -l bench_calls.jsonl            # one record per call: 3 routes x 8 tasks x 3 = 72

Illustrative output from an earlier run on the stand-in, trimmed from four routes to three and not re-measured, so your numbers will differ (all three routes reach the same local model, so differences are API-path overheads, not quality):

text
route              n fail   acc  ttft p50 total p50  total p95  tokens in/out  shadow $/1k calls
local-responses   24    0   62%     133ms      142ms      266ms    1215/61                 0.0063
local-chat        24    0   62%     140ms      153ms      172ms    1215/61                 0.0063
local-anthropic   24    0   67%     133ms      142ms      159ms    1215/61                 0.0063

What this teaches. The accuracy gap (62% against 67%) is one answer out of 24 and sits inside the model's own sampling noise, so it says nothing about the routes. A route that reports no usage on streams would show 0/0 tokens and a $0 shadow cost, and a benchmark that trusted it would report that route as free (03.7, 5.4). A hosted run needs real usage on every route, or must exclude the row. The 0.0063 figures come from the price table at its dated rates and describe tokens, not quality. Each call's record in bench_calls.jsonl carries the outcome, route, API, request ID, token buckets, cost_usd (0.0 for the free local routes and null when unknown, never a silent zero), attempts and latency.

Done when:

  • One command runs the whole task set, at least three times per route, and writes a results file and a per-call log.
  • Failures and retries are visible in the output, not dropped.
  • The table states its sample sizes, marks shadow costs as such, and names the price table version.
  • Your memo says which differences are real and which are noise, and lists at least two things the stand-in cannot tell you about hosted models (for example rate limits, caching, regional latency).

Extensions: Point the benchmark at hosted aliases (fast, smart) in provider_agnostic/models.yaml, so cost comes from real usage and the price table (03.7, Part 3). Respect each provider's rate limits with a limiter and a per-provider concurrency budget (03.8, 9.5, 03.9, 4.7). Add a cached-prefix task and report the cache hit rate and net saving (03.7, Part 10). Add a cost guard that stops the run at a dollar budget (03.7, 12.2). For quality that a string match cannot score, you need an evaluation method that Module 10A teaches.


Stretch (optional)

Stretch (optional): Streaming gateway#

Goal: A small FastAPI service that exposes one streaming endpoint over any provider, built on the 03.11 client. A request names an alias; the gateway streams your own event protocol back, falls back along an ordered chain when the first route fails before producing text, records cost and logs, and has tests that need no keys.

Prerequisites: lessons 03.3 (Part 11), 03.10 (Parts 7 and 8) and 03.11 (Parts 7 to 9), the FastAPI basics from lesson 01B.7, and the stand-in running.

What you'll practise:

  • Your own event protocol and FastAPI's native server-sent events (lesson 03.3, 11.2, 11.3, 11.4)
  • Disconnects and cancellation that stop the upstream stream (11.6, 8.5)
  • Production concerns: buffering, auth, limits and safe error messages (11.7)
  • Aliases mapped to ordered fallback chains, and what a fallback may and may not do (lesson 03.11, 7.1, 8.4)
  • Hooks for logging, cost and metrics (03.11, Part 9)
  • Testing a web service against fakes and the stand-in (lesson 03.10, Part 7, Part 8)

Setup: the provider_agnostic package and helper files, and uv add fastapi uvicorn httpx pytest.

Steps:

  1. Add a dead route and a chain. Copy models.local.yaml to models.gateway.yaml. Add a model local-dead with base_url: http://localhost:9/v1 (nothing listens there) and the alias resilient: [local-dead, local-responses].
  2. Design the protocol. Use the table in 03.3, 11.2: delta, done and error events, each with an increasing id. Never forward a provider's own events or exception text to the client.
  3. Write the endpoint. POST /v1/chat/stream takes {"model": alias, "message": str, "max_output_tokens": int} with length limits in a Pydantic body, builds a Request, and iterates client.astream(req), yielding ServerSentEvent(data={"text": ...}, event="delta", id=...) for each TextDelta and a done event carrying the finish reason, response.model_key and len(response.attempts) for Done. Catch LLMError and send an error event with only the class name and the retryable flag. In a finally, call await stream.aclose() so a disconnect closes the upstream stream.
  4. Add the hooks. Build the client with hooks=[LogHook(), JsonlCostHook("gateway_calls.jsonl")], where LogHook subclasses Hook and overrides attempt() to log the model, attempt number, outcome and latency. Hooks are synchronous and run on the event loop, so keep them fast (03.11, Part 9). Use Policy(max_attempts=1, ...) so the first failure moves to the next model.
  5. Know the fallback rule. The client falls back only before the first content event reaches you; after that, switching model would mix two answers (03.3, 7.5). Test both sides: a dead first route falls back; a stream that breaks after its first delta surfaces an error event and does not silently continue elsewhere.
  6. Test it. Use FastAPI's TestClient with the gateway app against the stand-in: one test that resilient is served by local-responses with two attempts, and one that an unknown alias gives an error event whose body does not echo the alias. Then add a keyless test with a mock transport under the real SDK (03.10, 7.3) for the mid-stream break.
  7. Harden it. Add a per-user concurrent-stream cap and a bearer-token check as in 03.3, 11.4, a total deadline, and proxy-safe headers (11.7).

Hints if you are stuck: test the endpoint with curl -N before writing any test, so you see events arrive one by one. If the whole answer arrives at once, something between you and the client is buffering (03.3, 11.7). If the fallback never triggers, check that Policy(max_attempts=1, ...) is set and that the dead route fails before any text is produced.

Verify it, and what you should see:

bash
uv run pytest -q test_gateway.py                                  # 2 passed
uvicorn gateway:app --port 8000 &
curl -sN -X POST localhost:8000/v1/chat/stream -H 'content-type: application/json' \
     -d '{"model":"resilient","message":"Say hi in three words."}'
text
event: delta
data: {"text": "Hi"}
id: 1

event: delta
data: {"text": " there"}
id: 2
...
event: done
data: {"status": "stop", "served_by": "local-responses", "attempts": 2}
id: 5

The server log shows the fallback (ConnectionFailed on local-dead, then success on local-responses):

text
INFO attempt call=36fc5a8fa6bb454d model=local-dead n=1 ok=False error=ConnectionFailed 42ms
INFO attempt call=36fc5a8fa6bb454d model=local-responses n=1 ok=True error=None 218ms

and gateway_calls.jsonl has one record with "alias": "resilient", "model_key": "local-responses", "attempts": 2, "cost_usd": 0.0. An unknown alias returns event: error with {"message": "ConfigError", "retryable": false}.

Done when:

  • One endpoint streams from any alias in the registry, using only your own event protocol.
  • A dead first route falls back to the second with no visible error, and the log and cost record show both attempts.
  • A client disconnect stops the upstream request (check the log or the provider's side).
  • Errors sent to clients are safe strings, and the tests pass with no key set.
  • You can explain, in two sentences, why a stream that fails after the first token is not retried on another model.

Extensions: A /v1/chat non-streaming route that uses acomplete(). Rate limits per user (03.8, 9.5). A budget gate as request middleware that refuses calls over a daily limit (03.7, 12.3). Metrics and OpenTelemetry spans (03.10, 4.7). Hosted, needs keys: use provider_agnostic/models.yaml with the chain fast and check that a revoked key on the first route falls through to the next (03.11, 8.3).


Stretch (optional)

Stretch (optional): Resumable batch classifier#

Goal: Classify a file of support tickets through a Batch API with a job that can be killed at any moment and resumed without paying twice: deterministic IDs, a SQLite checkpoint, chunking under the provider's queue limits, validation of every result, and a report of everything that failed.

Prerequisites: lessons 03.8 and 03.9 (Parts 6, 7 and 11), and a scratch folder holding the lesson's batch files. No stand-in is needed: this project uses the lesson's mock Batch API.

What you'll practise:

  • What a Batch API is, and its statuses, expiry and partial results (lesson 03.9, Part 6, 7.3)
  • Deterministic IDs and idempotent resubmission (11.1) and a local manifest (11.2)
  • Validating every result, with a schema where you can (11.3, 11.3b)
  • Splitting a job under request, size and queued-token limits, and estimating before you submit (11.4, 11.5)
  • Retrying failures without duplicating work (11.7)

Setup: the files named in 03.9's Setup in one folder, including batch_runner.py (11.6), tickets.py, openai_batch_io.py, batch_cost.py, mock_openai_batch.py and mock_llm.py. The stand-in cannot run batches (all batch endpoints answer 404 locally), so this project runs against the lesson's mock Batch API, which keeps its state in a file like a real provider (7.5). The real SDK and the real BatchJob code run; only the server is a mock.

Steps:

  1. Run the lesson's demo. Run it once with a simulated crash, then again, then a third time: CRASH_AT=after_create_triage-v1-b0001 uv run python s11_6_resumable.py (it exits with code 1), then uv run python s11_6_resumable.py twice. Read each line of output against the flowchart in 11.6.
  2. Bring your own data. Write tickets.csv with 60 to 100 rows (ticket_id,text), including one ticket ID with unsafe characters (such as ZD#10236/a) and one duplicate. Load it with job.load([Ticket(...), ...]). Confirm that loading twice adds nothing (11.1).
  3. Estimate before you submit. Print the request count, estimated tokens and cost for the job, and the number of chunks it will need under your queue cap (11.5, plan_chunks in chunking.py). Exit if the estimate exceeds a budget you set.
  4. Validate with a schema. Replace the one-word parse_label check with the structured result from 11.3b, so a malformed reply becomes a retryable failure and never a wrong label.
  5. Kill it for real. Start the job and stop it with kill -9 at three different moments (use the crash points named in the lesson's exercises, or a plain kill -9 while it polls). After every kill, the next run must pick up where it stopped, never resubmit a finished item, and recover a batch that was created but not recorded.
  6. Handle the bad cases. Make one ticket text that the mock rejects for the whole batch and one that fails on every attempt, as in the lesson's DEMO=bad run. Check that the rejected batch is not resubmitted, the poison ticket is marked failed after its attempts, and job.failures() lists both with a reason.
  7. Export. Write labels.csv (ticket_id,label) for the done items and failures.csv for the rest. Check that every input row appears in exactly one of them.

Hints if you are stuck: make step 1 work exactly as the lesson shows before changing any data. After every crash, read the SQLite manifest (SELECT status, count(*) FROM items GROUP BY status, and the same for batches) or call job.summary() to see what the job believes, instead of guessing. If a resumed run resubmits finished work, the item IDs are not deterministic: check what goes into them (03.9, 11.1).

Verify it, and what you should see: the lesson's own demo, run in a scratch folder:

text
before: {'pending': 23}
  submitted triage-v1-b0000 = batch_2 (5 items, ~130 tokens; queue now ~130)
  !! crashing at after_create_triage-v1-b0001
exit 1

and after the resumed run:

text
after:  {'done': 23} | cost $0.000063
provider saw 7 batches created; at most 2 open at once; our queue estimate peaked at ~260 tokens

The "at most 2 open at once" line is the queue cap working: 23 tickets in chunks of 5 never put more than two chunks in the provider's queue. The mock labels tickets at random with some failures, so the count of successes in each batch varies; the invariants do not: no item is lost, none is submitted twice after a successful collection, and the third run finds nothing to do.

Done when:

  • You can kill the process at three different points and the job finishes correctly every time.
  • A second run after completion makes no new batches and spends nothing.
  • Rejected batches and poison items end in the failure report, with reasons, and nothing is silently dropped.
  • The estimate runs before any submission and can stop the job.
  • The two export files together account for every input row exactly once.

Extensions: Add Anthropic's and Gemini's batch formats behind the same manifest (03.9, Parts 8 and 9). Use the Flex tier for the same job and compare cost and wall time with the calculator in Part 14. Receive completion by webhook instead of polling (13.7). Hosted, needs keys: point BatchJob at a real OpenAI client, run 20 tickets first, and check the cost against your estimate (03.9, 7.4).

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close