Module 09: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
Four projects: two starters and two stretches (the multimodal search is optional). Most of the module needs no API key. Every project has a keyless path built on the lessons' fakes, recorded outputs and pure-local code — the same pattern the lessons use, where a scripted backend or fake embedder proves the plumbing and a hosted provider proves the judgement. Provider keys (OpenAI, Anthropic, Gemini, OpenRouter, and specialists like ElevenLabs or Deepgram) are the stretch goal: you add a .env key or swap one backend function, not rewrite the pipeline.
First time? Do lesson 03.1, Part 4 once (uv init multimodal-apps --bare --python 3.13, then uv add the provider SDKs), or reuse the llm-apis project the Module 03 lessons use. Each project below gives its own uv add line with the packages its lessons use (names only, so you get the newest release; each lesson's Setup says which versions its samples were checked against). Run scripts with uv run python file.py.
Two honesty notes that apply everywhere. First, samples that call hosted models were written against the official documentation as of November 2026 and their outputs are labelled illustrative — model names, voices, formats, limits and prices change monthly, so re-check the lessons' "facts at a glance" owners (module index) before you rely on a value. Second, you will need real media for the interesting parts: the lessons generate tiny synthetic inputs (a tone-burst WAV, a Pillow-drawn image) that exercise the code but contain no real speech or readable document. For transcription and extraction quality you need audio you recorded yourself or clips/images/documents you have the rights to — the projects say where.
Starter: Receipt extractor#
Goal: Turn receipt and invoice images (and PDFs, if you have some) into validated structured data: a Pydantic Invoice, arithmetic and check-digit validation, a field-level score against a labelled set, and a review queue file for everything that isn't confident enough to auto-approve.
This is the module's first running example: lesson 09.2 builds the whole package end to end, and lesson 09.1 supplies the image-side prompting and pipeline discipline. The keyless path matters here: the only step that needs a model is the extraction call itself. Feed the pipeline recorded model responses (JSON you write by hand, shaped like the model's output) and every other stage — schema validation, arithmetic checks, scoring, routing — runs for real.
What you'll practise:
- Choosing the document route — native PDF input, page images or parser-then-LLM — and why the choice is about accuracy, cost, latency and privacy (lesson 09.2, 1.2, 2.1–2.5)
- Document schema design: line items, totals, currencies, dates, evidence fields (
page,quote,bbox), nullable fields,unreadableflags (09.2, 3.1, 3.2) - Validation beyond the schema: sum-of-lines arithmetic, date sanity, IBAN/VAT check digits, cross-field rules, reconciliation against master data (09.2, 3.3, 3.4)
- Multi-page handling: page-by-page vs whole-document, table continuation, document-type routing, bundles (09.2, Part 4)
- Reliability engineering: confidence and verification, human-in-the-loop review, idempotency and audit trails, error budgets and straight-through rates (09.2, Part 6)
- Field-level evaluation: precision/recall/exact-match with tolerance rules for money and dates, normalisation before comparison, the scorer (09.2, Part 7)
- The vision side that feeds it: preprocessing (resize, EXIF orientation, compression), caching by image hash, cost arithmetic, screening uploads (09.1, Part 5)
- Structured output mechanics on every provider — this lesson reuses 03.4 rather than re-teaching it (09.2, Part 8)
Setup:
uv init receipt-extractor --bare --python 3.13 && cd receipt-extractor
uv add pydantic python-dotenv pillow pypdfium2 pypdf
# Provider path only (skip for the keyless run):
uv add openai anthropic google-genai.env needs OPENAI_API_KEY or ANTHROPIC_API_KEY (and, if you choose those optional providers, GEMINI_API_KEY or OPENROUTER_API_KEY) only for the hosted path. Copy the lesson's package files into your project root — schema.py, checkdigits.py, validators.py, normalise.py, score.py, cost_model.py (09.2, 3.1, 3.3, 7.1, 7.6, 2.6) — plus extract.py and cli.py from Part 8. You will write pipeline.py yourself in step 4; the lesson gives its pseudocode.
Steps:
- Generate starter documents. Write
make_docs.pythat draws three receipt images with Pillow, saved asdocs/receipt_clean.png,docs/receipt_discount.pnganddocs/receipt_bad_total.png(a clean one, one with a discount line as a negative line item, and one where the line amounts add up to 52.10 but the printed subtotal and total both say 48.90 (your review-queue trigger)). UseImageDraw.textwith a TrueType font if your system has one (ImageFont.truetype), falling back toload_default(). Also write oneexpected.jsonwith the correctInvoicefields for the clean receipt — this is your labelled set. If you have rights to a real receipt photo or a PDF invoice, add it as a fourth document; the Pillow drawings are for pipeline mechanics, not for judging VLM accuracy. Also save a PDF copy of each drawing (img.convert("RGB").save("docs/receipt_clean.pdf")works in Pillow): the lesson's hostedextract_*functions send PDFs, not PNGs, so step 7 needs them. - Run the keyless path first. Write
recorded/containing one JSON file per document, shaped exactly like the model's structured output for that document (anInvoicedump). Writefake_extract.pywith a functionextract_recorded(doc_id) -> Invoicethat loads the matching file and callsInvoice.model_validate— the same validation the realextract.pypath ends with. This is yourScriptedModelequivalent: it exercises schema parsing, not model judgement. - Wire validation and scoring. Run each recorded
Invoicethroughvalidators.check_invoice_mathandvalidators.check_identifiers, then score it againstexpected.jsonwithscore.py'sscore_record(pred, gold), which takes two plain dicts (passinvoice.model_dump(mode="json")for the prediction). Importingscore.pyalso runs the fixture demo at the bottom of the lesson's file, so wrap that block inif __name__ == "__main__":in your copy. Confirm the mismatched document produces validator problems and fails its field score — that's the signal your review routing keys on. Note what the lesson'scheck_invoice_mathactually compares: the sum of the line amounts againstsubtotal(plus date order and the sign oftotal). So in the recorded JSON for the bad receipt, make the lines add up to 52.10 whilesubtotalandtotalcarry the printed 48.90. To catch a wrongtotalon its own, add thesubtotal + tax_total ≈ totalrule from 09.2, exercise 1 first. - Write
pipeline.py. Implement the lesson's pseudocode as real code: sniff bytes → hash the file → check an idempotency store (a JSON file mappingsha256 → result, so re-running doesn't re-extract) → classify document type → extract via the chosen backend (extract_recordednow,extract.extract_openaietc. later) → run validators → route: problems orunreadable_fieldsnon-empty or low confidence → append toreview_queue.jsonlwith the image path, extracted fields, problems andmodel/prompt_version; else → write toapproved.jsonlwith an audit record (file hash, provider, model, prompt version, cost estimate fromcost_model.py). - Make the review queue useful. For each queued item include enough for a human to decide without re-running anything: the source path, the extracted JSON, the validator problems, and the page render (for a PDF, use
render_pages.py's pypdfium2 path from 09.2, 2.2 to drop a PNG beside it). - Exercise the failure gallery. Feed the pipeline three edge cases from 09.2, 6.7: a recorded response with a missing
total(should route to review viaunreadable_fields), one with a wrong-but-schema-valid total (the validators catch it once you have added thesubtotal + tax_total ≈ totalrule from step 3), and one with an IBAN that fails mod-97 (checkdigits.pycatches it). Check each lands inreview_queue.jsonlwith the right problem string. - Add the hosted path behind a flag. Give your
pipeline.py--providerand--liveoptions: without--liveit callsextract_recorded; with--live --provider openaiit callsextract.extract_openai(path)(orextract_anthropic;extract_geminiandextract_openrouterare optional) on the PDF copy of each receipt. The lesson'scli.pyis a separate single-document debugging tool (python cli.py docs/receipt_clean.pdf --provider openai): it takes a PDF path and--provideronly, has no recorded mode and no--liveflag. The drawn receipts may or may not extract well — a Pillow-drawn "receipt" is not a real document photo; that's expected and is exactly why the recorded path exists. If you have a real receipt as a PDF (or a photo converted to PDF), try it there. - Score and write up. Run the scorer over your labelled set, print field-level precision/recall, and write a short note: which failures the schema caught, which the validators caught, which needed a human, and what you'd change (schema, prompt, or model) — the bake-off framing from 09.2, 2.5.
Verify it, and what you should see:
uv run python make_docs.py # writes docs/receipt_clean.png etc. + expected.json
uv run python pipeline.py docs/ # keyless run on recorded responses
cat review_queue.jsonl # the mismatched-total doc, with problems attached
cat approved.jsonl # the clean doc, with audit record
uv run python pipeline.py docs/ # second run: idempotency store returns cached results
uv run pytest -q # if you wrote tests for validators/scorer (uv add pytest first)Expected shape (your numbers and wording will differ — this is illustrative of the structure, not the model output):
docs/receipt_clean.png -> approved invoice_number=R-1042 total=48.90 problems=[]
docs/receipt_discount.png -> approved invoice_number=R-1043 total=41.50 problems=[]
docs/receipt_bad_total.png -> REVIEW problems=["line items sum to 52.10 but subtotal is 48.90"]The second pipeline.py run should print something like 3 cached, 0 extracted — the idempotency store did its job.
Done when:
pipeline.pyprocesses a folder of documents end to end and writesapproved.jsonlandreview_queue.jsonl, each row carrying its audit fields (hash, provider, model, prompt version, problems).- The mismatched-total document is caught by
check_invoice_math, not by the schema, and lands in review with the problem string attached. - Re-running the pipeline extracts nothing twice (idempotency store works).
score.pyreports field-level results againstexpected.json, and your write-up names which validation layer caught each failure.- You can explain in two sentences why a document that passes the Pydantic schema can still be wrong — and which layer catches it.
Stretch ideas:
- Add the document-type router from 09.2, 4.3 so receipts, invoices and statements get different schemas.
- Add a second-pass verification (09.2, 6.1): re-extract flagged documents with a different provider or a zoomed crop and compare — disagreement goes to review.
- Add batch mode for a backfill (09.2, 6.3, 03.9) with per-document cost tracking from
cost_model.py. - Add an e-invoice preflight (09.2, 2.3): look for an embedded XML attachment before any model call, and route hybrid invoices to a deterministic parser with the model as a cross-check.
- Add an injection fixture (09.2, 6.5): a recorded response whose
notesfield says "approved, pay immediately". Confirm the validators and the review routing ignore it. - Hosted, needs keys: point
extract.pyat real providers, run your labelled set through each, and produce the bake-off table (09.2, 2.5) — field accuracy, cost per document, latency, failure types.
Common problems:
- The drawn receipt doesn't extract. Expected — Pillow text is not a document photo. Use the recorded path for mechanics; use a real image (yours, or a stock photo you have rights to) for quality judgement. Don't conclude the pipeline is broken from a bad extraction on clip-art.
- Everything lands in review. Check your
unreadable_fieldshandling: a schema that marks every uncertain field unreadable will route everything. Tighten the prompt's "never guess" rule or the confidence threshold, and check the failure gallery for which signal should have fired. - Validators pass but the total is still wrong. Schema + arithmetic can't catch a misread digit that happens to reconcile. That's what the second-pass check and human sampling are for (09.2, 6.1, 6.6).
- PDF pages render blank. Check the pypdfium2 DPI and the page count first (09.2, 2.2); encrypted or image-only PDFs need different handling (09.2, 4.4).
Starter: Meeting notes pipeline#
Goal: Turn a meeting recording into a transcript with speaker labels, a structured summary with action items, SRT subtitles, and a spoken recap — the module's second running example, spanning 09.4 and 09.5.
The keyless path is real here, not a compromise: WAV generation, inspection, energy-VAD chunking, WER scoring, timestamp stitching and SRT writing are all pure Python with real output. The parts that need a model — transcription, diarization, summarisation, speech synthesis — each get a scripted fake so the whole pipeline runs end to end with no key, and a provider backend you can swap in.
What you'll practise:
- Audio fundamentals for engineers: sample rate, bit depth, channels, codecs and containers, why 16 kHz mono is the ASR standard, and ffmpeg conversion (09.4, Part 1)
- Measuring transcription quality with WER and its normalisation traps (09.4, 2.3)
- Choosing an STT route — OpenAI
gpt-transcribe, Gemini transcription, OpenRouter's STT endpoint, specialist vendors, open models — and reading the deprecation clock (09.4, Part 3) - Long audio: VAD-based chunking on silence, stitching segments back onto the timeline, bounded parallelism (09.4, Part 8)
- Diarization: what speaker labels are and aren't, provider support, naming speakers downstream (09.4, Part 9)
- Post-processing transcripts into products: cleanup, summaries with timestamps, SRT/VTT subtitles, RAG over speaker-turn chunks (09.4, Part 12)
- Text-to-speech fundamentals: formats, TTFA vs total time, wrapping PCM in WAV (09.5, Part 2)
- Designing text for speech:
verbalise()for numbers/dates/IDs, the voice-friendly LLM prompt, SSML awareness (09.5, Part 9) - The streaming LLM → TTS sentence pipeline and its backpressure rules (09.5, Part 11)
- TTS caching and cost: pricing units, the content-hash cache, cost caps (09.5, Part 12)
- Consent and privacy for recorded speech (09.4, Part 13, 09.5, Part 14)
Setup:
uv init meeting-notes --bare --python 3.13 && cd meeting-notes
uv add python-dotenv pydantic
# Provider path only:
uv add openai google-genai httpx websockets elevenlabs
# Optional, for real-audio chunking quality (see 09.4, 7.3's table):
uv add faster-whisper # pulls its own deps; model weights download on first runThe keyless path needs nothing beyond the standard library — every file below is pure Python. .env keys are needed only when you wire a real provider.
Steps:
- Generate and inspect test audio. Copy
make_test_wav.pyandwav_inspect.pyfrom 09.4, 1.3: it writes an 8-second 16 kHz mono WAV with three tone bursts in silence — exactly what a VAD has to find. Run both; confirm the RMS windows light up only during the bursts. If you have a real recording you made yourself (a voice memo, a meeting you ran), convert it withffmpeg -i in.m4a -ar 16000 -ac 1 meeting_16k.wavper 09.4, 1.4 and inspect it too. - Score WER. Copy
wer.pyfrom 09.4, 2.3 and build aeval/folder with five reference/hypothesis pairs: one perfect, one with a substitution, one with an inserted "thank you", one differing only in punctuation and case (should score 0 after normalisation), and one missing a number. Print WER for each and note which normalisation choice a legal team would argue about (09.4 exercise 2). - Chunk on silence. Copy
vad_chunk.pyfrom 09.4, 8.2 and run it on your WAV. Then writechunk_audio.pythat usesvad_segmentsto cut the WAV into per-segment files (stdlibwavecan slice PCM frames), andstitch.py's rebase logic (09.4, 8.3) to map per-chunk transcript timestamps back onto the full recording. Verify no segment boundary lands mid-burst on the synthetic file. - Define the canonical transcript. Copy the
Segment/Transcriptdataclasses andto_plain_textfrom 09.4, 12.4 intotranscript.py. Add ato_speaker_turns()helper that groups consecutive same-speaker segments — diarization output and summary prompts both want turns, not raw segments. - Write the scripted backends.
fake_stt.pyreturns a cannedTranscriptfor the synthetic file (three "utterances" matching the three tone bursts, withspk_1/spk_2alternating — this is your diarization fake too).fake_summarise.pyreturns a structured dict{"summary": ..., "decisions": [...], "action_items": [{"text","owner","due","timestamp"}]}built from the canned transcript.fake_tts.pywrites a WAV per chapter usingaudio_lab.py'ssine_pcmat different frequencies per speaker — a placeholder voice, clearly labelled. - Implement
summarisefor real. The one stage worth a real model: writesummarise_llm(transcript)that sendsto_plain_text()to a chat model with structured output per 03.4, asking for the action-item shape from step 5 — owner, due, and the timestamp of the turn it came from (09.4, 12.2). Run it on the 03.1 stand-in or a hosted key; keepfake_summariseas the CI path. - Subtitles. Copy
srt_writer.pyfrom 09.4, 12.3 and emitmeeting.srtfrom the transcript segments. Check the cue timings againstwav_inspectoutput. - The spoken recap. Copy
recap_script.py,text_for_speech.py(verbalise) andsentence_stream.py(SentenceBuffer) from 09.5, Part 16 and 09.5, 9.2/11.2. Feed the summary dict throughverbalise, split into sentences withSentenceBuffer, and synthesize each chapter —fake_ttskeyless, a real TTS provider behind a flag. Join chapters withjoin_wavs's crossfade fromaudio_lab.py(09.5, 10.2). - Cache and cost. Wrap the TTS call in the
SpeechCachepattern from 09.5, 12.2 — key on model + voice + text + format + rate — and print the cost estimate withcost_and_eval.py'sCHARS_PER_MINUTEand the pricing-unit table from 09.5, 12.1. Show that re-running the recap costs ~nothing the second time. - Assemble the CLI. Finish
meeting_pipeline.pyfrom 09.4, 12.4: replace theNotImplementedErrorstages with calls to your backends, addargparse(pathand--backend fake|live), and writeout/transcript.json,out/meeting.srt,out/recap_*.wavandout/notes.md. The verification commands below run this file. - Consent checklist. Write
CONSENT.md— one page covering notice before recording, retention (delete audio after N days, keep text), speaker-level deletion, and the biometric sensitivity of voiceprints (09.4, 13.1). This is engineering awareness, not legal advice — say so.
Verify it, and what you should see:
uv run python make_test_wav.py && uv run python wav_inspect.py meeting_sample.wav
uv run python vad_chunk.py meeting_sample.wav
uv run python meeting_pipeline.py meeting_sample.wav --backend fake
ls out/ # transcript.json, meeting.srt, recap_*.wav, notes.md
uv run python meeting_pipeline.py meeting_sample.wav --backend fake # cached: no re-synthesisExpected shape (illustrative — your canned transcript and timings differ):
transcript: 3 segments, 2 speakers, 8.0s
meeting.srt: 3 cues
recap: 2 chapters -> out/recap_1.wav (3.2s), out/recap_2.wav (2.8s)
cost: ~$0.000 cached / est. $0.004 uncached at ElevenLabs-like per-char rates
second run: 2 cache hits, 0 provider callsWith --backend live (keys needed) the same command should produce a real transcript of your recording, real subtitles, and a spoken recap you can play.
Done when:
meeting_pipeline.pyruns end to end keyless on the synthetic WAV and producestranscript.json,meeting.srt, chapter WAVs andnotes.md.- VAD chunking finds the three bursts, stitching rebases timestamps correctly, and no cue is split mid-word.
summarise_llmreturns action items with owner, due and timestamp; the fake path proves the shape without a key.- The recap audio plays, chapters join without clicks (crossfade), and a second run hits the cache.
CONSENT.mdexists and names the retention and deletion rules your pipeline would enforce.- Your notes say which stages are fake, which are real, and what real audio would change.
Stretch ideas:
- Real STT: wire
transcribe()to OpenAIgpt-transcribeor Geminigemini-3.5-transcribeper 09.4, Parts 4–5, chunking long audio per 09.4, Part 8 and scoring against a hand-corrected reference withwer.py. - Real diarization: provider speaker labels or pyannote (09.4, Part 9) feeding
to_speaker_turns, then LLM speaker naming with human confirmation. - Real TTS: swap
fake_ttsfor a provider per 09.5, Parts 4–7, stream LLM tokens throughSentenceBufferper 09.5, Part 11, and measure TTFA. - Push the transcript into retrieval: speaker-turn chunks with
start_ms/speakermetadata per 09.4, 12.5 — the seed of Module 07 RAG.
Common problems:
- The synthetic WAV "transcribes" to nonsense. It will — tone bursts aren't speech. The fakes exist so the pipeline mechanics are real; transcription quality needs real audio and a real (or stand-in) model. Don't debug the fake.
- WER scores are huge on trivial pairs. Check normalisation first — punctuation and case differences dominate before you tune anything (09.4, 2.3).
- Chunks split words. Energy VAD fails on noise and crosstalk; for real audio use Silero VAD or provider-side VAD (09.4, 8.2). On the synthetic file, loosen
pad_ms. - The recap sounds robotic / reads "14:30" wrong. That's
verbalise()doing its documented-best-and-imperfect job (09.5, 9.2); add domain rules for the cases that matter and keep a review step. - Second run still calls the provider. Your cache key must include every parameter that affects output — model, voice, text, format, rate (09.5, 12.2).
Stretch: Voice assistant#
Goal: A voice agent that takes speech in, calls real tools mid-conversation, speaks replies back, handles barge-in correctly (including truncating what the model thinks it said), and reports its own latency and cost — built first on scripted fakes so every control path runs keyless, then pointed at real providers.
This is the module's hardest project because the interesting bugs live in the control logic, not the models: turn-taking, interruption, context truncation, tool confirmation and latency budgets. 09.6 owns the foundations and 09.7 owns the provider APIs and the from-scratch cascade.
What you'll practise:
- Choosing the architecture — cascaded STT → LLM → TTS vs speech-to-speech realtime vs GPT-Live's delegated backend — with the honest trade-off table (09.6, 1.3, 09.7, Part 1)
- Realtime transport and wire-format basics: PCM16 formats, base64 chunks, jitter buffering (09.6, Part 3)
- Turn-taking: energy VAD vs ML VAD, end-of-turn detection, and the two barge-in jobs — stop playback and truncate context (09.6, Part 4, 09.7, 1.5)
- The event-driven session model and its state machine (09.6, Part 5, 09.7, 3.3)
- Tools inside a voice loop: filler phrases, async execution, spoken confirmation before irreversible actions (09.7, 11.2)
- Conversation design for speech: the system-prompt blueprint, entity capture, readbacks (09.7, Part 12)
- Operations: per-turn latency measurement, cost-per-minute modelling, scripted test callers, fallbacks (09.7, Part 13)
- Session lifecycle, reconnection and limits on the real APIs (09.7, 5.6, 09.6, 5.4)
Setup:
uv init voice-agent --bare --python 3.13 && cd voice-agent
uv add python-dotenv pydantic pytest
# Keyless path needs nothing more (pytest runs your scripted-call suite). Provider path (packages per 09.7's Setup):
uv add "openai[realtime]" google-genai websockets httpx fastapi uvicorn
# Framework path (optional):
uv add "pipecat-ai[openai,deepgram,elevenlabs,silero,webrtc,runner]" # or livekit-agents; see 09.7, 10.2Steps:
- Start from the simulator. Copy
cascade_sim.pyfrom 09.7, 10.3 — asyncio queues,FakeSTT/FakeLLM/FakeTTS, and the barge-in that cancels TTS and truncates context. Run it; confirm the "model generated" vs "user actually heard" lines differ. This file is your agent's skeleton: every later step replaces a fake with a real stage behind the same interface. - Generalise the turn loop. Turn the demo into
voice_session.py: aTurnManagerthat (a) collects final STT transcripts, (b) runs the LLM turn collecting deltas, (c) streams sentence chunks to TTS viaSentenceBuffer(09.5, 11.2), (d) on barge-in cancels TTS and the in-flight LLM stream, computesplayed_ms, and appends the heard text — not the generated text — to history. Writetruncate_context(played_ms, generated_ms)per 09.6 exercise 7. - Add the tool layer. Copy
voice_tool_policy.pyfrom 09.7, 11.2 and implement three tools for your domain — e.g.lookup_order,search_docs,book_callback— withneeds_confirmtrue only forbook_callback. Route tool calls throughconfirm_before_execute: the agent must read back "…book a callback Thursday at 2pm? Say yes to confirm" and wait. Wire the tool results back as spoken-friendly text throughverbalise(). - Add a scripted caller.
scripted_caller.pyplays the user's side: a list of utterances (with barge-in timings) fed through the sameFakeSTTinterface, so a "call" is a deterministic test. Writetest_calls.pyasserting: order lookup returns the right facts,book_callbackwithout "yes" changes nothing, and after a barge-in the next assistant turn never references the unheard part of its previous reply. - Measure latency. Write
latency_report.py: instrument each stage with timestamps (STT final → LLM first token → TTS first audio → playback start) and print a per-turn latency report plus p50/p95 across the scripted calls (09.7, 13.2). Compare againstlatency_budget.py's stage table from 09.6, 3.4 — identify which stage dominates your simulated turns. - Model the cost. Run
voice_cost.pyfrom 09.7, 13.3 (andvoice_cost.py's sibling in 09.6, Part 8) with your call profile — call length, talk-time ratio, tool calls — and print cost per minute for cascade vs OpenAI Realtime vs Gemini Live vs GPT-Live (the lesson's file prints all four). State which assumptions move the ranking. - Wire one real stage at a time. Keep the fakes for the stages you have no key for. The cheapest real upgrade is usually the LLM (03.1 stand-in or a hosted key): swap
FakeLLM.respondfor a real chat call with tool definitions per 03.5 and the agent loop from 08A.2. Then STT (realtime transcription per 09.4, 4.4 or file API), then TTS (09.5, Part 4). - (Optional) Go realtime. With an OpenAI or Gemini key, adapt the session code to the real event model —
session.update,input_audio_buffer.append,conversation.item.truncateon OpenAI (09.7, Part 3), orBidiGenerateContentSetupandsessionResumptionUpdateon Gemini Live (09.7, Part 5). Start from the server-side WebSocket examples in 09.7, Part 8 and the browser token flow in Part 9. Keep your TurnManager's truncation logic — the provider handles audio truncation, but the context rule is yours. - Write the operator page. One page covering: architecture choice and why, the latency report, the cost model, the consent/recording notice your deployment needs (09.7, Part 14), and the fallback plan when the voice path degrades to text (09.7, 13.5).
Verify it, and what you should see:
uv run python voice_session.py # scripted demo, keyless
uv run python -m pytest test_calls.py -q # scripted-call suite passes
uv run python latency_report.py # per-turn stage timings + p50/p95
uv run python voice_cost.py # cost/min for each architectureExpected shape (illustrative — your tools, canned replies and simulated timings will differ):
[turn] user: 'where is my order A-1042?'
heard : 'Your order A-1042 shipped '
tools : lookup_order -> {'status': 'delivered', 'eta': 'Friday'}
[turn] user: 'book a callback Thursday at 2'
agent : '...book a callback Thursday at 2 pm? Say yes to confirm.'
user : 'yes'
tools : book_callback -> {'id': 'CB-221', 'when': 'Thu 14:00'}
latency p50: stt 40ms | llm-first 90ms | tts-first 60ms | total 410ms
cost: cascade ~$0.034/min, realtime ~$0.081/min (09.7's defaults; your prices differ — they are parameters)With real stages wired, the same scripted caller should drive a live session and the latency report should show real numbers — expect the VAD/end-of-turn wait and model first-audio to dominate, per 09.6, 3.4.
Done when:
- The scripted-call suite passes keyless: tool call, confirmation gate, barge-in truncation and context correctness all verified.
- After a barge-in, the model's next turn never claims it said something the user didn't hear.
book_callbackcannot execute without an explicit spoken yes;lookup_ordernever asks.- The latency report prints per-stage timings and p50/p95; the cost model prints per-minute figures with prices as parameters.
- You can swap any single stage (STT, LLM, TTS) between fake and real without touching the turn logic.
- Your operator page names the consent notice, the fallback path and the abuse controls (caller authentication, rate limits) a real deployment needs.
Stretch ideas:
- Add RAG in the voice loop: pre-fetch retrieval on intent keywords, speak top-3 as one sentence, keep citations for a follow-up text channel (09.7, 11.3).
- Add warm handoff: summarise the call transcript and "transfer" with context, or book a callback as the IVR-replacement pattern (09.7, 11.1).
- Add session resilience: reconnect with
sessionResumptionUpdateon Gemini or session limits handling on OpenAI (09.7, 5.6, 09.6, 5.4). - Framework route: rebuild the cascade on Pipecat or LiveKit Agents (09.7, 10.2) and diff its behaviour against your from-scratch version — the comparison is the lesson.
- Hosted, needs keys: run the OpenAI Realtime or Gemini Live session from Part 8 with your tools wired as function calls, and measure real TTFA against your latency budget.
Common problems:
- The agent "remembers" saying things the user never heard. You appended the generated reply, not the heard portion — the single most common voice-agent bug (09.6, 4.3, 09.7, 10.3). Fix the truncation, then re-run the scripted barge-in test.
- It interrupts the user constantly. Your end-of-turn silence threshold is too aggressive — raise
silence_duration_mstoward the 500–800 ms sweet spot, or switch to semantic VAD (09.6, 4.2). - Tool calls create dead air. Add the filler path (
run_voice_tool'sSLOW_TOOL_THRESHOLD_S) and consider async tools that return "pending" then follow up (09.7, 11.2). - The browser can't use your key. Mint an ephemeral client secret server-side and use WebRTC — never ship provider keys to the client (09.7, Part 9).
- Costs explode on long calls. Realtime audio is billed per token of context resent each turn; model your actual talk-time ratio before choosing architecture (09.7, 13.3).
Stretch (optional): Multimodal search#
Goal: A search service over product images, document pages and video segments — caption each item, embed both the caption and a media proxy, retrieve across branches with RRF fusion, and answer questions from the top hits with citations. Runs end to end keyless on the lesson's fakes; provider adapters are the stretch.
This project assumes Modules 05–07 (it reuses their VectorStore contracts) and combines 09.8's video segmentation with 09.9's retrieval machinery.
What you'll practise:
- The multimodal embedding landscape and who can't do it (09.9, Part 1)
- Shared-space semantics and the modality gap, demonstrated on synthetic vectors (09.9, Part 2)
- The four design patterns — raw media, describe-then-embed, hybrid, late interaction — and the decision table (09.9, Part 3)
- Indexing media: payload design, media chunking, perceptual-hash dedup, embedding-cost arithmetic (09.9, Part 4)
- Query types: text-to-media, visual search, refinement limits, VLM reranking, query rewriting (09.9, Part 5)
- Multimodal RAG: retrieve media, answer with a VLM, cite pages/regions/timestamps (09.9, Part 6)
- Video segmentation feeding the index:
segment_video,map_segments,chapters_from_summaries(09.8, 3.9) and timestamp parsing (09.8, 3.10) - Retrieval evaluation: recall@k on a labelled query set (09.9, 6.5, 06.10)
Setup:
uv init multimodal-search --bare --python 3.13 && cd multimodal-search
uv add numpy pillow python-dotenv
# Provider path only:
uv add openai google-genai voyageai cohereSteps:
- Run the lesson's service. Copy
multimodal_search.pyfrom 09.9, 7.2 and run it —FakeMediaEmbedder+FakeCaptioner+NumpyVectorStore, real output, no keys. Read the demo output honestly: correct item always rank 1, thin margins, the toy modality gap handicapping the media branch on text queries. - Grow the catalogue. Replace
CATALOGUEwith 20–30MediaItems across three modalities:image(product shots — generate simple ones with Pillow: coloured shapes + a label, or use images you have rights to),pdf_page(reuse pages from your receipt project or draw invoice-like pages), andvideo_segment/audio_segmentitems whose captions you write by hand (the fake embedder is text-only anyway). Give each real metadata (sku,price,page,start_s) — the payload is what citations and filters need (09.9, 4.1). - Add a keyword branch. Extend the service with a third retrieval branch doing substring matching on captions (the lesson's exercise 5), fused by the same
_rrf. Test whether an exact-term query ("INV-2042") improves — and write down why RRF still matters when one branch is lexical. - Deduplicate. Copy the aHash/dHash perceptual-hash code from 09.9, 4.5 (
phash_demo.py) intodedup.py. At ingest, hash each image and skip near-duplicates within a Hamming threshold you tune on your own images — near-duplicates waste embedding budget and pollute results. - Video segments as items. Use
segment_video/map_segments/chapters_from_summariesfrom 09.8, 3.9 withfake_describeto turn a long video intoMediaItem(modality="video_segment", metadata={"start_s","end_s"})entries — caption = the segment summary. This is the "index instead of stuffing" pattern from 09.8, 3.8. - Measure recall@k. Write
eval_queries.json— 10–15 queries with relevant item IDs marked (mix text→image, text→page, image→image viaquery_kind="image"). Implementrecall_at_kper 09.9 exercise 7: runsearch(), compute recall per branch (caption vs media) separately. The gap between branches is the modality-gap lesson made concrete. - Multimodal RAG (hosted stretch). For the top-3 hits on a query, fetch the media (image bytes or page render) and ask a VLM the question with citations — page number, region or
MM:SStimestamp — per 09.9, 6.3 and the VLM-rerank sketch in 09.9, 5.4. Parse timestamps back withparse_timestampsfrom 09.8, 3.10. Keyless version: aFakeAnswererreturning canned citations proves the plumbing. - Provider adapters (optional, needs keys). Implement one real
MediaEmbedderfrom 09.9, 7.3 — Gemini, Voyage or Cohere — behind the same protocol, re-run your recall eval, and compare against the fake. Watch for therole/input_typeasymmetry each provider wants. - Cost and operations notes. Run
media_embed_cost.pyfrom 09.9, 4.4 with your catalogue size; write down what re-embedding on model change costs (09.9, Part 9) and what your access-control story is for media containing faces.
Verify it, and what you should see:
uv run python multimodal_search.py # lesson demo, real output
uv run python ingest.py # your catalogue -> caption+media branches
uv run python eval_recall.py # recall@3 per branch
uv run python dedup.py # near-duplicate report on your imagesExpected shape (your catalogue and fake differ; structure is what matters):
indexed 54 vectors (27 items -> caption+media branches; 3 near-dups skipped)
query: 'blue backpack' -> p002 rank 1 [caption] recall@3 caption=1.00 media=0.67
query: 'invoice total' -> p006 rank 1 [caption] recall@3 caption=1.00 media=0.33
image query 'red shoe' -> p001 rank 1 [media ] (media branch takes over)
recall@3 overall: caption 0.92, media 0.71, fused 0.95Done when:
- The service ingests your mixed-modality catalogue, dedups near-duplicates, and answers text and image queries with sensible rank-1 hits.
eval_recall.pyreports recall@k per branch and fused, on a labelled query set you can defend.- Video segments appear as searchable items with
start_s/end_smetadata and timestamped citations work end to end (fake or real answerer). - You can name which design pattern each corpus type uses and why, per the 09.9, 3.5 decision table.
- Your notes cover the modality gap's effect on your scores and the re-embedding cost of a model swap.
Stretch ideas:
- Hybrid retrieval: add BM25/keyword over captions alongside both vector branches (09.9, 4.2, 06.8).
- Late-interaction page retrieval for your PDF archive (ColPali-style, 09.9, 3.4) — the pattern for layout-heavy documents.
- VLM reranking of top-N hits to fix the thin-margin problem the fake exposes (09.9, 5.4).
- Persist the index: swap
NumpyVectorStorefor a real store per 06.5 — theVectorStoreprotocol means one adapter. - Hosted, needs keys: wire
GeminiEmbedder/VoyageEmbedder/CohereEmbedderand a realVlmCaptioner, re-run the recall eval, and compare providers on your data — the only honest way to pick an embedding model.
Common problems:
- Media-branch results look random. That's the modality gap plus a text-only fake — real media embeddings close most of it, but expect cross-modal scores on a different scale and set thresholds per branch (09.9, Part 2).
- Everything retrieves the same item. Check your caption coverage — items with empty captions only exist in the media branch, and the fake's keyword mapping is deliberately crude. Real captions change the ranking completely.
- Dedup eats distinct products. Tune the Hamming threshold on your images; product shots of similar items sit close together (09.9 exercise 3).
- Video segments have no good captions.
fake_describeoutput is canned — real segment captions need the frame-sampling pipeline from 09.8, Part 3 plus a VLM call. - Recall looks great but answers are wrong. Retrieval finds the right item; the VLM still has to read it. That's the RAG half — citations and context budget are 09.9, Part 6's subject, and evaluation depth is Module 10A's.
That closes the module. The index maps every lesson; Module 10A: Evaluation Foundations takes over the eval methodology these projects only preview; Modules 11A to 11C own the operations depth; Module 12 owns the security depth; and Module 13B is where the capstones are built.