Module 01B: Projects

Foundations6 projects0 of 6 complete

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

Six projects: three starters and three stretches (the streaming gateway is optional). Every one runs keylessly — no API key, no account, no paid service, and nothing to install beyond the packages the lessons name. The "model" in every project is ScriptedBackend, the deterministic fake from lesson 01B.3, Part 7, and the "APIs" are the fake ticket API and httpx.MockTransport/respx doubles from 01B.5. Nothing here calls a real provider; where a project shows the shape of a provider call it links to Module 03 instead.

First time? Build the project once, exactly as 01B.1 §7.4 shows: uv init aitoolkit --package --python 3.13, then uv add the runtime packages (httpx pydantic pydantic-settings python-dotenv "fastapi[standard]" uvicorn tenacity) and uv add --dev the test tools (pytest pytest-asyncio respx ruff). The lessons were checked against the package versions listed in the module overview, so if a newer release changes a name or default, read that package's changelog. Run everything with uv run ... — it syncs the locked environment for you. Starter A walks you through assembling the package the lessons have been building; the other projects reuse its modules.


Starter

Starter: aitoolkit from scratch#

Goal: Assemble the aitoolkit package the eleven lessons describe into one installable project — settings, the fake backend, models, the HTTP client, concurrency helpers, the FastAPI service, resilience, logging and a pytest suite — and run it end to end.

What you'll practise:

  • The uv project workflow: pyproject.toml (PEP 621), dependency groups, the committed lockfile and the src/ layout (lesson 01B.1, §7.3, §7.4)
  • Typed settings with SecretStr and cached get_settings() (01B.2 §4.13)
  • ScriptedBackend with complete()/stream() and the calls log (01B.3, Part 7)
  • Result/Ok/Err, bounded_gather, RateLimiter, run_pipeline (01B.4 §10.1)
  • The typed TicketClient/AsyncTicketClient and MockTransport testing (01B.5 §9, §8.1)
  • The shared Ticket/TicketIn/Completion* models (01B.6 §7.4)
  • The FastAPI service with /health, /v1/echo, /v1/complete, /v1/stream (01B.7, Part 8)
  • The pytest suite: fixtures, the socket guard, fakes over mocks (01B.8, Part 9)
  • retry_async, CircuitBreaker, Deadline (01B.9, Part 8)
  • logging_setup.py, cli.py and the consolidated tree (01B.10, Part 5)

Setup: the uv commands in the page intro above, plus uv add numpy pandas only if you also want lesson 01B.11's examples runnable in the project (not needed for this project).

Steps:

  1. Create the skeleton. Run uv init aitoolkit --package --python 3.13 && cd aitoolkit, then the uv add/uv add --dev lines from 01B.1 §7.4. Create .env.example (names only — copy the block from 01B.2 §4.13), .env (empty or placeholder values, never committed), and the .gitignore from 01B.1 §7.4. Make tests/, scripts/, data/. Then make the two hand edits to pyproject.toml that 01B.1 §7.4 lists (the [project.scripts] entry and the ruff/pytest tables), because uv add does not write them.
  2. src/aitoolkit/settings.py. Copy the listing from 01B.2 §4.13 verbatim — Settings(BaseSettings) with env_file=".env", extra="forbid", the provider SecretStr fields, the timeout/retry/connection knobs and @lru_cache get_settings().
  3. src/aitoolkit/backend.py. Copy ScriptedBackend, Completion and Usage from 01B.3, Part 7. This is the module's canonical fake — do not "improve" it; later lessons depend on its exact contract (await backend.complete(prompt), backend.stream(prompt), backend.calls).
  4. src/aitoolkit/concurrency.py. Copy the deliverable from 01B.4 §10.1: Ok/Err/Result, bounded_gather, RateLimiter (with injectable sleep/now), run_pipeline.
  5. src/aitoolkit/models.py. Copy from 01B.6 §7.4: Priority, Status, Ticket, TicketIn, CompletionRequest, Usage, Completion.
  6. src/aitoolkit/http.py. Copy TicketAPIError, TicketClient and AsyncTicketClient from 01B.5 §9. Keep BASE_URL = "https://tickets.example.com/v1" — it is fictional; tests use MockTransport, never the network.
  7. src/aitoolkit/service.py. Copy the deliverable from 01B.7, Part 8: lifespan-built ScriptedBackend, DEMO_API_KEYS, require_api_key with secrets.compare_digest, the error envelope, request-ID middleware, and /health, /v1/echo, /v1/complete, /v1/stream (EventSourceResponse).
  8. src/aitoolkit/resilience.py. Copy from 01B.9, Part 8: is_transient, RETRYABLE_STATUSES, retry_async, CircuitBreaker, Deadline. Also save the parse_retry_after helper from 01B.9 §4.3 as src/aitoolkit/retry_after.py, because resilience.py imports it when an error response carries a Retry-After header.
  9. tests/. Copy conftest.py (the socket-guard and settings-cache fixtures) and the test files from 01B.8, Part 9: test_settings.py, test_models.py, test_concurrency.py, test_resilience.py, test_http.py, test_service.py — adjusted to your file names. The suite is written against exactly the models.py and service.py interfaces in steps 5 and 7 (Completion has text/model/usage/finish_reason; Ticket's only required field is subject, accepted as title too; see 01B.10 §5.3), so it should pass as copied; if a test fails after you edit a module, that is the suite doing its job. The suite must pass with no network and no .env secrets.
  10. logging_setup.py, cli.py, __main__.py. Copy from 01B.10: configure_logging with dictConfig and the JsonFormatter, the request-ID filter, the aitoolkit console-script entry point, and wire service.py's lifespan/middleware to them as the consolidated listing shows. That listing also marks two small additions to earlier files that these modules need: the log_json: bool = False field on Settings (settings.py, step 2; without it LOG_JSON in .env fails under extra="forbid") and the get_backend() factory at the bottom of backend.py (step 3; cli.py calls it).
  11. Run it end to end (below), then write a short README.md: layout, uv sync, uv run pytest, uv run uvicorn aitoolkit.service:app, the curl commands, and where the fake backend gets swapped for a real SDK (03.1).

Verify it, and what you should see:

bash
uv sync --locked
uv run pytest
uv run uvicorn aitoolkit.service:app --port 8000 &
curl -s localhost:8000/health
curl -s -X POST localhost:8000/v1/echo -H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' -d '{"message": "hello"}'
curl -sN -X POST localhost:8000/v1/complete -H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' -d '{"prompt": "weather in Paris?"}'
curl -sN -X POST localhost:8000/v1/stream -H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' -d '{"prompt": "tell me a joke"}'
Example output · illustrative1 line
{"status":"ok","service":"aitoolkit","env":"dev"}
json
{"message":"hello","length":5}
json
{"text":"(no scripted reply for this prompt)","model":"fake-tiny","usage":{"input_tokens":3,"output_tokens":6},"finish_reason":"stop"}

The service builds ScriptedBackend() with no canned replies, so /v1/complete answers with its default reply (shown above) and /v1/stream streams that same text word by word. To see a canned answer instead, change the lifespan to ScriptedBackend(replies={"weather": "It is sunny and 21C."}) and ask about the weather. The /v1/stream endpoint emits event: token / data: {"token": ...} frames as ScriptedBackend.stream() yields chunks, ending with event: done / data: [DONE] — watch them arrive with curl -N. A request without X-API-Key gets 401; a bad body gets the 422 error envelope. uv run pytest reports all tests passing — the count depends on which test files you copied (the lesson's listing shows the shape).

Done when:

  • uv sync --locked succeeds from a clean clone of your folder and uv run pytest passes with the socket guard proving nothing touched the network.
  • The service answers /health, /v1/echo, /v1/complete and /v1/stream as shown, enforces X-API-Key, and emits request IDs in the JSON logs.
  • uv run aitoolkit --help (or python -m aitoolkit --help) shows the CLI from 01B.10.
  • git status shows .env ignored, uv.lock tracked, .venv/ ignored.
  • Your README explains the layout and the run commands in your own words.

Stretch ideas: Add a /v1/tickets route that proxies AsyncTicketClient through MockTransport in tests (01B.5 §8). Wire resilience.retry_async into the /v1/complete path and prove a fail_first=1 backend still answers (01B.9). Add a make test/make lint Makefile (01B.1 §8.6). Later, with keys: follow 01B.10's "swap the fake backend" instructions to point service.py at a real provider SDK via 03.1 — that is the llm_service shape of 11C.1.

Common problems:

  • ModuleNotFoundError: aitoolkit — you ran from the wrong directory or the project isn't installed; cd into the project root and uv sync (01B.1).
  • uv add writes to dependencies but you wanted dev tools — use uv add --dev (01B.1 §4.3).
  • Tests fail with socket errors — the conftest.py socket guard is working as intended; a test is hitting the network. Find and fake it (01B.8 §5.5).
  • /v1/* returns 404 — the include_router ordering trap the consolidation notes warn about; mount the router after the decorated routes (01B.10 Part 5).
  • ValidationError on startup — a stray .env line matches no Settings field because of extra="forbid"; remove it or set the variable it names (01B.2 §4.2).
  • SSE looks buffered — use curl -N; proxies may need X-Accel-Buffering: no (01B.7 Part 6).
Starter

Starter: Async fan-out CLI#

Goal: A command-line tool that classifies a file of support tickets through ScriptedBackend — hundreds of slow fake calls run with bounded concurrency, a rate limiter and retries, results streamed to JSONL as they finish, failures collected into a report — the shape of every ingestion and eval job you will write later.

What you'll practise:

Setup: inside your aitoolkit project (Starter A or the lesson skeleton): uv add httpx pydantic tenacity and uv add --dev pytest pytest-asyncio.

Steps:

  1. Create data/tickets.jsonl. Write a generator scripts/make_tickets.py that emits 200 JSON Lines rows {"id": "T-0001", "subject": ..., "body": ...} with random.seed(7) — mix billing/bug/question subjects. (Or paste 30 rows by hand.)
  2. src/fanout/backend_wrap.py. A classify(prompt) -> str coroutine calling await backend.complete(f"Classify: {prompt}", model="fake-tiny") inside asyncio.timeout(10); wrap it with retry_async from aitoolkit.resilience so a failed call is retried twice (three attempts in all) with jittered backoff. The default policy would not retry here, because is_transient only accepts httpx errors, TimeoutError and ConnectionError, and ScriptedBackend's injected failure is a RuntimeError. Override the predicate for this project: retry_async(retry=retry_if_exception_type(RuntimeError), stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.05, max=0.5)), with the three names imported from tenacity. (The short wait keeps the runs quick; the 01B.9 Part 8 overrides are plain keyword arguments to tenacity's retry.)
  3. src/fanout/cli.py. argparse with --input, --output results.jsonl, --failures failures.csv, --concurrency 8, --rate 20, --limit N. Build the ScriptedBackend with replies={"billing": "billing", "charged": "billing", "crash": "bug", "error": "bug"} and fail_first from --inject-failures N (default 0; the first N backend calls raise, retries included).
  4. Run the pipeline. asyncio.run(main()) calls run_pipeline(items, classify, limit=args.concurrency, on_progress=...) with a RateLimiter(rate=args.rate) acquired inside classify. Write each Ok to results.jsonl (one JSON object per line, flushed as produced via the progress callback or a post-pass over ordered results) and each Err to failures.csv with id,error.
  5. Print the summary. Total, ok, failed, elapsed seconds, and effective throughput — then compute what sequential would have cost (items × latency) and print the speed-up. Label timings machine-dependent.
  6. Tests (tests/test_fanout.py): a fail_first=2 backend still yields 200 Oks (two failed calls can never use up three attempts, whichever item they hit); with limit=1 and fail_first=3, exactly the first item is an Err with the error recorded, because its three attempts are the three failing calls; results align with input order; the socket guard proves nothing left the process.
  7. Compare the knobs. Run --concurrency 1 vs --concurrency 16 and --rate 5 vs --rate 100; paste the three timings and explain which bound bit (01B.4 §6).

Verify it, and what you should see:

bash
uv run python -m fanout.cli --input data/tickets.jsonl --concurrency 8 --rate 20
wc -l results.jsonl failures.csv
uv run python -m fanout.cli --input data/tickets.jsonl --concurrency 8 --rate 20 --inject-failures 250
Example output · illustrative2 lines
processed 200 items: 200 ok, 0 failed in 9.2s (22 items/s; sequential would be ~10s)
wrote results.jsonl (200 rows) and failures.csv (0 rows)

With --rate 20 the limiter, not the concurrency, is the binding constraint: 200 calls at 20 per second take about 9 s (the bucket starts full, so the first 20 are free), and a sequential run at the fake backend's 0.05 s latency would take about the same, so the speed-up here is about 1x. Raise --rate (try 200) and the concurrency bound takes over; step 7 asks you to find that out. results.jsonl holds {"id": "T-0001", "label": "billing", "ok": true}-style rows; failures.csv has only its id,error header.

The second run injects 250 failing calls, more than the retries can absorb: every item that starts while failing calls remain burns all three attempts, so roughly 80 of the 200 items end up in failures.csv (the exact number depends on timing) while results.jsonl shrinks to the rest. Partial failure is data, not a crash.

Done when:

  • One command processes the whole file with bounded concurrency and a rate limit, writes both output files, and prints a summary.
  • Injected transient failures are retried; permanent-looking failures land in failures.csv with reasons.
  • Result rows stay aligned with input order regardless of completion order.
  • The tests pass, including the retry-recovery and partial-failure cases.
  • Your notes state which of --concurrency/--rate/--limit was the binding constraint in each run, with the arithmetic.

Stretch ideas: Add a WindowBatcher stage that accumulates 10 items or 0.5 s and submits them as one "batch prompt" (01B.4 §5). Add single-flight dedup so ten identical subjects share one call (01B.4 §7.1). Put a CircuitBreaker in front of the backend and show the open state after repeated failures (01B.9 Part 6). Real HTTP: point classify at a httpx.AsyncClient hitting the lesson's local http.server fake (01B.5 §8.3) instead of ScriptedBackend.

Common problems:

  • Everything runs but finishes suspiciously fast with wrong counts — you used asyncio.gather unbounded or dropped task references; use run_pipeline/bounded_gather (01B.3 §8.2, 01B.4 §2.1).
  • RuntimeWarning: coroutine was never awaited — a missing await inside classify; the warning text is in 01B.3 §4.2.
  • Retries multiply latency — retry_async wraps the call and you also re-queue the Err items in an outer loop (run_pipeline itself never retries); pick one retry layer (01B.9, 03.8 §5.5).
  • time.sleep used "to simulate latency" — it freezes the whole event loop; ScriptedBackend already sleeps asynchronously (01B.3 §2.5).
  • The run hangs at the end — queue.join() waits on a task_done() that never ran, or workers never got their sentinel (01B.4 §3.2).

Starter

Starter: Validate and repair#

Goal: A small library plus CLI that takes messy "model reply" fixtures — fenced JSON, prose around JSON, truncated JSON, wrong types, single quotes — extracts the first validatable JSON value, validates it against a Pydantic model, reports exactly which fields failed, and emits a repair prompt a model could answer. With pytest tests.

What you'll practise:

  • iter_json_values/extract_json — raw_decode scanning that survives braces in strings and prose (01B.6 §7.2)
  • model_validate versus model_validate_json, TypeAdapter, and the required/optional/nullable trap (01B.6 §3, §2.2)
  • ValidationError.errors() anatomy turned into a readable repair message (01B.6 §3.5)
  • Field constraints, Literal categories and @model_validator cross-field rules (01B.6 Parts 2 and 4)
  • Table-driven pytest with parametrize, tmp_path and per-fixture expected statuses (01B.8 Parts 2–4)

Setup: in a fresh uv init validate-repair --bare --python 3.13 folder (or inside aitoolkit): uv add pydantic and uv add --dev pytest. In a --bare project the modules sit at the project root (extractor.py, models.py, repair.py, extract.py) and the tests in tests/, and pytest does not put the root on sys.path by itself, so add this to pyproject.toml or the tests will fail with ModuleNotFoundError: No module named 'extractor':

toml
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]

Steps:

  1. Fixtures. Create fixtures/ with eight reply_*.txt files covering: clean JSON; json fenced with preamble; JSON followed by prose; a } inside a string value; two JSON objects where only the second validates; a JSON array (should be rejected by the model); single-quoted pseudo-JSON; truncated JSON.
  2. extractor.py. Copy iter_json_values and extract_json from 01B.6 §7.2 verbatim (stdlib only). Add first_valid(text, model) that iterates values and returns the first that passes model.model_validate.
  3. models.py. Define Extraction(BaseModel) with model_config = ConfigDict(extra="forbid"): subject: str (3–200 chars), category: Literal["billing","bug","question","other"], priority: Literal["low","normal","high","urgent"] = "normal", confidence: float = Field(ge=0, le=1), and a @model_validator rule that urgent priority requires confidence >= 0.8.
  4. repair.py. repair_prompt(errors: list[dict]) -> str renders each ValidationError.errors() entry as - <loc>: <msg> inside an instruction ("Return ONLY corrected JSON matching this schema…"). Strip input values from the message — they can carry PII.
  5. extract.py CLI. argparse taking files or a directory; per fixture print OK/NO_JSON/INVALID plus the first error's loc/msg, and write --repair prompts for invalid ones to repairs/.
  6. tests/test_extract.py. Parametrise over the eight fixtures with expected statuses; assert first_valid picks the second object in the two-object fixture; assert the repair prompt contains the failing field's loc; assert truncated and single-quoted inputs give NO_JSON, never a guessed parse.
  7. Run and inspect. uv run pytest -q then uv run python extract.py fixtures/ — read each failure and classify it: no JSON found, schema-invalid, or business-rule-invalid.

Verify it, and what you should see:

bash
uv run pytest -q
uv run python extract.py fixtures/
Example output · illustrative8 lines
reply_clean.txt        OK
reply_fenced.txt       OK
reply_prose_after.txt  OK
reply_brace_string.txt OK
reply_two_objects.txt  OK  (second object used)
reply_array.txt        INVALID  (root): Input should be a valid dictionary or instance of Extraction
reply_single_quotes.txt NO_JSON
reply_truncated.txt    NO_JSON

repairs/reply_array.txt.prompt contains a message naming (root) and the dictionary requirement. (A model-level error has an empty loc tuple, so your repair renderer should print a label such as (root) instead of an empty field name.) The tests print 8 passed-style counts depending on parametrisation.

Done when:

  • All eight fixtures classify correctly and first_valid never returns a value that fails validation.
  • repair_prompt output names field locations and never echoes raw input payloads.
  • The pytest suite passes offline with no network guard needed (it is pure parsing).
  • Your notes classify each failure as extraction, schema or business-rule, and say which layer caught it.

Stretch ideas: Wrap first_valid + repair_prompt in a loop driven by ScriptedBackend scripted replies to demonstrate one bounded repair round-trip (01B.6 §7.2, 03.4 Part 7). Add a --strict mode using model_validate_json with strict types (01B.6 §3.4). Emit the model's model_json_schema() alongside repairs so the "model" knows the contract (01B.6 §5.3).

Common problems:

  • json.loads before validation — it chokes on prose and fences; use raw_decode scanning (01B.6 §7.2).
  • Catching bare Exception around model_validate — you swallow ValidationError and real bugs; catch ValidationError only.
  • "confidence": "high" parses under lax mode — that's coercion doing its job or hurting you; check the coercion table before blaming the fixture (01B.6 §3.4).
  • The two-object fixture returns the first object — by design it returns the first that validates; if both validate, first wins (01B.6 §7.2).
  • Repair prompts leak fixture content — errors() includes input; strip it (01B.6 §3.5).
Stretch

Stretch: Resilient API client library#

Goal: A small installable ticketapi package: a typed async client for the fake ticket API with explicit timeouts, retry-with-backoff on transient failures, a circuit breaker, a rate limiter, cursor pagination into Pydantic models, a MockTransport test suite and a README — the shape of every provider client you will wrap later.

What you'll practise:

  • The configured AsyncTicketClient pattern: one client per process, bearer auth, domain errors, cursor pagination (01B.5 §9, §7)
  • httpx.Timeout phases and httpx.Limits pool sizing (01B.5 §3.3, §3.4)
  • The exception hierarchy and what is retryable (01B.5 §4, 01B.9 Part 1)
  • retry_async with is_transient, CircuitBreaker, Deadline (01B.9, Part 8, Part 6)
  • RateLimiter inside the concurrency bound (01B.4 §10.1)
  • httpx.MockTransport and respx tests that never touch the network (01B.5 §8, 01B.8 §7)
  • Pydantic decode at the boundary (Ticket.model_validate) (01B.6 §3.2)

Setup: uv init ticketapi --package --python 3.13 && cd ticketapi, then uv add httpx pydantic tenacity pydantic-settings and uv add --dev pytest pytest-asyncio respx.

Steps:

  1. Scaffold src/ticketapi/ with client.py, errors.py, models.py (re-export or adapt Ticket/TicketIn from the lesson), settings.py (timeout/connect/pool/rate fields via pydantic-settings), __init__.py.
  2. Port the client. Start from AsyncTicketClient in 01B.5 §9: one httpx.AsyncClient built in __init__/__aenter__ with base_url, bearer header, httpx.Timeout(...) and httpx.Limits(...) from settings.
  3. Layer resilience in the right order (01B.9, 01B.4 §10.1): a per-request deadline (asyncio.timeout or Deadline) outermost → CircuitBreaker (one per route) → retry_async (transient httpx errors + retryable statuses) → RateLimiter.acquire() before every attempt, retries included → the per-attempt httpx.Timeout innermost. Document the order in a comment — it is 01B.9 §6.7's composition table made code, and the breaker sits outside the retries so that one logical request counts as one outcome.
  4. Decode to models. get_ticket/aiter_tickets return Ticket via Ticket.model_validate(response.json()) — not raw dicts.
  5. Tests (tests/test_client.py): MockTransport handler returning 429 then 200 (assert retry recovers and Retry-After is honoured if you parse it); 500×N exhausting attempts → TicketAPIError; a handler that always fails → circuit opens and subsequent calls fail fast; two-page pagination yields all items in order; a ReadTimeout maps to a retryable error.
  6. README.md: install (uv sync), quickstart against MockTransport, the config table, the failure semantics (what raises, what retries, when the circuit opens), and a "production notes" section linking 03.8 and 11C.3.
  7. Optional sync facade: TicketClientSync wrapping asyncio.run per call for scripts (01B.3 §6.1).

Verify it, and what you should see:

bash
uv run pytest -q
uv run python -c "import asyncio; from ticketapi import TicketClient; ..."   # against MockTransport

Example output (illustrative): 12 passed-style pytest summary; the demo prints three Ticket(...) reprs and one TicketAPIError: 503 upstream_unavailable: ... after the circuit opens. Timing values in logs are machine-dependent.

Done when:

  • pytest passes fully offline (the socket guard or MockTransport proves it).
  • A flaky-then-healthy transport recovers transparently; a permanently failing one trips the circuit and fails fast.
  • Pagination yields Ticket models in order across pages.
  • The README lets a stranger configure timeouts, retries and the rate limit without reading the source.
  • You can name, in one sentence each, which layer owns timeout, retry, rate-limit and circuit-breaking — and why the order matters.

Stretch ideas: Swap MockTransport for respx route mocks and compare (01B.8 §7). Add single-flight caching on get_ticket (01B.4 §7.1). Add an Idempotency-Key header option for POSTs (01B.9 §3). Consider an httpx2-based variant if your project already depends on the provider SDKs (01B.5 §1.5, 03.1 §4.5).

Common problems:

  • Retrying inside retries — the client retries and the caller's tenacity decorator retries; one layer owns retries (01B.9, 03.8 §5.5).
  • except httpx.HTTPError swallowing HTTPStatusError and InvalidURL alike — classify first (01B.5 §4.2).
  • AsyncClient created per call — pool and TLS handshake per request; one per process (01B.5 §3.1).
  • PoolTimeout misdiagnosed as a server problem — it is your own concurrency exceeding max_connections; align the semaphore (01B.5 §7.2).
  • Circuit breaker tested with real sleeps — inject a clock/fake sleep like RateLimiter does (01B.9 Part 8).

Stretch (optional)

Stretch (optional): Streaming gateway#

Goal: A FastAPI service that exposes POST /v1/complete and POST /v1/stream over ScriptedBackend, streaming Server-Sent Events back to clients with request IDs, API-key auth, JSON logs and clean disconnect handling — plus an async test that reads the stream. The shape of the provider gateways in Modules 07 and 11, minus the provider.

What you'll practise:

  • EventSourceResponse/ServerSentEvent and StreamingResponse with an async generator (01B.7 Part 6)
  • Lifespan-built shared backend, Depends for settings/auth, app.state (01B.7 Part 8, §4)
  • Async generators, aclose() on early exit, disconnect handling (01B.3 Part 5)
  • Request-ID middleware and structured JSON logging with redaction (01B.10 Part 1)
  • APIKeyHeader + secrets.compare_digest, error envelope, safe error messages (01B.7 Parts 3 and 5)
  • Testing SSE with FastAPI TestClient/httpx.ASGITransport (01B.7 §7.2, 01B.8 §7)

Setup: inside aitoolkit (or a fresh uv init gateway --package --python 3.13): uv add "fastapi[standard]" httpx pydantic pydantic-settings and uv add --dev pytest pytest-asyncio.

Steps:

  1. src/gateway/app.py (with an empty src/gateway/__init__.py; in a --package project the editable install puts src/ on the import path, so gateway.app and your tests can import it). FastAPI(lifespan=...) that builds one ScriptedBackend (configurable replies/latency) into app.state.backend; get_settings/get_backend dependencies; reuse aitoolkit.settings, aitoolkit.backend, aitoolkit.models.
  2. POST /v1/complete — non-streaming: CompletionRequest body → backend.complete() → Completion JSON, wrapped in asyncio.timeout(settings.request_timeout_seconds).
  3. POST /v1/stream — SSE: an async generator reads backend.stream(prompt) chunks and yields ServerSentEvent(data={"text": chunk}, event="delta", id=...), then a final done event with model and usage estimate. In finally, await gen.aclose() so a disconnect stops the backend's generator.
  4. Auth + middleware. X-API-Key dependency against a GATEWAY_KEYS map with compare_digest; a middleware that mints a request ID (contextvars), binds it to the log record, echoes it as X-Request-ID, and times the request; configure_logging(json_logs=True) from aitoolkit.logging_setup.
  5. Error envelope. Map TimeoutError→504, auth→401, validation→422, everything else→500 with only the exception class name in the body — never internals or prompts.
  6. tests/test_gateway.py. TestClient test for /v1/complete (200 + shape) and 401 without a key; an httpx.ASGITransport async test that reads /v1/stream to completion and asserts ordered delta events then done; a disconnect test that cancels the response mid-stream and asserts the backend generator was closed (e.g. via a flag or backend.calls count).
  7. Run it. uv run uvicorn gateway.app:app --port 8000 then curl -sN -X POST localhost:8000/v1/stream ... -d '{"prompt": "hi"}' and watch frames arrive; try without the key.

Verify it, and what you should see:

bash
uv run pytest -q
curl -sN -X POST localhost:8000/v1/stream -H 'content-type: application/json' -H 'X-API-Key: k1' -d '{"prompt": "tell me a joke"}'
Example output · illustrative11 lines
event: delta
data: {"text": "Why "}
id: 1

event: delta
data: {"text": "did "}
id: 2
...
event: done
data: {"model": "fake-tiny", "finish_reason": "stop"}
id: 9

Server logs show one JSON line per request with request_id, method, path, status, duration_ms — and no prompt text.

Done when:

  • Both endpoints work; /v1/stream delivers frames incrementally under curl -N and ends with done.
  • A client disconnect closes the upstream generator (verified by test or log).
  • Every response carries X-Request-ID; logs are single-line JSON with no secrets or prompt bodies.
  • The async stream test passes with no real server and no key beyond the demo map.
  • You can explain why a mid-stream failure surfaces as an error event rather than a retried request (03.3 §7.5).

Stretch ideas: Add a second "provider" backend and an ordered fallback chain for /v1/complete (03.11 §8.4). Add a per-key concurrency cap with asyncio.Semaphore (01B.4 §2.1). Add /healthz readiness that pings the backend (11C.3 §8.1). Hosted, needs keys: swap ScriptedBackend for a real provider client following 03.3 Part 11.

Common problems:

  • SSE arrives all at once — missing curl -N, or a proxy buffering; set X-Accel-Buffering: no and check middleware order (01B.7 Part 6).
  • RuntimeError: async generator ignored GeneratorExit / hangs on disconnect — you must await gen.aclose() in finally, not just break (01B.3 §5.2).
  • time.sleep or a sync call inside the stream generator stalls all clients — keep the loop async (01B.3 §8.1).
  • Error bodies leak prompts or stack traces — return class names only; log details server-side (01B.7 §3.2).
  • TestClient hangs reading the stream — use the async ASGITransport client or read with a timeout (01B.7 §7.2).

Stretch

Stretch: Data analysis with NumPy and pandas#

Goal: Generate a small eval-results dataset and a usage/cost log, then answer the questions AI engineers actually ask — "which model scored best per prompt?", "what did each model cost per resolved ticket?", "which embeddings are nearest to this query?" — with NumPy and pandas, and write a one-page report. No plots required.

What you'll practise:

  • NumPy arrays, dtype, broadcasting, reductions and argsort/argpartition top-k (01B.11 Parts 2–3)
  • Dot products, norms and cosine similarity — the retrieval maths (01B.11 Part 4)
  • pandas DataFrame IO, boolean filters, groupby/agg, pivot_table, merge, missing data and dtypes (01B.11 Part 5)
  • The four worked examples' shapes: cosine search, eval table, usage/cost log, messy CSV cleaning (01B.11 Part 6)
  • The stdlib equivalents so you can verify the libraries' answers by hand (01B.11 Part 7)
  • When pandas is the wrong tool (01B.11 Part 8)

Setup: uv init data-lab --bare --python 3.13 && cd data-lab, then uv add numpy pandas (Parquet needs pyarrow — optional, awareness only).

Steps:

  1. gen_data.py. Seeded (random.seed(11)) generator writing: eval_results.csv (~120 rows: run_id,prompt_id,model,score,passed,latency_ms, two models fake-small/fake-large, some score cells empty and two rows with a bad model name); usage_log.jsonl (~200 rows: ts,model,input_tokens,output_tokens,request_id); embeddings.npz via numpy.savez — 8 hand-designed 4-d vectors labelled by topic plus 2 query vectors; tickets_dirty.csv (~40 rows with mixed-case categories, blanks, a stray comma field, duplicate IDs).
  2. analysis/eval_table.py. Load eval_results.csv; clean (to_numeric(errors="coerce") on score, normalise the bad model name or drop it); groupby("model")["score"].agg(["mean","count"]); a pivot_table of mean score by prompt_id × model; the list of passed == False rows.
  3. analysis/cost.py. Load usage_log.jsonl with pandas.read_json(lines=True); join a small price dict ({"fake-small": (0.15, 0.60), "fake-large": (0.80, 3.20)} $/1M tokens); compute cost per row, daily totals (dt.floor("D") or to_period), and cost per resolved ticket by merging with eval passed on run_id/prompt_id.
  4. analysis/search.py. Load the .npz; L2-normalise rows (v / np.linalg.norm(v, axis=1, keepdims=True)); scores = matrix @ query for each query; np.argpartition(-scores, 2)[:3] gives the top-3 indices in no particular order, so argsort just those three scores before printing labels + scores. Verify one query's top-1 by hand with the stdlib math version from 01B.11 Part 7.
  5. analysis/clean_tickets.py. Clean tickets_dirty.csv: strip whitespace, lowercase categories, fillna/drop policy you justify, dedupe by ID keeping last; write tickets_clean.csv.
  6. REPORT.md. One page: the three tables above, the top-3 retrieval results, three findings (e.g. "fake-large scores +X but costs Y× per resolved ticket"), and one paragraph on what pandas made easy versus what the stdlib version cost you.

Verify it, and what you should see:

bash
uv run python gen_data.py
uv run python analysis/eval_table.py && uv run python analysis/cost.py && uv run python analysis/search.py
Example output · illustrative6 lines
model        mean_score  count
fake-large       0.84    58
fake-small       0.71    57

cost per resolved ticket: fake-small $0.00041, fake-large $0.00287
query 'billing outage' top-3: T3-billing(0.91) T7-outage(0.88) T1-billing(0.72)

Done when:

  • gen_data.py is deterministic — re-running reproduces identical files.
  • All three analyses run and print the tables above; the NumPy top-3 matches your hand computation.
  • REPORT.md states findings with numbers, not vibes, and names one thing pandas hid from you (dtype coercion, index alignment, NaN semantics).
  • You can point at the pandas-3.x gotcha you avoided or hit (Copy-on-Write, str dtype, inplace) — 01B.11 Part 5.

Stretch ideas: Write results to Parquet (pyarrow) and read back (01B.11 Part 5). Load usage_log into SQLite via pandas.read_sql and compare SQL GROUP BY to groupby (01B.11 Part 5, 00.7). Add a try/except-free validation pass with Pydantic on the CSV rows before analysis (01B.6). Compute embeddings' cosine matrix for all 8 docs and eyeball the cluster structure.

Common problems:

  • SettingWithCopyWarning/silent no-op assignment — pandas 3 Copy-on-Write changed the rules; use df = df.assign(...) or .loc (01B.11 Part 5).
  • Float equality on scores — use np.isclose/pytest.approx, never == (01B.11 Part 2).
  • NaN surprises in groupby.mean — decide skipna/min_count deliberately and report the count column.
  • Iterating rows in Python "for clarity" — vectorise or use itertuples; row loops are the classic perf trap (01B.11 Part 8).
  • np.load on .npz returns arrays lazily — call .files/index keys correctly and keep allow_pickle=False default.

← Module 01B index | Module 01A: Python Essentials →

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