Module 03: Projects
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: 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:
- 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 thelocalfallback chain —local-responses,local-chatandlocal-anthropic— as in 03.11, Part 10's demo. Printr.text,r.finish_reason.valueandr.usage. All three should answer. - Stream one turn. Write
chat.pywith a functionstream_turn(client, model, system, history)that iteratesclient.stream(Request(...)), prints eachTextDeltawithflush=True, records the time of the first one, and returnsevent.responsewhen it seesDone. Wrap the loop intry/finally: stream.close()so that Ctrl-C closes the connection and the provider stops generating (03.3, 8.5). - Keep the history. Append
Message.user(line)before the call andresponse.messageafter it (not a newMessage.assistant(text):response.messagecarries 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. - Add commands. Handle
/models(listregistry.aliasesandregistry.models),/model NAME(callclient.preflight(NAME)first, so a typo fails now and not in the middle of the next turn),/system TEXT,/history,/newand/quit. The history is provider-neutral, so after/modelthe 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. - Save after every turn. Write
conversations/NAME.jsonwith{"version": 1, "model", "system", "messages": [m.model_dump(mode="json") ...]}, writing to a.tmpfile and thenos.replaceso a crash never leaves half a file. Add--resume, which loads the file withMessage.model_validate, and let an explicit--modeloverride the saved one. Store the whole message (all parts), not just the text, for the reasons in 03.2, 5.1. - Handle failure. Catch
LLMErroraround 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 itsretryableflag, and carry on. Do the same forKeyboardInterrupt: an interrupted turn is not kept. - Test the store. Write
test_store.pywith two pytest tests (03.10, 7.1): a conversation saved and reloaded equals the original messages, and loading a missing name raisesFileNotFoundError. Use pytest'stmp_pathandmonkeypatchso the tests never touch your realconversations/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:
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 demoOutput (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:
[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:
printf 'Repeat my name.\n/quit\n' | uv run python chat.py --registry provider_agnostic/models.local.yaml --name demo --resume --model local-chatIt 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: 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:
- Write the corpus. Make an
invoices/folder with six text files and anexpected.jsonwith 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 aZwischensummeand 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 isnull: a good extractor must not invent an invoice from it. - Run the extractor as written. Write
run_extract.py, which reads each file and callsextract(openai_backend(client, effort=None), Invoice, text, system=..., models=["gpt-6-luna", "gpt-6.1-terra"], attempts_per_model=2)with anOpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)client. Useeffort=Nonebecause the 0.5B model cannot think and rejects reasoning settings. Print one line per document: the status, the kind of each attempt, andREVIEWifresult.needs_revieworbusiness_checks()raised a flag. Save every result toresults.jsonl. - Read the failures. Look at
result.errorsandresult.attemptsfor 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 theInvoicerule "lines add up to the total", however well the model reads it. That is a schema bug, not a model bug. - Fix the schema. Add
InvoiceWithTax(Invoice)with ataxfield and a rule that lines plus tax equal the total (03.4, 7.4). Add a--schema plain|taxoption and compare the two runs. - Score it. Compare each extracted object with
expected.jsonfield 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. - Prove the repair loop without a model. The local model is too unreliable to demonstrate retries on demand, so write
test_repair.pywith a scripted backend: a function with the extractor's backend signature that returns canned JSON in order, built withoutcomes.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 yieldsstatus == "ok", the retry's conversation isuser, assistant, user, and the last message quotes the exact validation error. Second, four bad answers across two models yieldinvalid_after_retrieswithneeds_reviewtrue and no value, and the second model's first call is a fresh one-message conversation. - Exercise the call-failure path. Run
uv run python run_extract.py --models no-such-modelon a single document. A 404 is a bad request, whichclassify()marks not retryable, so the status must beerrorafter one attempt and not four (03.8, Part 4). - 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:
uv run python test_repair.py1. 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 passedThis output is identical on every run. The local model's runs are not. One run on the stand-in with the plain Invoice schema:
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 REVIEWand 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:
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.pyprocesses the folder, prints a status per document and writesresults.jsonlwith the status, attempt kinds, value, errors and review flag.- The VAT invoice is handled by the
taxschema and not by retrying. test_repair.pypasses 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: 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:
- Pricing tokens from a dated price table, and why a free local model needs a "shadow price" to be comparable (lesson 03.7, Part 3, Part 4)
- Recording every call with its request ID, tokens and cost, including the ones that fail (03.7, Part 5; 03.10, Part 4)
- Retries, timeouts and rate limits that do not distort the measurement (lesson 03.8, 5.5, Part 6, 9.5)
- Bounded concurrency with every outcome kept (lesson 03.9, 4.2, 4.4, 4.7)
- Measuring time to first token on streams (lesson 03.3, Part 12)
- Reproducible, cheap, repeatable runs (03.10, 5.5, 13.2)
Setup: the provider_agnostic package and helper files, plus bounded.py (03.9, 4.4).
Steps:
- Fix the task set. Write
tasks.jsonlwith 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). - Call one route, streaming. Write
one_call(client, route, task)that iteratesclient.astream(Request(model=route, messages=[...], max_output_tokens=20)), notes the time of the firstTextDelta, and onDonereturns a dictionary with the route, task, whether it was correct, time to first token, total time, andusage.total_input_tokensandusage.output_tokens(03.3, 12.1). - Run each route with bounded concurrency. Build
(key, lambda)pairs for every task × repetition (use at least 3 repetitions) and run them withrun_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 withok: false, not a missing row (03.9, 4.4). - Log every call. Build the client with
hooks=[JsonlCostHook("bench_calls.jsonl")]andPolicy(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. - 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). - 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.
- 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.jsonlto the report code and checks the table. - 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:
uv run python bench.py --repeat 3
wc -l bench_calls.jsonl # one record per call: 3 routes x 8 tasks x 3 = 72Illustrative 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):
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.0063What 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): 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:
- Add a dead route and a chain. Copy
models.local.yamltomodels.gateway.yaml. Add a modellocal-deadwithbase_url: http://localhost:9/v1(nothing listens there) and the aliasresilient: [local-dead, local-responses]. - Design the protocol. Use the table in 03.3, 11.2:
delta,doneanderrorevents, each with an increasingid. Never forward a provider's own events or exception text to the client. - Write the endpoint.
POST /v1/chat/streamtakes{"model": alias, "message": str, "max_output_tokens": int}with length limits in a Pydantic body, builds aRequest, and iteratesclient.astream(req), yieldingServerSentEvent(data={"text": ...}, event="delta", id=...)for eachTextDeltaand adoneevent carrying the finish reason,response.model_keyandlen(response.attempts)forDone. CatchLLMErrorand send anerrorevent with only the class name and theretryableflag. In afinally, callawait stream.aclose()so a disconnect closes the upstream stream. - Add the hooks. Build the client with
hooks=[LogHook(), JsonlCostHook("gateway_calls.jsonl")], whereLogHooksubclassesHookand overridesattempt()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). UsePolicy(max_attempts=1, ...)so the first failure moves to the next model. - 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
errorevent and does not silently continue elsewhere. - Test it. Use FastAPI's
TestClientwith the gateway app against the stand-in: one test thatresilientis served bylocal-responseswith two attempts, and one that an unknown alias gives anerrorevent 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. - 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:
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."}'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: 5The server log shows the fallback (ConnectionFailed on local-dead, then success on local-responses):
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 218msand 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): 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:
- 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), thenuv run python s11_6_resumable.pytwice. Read each line of output against the flowchart in 11.6. - Bring your own data. Write
tickets.csvwith 60 to 100 rows (ticket_id,text), including one ticket ID with unsafe characters (such asZD#10236/a) and one duplicate. Load it withjob.load([Ticket(...), ...]). Confirm that loading twice adds nothing (11.1). - 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_chunksinchunking.py). Exit if the estimate exceeds a budget you set. - Validate with a schema. Replace the one-word
parse_labelcheck with the structured result from 11.3b, so a malformed reply becomes a retryable failure and never a wrong label. - Kill it for real. Start the job and stop it with
kill -9at three different moments (use the crash points named in the lesson's exercises, or a plainkill -9while 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. - 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=badrun. Check that the rejected batch is not resubmitted, the poison ticket is marked failed after its attempts, andjob.failures()lists both with a reason. - Export. Write
labels.csv(ticket_id,label) for the done items andfailures.csvfor 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:
before: {'pending': 23}
submitted triage-v1-b0000 = batch_2 (5 items, ~130 tokens; queue now ~130)
!! crashing at after_create_triage-v1-b0001
exit 1and after the resumed run:
after: {'done': 23} | cost $0.000063
provider saw 7 batches created; at most 2 open at once; our queue estimate peaked at ~260 tokensThe "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).