Module 01B: Projects
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: 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
uvproject workflow:pyproject.toml(PEP 621), dependency groups, the committed lockfile and thesrc/layout (lesson 01B.1, §7.3, §7.4) - Typed settings with
SecretStrand cachedget_settings()(01B.2 §4.13) ScriptedBackendwithcomplete()/stream()and thecallslog (01B.3, Part 7)Result/Ok/Err,bounded_gather,RateLimiter,run_pipeline(01B.4 §10.1)- The typed
TicketClient/AsyncTicketClientandMockTransporttesting (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.pyand 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:
- Create the skeleton. Run
uv init aitoolkit --package --python 3.13 && cd aitoolkit, then theuv add/uv add --devlines 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.gitignorefrom 01B.1 §7.4. Maketests/,scripts/,data/. Then make the two hand edits topyproject.tomlthat 01B.1 §7.4 lists (the[project.scripts]entry and the ruff/pytest tables), becauseuv adddoes not write them. src/aitoolkit/settings.py. Copy the listing from 01B.2 §4.13 verbatim —Settings(BaseSettings)withenv_file=".env",extra="forbid", the providerSecretStrfields, the timeout/retry/connection knobs and@lru_cache get_settings().src/aitoolkit/backend.py. CopyScriptedBackend,CompletionandUsagefrom 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).src/aitoolkit/concurrency.py. Copy the deliverable from 01B.4 §10.1:Ok/Err/Result,bounded_gather,RateLimiter(with injectablesleep/now),run_pipeline.src/aitoolkit/models.py. Copy from 01B.6 §7.4:Priority,Status,Ticket,TicketIn,CompletionRequest,Usage,Completion.src/aitoolkit/http.py. CopyTicketAPIError,TicketClientandAsyncTicketClientfrom 01B.5 §9. KeepBASE_URL = "https://tickets.example.com/v1"— it is fictional; tests useMockTransport, never the network.src/aitoolkit/service.py. Copy the deliverable from 01B.7, Part 8: lifespan-builtScriptedBackend,DEMO_API_KEYS,require_api_keywithsecrets.compare_digest, the error envelope, request-ID middleware, and/health,/v1/echo,/v1/complete,/v1/stream(EventSourceResponse).src/aitoolkit/resilience.py. Copy from 01B.9, Part 8:is_transient,RETRYABLE_STATUSES,retry_async,CircuitBreaker,Deadline. Also save theparse_retry_afterhelper from 01B.9 §4.3 assrc/aitoolkit/retry_after.py, becauseresilience.pyimports it when an error response carries aRetry-Afterheader.tests/. Copyconftest.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 themodels.pyandservice.pyinterfaces in steps 5 and 7 (Completionhastext/model/usage/finish_reason;Ticket's only required field issubject, accepted astitletoo; 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.envsecrets.logging_setup.py,cli.py,__main__.py. Copy from 01B.10:configure_loggingwithdictConfigand theJsonFormatter, the request-ID filter, theaitoolkitconsole-script entry point, and wireservice.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: thelog_json: bool = Falsefield onSettings(settings.py, step 2; without itLOG_JSONin.envfails underextra="forbid") and theget_backend()factory at the bottom ofbackend.py(step 3;cli.pycalls it).- 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:
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"}'{"status":"ok","service":"aitoolkit","env":"dev"}{"message":"hello","length":5}{"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 --lockedsucceeds from a clean clone of your folder anduv run pytestpasses with the socket guard proving nothing touched the network.- The service answers
/health,/v1/echo,/v1/completeand/v1/streamas shown, enforcesX-API-Key, and emits request IDs in the JSON logs. uv run aitoolkit --help(orpython -m aitoolkit --help) shows the CLI from 01B.10.git statusshows.envignored,uv.locktracked,.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;cdinto the project root anduv sync(01B.1).uv addwrites todependenciesbut you wanted dev tools — useuv add --dev(01B.1 §4.3).- Tests fail with socket errors — the
conftest.pysocket guard is working as intended; a test is hitting the network. Find and fake it (01B.8 §5.5). /v1/*returns 404 — theinclude_routerordering trap the consolidation notes warn about; mount the router after the decorated routes (01B.10 Part 5).ValidationErroron startup — a stray.envline matches noSettingsfield because ofextra="forbid"; remove it or set the variable it names (01B.2 §4.2).- SSE looks buffered — use
curl -N; proxies may needX-Accel-Buffering: no(01B.7 Part 6).
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:
run_pipelinewithlimit,queue_sizeandon_progress, returning orderedOk/Errresults (01B.4 §10.1, §2.4)RateLimitertoken bucket pacing call starts (01B.4 §4.2)retry_asyncover transient failures withis_transientclassification (01B.9, Part 8, Part 5)ScriptedBackend'sfail_firstfailure injection andcallslog (01B.3, Part 7)asyncio.timeoutper call andasyncio.runas the sync entry point (01B.3 §3.5, §3.1)- An
argparseCLI and atomic output writes (01B.10, Part 3, 01A.9 §2.5)
Setup: inside your aitoolkit project (Starter A or the lesson skeleton): uv add httpx pydantic tenacity and uv add --dev pytest pytest-asyncio.
Steps:
- Create
data/tickets.jsonl. Write a generatorscripts/make_tickets.pythat emits 200 JSON Lines rows{"id": "T-0001", "subject": ..., "body": ...}withrandom.seed(7)— mix billing/bug/question subjects. (Or paste 30 rows by hand.) src/fanout/backend_wrap.py. Aclassify(prompt) -> strcoroutine callingawait backend.complete(f"Classify: {prompt}", model="fake-tiny")insideasyncio.timeout(10); wrap it withretry_asyncfromaitoolkit.resilienceso a failed call is retried twice (three attempts in all) with jittered backoff. The default policy would not retry here, becauseis_transientonly acceptshttpxerrors,TimeoutErrorandConnectionError, andScriptedBackend's injected failure is aRuntimeError. 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 fromtenacity. (The shortwaitkeeps the runs quick; the 01B.9 Part 8 overrides are plain keyword arguments to tenacity'sretry.)src/fanout/cli.py.argparsewith--input,--output results.jsonl,--failures failures.csv,--concurrency 8,--rate 20,--limit N. Build theScriptedBackendwithreplies={"billing": "billing", "charged": "billing", "crash": "bug", "error": "bug"}andfail_firstfrom--inject-failures N(default 0; the first N backend calls raise, retries included).- Run the pipeline.
asyncio.run(main())callsrun_pipeline(items, classify, limit=args.concurrency, on_progress=...)with aRateLimiter(rate=args.rate)acquired insideclassify. Write eachOktoresults.jsonl(one JSON object per line, flushed as produced via the progress callback or a post-pass over ordered results) and eachErrtofailures.csvwithid,error. - 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. - Tests (
tests/test_fanout.py): afail_first=2backend still yields 200Oks (two failed calls can never use up three attempts, whichever item they hit); withlimit=1andfail_first=3, exactly the first item is anErrwith 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. - Compare the knobs. Run
--concurrency 1vs--concurrency 16and--rate 5vs--rate 100; paste the three timings and explain which bound bit (01B.4 §6).
Verify it, and what you should see:
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 250processed 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.csvwith 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/--limitwas 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.gatherunbounded or dropped task references; userun_pipeline/bounded_gather(01B.3 §8.2, 01B.4 §2.1). RuntimeWarning: coroutine was never awaited— a missingawaitinsideclassify; the warning text is in 01B.3 §4.2.- Retries multiply latency —
retry_asyncwraps the call and you also re-queue theErritems in an outer loop (run_pipelineitself never retries); pick one retry layer (01B.9, 03.8 §5.5). time.sleepused "to simulate latency" — it freezes the whole event loop;ScriptedBackendalready sleeps asynchronously (01B.3 §2.5).- The run hangs at the end —
queue.join()waits on atask_done()that never ran, or workers never got their sentinel (01B.4 §3.2).
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_decodescanning that survives braces in strings and prose (01B.6 §7.2)model_validateversusmodel_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)Fieldconstraints,Literalcategories and@model_validatorcross-field rules (01B.6 Parts 2 and 4)- Table-driven pytest with
parametrize,tmp_pathand 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':
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]Steps:
- Fixtures. Create
fixtures/with eightreply_*.txtfiles covering: clean JSON;json fencedwith 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. extractor.py. Copyiter_json_valuesandextract_jsonfrom 01B.6 §7.2 verbatim (stdlib only). Addfirst_valid(text, model)that iterates values and returns the first that passesmodel.model_validate.models.py. DefineExtraction(BaseModel)withmodel_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_validatorrule thaturgentpriority requiresconfidence >= 0.8.repair.py.repair_prompt(errors: list[dict]) -> strrenders eachValidationError.errors()entry as- <loc>: <msg>inside an instruction ("Return ONLY corrected JSON matching this schema…"). Stripinputvalues from the message — they can carry PII.extract.pyCLI.argparsetaking files or a directory; per fixture printOK/NO_JSON/INVALIDplus the first error'sloc/msg, and write--repairprompts for invalid ones torepairs/.tests/test_extract.py. Parametrise over the eight fixtures with expected statuses; assertfirst_validpicks the second object in the two-object fixture; assert the repair prompt contains the failing field'sloc; assert truncated and single-quoted inputs giveNO_JSON, never a guessed parse.- Run and inspect.
uv run pytest -qthenuv 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:
uv run pytest -q
uv run python extract.py fixtures/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_JSONrepairs/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_validnever returns a value that fails validation. repair_promptoutput names field locations and never echoes rawinputpayloads.- 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.loadsbefore validation — it chokes on prose and fences; useraw_decodescanning (01B.6 §7.2).- Catching bare
Exceptionaroundmodel_validate— you swallowValidationErrorand real bugs; catchValidationErroronly. "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()includesinput; strip it (01B.6 §3.5).
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
AsyncTicketClientpattern: one client per process, bearer auth, domain errors, cursor pagination (01B.5 §9, §7) httpx.Timeoutphases andhttpx.Limitspool sizing (01B.5 §3.3, §3.4)- The exception hierarchy and what is retryable (01B.5 §4, 01B.9 Part 1)
retry_asyncwithis_transient,CircuitBreaker,Deadline(01B.9, Part 8, Part 6)RateLimiterinside the concurrency bound (01B.4 §10.1)httpx.MockTransportandrespxtests 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:
- Scaffold
src/ticketapi/withclient.py,errors.py,models.py(re-export or adaptTicket/TicketInfrom the lesson),settings.py(timeout/connect/pool/rate fields viapydantic-settings),__init__.py. - Port the client. Start from
AsyncTicketClientin 01B.5 §9: onehttpx.AsyncClientbuilt in__init__/__aenter__withbase_url, bearer header,httpx.Timeout(...)andhttpx.Limits(...)from settings. - Layer resilience in the right order (01B.9, 01B.4 §10.1): a per-request deadline (
asyncio.timeoutorDeadline) outermost →CircuitBreaker(one per route) →retry_async(transient httpx errors + retryable statuses) →RateLimiter.acquire()before every attempt, retries included → the per-attempthttpx.Timeoutinnermost. 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. - Decode to models.
get_ticket/aiter_ticketsreturnTicketviaTicket.model_validate(response.json())— not raw dicts. - Tests (
tests/test_client.py):MockTransporthandler returning429then200(assert retry recovers andRetry-Afteris 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; aReadTimeoutmaps to a retryable error. - README.md: install (
uv sync), quickstart againstMockTransport, 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. - Optional sync facade:
TicketClientSyncwrappingasyncio.runper call for scripts (01B.3 §6.1).
Verify it, and what you should see:
uv run pytest -q
uv run python -c "import asyncio; from ticketapi import TicketClient; ..." # against MockTransportExample 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:
pytestpasses fully offline (the socket guard orMockTransportproves it).- A flaky-then-healthy transport recovers transparently; a permanently failing one trips the circuit and fails fast.
- Pagination yields
Ticketmodels 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
tenacitydecorator retries; one layer owns retries (01B.9, 03.8 §5.5). except httpx.HTTPErrorswallowingHTTPStatusErrorandInvalidURLalike — classify first (01B.5 §4.2).AsyncClientcreated per call — pool and TLS handshake per request; one per process (01B.5 §3.1).PoolTimeoutmisdiagnosed as a server problem — it is your own concurrency exceedingmax_connections; align the semaphore (01B.5 §7.2).- Circuit breaker tested with real sleeps — inject a clock/fake sleep like
RateLimiterdoes (01B.9 Part 8).
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/ServerSentEventandStreamingResponsewith an async generator (01B.7 Part 6)- Lifespan-built shared backend,
Dependsfor 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:
src/gateway/app.py(with an emptysrc/gateway/__init__.py; in a--packageproject the editable install putssrc/on the import path, sogateway.appand your tests can import it).FastAPI(lifespan=...)that builds oneScriptedBackend(configurablereplies/latency) intoapp.state.backend;get_settings/get_backenddependencies; reuseaitoolkit.settings,aitoolkit.backend,aitoolkit.models.POST /v1/complete— non-streaming:CompletionRequestbody →backend.complete()→CompletionJSON, wrapped inasyncio.timeout(settings.request_timeout_seconds).POST /v1/stream— SSE: an async generator readsbackend.stream(prompt)chunks and yieldsServerSentEvent(data={"text": chunk}, event="delta", id=...), then a finaldoneevent with model and usage estimate. Infinally,await gen.aclose()so a disconnect stops the backend's generator.- Auth + middleware.
X-API-Keydependency against aGATEWAY_KEYSmap withcompare_digest; a middleware that mints a request ID (contextvars), binds it to the log record, echoes it asX-Request-ID, and times the request;configure_logging(json_logs=True)fromaitoolkit.logging_setup. - 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. tests/test_gateway.py.TestClienttest for/v1/complete(200 + shape) and 401 without a key; anhttpx.ASGITransportasync test that reads/v1/streamto completion and asserts ordereddeltaevents thendone; a disconnect test that cancels the response mid-stream and asserts the backend generator was closed (e.g. via a flag orbackend.callscount).- Run it.
uv run uvicorn gateway.app:app --port 8000thencurl -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:
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"}'event: delta
data: {"text": "Why "}
id: 1
event: delta
data: {"text": "did "}
id: 2
...
event: done
data: {"model": "fake-tiny", "finish_reason": "stop"}
id: 9Server 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/streamdelivers frames incrementally undercurl -Nand ends withdone. - 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
errorevent 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; setX-Accel-Buffering: noand check middleware order (01B.7 Part 6). RuntimeError: async generator ignored GeneratorExit/ hangs on disconnect — you mustawait gen.aclose()infinally, not justbreak(01B.3 §5.2).time.sleepor 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).
TestClienthangs reading the stream — use the asyncASGITransportclient or read with a timeout (01B.7 §7.2).
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 andargsort/argpartitiontop-k (01B.11 Parts 2–3) - Dot products, norms and cosine similarity — the retrieval maths (01B.11 Part 4)
- pandas
DataFrameIO, 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:
gen_data.py. Seeded (random.seed(11)) generator writing:eval_results.csv(~120 rows:run_id,prompt_id,model,score,passed,latency_ms, two modelsfake-small/fake-large, somescorecells empty and two rows with a bad model name);usage_log.jsonl(~200 rows:ts,model,input_tokens,output_tokens,request_id);embeddings.npzvianumpy.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).analysis/eval_table.py. Loadeval_results.csv; clean (to_numeric(errors="coerce")onscore, normalise the bad model name or drop it);groupby("model")["score"].agg(["mean","count"]); apivot_tableof mean score byprompt_id × model; the list ofpassed == Falserows.analysis/cost.py. Loadusage_log.jsonlwithpandas.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")orto_period), and cost per resolved ticket by merging with evalpassedonrun_id/prompt_id.analysis/search.py. Load the.npz; L2-normalise rows (v / np.linalg.norm(v, axis=1, keepdims=True));scores = matrix @ queryfor each query;np.argpartition(-scores, 2)[:3]gives the top-3 indices in no particular order, soargsortjust those three scores before printing labels + scores. Verify one query's top-1 by hand with the stdlibmathversion from 01B.11 Part 7.analysis/clean_tickets.py. Cleantickets_dirty.csv: strip whitespace, lowercase categories,fillna/drop policy you justify, dedupe by ID keeping last; writetickets_clean.csv.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:
uv run python gen_data.py
uv run python analysis/eval_table.py && uv run python analysis/cost.py && uv run python analysis/search.pymodel 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.pyis deterministic — re-running reproduces identical files.- All three analyses run and print the tables above; the NumPy top-3 matches your hand computation.
REPORT.mdstates 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,
strdtype,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; usedf = df.assign(...)or.loc(01B.11 Part 5).- Float equality on scores — use
np.isclose/pytest.approx, never==(01B.11 Part 2). NaNsurprises ingroupby.mean— decideskipna/min_countdeliberately 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.loadon.npzreturns arrays lazily — call.files/index keys correctly and keepallow_pickle=Falsedefault.