Module 11C: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
Three projects: one starter and two stretches (the self-hosted gateway is optional). The optional operations pack is in Module 11A's projects. Every project here runs keylessly. The module's code is pure Python: traces go to JSONL files, metrics to an in-memory backend, caches to dicts, routers and breakers run against fakes, and the FastAPI service is tested with an injected fake client. No provider keys, no GPU, no cloud account, no services started. Hosted providers and real deployments are the stretch goal for each project once you have keys or an account: the lessons' samples are labelled illustrative and the code paths are identical, only the wiring changes.
The building blocks. Each project assembles files the lessons ship, all under one llm-service project (uv init llm-service --bare --python 3.13, as in lesson 11A.1's Setup):
- From 11A.1:
llm_service/tracekit.py(the dependency-free JSONL trace core with the fail-openSafeExporter),trace_view.py(the trace debugging CLI),demo.py(sample-trace generator),telemetry.py(the OTel facade) - From 11A.2:
llm_service/metrics.py(Metricsfacade,MemoryBackend,PrometheusBackend),metrics_prometheus.py,metrics_hook.py(ServiceMetricsHook),otel_metrics.py, plus theslo_calc.pyand cost-anomaly scripts - From 11B.3:
llm_service/cache.py(ExactCache,SemanticCache,request_key, single-flight) andcache_economics.py - From 11B.1:
llm_service/economics.py(cost/latency model),budget.py(TenantQuota,hedged_call),waste_report.pyandmake_fixture.py, plus the small demo drivers (economics_demo.py,hedge_demo.py,quota_demo.py,buildvsbuy_demo.py) - From 11B.5:
llm_service/router.py(rules, splits, cascade, classifier routers, decision log,AllowListRouter) androuter_eval.py(the offline evaluator) - From 11C.3:
llm_service/resilience.py(the complete file: circuit breaker, bulkheads, deadlines,FallbackChain, shared rate limiter),stream_fallback.py(fallback for streaming calls) and the chaos suite - From 11C.1: the
llm_service/app package (settings.py,deps.py,schemas.py,serialize.py,errors.py,main.py,jobs.py,logging.py),tests/test_app.py,Dockerfile,compose.yaml,nginx/llm_service.conf - From 11C.2:
scripts/eval_gate.py,scripts/check_model_deprecations.py,scripts/diff_prompts.py,make_fixtures.py(writes thefixtures/tree), the workflow YAML and the gate configs (gates/<tier>.yamlin the workflows; the stdlibeval_gate.pyreads the same keys as JSON, for examplefixtures/gates/pr.json) - From 11C.6 (optional gateway project only): the stdlib calculators
breakeven.py,gpu_sizing.pyandbench_openai_compatible.py
The starter project works on the docs_qa package from Module 07 (or your own Module 08A agent) because it already has the right seam: an injectable LLM/LLMFn that a fake fills. If you do not have docs_qa, the starter's steps say exactly which file to create instead.
Starter: Production-ise a project#
Goal: Take a working LLM feature — the docs_qa RAG package from Module 07, or a Module 08A agent loop — and add the observability, caching, resilience, metrics and cost-reporting layers a production deployment needs, all running keylessly on fakes.
What you'll practise:
- The JSONL trace record schema and the dependency-free trace kit with a fail-open exporter (lesson 11A.1, 2.6, 4.2, 9.2)
- Debugging a real trace with the viewer CLI, and turning a failing trace into an eval case (11A.1, 9.1, 6.3)
- Exact-match response caching with correct key anatomy, TTLs, per-tenant scope and single-flight (lesson 11B.3, 3.2, 3.5, 3.6, 7.6, 8.4)
- Cache economics: the hit-rate × saving − overhead formula applied to your own numbers (11B.3, 6.1, 6.2)
- Circuit breakers, fallback chains with policies and the degradation ladder, tested against a flaky fake provider (lesson 11C.3, 3.4, 6.2, 6.3, 6.6, 12)
- Backend-agnostic metrics wired through the client hooks, with
MemoryBackendfor tests and a/metricsexposition (lesson 11A.2, 3.2, 3.3, 3.4) - A cost/latency model and a waste report over your own traces (lesson 11B.1, 1.5, 3.2, Part 9)
- A simple rule-based router if your feature has more than one task type (lesson 11B.5, 3.2, 3.5, 3.6)
Setup: the docs_qa package from Module 07's starter project (or your Module 08A agent project), inside a fresh llm-service project. Dependencies are deliberately tiny — tracing and caching are stdlib-only; metrics need prometheus-client only if you want the Prometheus backend:
uv init llm-service --bare --python 3.13 && cd llm-service
uv add pydantic python-dotenv pytest
# optional, for the Prometheus backend in step 6:
# uv add prometheus-clientLayout. Put the module files in llm-service/llm_service/ (the folder 11A.1 uses). Scripts that import a sibling by bare name (demo.py, trace_view.py, waste_report.py, make_fixture.py, demo_router.py, economics_demo.py) are run from inside that folder (cd llm_service). Scripts that import llm_service.resilience (s3_breaker_demo.py, s6_chain_demo.py, s7_limiter_demo.py) and your own test_production.py live in the project root and are run from there.
Copy tracekit.py, trace_view.py, demo.py from 11A.1; cache.py, cache_economics.py from 11B.3; economics.py, budget.py, waste_report.py, make_fixture.py from 11B.1; router.py, router_eval.py, demo_router.py from 11B.5; and resilience.py plus s3_breaker_demo.py, s6_chain_demo.py, s7_limiter_demo.py from 11C.3 — each lesson prints its files in full, and 11C.4's appendix lists where they live. metrics.py and metrics_hook.py from 11A.2 need the provider_agnostic hook interface; if you are not using that client, skip step 6's hook wiring and call Metrics.record_call(...) and Metrics.observe(...) directly — the facade is backend-agnostic by design.
Steps:
- Baseline first. Run your project's smoke path (
uv run python ask.pyfordocs_qa, or your agent's demo) and note the call seam:generate_answer(..., llm, ...)fordocs_qa,run_agent(adapter, ...)for an agent. Everything you add wraps that call — one injection point, not scattered edits. - Trace it. Copy
tracekit.pyand writetraced_llm.py: a wrapper around yourLLMFn/LLMthat emits one span per model call in the 11A.1, 2.6 JSONL schema — model, prompt version, token columns (uncached/cached/write, output, reasoning where reported),cost_usd, latency,finish_reason,outcome— inside a root span for the request, withfeature,tenant_hashandsession_idjoin keys repeated on every span. Ship records throughSafeExportertotraces.jsonlso a broken sink can never break a request (11A.1, 4.2). Content stays out: hash or length-prefix prompts, never store raw text by default (11A.1, Part 7). - See it. Run
demo.pyto produce the lesson's sample traces, thenpython trace_view.py traces.jsonl --summaryand--by featureon your traces (11A.1, 9.2). Deliberately break one answer (point the fake at a refusal or a truncated finish) and find it with--errors— that is the debugging loop the whole module assumes. - Cache it. Copy
cache.pyand wrap the model call inExactCachewith arequest_keycarrying scope, model, prompt/template version, generation params, tool/state hash and the normalised request — every input that could change the answer (11B.3, 3.2). GiveExactCachea TTL (ttl_seconds) and pass a per-tenantscope=torequest_key(3.5, 3.6). Prove single-flight: fire N concurrent identical requests at a slow fake and assert the provider callable ran once (7.6). - Resilience it. Copy
resilience.pyand build aFallbackChainin front of your model call: primary route, a breaker per route, a policy that falls back on timeout/5xx-class errors and never on refusals, bad requests or quota errors (11C.3, 6.2). Point the primary at aFlakyProvider-style fake that fails 60% of the time and watch the breaker open, skip the dead route and degrade honestly (3.4, 6.6). Stamp every degraded answer with provenance so logs and users can tell (6.5). If your feature streams, also rundemo_stream.pyand decide, in your write-up, what your UI does when a stream breaks after the first chunk: surface the partial text or restart with a visible reset (6.7). - Measure it. Wire
Metrics(MemoryBackend())and emit the catalogue's core series — requests by outcome, latency histogram, tokens, cost, cache hits — either throughServiceMetricsHookif you have theprovider_agnosticclient, or by calling the facade from your wrappers (11A.2, 3.2, 3.3). Keep label values bounded — feature, model, outcome — never user IDs (1.5). If your project is thedocs_qaFastAPI service from Module 07's stretch project, add the/metricsroute exactly as 11A.2, 3.4 shows. - Cost it. Generate
traces_fixture.jsonlwithmake_fixture.py, runwaste_report.pyon your traces, and read the ranked waste signals — retries, truncations, missed cache reads, cost drift (11B.1, 3.2). Then model your feature ineconomics.py: aRequestProfile(calls, tokens, retries, other costs) and the latency budget, and compute the monthly bill (11B.1, 1.5). Applycache_economics.py'snet_savingto your measured hit rate and state your break-even (11B.3, 6.2). - Route it (if you have two task types). If your feature mixes easy and hard requests — a classifier plus an answer, say — add a
RuleRouterfromrouter.pythat sends easy slices to the cheap fake route and hard ones to the strong route, with aWeightedSplitRoutercanary arm and decision logging to JSONL (11B.5, 3.2, 3.5, 3.6). Rundemo_router.pyfirst to see every router type with fakes. - Prove it without a model. Write
test_production.py: (a) an identical second request hits the cache and the fake model is called once; (b) aFlakyProviderat 100% failure produces a degraded-path answer with provenance, not an exception; (c) a scope change (tenant-a→tenant-b) misses the cache; (d)waste_report.pyparses your realtraces.jsonland reports nonzero requests. All four run on fakes — no key, no network.
Verify it, and what you should see:
cd llm_service
uv run python demo.py # writes traces_sample.jsonl (11A.1's fixture) next to demo.py
uv run python trace_view.py traces_sample.jsonl --summary # then the same on your own traces.jsonl from step 2
uv run python make_fixture.py && uv run python waste_report.py traces_fixture.jsonl
cd ..
uv run python s3_breaker_demo.py # the flaky-provider breaker demo (11C.3)
uv run pytest -q test_production.py # 4 passedWhat to look for: trace_view.py --summary prints per-route request counts, error counts and cost totals parsed from your JSONL; waste_report.py prints ranked signals with the fixture's known waste visible (retries, truncations, missed cache reads); the breaker demo shows the closed→open→half-open transitions with jittered probes; and your test run proves the cache, breaker, scope isolation and report all work on fakes. Numbers and timings will differ from any hosted run — the fakes are deterministic where it matters and the trace schema is the contract.
Done when:
- Every model call in your project emits a JSONL span in the 11A.1 §2.6 schema, viewable with
trace_view.py, and a deliberately broken answer is findable via--errors. - An identical repeated request is served from
ExactCachewith no second model call, and a different tenant or prompt version misses. - A 100%-failing primary degrades through the fallback chain with provenance stamped, and the breaker demonstrably opens and recovers.
metrics.pyreports requests/outcomes/latency/tokens/cost/cache-hits, and/metrics(if you have the service) serves the exposition.waste_report.pyruns on your real traces and your write-up names the top waste signal and the playbook lever that addresses it.test_production.pypasses with no keys set.
Stretch ideas: Swap ExactCache for SemanticCache and tune its threshold on a labelled set of 20 query pairs (11B.3, 4.3). Add TenantQuota from budget.py as a per-tenant daily token cap (11B.1, 7.2). Turn one failing trace into an evalkit case (11A.1, 6.3). Hosted, needs keys: point the same wrappers at provider_agnostic/models.yaml aliases and compare fake-vs-real traces; the wrappers don't change.
Common problems:
ImportError/ModuleNotFoundErrorforcost_calc,prices,llm_errors— those areprovider_agnostic's borrowed top-level modules; copy the six files beside the package as 11C.1's Setup describes, or use the packaged wheel.- Traces with no
cost_usd— your fake returns no usage; either teach the fake to report token counts or recordcost_source: "unknown"and letwaste_report.pycount it honestly (it does — the fixture has two such spans). - Cache hits that shouldn't happen — your
request_keyis missing an input that changes the answer (model version, prompt version, temperature, tool state). Re-check 11B.3, 3.2 component by component. - The breaker never opens — your
min_calls/windowconfig is too loose, or failures are being retried inside the provider call so the breaker only sees successes. Remember: retries live in one layer (11C.3). - Metrics exploding in cardinality — a user ID or request ID ended up as a label. Coerce to the bounded vocabulary the lesson defines; IDs belong in traces (11A.2, 1.5).
Stretch: Deployed AI service#
Goal: Assemble the module's running project end to end — the production FastAPI llm_service with tracing, metrics, caching, routing and resilience wired in — plus its container, deploy configuration and CI/CD pipeline with an eval gate. Everything runs locally against the fake client; pushing to a real cloud is the optional final step.
What you'll practise:
- The deployment-target decision and the production service anatomy: app factory,
pydantic-settings, injected client with lifespan, auth, per-tenant limits, the streaming endpoint, background jobs, structured logging, health/readiness, graceful shutdown and error mapping (lesson 11C.1, 1.4, 2.2, 2.3, 2.6, 2.7, 2.8, 2.9) - SSE through proxies and the two error boundaries (11C.1, 2.15)
- Containerisation and secrets: multi-stage
uvDockerfile, non-root,.dockerignore, runtime-only secrets (11C.1, 3.1, 3.2, 4.2) - Scaling on the right signals: concurrency not CPU, queue-plus-worker, backpressure, cold starts, residency (11C.1, 5.3, 5.5, 5.8)
- Release strategies for a service with in-flight streams (11C.1, 6.2, 6.3, 6.4)
- The CI pipeline: test pyramid, change-risk classification, eval gates with
eval_gate.py, prompt registries, model deprecation watch, release evidence (lesson 11C.2, 1.3, 1.4, 3.3, 5.1, 6.2, 9.3) - Testing the deployed shape without keys:
TestClientagainst the fake client (11C.1, 2.16)
Setup: a fresh llm-service project plus the provider_agnostic package from 03.11 — install its wheel (uv add --editable ../agnostic-client) or copy sources plus the six borrowed files (cost_calc.py, prices.py, prices.yaml, llm_errors.py, retry_after.py, check_response.py) and add openai anthropic google-genai pyyaml. Then:
uv add fastapi "uvicorn[standard]" pydantic \
pydantic-settings httpx python-dotenv prometheus-client
uv add --dev pytestAdd [tool.pytest.ini_options] pythonpath = ["."] to pyproject.toml so tests/ imports llm_service and provider_agnostic (11C.1's Setup). The .env needs LLM_SERVICE_API_KEYS_JSON='{"dev-token":"dev-tenant"}' for local auth; provider keys only matter if you point the service at hosted routes.
Steps:
- Lay down the app. Copy
settings.py,deps.py,schemas.py,serialize.py,errors.py,main.py,jobs.py,logging.pyfrom 11C.1, Part 2 intollm_service/. Build the client indeps.pyagainst amodels.local.yaml-style registry whose entries point at your fake or the Module 03 stand-in; keepFakeClientfromtests/test_app.pyas the default when no keys are set. - Wire the observability. Attach
ServiceMetricsHook(metrics)and your trace wrapper to the client hooks, and add the/metricsroute (11A.2, 3.3, 3.4). Confirm request IDs flow fromlogging.py's middleware into trace attributes. - Wire caching and resilience. Put
ExactCachein front of the completion path with scope per tenant, and aFallbackChainwith per-route breakers behind the router's chosen alias (11B.3, 8.4, 11C.3, 6.6). Add one deliberately dead route to the registry to prove fallback fires before the first byte. - Route. Add
router.py'sRuleRouterin front of model selection: aroutes.yamlmapping feature → alias, a canary arm, and the decision log to JSONL (11B.5, 3.5). - Run it.
uv run uvicorn llm_service.main:app --port 8000and exercise/healthz,/readyz,/metrics,POST /v1/chatandPOST /v1/chat/streamwithcurl -N. Then run the lesson'stests/test_app.pysuite plus your own tests for cache-hit, fallback and metrics paths — all againstFakeClient, no keys. - Containerise. Write the
Dockerfileandcompose.yamlfrom 11C.1, Part 3 — multi-stageuvbuild, non-root user, pinned base, manifests copied before source for layer caching.docker buildit if you have Docker; the lesson marks it reference/unrun either way. Verify.envis not in the image (docker history/.dockerignore). - Ship the pipeline. Copy
.github/workflows/{ci,eval,release,nightly}.yml, the gate configs,release/models.json,fixtures/model_catalogue.jsonandscripts/{eval_gate.py,check_model_deprecations.py,diff_prompts.py}from 11C.2, and savemake_fixtures.pyfrom 3.3. Runmake_fixtures.pyonce, then runeval_gate.py --run fixtures/runs/candidate --baseline fixtures/runs/baseline --config fixtures/gates/pr.json --dataset fixtures/evals/support-triage.jsonl(it also needs the Module 10Aevalkitpackage onPYTHONPATH) and confirm it prints theFAILverdict with exit code 2 (11C.2, 3.3, Exercise 2). Write the prompt-change PR template from 5.3. - Operate it. Fill in the
ops/artefacts for this service:ai_inventory.yaml(every prompt, model alias, tool, index),retention_schedule.yamlfor traces/feedback/eval data,slo.mdfrom your metrics, one runbook per incident class you actually face, andreadiness_checklist.json— then runreadiness.py,severity.py,incident_metrics.pyandoncall.py(11C.4, Parts 1–3 and 7). - Deploy (optional, needs a cloud account). Follow 11C.1, Part 6: build → staging → smoke → canary → prod with the rolling-drain rules for in-flight streams. Treat every cloud command as reference until you've read the target's current docs — the lesson's decision table (1.4) is the starting point, not a guarantee.
Verify it, and what you should see:
uv run pytest -q # the 11C.1 fake-client suite + yours: all pass, no keys
uv run uvicorn llm_service.main:app --port 8000 &
curl -s localhost:8000/healthz # {"status":"ok"}
curl -s localhost:8000/readyz # {"ready":true}, or 503 {"ready":false} before the client is built
curl -s localhost:8000/metrics | head # exposition or the MemoryBackend JSON dump
curl -sN -X POST localhost:8000/v1/chat/stream -H 'content-type: application/json' \
-H 'authorization: Bearer dev-token' \
-d '{"model":"<alias>","messages":[{"role":"user","content":"Say hi."}]}'
uv run python make_fixtures.py # 11C.2 section 3.3: writes fixtures/evals, fixtures/runs/{baseline,candidate}, fixtures/gates/pr.json
PYTHONPATH=. uv run python scripts/eval_gate.py --run fixtures/runs/candidate --baseline fixtures/runs/baseline \
--config fixtures/gates/pr.json --dataset fixtures/evals/support-triage.jsonl # FAIL, exit 2Expected shape: health endpoints answer without touching a provider; /metrics serves the catalogue; the stream emits SSE events and an error event (never a mid-stream HTTP error) if the route fails after the first byte (11C.1, 2.8); the eval gate refuses to pass on the deliberately failing fixture; and traces.jsonl + the metrics backend show the same request from both angles.
Done when:
- The app boots with zero provider keys against the fake client, and
pytestpasses including your cache/fallback/metrics tests. /healthzvs/readyzbehave differently under a deliberately broken dependency (the lesson's distinction).- A stream survives a client disconnect without orphaned upstream work, and a mid-stream failure surfaces as an SSE
errorevent. - The Dockerfile builds (or its layer ordering is correct by inspection) with no secrets inside.
eval_gate.pyproducesFAIL/WARN/PASSon fixtures, and the workflow YAML is internally consistent (environments, secrets, fork guards).ops/contains a filled inventory, retention schedule, SLO doc, at least three runbooks and a readiness checklist with an honest score.
Stretch ideas: Add the queue-plus-worker job path with an Idempotency-Key contract (11C.1, 2.9, 2.10). Wire otel_metrics.py and the OTel tracing facade so the same code exports to a collector (11A.1, Part 3, 11A.2, 3.5). Run the chaos suite from 11C.3, 8.3 against the wired service. Hosted: deploy to one PaaS target from the decision table and repeat the smoke checks.
Common problems:
ModuleNotFoundErrorforprovider_agnostic's borrowed modules — copy the six files beside the package or install the wheel; the imports are top-level, not package-relative (11C.1's Setup).- SSE that works in
curlbut breaks behind nginx —proxy_bufferingand read timeouts; apply the lesson'sX-Accel-Buffering: nosnippet and keep-alive pings (11C.1, 2.15). - Every request 401s —
LLM_SERVICE_API_KEYS_JSONunset; the dev token map is required even locally. - The eval gate passes everything — your
gates/*.yamlthresholds are too loose ormin_casestoo small; the lesson's statistical-gate section (3.3) explains the "too wide to tell" state. - Fork-PR evals leaking secrets — check
eval.ymlusespull_request(notpull_request_target) for secret-bearing jobs (11C.2, 4.2). - Metrics wired but empty — hooks fire per attempt, and your fake client may bypass the hook path; call the facade directly in tests to isolate (11A.2, 3.3).
Stretch (optional): Self-hosted model gateway#
Goal: Decide — with arithmetic, not vibes — whether an open-weight model should serve part of your traffic; if so, serve it behind an OpenAI-compatible endpoint, cascade between it and a hosted model on quality signals, and measure the cost-quality frontier. The calculators and routing run keylessly; actually running a model needs Ollama or a GPU, which is why this is optional.
What you'll practise:
- The API-vs-self-host decision: break-even on utilisation, GPU-hour arithmetic, the four routes (your hardware, rented GPUs, managed hosts, edge) (lesson 11C.6, 1.2, 1.3, 3.4)
- VRAM and KV-cache sizing so the model doesn't OOM at long context (11C.6, 3.1)
- Picking a runtime honestly: Ollama for the laptop, vLLM for production, llama.cpp underneath, managed hosts as the middle route (11C.6, Part 4, Part 5, Part 6)
- The OpenAI-compatible provider swap: one client,
base_urldecides where it runs (11C.6, 7.1) - Production-serving concerns: prefix/KV caching, concurrency and queueing, security (auth in front of the server,
safetensorsprovenance), licence compliance (11C.6, 7.3, 7.6) - Cascades that escalate on quality, not just errors, between local and hosted routes (lesson 11B.5, 2.9, 3.3)
- The offline router evaluator and the cost-quality frontier (11B.5, 3.7, 4.1)
- The prompting/RAG/fine-tuning rung check before you commit to serving a tuned model yourself (lesson 13A.8, Part 1, 9.1)
Setup: Python 3.11+ stdlib for the calculators (breakeven.py, gpu_sizing.py, bench_openai_compatible.py — save each snippet under its own name and run it, per 11C.6's Setup). For the serving parts you need one of: Ollama installed (see 03.1, Part 12 for the stand-in pattern), or a GPU host you control, or a managed open-model host with an API key. The llm-service project and router.py/router_eval.py from 11B.5 are reused as-is.
Steps:
- Do the economics first. Run
breakeven.pywith your real token volumes and price quotes; sweep utilisation from 10% to 90% and find where self-hosting wins (11C.6, 1.2). Rungpu_sizing.pyfor your candidate model: weights at your chosen quantization plus KV cache at your expected context and concurrency — the OOM trap is almost always KV cache, not weights (3.1). Write down the answer before touching a server: in 11C.6's worked example the API wins below roughly 75% sustained utilisation, and 11B.1's calculator crosses over elsewhere, so your own numbers decide. - Pick the model and the licence. Choose an open-weight family from 11C.6, Part 2; check its licence permits your use (commercial serving, redistribution, derivatives) — the licence gate fires before download, not after (2.3).
- Stand up the cheapest honest server. On a laptop, Ollama with a small quant (the lesson's Modelfile example) or
llama-server; on a GPU box, the vLLM OpenAI-compatible server command from 11C.6, 5.1 and the compose reference from 10.2. Put auth in front of it — an unauthenticated model server is a finding, not a shortcut (7.6). - Prove the swap. Point the
openaiSDK at the local server withbase_urland a dummy key, exactly as 11C.6, 7.1 shows — same client code as the hosted route. Then runbench_openai_compatible.py(10.3) against it for TTFT, throughput and tokens/s, and compare with the hosted route's numbers from your traces. - Cascade between them. In
router.py, build aCascadeRouter: local route first with a validator (schema validity, refusal check, confidence signal), hosted route as the escalation — and log every routing decision (11B.5, 3.3, 3.6). The fallback must honour the same data policy as the primary (11C.3, 6.4) — if privacy was why you self-hosted, the hosted fallback needs its own justification or a "queue and retry" degraded path. - Measure the frontier. Run your eval suite (or a labelled subset) on both routes, build the
ResultsTable, and runrouter_eval.py: oracle bound, regret, cost-at-equal-quality per slice (11B.5, 3.7, 4.1). The question the project answers: at what traffic mix does the cascade beat always-hosted and always-local? - Check the ladder before fine-tuning. If the local model's gap is format or tone rather than knowledge, you are probably on the wrong rung — walk the 13A.8 decision ladder and the symptom→treatment table (2.2) before considering a tune; run
ftecon.pyfor the crossover-volume arithmetic if you get that far (9.1).
Verify it, and what you should see:
python3 breakeven.py # API-vs-self-host table at your parameters
python3 gpu_sizing.py # weights + KV cache fit (or the honest OOM warning)
python3 bench_openai_compatible.py --base-url http://localhost:11434/v1 --model <name>
uv run python router_eval.py # oracle / regret / frontier table on your ResultsTableExpected: the calculators print real arithmetic you can defend; the benchmark reports TTFT/throughput/tokens-per-second against the local endpoint; the router evaluator prints the oracle bound and your cascade's regret — the number that says whether routing is earning its complexity. Hosted comparisons are illustrative until you have keys.
Done when:
- You can state, with your own numbers, the utilisation break-even for self-hosting and whether your workload clears it.
- The chosen model's VRAM budget (weights + KV cache at your context/concurrency) fits your hardware with headroom, or you've chosen a smaller quant/runtime honestly.
- The local server answers through the same client code as the hosted route, with auth in front and a pinned model version.
- The cascade demonstrably escalates on validator failure (show a trace where the local route's bad answer was rejected and the hosted route served), and decision logs show the split.
router_eval.pyreports your policy's cost-at-equal-quality against the oracle bound, per slice.- Your write-up answers the frontier question: which route serves which slice, at what measured cost and quality.
Stretch ideas: Add the hybrid router pattern from 11C.6, 8.2 — local for sensitive/cheap slices, hosted for hard ones — with the classifier's confidence threshold bounding misroutes. Evaluate a fine-tuned open model with LoRA adapters served on one base (11C.6, 7.7) — awareness-level, per 13A.8. Measure prefix-cache hit rate on the self-hosted server (11C.6, 7.3) and fold the savings into breakeven.py.
Common problems:
- Model fits in VRAM but OOMs under load — KV cache scales with context × concurrency; quantize KV, cap
--max-model-len, or reduce parallel slots (11C.6, 3.1). - Quantization quietly broke tool-calling — a 2-bit quant that chatters on JSON schemas; re-run your capability probe (structured output + tools) on the quant you actually ship (11C.6, 2.4).
- The "free" local model costs more than the API — low GPU utilisation makes the fleet's fixed cost per request worse than per-token pricing; that's the whole point of the break-even calculator.
- Cascade sends everything to the hosted route — your validator accepts nothing (threshold too strict) or the local model's outputs never parse; check the validator on canned local outputs first.
- Prefix caching leaking across tenants — self-hosted prefix caches are shared per replica; namespace per tenant or isolate replicas (11C.6's Check yourself).
- Licence surprise at ship time — the model card's licence restricts your use case; the gate belongs in CI, not in your launch checklist (11C.6, 2.3).