09.9 Multimodal Embeddings and Retrieval

Agents & multimodalLesson 9 of 1012,802 wordsOptional9 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

Module 06 taught you to embed text and search vectors. This lesson takes the same machinery and points it at everything else a product might need to find: product photos, scanned invoices, slides, video clips, podcast episodes, design assets. A multimodal embedding maps text, images, audio, video and document pages into one shared vector space, so a sentence can retrieve a picture and a picture can retrieve a sentence. This lesson is about building search and retrieval on top of those vectors: which models exist as of November 2026, why the shared space has a geometric quirk called the modality gap, the four design patterns for multimodal retrieval, how to index media cheaply, the query types you will actually see, how multimodal RAG answers questions from pictures and pages, and a complete search-service skeleton you can adapt.

What you'll learn

  • The multimodal embedding landscape as of November 2026: Gemini's gemini-embedding-2, Voyage's voyage-multimodal-3.5, Cohere's Embed v5/v4, Jina's v5-omni, open-weight families (CLIP, SigLIP, ImageBind, Qwen3-VL-Embedding, the ColPali/ColQwen late-interaction line), plus the cloud routes (AWS Titan, Google Cloud, OpenRouter) — and which of the four path providers can't do it at all
  • What "one shared space" really means, and the modality gap: why text-to-text and image-to-text scores sit on different scales, demonstrated on synthetic vectors you can run yourself
  • The four design patterns — embed raw media, describe-then-embed, hybrid both, and late-interaction page retrieval — with a decision table
  • Indexing media: what to store in the payload, how to "chunk" a video, an audio file or a PDF page, perceptual-hash deduplication, hybrid caption-plus-vector search, and the cost arithmetic of embedding pixels and seconds
  • The query types: text-to-media, visual search, "like this but…" refinement and its limits, cross-modal reranking with a VLM, and query rewriting
  • Multimodal RAG: retrieving media items and answering with a vision model, citing pages/regions/timestamps, page-image RAG vs text-extraction RAG, and how images eat your context budget
  • A complete multimodal search service: a MediaEmbedder protocol with provider adapters, a pure-NumPy index you can run today, a captioning pipeline, and a query API
  • Operations and privacy: faces and biometrics, copyright, storage costs, re-embedding on model change, and access control on media

What you don't need

  • API keys for most of the lesson. Every concept has a pure-Python or pure-NumPy part you can run with no network at all; the provider calls are labelled illustrative and written against the official documentation.
  • The embedding fundamentals. Vectors, cosine similarity, embedding APIs, vector databases, hybrid search, reranking and retrieval metrics are Module 02 and Module 06; this lesson links to them and adds the multimodal layer on top.
  • A running vector database. The service skeleton in Part 7 runs on a NumPy store; swapping in Qdrant, pgvector or Pinecone is 06.5's subject.

Setup

The runnable parts need Python 3.11+ and NumPy; the perceptual-hashing sample also uses Pillow. If you don't have a project yet:

bash
uv init multimodal-search --bare --python 3.13 && cd multimodal-search
uv add numpy pillow python-dotenv
# or: pip install numpy pillow python-dotenv

The samples were checked against pillow 13.0.0 as of November 2026; a plain install gives you the newest release.

Provider samples additionally need the provider SDKs from earlier modules and keys in .env (see lesson 03.1 for the file format):

bash
uv add openai google-genai voyageai cohere
# or: pip install openai google-genai voyageai cohere

These were checked against openai 3.42.1, google-genai 2.34.0, voyageai 0.5.0 and cohere 7.3.1 as of November 2026. A plain install gives you the newest release; the multimodal embedding endpoints are the newest part of each SDK, so check the changelog if a request class or parameter is missing.

bash
# .env  (never commit this file)
GEMINI_API_KEY=...   # optional
VOYAGE_API_KEY=...
COHERE_API_KEY=...
JINA_API_KEY=...
OPENROUTER_API_KEY=...   # optional gateway

You only need the keys for the providers you actually call — and you can skip every hosted call and still learn the whole pipeline, because the service in Part 7 ships with a deterministic fake embedder.


What you must be able to do after this lesson#

  • Explain the modality gap in a shared embedding space
  • Choose a multimodal retrieval design pattern
  • Index images, audio, video and PDF pages for search
  • Run text-to-media and visual search queries
  • Answer questions over retrieved media with citations

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Can we search product photos by describing them?" Part 1, Part 5
"Why do image results score lower than text results for the same query?" Part 2
"Should we embed the image, the caption, or both?" Part 3
"How do we search scanned PDFs without OCR?" Part 3, Part 6
"Embedding a video costs what, exactly?" 4.4 Embedding-cost arithmetic
"Why did the same catalogue re-embed cost a fortune?" 4.4 Embedding-cost arithmetic, 4.5 Deduplication and near-duplicates
"The vector search found the right page but the answer was wrong." Part 6
"We need to show the customer where in the document the answer is." 6.3 Citations: pages, regions and timestamps
"Can we do 'find images like this one but bluer'?" 5.3 Image-plus-text refinement
"Which embedding model should we use for our image library?" Part 1, 3.5 The design-pattern decision table
"Is it safe to store face embeddings next to product photos?" Part 9

Part 1: The multimodal embedding landscape#

Reference

1.1 What "multimodal embedding" means here#

02.3, 10.4 introduced the idea with CLIP: an image encoder and a text encoder trained together so a photo and its caption land near each other. This lesson uses the term in its 2026 sense: a model that maps two or more modalities into one shared vector space, so any modality can be compared with any other by cosine similarity. The modalities that matter for retrieval products are:

Modality Typical retrieval item Typical query
Text captions, OCR text, transcripts, metadata a sentence
Image product photos, page scans, figures, design assets a sentence, or another image
PDF page one rendered page = one "image" to the model a sentence
Video sampled frames or a clip segment a sentence, or a frame
Audio a spoken segment or whole clip a sentence, or an audio clip

Two architectures produce these vectors, and the difference drives almost every decision later in the lesson:

  • Two-tower (CLIP-style): separate encoders per modality, trained with a contrastive loss so matching pairs are close. Cheap at query time, but the towers can drift apart — this is the origin of the modality gap in Part 2.
  • Single-backbone: one transformer reads interleaved text and media tokens (Voyage's multimodal models, Jina's v5-omni, Google's gemini-embedding-2, Qwen3-VL-Embedding). Often better cross-modal alignment, at the cost of heavier inputs — you send the actual pixels or audio, not a pre-computed feature.

1.2 The hosted models, verified as of November 2026#

This table is the landscape you will actually choose from. Every row was checked against the provider's official documentation or model page; each row cites the official page it was verified on. Prices move — treat them as "as of November 2026" and re-check the linked pricing page before you commit.

Provider / model Modalities in → vector Max input Dims Price structure (Nov 2026)
Google gemini-embedding-2 (Gemini API, also on Vertex AI and OpenRouter) text, image, audio, video, PDF — one space 8,192 tokens shared across modalities 128–3,072 (default 3,072; recommended 768/1,536/3,072; Matryoshka) per modality: text $0.20/M tok, image $0.45/M tok ($0.00012/img), audio $6.50/M tok ($0.00016/s), video $12.00/M tok ($0.00079/frame); Batch API 50% off; free tier exists but Google may train on free-tier content
Voyage voyage-multimodal-3.5 interleaved text, image, video 32k tokens 1,024 default; 256/512/2,048 options $0.12/M text tokens plus $0.60/B image pixels; images clamped to 50k–2M pixels ($0.00003–$0.0012 each); first 200M tokens + 150B pixels free
Cohere embed-v5.0-pro / embed-v5.0-fast text, images, fused text+image (PDF pages as mixed inputs) 128k tokens 256–2,048 (default 2,048; Matryoshka) $0.12/M tok (pro), $0.08/M tok (fast); image tokens billed separately (~$0.40/M image tokens); trial keys free. Figures as stated in Cohere's Embed 5 launch post (30 September 2026; see also 06.1); Cohere's pricing pages show no per-token figure, so confirm in your dashboard
Cohere embed-v4.0 text, images, mixed 128k 256–1,536 (default 1,536) ~$0.12/M tok (reported; not on Cohere's pages, check your dashboard)
Jina jina-embeddings-v5-omni-small / -nano text, image, audio, video, PDF 32k / 8k tokens 1,024 / 768 (Matryoshka to 32) open weights (API also hosted); video = 32 uniformly sampled frames; text-only output byte-identical to v5-text
Jina jina-clip-v2 text + image only — — lighter option, still offered
AWS amazon.titan-embed-image-v1 (Bedrock) text + image (English only) 256 text tokens; image ≤25 MB, ≤2,048×2,048 px 256/384/1,024 (default 1,024) Bedrock on-demand pricing; older model (2023) but still listed Active
Google Cloud multimodalembedding@001 (Vertex AI) text, image, video (no audio, no PDF; video embeddings ignore the soundtrack) text: English only, ~32 tokens; images resized to 512×512, ≤20 MB; video analysed 2 minutes at a time 1,408 default; 128/256/512 options the older Vertex multimodal model, still listed beside gemini-embedding-2 on Vertex AI's multimodal embeddings page (checked 2026-11-08); for new work on Vertex prefer gemini-embedding-2, which covers all five modalities, and don't mix the two models' vectors
OpenRouter /embeddings whatever the routed model supports — gemini-embedding-2 is listed with per-modality pricing per model per model pass-through pricing; input_type and multimodal input accepted where supported

Two important absences:

  • OpenAI has no multimodal embedding endpoint. text-embedding-3-small and text-embedding-3-large accept text only — the input parameter is a string, token array or list of strings, and the model cards list "Input modalities: text". If your corpus is images, OpenAI embeddings alone cannot see them; you caption first (Pattern 2 below) or use another provider.
  • Anthropic has no embeddings API at all — text or otherwise — as 06.1 established; Anthropic's own docs point users to Voyage AI for embeddings.

1.3 Open-weight models: run them yourself#

When data can't leave your infrastructure — medical images, internal design assets, anything under a strict retention policy — the open-weight families are the answer. As of November 2026 the credible options are:

Family What it does Notes for retrieval
CLIP (OpenAI, 2021) and OpenCLIP image ↔ text, two towers the original; still the baseline everyone compares against; many fine-tuned variants on Hugging Face
SigLIP / SigLIP 2 (Google) image ↔ text, sigmoid loss instead of softmax often better than CLIP at similar size; SigLIP 2 (February 2025, Apache-2.0 on the Hub) adds multilingual and dense-feature training, e.g. google/siglip2-so400m-patch14-384; the first-generation google/siglip-so400m-patch14-384 is still widely downloaded; both run in transformers (SigLIP 2 checkpoints)
ImageBind (Meta, 2023) binds six modalities (image, text, audio, depth, thermal, IMU) through image-pair training the classic "embed anything" research model; heavy, and its non-image modalities are weaker than dedicated models
Qwen3-VL-Embedding (Alibaba, 2B and 8B) text, image, screenshot, video, mixed — one space 32K context; native dims 2,048 (2B) and 4,096 (8B) with Matryoshka (MRL) truncation; instruction-aware; Apache-2.0; 33 languages; the model card reports MMEB-V2 overall 77.8 for the 8B and 73.2 for the 2B, the best of the models in its comparison table when published (it also lists a closed Seed-1.6 model at 76.9), so check the live MMEB leaderboard rather than assuming it still tops it; ships with Qwen3-VL-Reranker (2B, 8B) cross-encoders for the second stage (model card)
ColPali → ColQwen → ColQwen3 page images as multi-vector (late interaction) not a single-vector model — see 3.4; the foundation of visual document retrieval. The official vidore Hub organisation publishes ColPali, ColQwen2 and ColQwen2.5 checkpoints; checkpoints named "ColQwen3" on the Hub (for example TomoroAI/tomoro-colqwen3-embed-4b and -8b, whose cards list Apache-2.0 as of 9 November 2026) come from other organisations, so read each model card and licence
NVIDIA Nemotron ColEmbed late-interaction visual document embeddings nvidia/nemotron-colembed-vl-4b-v2 and -8b-v2 (built on Qwen3-VL), plus nvidia/llama-nemotron-colembed-vl-3b-v2; the 8B card says it ranked No. 1 on ViDoRe V3 as of 26 January 2026 with a score of 63.54, a dated claim that may have moved. Licence: CC-BY-NC-4.0, non-commercial — not usable in a commercial product without a separate agreement with NVIDIA (model card)

Practical notes:

  • Hardware is the real cost. A 2B–8B VLM-based embedder wants a GPU for reasonable throughput; CLIP/SigLIP-scale models (150M–900M) run on CPU for modest corpora. sentence-transformers and fastembed (ONNX Runtime, CPU-friendly — 06.1, 4.x) are the usual loaders.
  • Licences vary. CLIP is MIT; SigLIP weights have their own terms; Qwen models carry Apache-2.0 or custom licences depending on size — check each model card before commercial use. Jina's open weights are CC BY-NC (non-commercial) per 06.1.
  • You now own the pipeline. Self-hosting means you own batching, quantization (int8 vectors are ~4× smaller, binary ~32×, than float32 — 06.4, Part 4), versioning and re-embedding. That's 06.2's subject, applied to bigger inputs.

1.4 Input limits and pricing per modality#

The limits that bite in production, verified November 2026:

Gemini gemini-embedding-2 (aistudio.google.com/docs/embeddings):

  • 8,192 tokens shared across all modalities in one request; input beyond that is silently truncated — the tail of your document just disappears.
  • Image: up to 6 per request, PNG/JPEG (the Vertex docs list a wider set: WebP, BMP, HEIC, HEIF, AVIF), max 16,384×16,384 px; billed 258 tokens per image.
  • Audio: ≤180 s, MP3/WAV; 25 tokens per second.
  • Video: ≤120 s; the Gemini API docs say the system processes a maximum of 32 frames (short clips at 1 fps, longer clips uniformly sampled to 32), while the Vertex doc describes "up to 120 frames" at 66 tokens per frame — the two Google docs disagree on the frame cap; check the current page for your surface. Audio tracks inside video files are not processed.
  • PDF: 1 file, ≤6 pages; rendered as images at 258 tokens per page (plus OCR text tokens if enabled).
  • Upgrading from gemini-embedding-001: the older text-only model (still available, $0.15/M input tokens, as of November 2026) and gemini-embedding-2 live in incompatible spaces, so moving means re-embedding the whole corpus. The API shape also changes: 001 takes a task_type (RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, …), while 2 has no task_type and uses the text prefixes shown in 2.2 and 7.3; 2 also normalises truncated (output_dimensionality below 3,072) vectors for you, whereas 001 needs manual normalisation (checked on the embeddings page and pricing page, 2026-11-08).

Voyage voyage-multimodal-3.5: 32k tokens; accepts interleaved text, image_url, image_base64, video_url, video_base64 content pieces (text + image + video — no audio); images under 50k pixels are upscaled and billed as 50k, over 2M pixels downsampled and billed as 2M. Hard per-call caps that bite in production: ≤1,000 inputs per call, each image ≤16M pixels and ≤20 MB, each video ≤20 MB; tokens are counted at 1 per 560 image pixels and 1 per 1,120 video pixels (32k per input, 320k per call).

Cohere Embed v5/v4: inputs array (max 96 per call) where each input's content mixes {"type": "text"} and {"type": "image_url"} pieces — this is the natural shape for "embed this PDF page screenshot with its caption". Images via images (data URIs) cap at 20 MB combined on v4+; the v3 family is limited to 1 image per call at 5 MB. Rate limits are much tighter for images than text: the Embed endpoint allows 2,000 inputs/minute on both trial and production keys, but image embedding is capped at 5 inputs/min on trial keys vs 400/min on production (06.1).

Jina v5-omni: pass typed objects (image, audio, video, pdf keys with URL or base64) in the input array; PDF input is supported — pages are rendered as images and processed through the vision pathway (the model cards don't state a per-request file cap, so chunk large PDFs yourself); audio WAV/MP3/FLAC/OGG/M4A/Opus; video as 32 frames.

AWS Titan image embeddings: English only, 256 text tokens max, image ≤25 MB and ≤2,048×2,048 px, output 256/384/1,024 dims. It's a 2023 model — fine for simple image search, but don't expect it to compete with 2026 frontier embedders on charts or documents.

1.5 The provider-coverage table for this lesson#

Capability OpenAI Anthropic Gemini OpenRouter Voyage Cohere Jina Open weights
Multimodal embedding API ❌ text only ❌ none ✅ gemini-embedding-2 ✅ routes to models that have it ✅ voyage-multimodal-3.5 ✅ Embed v4/v5 ✅ v5-omni ✅ CLIP/SigLIP/Qwen3-VL/ColPali
Used here as — (caption first) — primary example aggregator route specialist specialist open weights + API self-hosted

Part 2: Shared-space semantics and the modality gap#

2.1 What the modality gap is#

A multimodal embedding model promises "one space", but in practice the space is often lumpy: image vectors cluster in one region, text vectors in another, audio somewhere else — even when image and its perfect caption should be neighbours. Liang et al. (2022), Mind the Gap: Understanding the Modality Gap in Multi-modal Contrastive Representation Learning (NeurIPS 2022), showed this geometrically for CLIP: the two modalities sit "at arm's length", a gap created by model initialisation and preserved by the contrastive loss. Later work found the gap varies by model — single-backbone designs like Voyage's and Jina's narrow it, and some 2026 models market "no modality gap" explicitly — but no model eliminates the engineering problem entirely: scores are only comparable within a modality pair you have measured.

Why it matters to you as an engineer:

  1. Scores aren't portable across modality pairs. A cosine of 0.35 might be an excellent text→image match and a terrible image→image match. Never reuse one global threshold.
  2. Same-modality bias. In two-tower models, a text query can retrieve irrelevant text chunks over a relevant image simply because text vectors live nearer other text vectors. Voyage's docs call this out explicitly as the failure CLIP-style architectures have and their single-backbone design avoids.
  3. Arithmetic breaks. "Image vector minus text vector plus another text vector" (the classic word-arithmetic trick from 02.3, 2.6) mostly doesn't transfer across the gap — see 5.3.

2.2 See it: a synthetic modality gap#

You can demonstrate the effect without any model. Build a toy space where "text" and "image" vectors of the same item are pulled apart by a constant offset — exactly what the gap looks like — then run a text query and watch what it retrieves:

python
# modality_gap_demo.py — pure NumPy, deterministic (seed 0). Run: uv run python modality_gap_demo.py
import numpy as np

rng = np.random.default_rng(0)
DIM = 17
GAP = np.zeros(DIM); GAP[16] = 0.9          # every image vector is pushed along a dim no topic uses

def unit(v):
    return v / np.linalg.norm(v)

# 4 "items": each has a text vector and an image vector for the same thing.
# Items 0-1 are about "red shoes"; items 2-3 about "blue hats".
topics = [np.array([1,0,0,0] + [0]*13, float),
          np.array([0,1,0,0] + [0]*13, float),
          np.array([0,0,1,0] + [0]*13, float),
          np.array([0,0,0,1] + [0]*13, float)]

corpus = []   # (kind, item, vector)
for i, t in enumerate(topics):
    corpus.append(("text",  i, unit(t + 0.05 * rng.standard_normal(DIM))))
    corpus.append(("image", i, unit(t + GAP + 0.05 * rng.standard_normal(DIM))))

query = unit(topics[0] + 0.05 * rng.standard_normal(DIM))   # "something like item 0", as TEXT

scores = [(kind, item, float(unit(v) @ query)) for kind, item, v in corpus]
scores.sort(key=lambda x: -x[2])
print("query: a TEXT vector near topic 0 ('red shoes')")
for kind, item, s in scores:
    print(f"  {s:+.3f}  {kind:5s} item {item}")

same_text = [s for k, i, s in scores if k == "text"]
same_image = [s for k, i, s in scores if k == "image"]
print(f"\nbest text-vector score : {max(same_text):+.3f}")
print(f"best image-vector score: {max(same_image):+.3f}")
Output12 lines
query: a TEXT vector near topic 0 ('red shoes')
  +0.974  text  item 0
  +0.685  image item 0
  +0.067  text  item 1
  +0.055  image item 3
  +0.031  text  item 3
  -0.032  image item 1
  -0.080  text  item 2
  -0.088  image item 2

best text-vector score : +0.974
best image-vector score: +0.685

The toy exaggerates the gap (a real model's offset is subtler), but the lesson is exact: the image vector for the correct item scores 0.69 while the matching text vector scores 0.97 — a ~0.29 drop caused by nothing but which modality produced the vector. A threshold of 0.8, sensible for text-to-text, would return the text match and silently drop the image match. This toy is too clean to show the mirror-image problem — on a real embedder, a threshold of ~0.6 tuned on image pairs would sit inside the text near-miss mass and flood text results with borderline hits; that's an extrapolation from how real score distributions look, which is exactly why you calibrate thresholds on your own labelled data per modality pair (Part 6, 6.5) rather than reusing one.

2.3 What else differs across modalities#

Beyond the gap, three modality-specific quirks change retrieval behaviour:

  • Information density differs. One image token-budget buys far more "content" than one text token — a 258-token image carries a whole scene. Dense media vectors are "broader" (they average many objects), so precision on specific details (a SKU printed on a box, a timestamp on a slide) is weaker than on text. This is the same gist-vs-detail trade-off 02.3, 10.6 describes for long text, amplified.
  • Temporal structure is lost or sampled. Video embeddings see a handful of frames (32 for Gemini, 32 for Jina); audio sees the whole clip but compresses it to one vector. "The moment the presenter shows the chart" is not reliably retrievable from a single vector — you need segments (4.3).
  • Length limits truncate silently. Gemini truncates past 8,192 shared tokens without error; Voyage truncates per its own rules; local models often warn once at load. Check usage/metadata on every response — 03.6, 3.3 covers the counting discipline for generation models; the same habit applies to embedding calls.

Part 3: The four design patterns#

Every multimodal retrieval system is one of four patterns — or a deliberate combination. The choice is the single most consequential decision in this lesson, so it gets a full section.

3.1 Pattern 1: embed the raw media#

Send the image, page render, video segment or audio clip straight to a multimodal embedding model and store the vector. This is what gemini-embedding-2, voyage-multimodal-3.5, Cohere Embed v4/v5 and Jina v5-omni are built for.

flowchart LR
    subgraph index [Index time]
        M["media item<br/>(image / page / clip)"] --> E["multimodal embedder"]
        E --> V[("vector store<br/>+ payload")]
    end
    subgraph query [Query time]
        Q["text or media query"] --> QE["same embedder"]
        QE --> S["cosine top-k"]
        V --> S
        S --> R["media items + payload"]
    end

When it's right:

  • The visual itself carries the meaning — product photos, design assets, charts, screenshots, handwritten notes, photos of physical objects.
  • You have (or can get) a multimodal embedding model that covers your modalities.
  • Cross-modal queries matter: "find the photo of the red sneaker" must match pixels, not just a caption someone wrote.

Costs and catches:

  • You pay per pixel/second/token of media — see 4.4. On a pixel-priced model such as Voyage the bill follows pixel count between its 50k and 2M clamps, so a 2-megapixel product shot costs 40× a tiny thumbnail billed at the 50k minimum (and a 16-megapixel original is billed as 2 megapixels anyway).
  • Resolution matters: downscale before embedding loses detail the model might have used; keep the original for display and embed a standardised size.
  • Some content is invisible to embeddings: fine print, exact colours specified by Pantone, serial numbers. The vector gets you close; the VLM rerank or the user finishes the job.

3.2 Pattern 2: describe, transcribe, OCR — then embed text#

Run the media through a perception model first — a VLM caption (09.1), OCR (05.4), speech-to-text (09.4) — then embed the resulting text with any text embedder (including OpenAI's or Anthropic's Voyage route). This is the classical RAG pattern applied to media.

When it's right:

  • The text layer is what users actually search for: invoices, contracts, transcripts, spec sheets, slide decks.
  • You already have OCR/ASR/VLM infrastructure and want one text index for everything.
  • Cost or privacy pushes you to a cheaper text embedder — text tokens are far cheaper than pixels.
  • The media model you need doesn't exist for your modality (e.g. OpenAI-only shops embedding audio).

Costs and catches:

  • You inherit every failure of the front-end model. A misread total, a hallucinated caption detail or a dropped speaker becomes a permanent retrieval blind spot — the vector can't recover what the caption never said. Mitigate with the validation habits from 09.2 and by keeping the source media linked for verification.
  • Two pipeline stages = two things to version, monitor and pay for (05.9).
  • Captions compress: a 5 MB page scan becomes ~500 tokens of description. Great for recall on topics, weak on exact lookup — which is why 4.2 exists.

3.3 Pattern 3: hybrid — embed both, search both#

Store two vectors per item (or one vector per modality piece): the raw-media embedding and the caption/OCR/transcript embedding, plus the caption text itself for BM25. At query time, run both retrievers and fuse — the hybrid machinery is 06.8's, applied across modalities.

flowchart TB
    subgraph doc ["One catalogue item"]
        IMG["product photo"] --> ME["media embedder"] --> MV[("media vector")]
        IMG --> CAP["VLM caption + attributes"] --> TE["text embedder"] --> TV[("text vector")]
        CAP --> BM[("BM25 index")]
    end
    subgraph q ["Query: 'blue running shoe, women'"]
        Q1["text embedder"] --> QS
        Q2["media embedder (optional)"] --> QS
        QS["score + fuse (RRF)"] --> TOP["top-k items"]
    end
    MV --> QS
    TV --> QS
    BM --> QS

When it's right:

  • You don't know ahead of time whether queries will be visual ("the shoe with the swoosh") or textual ("running shoe size 8").
  • Recall matters more than index cost — media corpora are usually small enough (thousands to low millions of items) that two vectors per item is affordable.
  • You want the caption text searchable by BM25 for exact terms (SKUs, model numbers) that embeddings mangle — the same argument 06.8, Part 1 makes for text.

Costs and catches:

  • Roughly double embedding cost and double index size (still small next to storing the media itself).
  • Fusion across modalities needs care: a media-vector score and a text-vector score aren't on the same scale — use rank fusion (RRF) or per-branch normalisation, not raw-score addition. 06.8, Part 2 covers this; the modality gap makes it more important, not less.
  • More moving parts: two embedders, two (or three) indexes, a fusion step. Earn it with eval data (6.5), not vibes.

3.4 Pattern 4: late-interaction page retrieval#

The odd one out. Instead of one vector per page, models like ColPali/ColQwen (and the newer ColQwen3, NVIDIA's Nemotron ColEmbed) embed a page image into hundreds of token-level vectors — one per image patch. A text query is also tokenised; matching uses MaxSim: for each query token, take the best-matching patch vector on the page, then sum. The math is 06.9, Part 5 (late interaction) and 06.3, Part 9; what changes here is that the "document" is a picture.

When it's right:

  • Visually complex documents where layout is the content: PDFs with tables, figures, multi-column scans, forms, slides, comics, sheet music — the ViDoRe benchmark ColPali was built for.
  • You want to skip OCR entirely: the model reads the rendered page directly, so handwriting-ish print, stamps and unusual fonts survive.
  • You can run a VLM-scale model (2B–8B) — these are not CPU-friendly.

Costs and catches:

  • Index size explodes. A page becomes ~100–1,000 patch vectors (a few hundred is typical for ColPali-style models at 32–128 dims per token). A 100k-page archive is tens of millions of vectors — you need a store with multi-vector support (Qdrant named/multivector collections, or dedicated ColBERT-serving infrastructure; check 06.5 for what your store supports as of November 2026).
  • Query latency is higher — MaxSim over hundreds of vectors per page candidate, though still milliseconds-scale with the right index.
  • It's a retrieval model, not a generator: you still send the winning page image to a VLM for the answer (Part 6).

Trying it (verified tooling, November 2026):

  • sentence-transformers v6 MultiVectorEncoder — the current recommended path. from sentence_transformers import MultiVectorEncoder; model = MultiVectorEncoder("vidore/colqwen2-v1.0-hf") loads ColPali/ColQwen checkpoints (and newer ColQwen3 / Nemotron ColEmbed ports — some need a revision= pin or trust_remote_code=True); encode_query/encode_document return per-token vectors and .similarity() computes MaxSim. Install the image extra for page-image inputs. See the Sentence Transformers multi-vector docs.
  • byaldi (AnswerDotAI) — RAGatouille's ColPali wrapper: RAGMultiModalModel.from_pretrained(...) indexes a folder of PDFs or images and answers searches with a familiar API. Still pre-release (v0.0.7, November 2024, no later release) — fine for experiments, not for production.
  • colpali-engine — the original training/inference package behind the ColPali paper; deprecated upstream, which now points new projects at MultiVectorEncoder. Useful for reading the reference implementation and reproducing papers.
  • Vector stores: the colpali-engine repo links official tutorials for Qdrant (multivector collections) and Elastic — check 06.5 before choosing.

3.5 The design-pattern decision table#

Your situation Start with Upgrade to when…
Product photos, design assets, "find similar" Pattern 1 (media embedder) queries need exact attributes → add caption text + BM25 (Pattern 3)
Invoices, contracts, reports — text is the content Pattern 2 (OCR/VLM → text embed) scans are visual-heavy (stamps, signatures, tables-as-images) → add page-image vectors (Pattern 3)
Mixed catalogue, unknown query mix Pattern 3 from the start eval shows one branch dominating → simplify to the winner
Archival PDFs, ViDoRe-style visual retrieval, no OCR pipeline Pattern 4 (ColPali/ColQwen) corpus outgrows multi-vector storage → fall back to page-image single vectors (Pattern 1) or OCR+text (Pattern 2)
Only OpenAI/Anthropic keys available Pattern 2 (their chat models caption/OCR; Voyage or Gemini embeds the text) —
Strict privacy, no media leaves the building Open-weight Pattern 1 (SigLIP/Qwen3-VL) or Pattern 4 self-hosted —

Part 4: Indexing media#

4.1 What to store per item#

A media record is a superset of the text-chunk record from 05.8. The vector store payload should carry everything needed to display, cite and filter the hit without a second lookup:

Field Why
id stable, content-addressed where possible (05.8, Part 3)
vector (+ vector_kind: media / caption / page-patch) the embedding itself; name the branch so fusion and debugging know which space a score came from
media_url or storage_key where the bytes live (object storage + signed URL — operations in Part 9)
thumbnail_url results grids need a small image; never ship the original
caption / ocr_text / transcript the Pattern-2/3 text; also what BM25 indexes
modality image / pdf_page / video_segment / audio_segment — required for per-pair thresholds (2.2)
page, bbox, timestamp_start, timestamp_end citation targets (6.3)
source, tenant, content_type, created_at filtering, ACLs and freshness — 06.6 owns the filter machinery; media makes it more important (see 9.4)
content_hash, phash dedup and change detection (4.5, 05.9)
embedding_model, embed_spec_version re-embedding bookkeeping (9.1)

4.2 Hybrid: caption text + media vector#

The strongest general-purpose layout for image/document corpora is three retrieval channels over one item, exactly the 06.8 pattern widened by one modality:

  1. Media-vector channel — raw image/page/clip embedding (Pattern 1).
  2. Caption-vector channel — embedding of the VLM caption / OCR text / transcript (Pattern 2).
  3. Keyword channel — BM25 over caption + OCR + metadata (06.7).

Fuse with RRF or per-channel normalisation (06.8, Part 2). The failure mode to watch: the caption channel and media channel often agree too much (the caption was generated from the image), so effective diversity comes from the BM25 channel and from query routing — send exact-term queries (SKUs, dates, names) mostly to BM25, conceptual queries mostly to the vectors (06.8, 5.2).

4.3 Chunking media for retrieval#

Text chunking (05.6, 05.7) has a media analogue for every modality:

Modality The "chunk" How to split What goes in the payload
PDF / scanned page one page render (or a region of a huge page) per page; split oversized pages into overlapping tiles for Pattern-1 embedding page, bbox, render DPI, OCR text
Image the whole image if small; tiles if large fixed grid or saliency crops for images >~1–2 MP; keep aspect ratio bbox per tile, parent image id
Video a time window (scene-aligned if possible) scene-change detection or fixed windows with overlap; embed N frames per segment or let the model sample (Gemini caps at 32) start_s, end_s, frames used, transcript slice
Audio a speaker turn or fixed window with overlap VAD/speaker-diarization boundaries (09.4 owns STT); embed per segment start_s, end_s, speaker label, transcript
Slide deck one slide per page of the PDF render slide number, title

Rules that carry over from text chunking:

  • Overlap matters less for media — a video segment boundary that clips a sentence is fixed by the transcript channel; an image tile that cuts an object is fixed by keeping tiles generous (20–30% overlap) and by the parent-image fallback.
  • Segment size is a cost/recall dial. Shorter video windows = more precise citations but more embeddings and more index rows; longer windows = cheaper but vaguer. Start at ~10–30 s for meeting/video search, measure, adjust.
  • Store the segment's own text. Every media chunk should carry its transcript/OCR slice so the keyword channel and the citation can quote it.

4.4 Embedding-cost arithmetic#

Media embedding is priced in different units per provider, so build the estimate per modality. The calculator below uses the verified November 2026 prices from Part 1 as parameters — look up current prices before trusting the output:

python
# media_embed_cost.py — pure Python, real output. Run: python3 media_embed_cost.py

# Prices as of November 2026 (USD). Verify on each provider's pricing page.
GEMINI_EMBED2 = {"text_per_mtok":0.20,"image_per_mtok":0.45,"image_tokens":258,
                 "audio_per_mtok":6.50,"audio_tokens_per_s":25,"video_per_mtok":12.00,
                 "video_tokens_per_frame":66}
VOYAGE_MM35 = {"text_per_mtok":0.12,"pixels_per_b":0.60,"min_px":50_000,"max_px":2_000_000}

def clamp_px(px):
    return min(max(px, VOYAGE_MM35["min_px"]), VOYAGE_MM35["max_px"])

def gemini_cost(items):
    """items: list of (modality, amount): text tokens, image count,
    audio seconds, or video seconds."""
    total = 0.0
    for mod, amt in items:
        if mod == "text":
            total += amt / 1e6 * GEMINI_EMBED2["text_per_mtok"]
        elif mod == "image":
            total += amt * GEMINI_EMBED2["image_tokens"] / 1e6 * GEMINI_EMBED2["image_per_mtok"]
        elif mod == "audio":
            total += amt * GEMINI_EMBED2["audio_tokens_per_s"] / 1e6 * GEMINI_EMBED2["audio_per_mtok"]
        elif mod == "video":
            frames = min(32, max(1, round(amt)))   # ~1 fps up to the 32-frame cap
            total += frames * GEMINI_EMBED2["video_tokens_per_frame"] / 1e6 * GEMINI_EMBED2["video_per_mtok"]
    return total

def voyage_cost(text_tokens, images):
    """images: list of pixel counts."""
    return (text_tokens / 1e6 * VOYAGE_MM35["text_per_mtok"]
            + sum(clamp_px(px) for px in images) / 1e9 * VOYAGE_MM35["pixels_per_b"])

# --- a product catalogue: 50k images, plus a month of queries ---
catalogue_images = [("image", 1)] * 50_000
queries = [("text", 20)] * 200_000                       # 200k text queries/mo

print("Gemini embed-2, 50k images @ ~258 tok each :", f"${gemini_cost(catalogue_images):.2f}")
print("Gemini embed-2, 50k images + 200k queries  :", f"${gemini_cost(catalogue_images + queries):.2f}")

# Voyage bills PIXELS not tokens: resolution directly changes the bill.
px_1mp = [1_000_000] * 50_000
px_4mp = [4_000_000] * 50_000     # clamped to 2M px each
print("Voyage mm-3.5, 50k imgs @1MP (50k text tok) :", f"${voyage_cost(50_000, px_1mp):.2f}")
print("Voyage mm-3.5, 50k imgs @4MP (clamped 2M)   :", f"${voyage_cost(50_000, px_4mp):.2f}")

# Video: one 10-minute clip vs ten 1-minute segments (each gets its own frame budget)
print("Gemini embed-2, one 10-min clip :", f"${gemini_cost([('video', 600)]):.4f}")
print("Gemini embed-2, 10x 1-min clips :", f"${gemini_cost([('video', 60)] * 10):.4f}")
Output6 lines
Gemini embed-2, 50k images @ ~258 tok each : $5.80
Gemini embed-2, 50k images + 200k queries  : $6.60
Voyage mm-3.5, 50k imgs @1MP (50k text tok) : $30.01
Voyage mm-3.5, 50k imgs @4MP (clamped 2M)   : $60.01
Gemini embed-2, one 10-min clip : $0.0253
Gemini embed-2, 10x 1-min clips : $0.2534

Read that carefully — the answers are counter-intuitive:

  • Gemini's per-image token price makes images cheap: 50k product photos ≈ $5.80 one-off (Google's pricing page rounds the per-image price to $0.00012, which would make it $6.00; either way, single dollars). Voyage's pixel pricing makes the same catalogue $30–60 — 5–10× more — because it bills megapixels.
  • Voyage clamps at 2M pixels, so a 4 MP image costs the same as an 8 MP one — but a 1 MP image still costs 5× a 200 kpx thumbnail. Resolution is a billing decision on Voyage and a token-count decision on Gemini (258 tokens regardless of size, up to the 16,384 px cap).
  • Segmenting video multiplies cost ~10× (each segment gets its own 32-frame budget). Index-time segmentation is a recall feature you pay for per segment — budget it.
  • The dominant term in a search product is usually queries × query cost, not the one-off index build. 200k queries added ~$1 here only because text is $0.20/M; on an image-query-heavy product (users uploading photos to search), re-run this with image queries.

4.5 Deduplication and near-duplicates#

Media corpora are full of duplicates: the same product shot re-uploaded, frames that differ by a re-encode, scanned copies of the same page. Exact content_hash catches byte-identical files (05.9, Part 2); perceptual hashing catches the near-identical ones.

A perceptual hash reduces an image to a tiny fingerprint that survives resizing, recompression and small edits:

  • aHash (average hash): shrink to 8×8 greyscale, compare each pixel to the mean → 64 bits.
  • dHash (difference hash): shrink to 9×8, compare each pixel to its right neighbour → 64 bits; usually more robust to brightness changes.
python
# phash_demo.py — pure Pillow + stdlib, real output. Run: uv run python phash_demo.py
import io
from PIL import Image, ImageDraw


def ahash(img: Image.Image, size: int = 8) -> int:
    """Average hash: 8x8 greyscale, each pixel vs the mean -> 64 bits."""
    g = img.convert("L").resize((size, size), Image.LANCZOS)
    px = list(g.tobytes())          # L mode: one byte per pixel
    avg = sum(px) / len(px)
    bits = 0
    for p in px:
        bits = (bits << 1) | (p > avg)
    return bits


def dhash(img: Image.Image, size: int = 8) -> int:
    """Difference hash: 9x8 greyscale, each pixel vs its right neighbour."""
    g = img.convert("L").resize((size + 1, size), Image.LANCZOS)
    px = list(g.tobytes())
    w = size + 1
    bits = 0
    for y in range(size):
        for x in range(size):
            bits = (bits << 1) | (px[y * w + x] > px[y * w + x + 1])
    return bits


def hamming(a: int, b: int) -> int:
    return bin(a ^ b).count("1")


def gradient_bg(top_left, bottom_right):
    img = Image.new("RGB", (128, 128))
    d = ImageDraw.Draw(img)
    for y in range(128):
        for x in range(128):
            t = (x + y) / 254
            c = tuple(int(a + (b - a) * t) for a, b in zip(top_left, bottom_right))
            d.point((x, y), c)
    return img


def make_product(colour, bg, box=(40, 30, 88, 92)):
    img = gradient_bg(*bg)
    d = ImageDraw.Draw(img)
    # a little 'scene': ellipse 'product' + a label stripe, like a catalogue shot
    d.ellipse(box, fill=colour)
    d.rectangle([44, 62, 84, 74], fill=(238, 238, 238))
    d.line([30, 100, 98, 100], fill=(120, 120, 120), width=2)
    return img


base = make_product((180, 30, 30), ((200, 210, 235), (150, 190, 230)))
# a genuinely different catalogue shot: dark scene, small object top-right
diff = Image.new("RGB", (128, 128), (24, 26, 30))
dd = ImageDraw.Draw(diff)
dd.rectangle([80, 16, 116, 52], fill=(30, 90, 200))
dd.line([10, 110, 118, 110], fill=(90, 90, 95), width=2)

buf = io.BytesIO()
base.save(buf, "JPEG", quality=60)
jpeg_reencoded = Image.open(io.BytesIO(buf.getvalue())).convert("RGB")

variants = {
    "original": base,
    "resized 50%": base.resize((64, 64)),
    "brightened +20": Image.eval(base, lambda p: min(255, int(p * 1.2))),
    "jpeg q60 re-encode": jpeg_reencoded,
    "object moved+resized": make_product(
        (180, 30, 30), ((200, 210, 235), (150, 190, 230)), box=(60, 50, 108, 100)),
    "different scene": diff,
}

print(f"{'variant':<24}{'aHash':>18}{'dHash':>18}{'ham(a)':>8}{'ham(d)':>8}")
for name, im in variants.items():
    a, d = ahash(im), dhash(im)
    print(f"{name:<24}{a:>#18x}{d:>#18x}"
          f"{hamming(a, ahash(base)):>8}{hamming(d, dhash(base)):>8}")
Output7 lines
variant                              aHash             dHash  ham(a)  ham(d)
original                0xffffe3c3c3e3ffff0xef97b36969b3d5bb       0       0
resized 50%             0xffffe3c3c3e3ffff0xef97b36969b3d5bb       0       0
brightened +20          0xffffe3c3c3e7ffff0xef97b36969b3d5ff       1       2
jpeg q60 re-encode      0xffffe3c3c3e3ffff0xed96b36969b2ddfb       0       5
object moved+resized    0xfffffff1f1e1f3fe0xfffefbdcdcd8e9b6      13      29
different scene            0x7070600000000 0x31313130c800501      46      30

Three honest lessons from that output:

  • Benign transforms are nearly free — resize, brightness and JPEG recompression all stay under ~5 bits; that's the design working.
  • Content changes separate cleanly — moving/resizing the object costs 13–29 bits, a different scene 30–46. Synthetic images are unusually hash-friendly (flat gradients, hard edges); real photos with texture, noise and clutter compress the gap between "same" and "different", which is why you test the threshold on your own corpus.
  • aHash and dHash disagree sometimes (29 vs 13 on the moved object) — run both and take the minimum distance, or pick whichever survives your worst-case transform. Typical dedup rule: hamming ≤ 5–10 = near-duplicate; tune it, don't guess it.

Use the hash for dedup at ingest (skip re-embedding a near-identical image — saves the embedding fee and keeps the index clean) and for "find duplicates" admin tools. For "visually similar but not identical" (the actual product-search job), the embedding does that work — perceptual hashes only answer "is this the same picture".


Part 5: Query types#

Deep-dive

Multimodal retrieval adds query shapes text search never had. Each has its own embedder call, its own score distribution and its own failure modes.

5.1 The query-type matrix#

Query type Example Embed the query as Searches
Text → media "red running shoe, women's" text vector image/page/clip vectors
Text → text-on-media "invoice total over $500" text vector caption/OCR/transcript vectors + BM25
Media → media upload a photo, "find similar" image vector image vectors (same-modality — usually the most reliable cross-modal-free case)
Media → text photo of a broken part → "find the manual page" image vector caption/text vectors
Hybrid → hybrid "like this shoe but in blue" image + text both channels, fused

The rule from 2.2 applies to every row: evaluate each (query-modality × doc-modality) pair separately. Image→image and text→image are different tasks with different score scales even on the same model.

5.2 Text-to-media: the flagship query#

"Describe it and find it" is the query that justifies multimodal embeddings. Engineering notes:

  • Query wording matters more than for text search. Embedding models respond to concrete visual language: "red sneaker side view on white background" beats "footwear item". For product search, consider an LLM query-expansion step (Module 07 owns query rewriting) that turns "I need something for my daughter's recital" into visual attributes. Keep the user's raw query for the keyword channel — expansion helps vectors, hurts exact match.
  • Attributes vs concepts. "Blue", "size 8", "under $50" are attributes — if they're in your metadata, filter on them exactly (06.6) rather than hoping the embedding caught them. Vectors handle the fuzzy part ("elegant", "looks like vintage").
  • Negatives are weak. "Shoe that is not red" doesn't subtract cleanly — embeddings don't do negation well (02.3, 10.6). Filter red out with metadata or post-filter.

5.3 Image-plus-text refinement, and its limits#

"Find images like this one but blue" tempts you toward vector arithmetic: v_image + (v("blue product photo") − v("product photo")). The honest answer: it mostly doesn't work across the modality gap, and even within one modality it's unreliable.

  • Word-arithmetic analogies (02.3, 2.6) are a curiosity of text embeddings trained on distributional semantics. "blue − red" is not a clean direction in image space; colour in a photo is entangled with lighting, material and scene.
  • What does work, in order of reliability:
    1. Attribute filter + image similarity: find visually similar items, then filter colour=blue in metadata. Works when colour is tagged.
    2. Text-query reformulation: send "blue version of this product" as a text query against caption vectors — the caption channel often carries colour words even when pixels don't dominate the vector.
    3. Iterative VLM refinement: retrieve top-k by image similarity, show them to a VLM with "which of these is blue?" — a rerank, not arithmetic (5.4).
    4. One fused query embedding: some models embed an image and a text instruction together as a single vector, so the "blue" is part of the query rather than arithmetic on two vectors. gemini-embedding-2 returns one aggregated embedding when you pass several parts (an image part and a text part) in one contents entry, while separate Content objects give separate embeddings; Cohere's inputs array has fused text+image items; Voyage's multimodal models take interleaved text and image pieces (1.2; Gemini behaviour checked on the embeddings page, 2026-11-08). Whether a fused query beats "similar images, then filter on colour" is an empirical question: put both on your eval set before choosing.
    5. Vector arithmetic — try it on your own model with your own eval set; on some 2026 embedders it helps marginally, on most it adds noise. Never ship it untested.

5.4 Cross-modal reranking with a VLM#

The two-stage pattern from 06.9 ports directly: embedding retrieves top-N (N=20–100), then a vision-language model reads query + candidate images/pages together and scores or re-orders. This is where the answer-quality jump happens, because the reranker sees pixels the bi-encoder compressed away.

python
# vlm_rerank.py — ILLUSTRATIVE: needs GEMINI_API_KEY + google-genai.
# Reranks image-search hits by asking a VLM to score each (query, image) pair.
import json
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

SCORE_PROMPT = """You are ranking product photos for a search query.
Query: {query}
Rate how well THIS image matches the query's visual intent.
Answer with a JSON object only: {{"score": <0-10>, "reason": "<10 words>"}}"""

def score_image(query: str, image_path: str) -> dict:
    img_bytes = Path(image_path).read_bytes()
    resp = client.models.generate_content(
        model="gemini-3.8-flash",          # any current VLM; see 02.9 model table
        contents=[
            types.Part.from_bytes(data=img_bytes, mime_type="image/jpeg"),
            SCORE_PROMPT.format(query=query),
        ],
        config=types.GenerateContentConfig(response_mime_type="application/json"),
    )
    return json.loads(resp.text)

def rerank(query: str, hits: list[dict]) -> list[dict]:
    """hits: [{"id":..., "image_path":...}] -> re-ordered by VLM score."""
    scored = []
    for h in hits:
        r = score_image(query, h["image_path"])
        scored.append({**h, "vlm_score": r["score"], "vlm_reason": r["reason"]})
    return sorted(scored, key=lambda h: -h["vlm_score"])
Example output · illustrative4 lines
query: "blue running shoe, side view"
hit sneaker_red_side.jpg   -> vlm_score 3  "red shoe, wrong colour"
hit sneaker_blue_side.jpg  -> vlm_score 9  "blue running shoe, side profile"
hit sneaker_blue_top.jpg   -> vlm_score 6  "blue shoe but top-down angle"

Engineering notes:

  • Cost control: the reranker sees N images × ~258–1,120 tokens each (03.6, Part 3). N=20–50 is the sweet spot; beyond that, use a smaller VLM or a specialist reranker (Jina's jina-reranker-m0 ranks page images against text queries — 06.9).
  • Batch the pairs. One call per (query, image) is N round-trips; where the API allows, send several images per call or use async concurrency (03.9).
  • The score is uncalibrated. A VLM's 0–10 is ordinal, not a probability — use it for ordering, set thresholds on your labelled set, and log the reason strings for debugging.
  • Provider coverage: Gemini and OpenAI chat models take images natively (03.6); Anthropic takes images too but has no embeddings API, so its role here is reranker/VLM only; OpenRouter routes image input to whichever model supports it (modalities in the catalogue — 03.6, 2.5).

Latency arithmetic. The module's cost model has a latency twin: the two-stage query path costs T_query ≈ T_embed + N·T_rerank when rerank calls run serially, T_embed + ⌈N/concurrency⌉·T_rerank when they run in parallel, and T_embed + ⌈N/B⌉·T_rerank when the API batches B pairs per call. Single-stage retrieval (no rerank) is just T_embed — the reranker is what buys precision, and this formula is what it costs. Measure your own p50s and plug them in:

python
# query_latency.py — pure Python arithmetic, real output. Run: python3 query_latency.py
# Latency model for the two-stage multimodal query path:
#   embed call -> top-N candidates -> N x VLM rerank calls -> answer.
# All times are YOUR measured p50s in milliseconds — substitute real numbers.

T_EMBED_MS = 120.0     # multimodal embed call, p50 (provider + network)
T_RERANK_MS = 900.0    # one (query, image) VLM scoring call, p50
N_RERANK = 20          # candidates sent to the reranker
CONCURRENCY = 8        # parallel rerank calls you can sustain
BATCH_PER_CALL = 4     # images scored per call if the API accepts batches

def serial_ms(t_embed, t_rerank, n):
    """Embed + n rerank round-trips, one after another."""
    return t_embed + n * t_rerank

def concurrent_ms(t_embed, t_rerank, n, conc):
    """Embed + ceil(n/conc) waves of parallel rerank calls."""
    import math
    return t_embed + math.ceil(n / conc) * t_rerank

def batched_ms(t_embed, t_rerank, n, per_call):
    """Embed + ceil(n/per_call) batched rerank calls (each ~t_rerank)."""
    import math
    return t_embed + math.ceil(n / per_call) * t_rerank

print(f"embed call                        : {T_EMBED_MS:.0f} ms")
print(f"single-stage (no rerank)          : {T_EMBED_MS:.0f} ms")
print(f"serial rerank, {N_RERANK} calls   : {serial_ms(T_EMBED_MS, T_RERANK_MS, N_RERANK):.0f} ms")
print(f"concurrent x{CONCURRENCY:<24}: {concurrent_ms(T_EMBED_MS, T_RERANK_MS, N_RERANK, CONCURRENCY):.0f} ms")
print(f"batched {BATCH_PER_CALL}/call{'':<17}: {batched_ms(T_EMBED_MS, T_RERANK_MS, N_RERANK, BATCH_PER_CALL):.0f} ms")

# Index-time throughput bound (calls/sec you can sustain -> items/sec):
# caption call + media embed call per item, plus provider rate limits.
T_CAPTION_MS = 800.0
items_per_sec = 1000.0 / (T_CAPTION_MS + T_EMBED_MS)
print(f"\nindex throughput ~{items_per_sec:.2f} items/s serial "
      f"-> 50k items ~= {50_000 / items_per_sec / 3600:.1f} h "
      f"(halve it with async concurrency; check rate limits)")

Output (real — pure Python arithmetic; the timings above are placeholder p50s, so substitute your own):

text
embed call                        : 120 ms
single-stage (no rerank)          : 120 ms
serial rerank, 20 calls   : 18120 ms
concurrent x8                       : 2820 ms
batched 4/call                 : 4620 ms

index throughput ~1.09 items/s serial -> 50k items ~= 12.8 h (halve it with async concurrency; check rate limits)

Read it as an engineer: at plausible VLM latencies, serial reranking is a product-killer (18 s p50), concurrency is the cheapest fix (2.8 s), and batching alone (4.6 s here) loses to it. Batching only pays when your provider accepts multi-image scoring calls and a 4-image call takes about as long as a 1-image call, which you must measure; the two combine (5 batched calls on 8 workers is a single wave). Check 03.9 for the concurrency/batch machinery and 03.8 for the timeout discipline a 20-call fan-out needs. The same shape applies at index time: caption + embed calls per item bound your backfill speed, and provider rate limits (1.4) cap it further — plan re-embeds as batch jobs (06.2), not interactive loops.

Users describe what they want loosely: "that jacket from the summer campaign", "the invoice with the weird logo". A rewrite step (Module 07 owns query understanding) can help twice:

  1. Expand to visual attributes for the vector query: "jacket, navy blue, Harrington style, campaign photo".
  2. Resolve references against session context or a catalogue: "the invoice" → the invoice ID if the conversation established it.

Keep three query variants and fuse or cascade: raw text → keyword channel, expanded text → text-vector channel, and (when the user uploaded an image) the image itself → media channel. Log which channel produced each hit — that's how you learn which rewrite earns its tokens.


Part 6: Multimodal RAG#

Text RAG (Module 07) retrieves chunks and asks an LLM to answer from them. Multimodal RAG retrieves media items — page images, photos, clips — and asks a vision-capable model to answer from the pixels. The retrieval half is this lesson; the generation half is 07.4 plus 03.6's media-input mechanics.

6.1 The pipeline#

flowchart LR
    Q["user question"] --> QE["query embedder<br/>(text or media)"]
    QE --> RET["retrieval:<br/>media vectors + caption vectors + BM25"]
    RET --> FUSE["fuse + optional VLM rerank"]
    FUSE --> CTX["context assembly:<br/>page images / clips / captions"]
    CTX --> VLM["VLM answer call<br/>(images + question + instructions)"]
    VLM --> ANS["answer + citations<br/>(page / bbox / timestamp)"]

6.2 Page-image RAG vs text-extraction RAG#

The central design choice for document corpora. Both are legitimate; they win on different content:

Text-extraction RAG (Pattern 2) Page-image RAG (Pattern 1/4)
Best for prose, specs, contracts, transcripts — text is the content tables, figures, charts, forms, scanned pages, slide decks, anything where layout carries meaning
Retrieval unit text chunk (~300–800 tokens) page image (one vector or late-interaction patches)
Answer stage text LLM VLM reads the page image(s)
Cost per query cheap: a few hundred text tokens of context expensive: each page ≈ 258–1,120 image tokens (03.6)
Weakness OCR/extraction errors become permanent; tables-as-text scramble expensive at scale; fine print and exact numbers still error-prone; needs a strong VLM
When it fails silently the right page retrieved, wrong chunk quoted the right page retrieved, VLM misreads a dense table

The pragmatic answer for most document products is hybrid: page-image vectors for recall (they see layout), caption/OCR text vectors + BM25 for precision on text queries, then a VLM that gets both the page image and the extracted text for the top pages. The VLM can cross-check the OCR text against the pixels — a cheap verification loop.

6.3 Citations: pages, regions and timestamps#

Multimodal answers need citations users can click. The payload fields from 4.1 exist precisely for this:

  • PDF/page: cite page + optionally bbox (normalized coordinates — the convention your VLM uses; Gemini's box format is covered in 09.1). Render the cited region as a cropped thumbnail for the UI.
  • Video: cite timestamp_start–timestamp_end; link to ?t=123 deep-links. If the model watched only sampled frames, cite the segment, not a precise second it can't see.
  • Audio: cite the speaker-turn window; pair with the transcript excerpt.
  • Images: cite the image id + optional region if your embedder/reranker produced one.

Citation discipline is 07.5's subject; the multimodal addition is that the citation target is a region of pixels or a span of time, so your UI needs crop/seek affordances, not just links.

6.4 Context budget with images#

Images are the most expensive thing you can put in a prompt. 04.6, Part 2 owns the budget mechanics; the multimodal numbers (as of November 2026, from 03.6):

  • One image typically costs ~258–1,120 tokens depending on provider, resolution and detail setting — order of magnitude: a page image ≈ a page of text, a photo ≈ several paragraphs.
  • k=5 pages ≈ 1.5k–5k image tokens — affordable. k=50 pages is not; that's a rerank-then-read pattern, not a stuff-everything pattern.
  • Video is the budget killer: sending a clip means frames × per-frame tokens. Prefer segment-level retrieval (a 30-s window) over whole-video context, and prefer transcript text for long-form understanding (09.8 covers video input depth).
  • The context-cost asymmetry argues for two-stage answers: retrieve cheaply with embeddings, then spend VLM tokens only on the 3–8 items that matter. This is the same economics as reranking (06.9) — embeddings are the cheap recall stage, the VLM is the expensive precision stage.

6.5 Evaluating multimodal retrieval#

Retrieval quality is measured before generation quality — 06.10 owns the metrics; the multimodal additions:

  • Label per modality pair. Your qrels need to know whether the relevant item was found via image→image, text→image, text→page, etc. A system can have great text→page recall and terrible text→image recall; one number hides it.
  • Recall@k is the headline for "did we retrieve the right page/photo at all"; add citation accuracy downstream (did the answer actually come from the cited region — Module 10A owns answer-level eval).
  • Build the labelled set from real queries. 30–100 queries with known relevant items per modality pair (06.10, Part 2); for visual search, "relevant" means visually appropriate, so label with images shown, not descriptions.
  • The modality-gap check is a diagnostic, not a metric: plot score distributions per pair (06.3, Part 3); a collapsed or shifted distribution tells you the model or the preprocessing changed.

Part 7: The multimodal search service#

Here is the running example promised in the module plan: multimodal search over a product catalogue — images with VLM captions, built on the Module 06 Embedder/VectorStore contracts (06.1, Part 10, 06.5, Part 7). The code is one file, multimodal_search.py; it runs end to end with the deterministic fake embedder and captioner (no keys, no network), and the provider adapters are sketched as comments against the verified APIs from Part 1.

7.1 The architecture#

flowchart TB
    subgraph ingest ["Index time (offline/batch)"]
        ITEM["MediaItem<br/>image / pdf_page / clip"] --> CAP["caption pipeline<br/>Captioner: VLM / OCR / STT — 09.1/05.4/09.4"]
        CAP --> CE["embedder.embed_documents(caption)"]
        ITEM --> ME["embedder.embed_media(media, kind, role=document)"]
        CE --> IDX[("VectorStore<br/>branch=caption")]
        ME --> IDX2[("branch=media")]
    end
    subgraph serve ["Query time"]
        Q["query text<br/>(or uploaded media)"] --> QE["embedder.embed_query(query)"]
        QE --> S1["store.query(branch=caption)"]
        QE --> S2["store.query(branch=media)"]
        S1 --> RRF["RRF fusion"]
        S2 --> RRF
        RRF --> HITS["MediaHit list<br/>-> VLM rerank (optional) -> UI"]
    end

7.2 The code#

Three seams, all borrowed from earlier modules: MediaEmbedder extends the 06.1 Embedder protocol (06.1, Part 10) with a media path; VectorRecord/ScoredRecord/VectorStore/NumpyVectorStore are the 06.5 contracts, with the code unchanged and the docstrings shortened, so this file runs standalone — in a real project you import them from your vector_store module; Captioner is the Pattern-2 front end the 7.1 diagram promised. The file runs end to end on fakes — swap any seam for a provider adapter from 7.3.

python
# multimodal_search.py — runnable end to end with FakeMediaEmbedder + FakeCaptioner.
# Real output below; needs only numpy.
from __future__ import annotations

import hashlib
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field, replace
from typing import Any, Protocol, runtime_checkable

import numpy as np


# --- the Module 06 contracts this service is built on (06.1 Part 10, 06.5
# Part 7). Code copied unchanged (docstrings shortened) so this file runs
# standalone; in a real project import them from your vector_store module
# instead. The `_matches` filter is 06.5's current version: it raises
# ValueError on an unsupported operator instead of ignoring it. ---

@dataclass(frozen=True)
class VectorRecord:
    id: str
    vector: tuple[float, ...]
    text: str = ""
    metadata: Mapping[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class ScoredRecord:
    record: VectorRecord
    similarity: float          # higher = more similar; cosine in [-1, 1]


class VectorStore(Protocol):
    """The 06.5 store contract. Swapping NumpyVectorStore for Qdrant or
    pgvector means writing one adapter — the service never knows."""

    def upsert(self, records: Sequence[VectorRecord]) -> None: ...
    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: Mapping[str, Any] | None = None) -> list[ScoredRecord]: ...
    def get(self, record_id: str) -> VectorRecord | None: ...
    def delete(self, record_ids: Sequence[str]) -> None: ...


def _cosine_similarity(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
    """Cosine similarity of `query` against each row of `matrix`.
    Returns zeros for zero-norm vectors instead of NaN."""
    q = query.astype(np.float32)
    m = matrix.astype(np.float32)
    qn = np.linalg.norm(q)
    mn = np.linalg.norm(m, axis=1)
    denom = np.where(qn * mn == 0, 1.0, qn * mn)
    return (m @ q) / denom


def _same(got: object, want: object) -> bool:
    """Equality that keeps True apart from 1 (Python says True == 1)."""
    return got == want and isinstance(got, bool) == isinstance(want, bool)


def _matches(meta: dict, filters: dict | None) -> bool:
    """Equality + simple range filters: {"tenant": "acme"} or
    {"score": {"$gte": 3}}. Deliberately minimal — see lesson 06.6.
    Strict on purpose, because tenant isolation rides on this function: an empty
    operator dict, an unknown operator or an $in that is not a list raises
    instead of matching everything, and True never equals 1."""
    if not filters:
        return True
    for key, want in filters.items():
        got = meta.get(key)
        if isinstance(want, dict):
            if not want:
                raise ValueError(f"empty filter for {key!r} would match every record")
            for op, v in want.items():
                if op == "$gte":   ok = got is not None and got >= v
                elif op == "$gt":  ok = got is not None and got > v
                elif op == "$lte": ok = got is not None and got <= v
                elif op == "$lt":  ok = got is not None and got < v
                elif op == "$in":
                    if not isinstance(v, (list, tuple, set, frozenset)):
                        # a string here would test "is got a substring of v?"
                        raise ValueError("$in needs a list of values")
                    ok = any(_same(got, x) for x in v)
                elif op == "$ne":  ok = not _same(got, v)
                else:              # never fail open: an unknown operator is an error
                    raise ValueError(f"unsupported filter operator {op!r}")
                if not ok:
                    return False
        elif not _same(got, want):
            return False
    return True


class NumpyVectorStore:
    """Exact cosine k-NN — the 06.5 in-memory store (docstring shortened).
    Good to ~100k vectors; beyond that use an ANN store (06.4)."""

    def __init__(self, dim: int | None = None):
        self._dim = dim
        self._records: dict[str, VectorRecord] = {}

    def upsert(self, records: Sequence[VectorRecord]) -> None:
        for r in records:
            if self._dim is None:
                self._dim = len(r.vector)
            if len(r.vector) != self._dim:
                raise ValueError(
                    f"dimension mismatch: store is {self._dim}, got {len(r.vector)}")
            self._records[r.id] = r

    def query(self, vector: Sequence[float], *, top_k: int = 10,
              filters: dict | None = None) -> list[ScoredRecord]:
        if self._dim is None:
            return []
        if len(vector) != self._dim:
            raise ValueError(f"query dim {len(vector)} != store dim {self._dim}")
        candidates = [(rid, r) for rid, r in self._records.items()
                      if _matches(r.metadata, filters)]
        if not candidates:
            return []
        ids = [rid for rid, _ in candidates]
        matrix = np.array([r.vector for _, r in candidates], dtype=np.float32)
        sims = _cosine_similarity(np.asarray(vector, dtype=np.float32), matrix)
        k = min(top_k, len(ids))
        top = np.argpartition(-sims, k - 1)[:k]
        top = top[np.argsort(-sims[top])]
        return [ScoredRecord(record=candidates[i][1], similarity=float(sims[i]))
                for i in top]

    def get(self, record_id: str) -> VectorRecord | None:
        return self._records.get(record_id)

    def delete(self, record_ids: Sequence[str]) -> None:
        for rid in record_ids:
            self._records.pop(rid, None)

    def __len__(self) -> int:
        return len(self._records)


@dataclass(frozen=True)
class MediaItem:
    """One searchable thing: a photo, a PDF page, a video segment, an audio clip."""
    id: str
    modality: str                      # image | pdf_page | video_segment | audio_segment
    caption: str = ""                  # Pattern-2 text; empty -> the Captioner fills it
    media_ref: str = ""                # URL or storage key for the bytes/thumbnail
    metadata: Mapping[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class MediaHit:
    item: MediaItem
    branch: str                        # "media" | "caption" | "keyword"
    rank: int
    score: float                       # fused RRF score, not a cosine


class Captioner(Protocol):
    """The Pattern-2 front end: turns raw media into the text the caption
    channel embeds (VLM caption / OCR text / transcript slice)."""
    name: str
    def caption(self, item: MediaItem) -> str: ...


class FakeCaptioner:
    """Keyless stand-in: canned captions per item id. A real deployment wires
    VlmCaptioner (adapters.py) or your OCR/STT pipeline (05.4 / 09.4)."""
    name = "fake-captioner-v1"
    CAPTIONS = {
        "p001": "red running shoe side view",
        "p002": "blue leather backpack",
        "p003": "green canvas tote bag",
        "p004": "black baseball cap",
        "p005": "navy Harrington jacket",
    }

    def caption(self, item: MediaItem) -> str:
        return self.CAPTIONS.get(item.id, "")


@runtime_checkable
class MediaEmbedder(Protocol):
    """The multimodal extension of Module 06's `Embedder` protocol
    (06.1 Part 10). Text goes through embed_documents/embed_query exactly
    like 06.x; media adds `kind` (the modality) and `role` — the
    document/query asymmetry every real provider wants: Cohere's
    input_type, Voyage's input_type, Gemini-2's task prefixes."""
    @property
    def model_id(self) -> str: ...       # feeds the 06.1 version guard
    @property
    def dimensions(self) -> int: ...
    def embed_documents(self, texts: Sequence[str]) -> list[list[float]]: ...
    def embed_query(self, text: str) -> list[float]: ...
    def embed_media(self, content: bytes | str, *, kind: str,
                    role: str = "document") -> list[float]:
        ...   # kind: image | pdf_page | video_segment | audio_segment
            # role: "document" (corpus) | "query" (search time)
            # content: raw bytes, or a URL string where the provider allows


class FakeMediaEmbedder:
    """Deterministic stand-in: maps keywords to topic directions + a modality
    offset (a toy modality gap) + a small role offset + hash-seeded noise.
    NOT a real embedding — it proves the plumbing, not the judgement."""

    DIM = 24

    @property
    def model_id(self) -> str:
        return "fake-mm-v1"

    @property
    def dimensions(self) -> int:
        return self.DIM

    TOPICS = {
        "shoe":    np.eye(1, 24, 0, dtype=np.float32).ravel(),
        "bag":     np.eye(1, 24, 1, dtype=np.float32).ravel(),
        "hat":     np.eye(1, 24, 2, dtype=np.float32).ravel(),
        "jacket":  np.eye(1, 24, 3, dtype=np.float32).ravel(),
        "invoice": np.eye(1, 24, 4, dtype=np.float32).ravel(),
    }
    ALIASES = {"shoe": "shoe", "shoes": "shoe", "sneaker": "shoe",
               "sneakers": "shoe", "running": "shoe",
               "bag": "bag", "bags": "bag", "backpack": "bag",
               "tote": "bag", "purse": "bag",
               "hat": "hat", "hats": "hat", "cap": "hat", "caps": "hat",
               "jacket": "jacket", "coat": "jacket", "jackets": "jacket",
               "invoice": "invoice", "bill": "invoice"}
    MODALITY_OFFSET = {"text": 0.0, "image": 0.55, "pdf_page": 0.30,
                       "video_segment": 0.40, "audio_segment": 0.45}
    ROLE_OFFSET = {"document": 0.0, "query": 0.04}

    def _vec(self, content: str, *, kind: str, role: str) -> list[float]:
        words = content.lower().replace("-", " ").split()
        topic = next((self.TOPICS[self.ALIASES[w]] for w in words
                      if w in self.ALIASES),
                     np.zeros(self.DIM, dtype=np.float32))
        seed = int(hashlib.md5(content.encode()).hexdigest()[:8], 16)
        rng = np.random.default_rng(seed)
        noise = 0.08 * rng.standard_normal(self.DIM)
        v = topic + noise
        v[20] += self.MODALITY_OFFSET.get(kind, 0.0)   # toy modality gap
        v[21] += self.ROLE_OFFSET.get(role, 0.0)       # toy query/doc asymmetry
        return (v / np.linalg.norm(v)).tolist()

    def embed_documents(self, texts: Sequence[str]) -> list[list[float]]:
        return [self._vec(t, kind="text", role="document") for t in texts]

    def embed_query(self, text: str) -> list[float]:
        return self._vec(text, kind="text", role="query")

    def embed_media(self, content: bytes | str, *, kind: str = "image",
                    role: str = "document") -> list[float]:
        # the fake is text-only: `content` is a text proxy for the media bytes
        text = (content.decode("utf-8", "ignore")
                if isinstance(content, (bytes, bytearray)) else str(content))
        return self._vec(text, kind=kind, role=role)


class MultimodalSearchService:
    """Index-time: caption each item (Captioner), embed the caption into the
    'caption' branch and a media proxy into the 'media' branch — one
    VectorStore, branch-tagged records. Query-time: embed the query, retrieve
    per branch, fuse by reciprocal rank."""

    def __init__(self, embedder: MediaEmbedder,
                 captioner: Captioner | None = None,
                 store: VectorStore | None = None):
        self.embedder = embedder
        self.captioner = captioner or FakeCaptioner()
        self.store = store or NumpyVectorStore(embedder.dimensions)
        self._items: dict[str, MediaItem] = {}

    def ingest(self, items: Sequence[MediaItem]) -> None:
        enriched = []
        for raw in items:
            caption = raw.caption or self.captioner.caption(raw)
            it = replace(raw, caption=caption) if caption != raw.caption else raw
            self._items[it.id] = it
            enriched.append(it)
        # batch the text channel — embed_documents is the 06.1 batch path
        captioned = [it for it in enriched if it.caption]
        vecs = (self.embedder.embed_documents([it.caption for it in captioned])
                if captioned else [])
        vec_by_id = {it.id: v for it, v in zip(captioned, vecs)}
        for it in enriched:
            if it.id in vec_by_id:
                self._put("caption", it, vec_by_id[it.id], text=it.caption)
            if it.media_ref or it.modality != "text":
                # The skeleton has no byte pipeline: it hands embed_media a
                # TEXT PROXY (the caption, else the id) standing in for the
                # media bytes/URL — the fake is text-only. Real adapters take
                # bytes or a URL; your ingest fetches media_ref first (Part 9).
                proxy = it.caption or it.id
                mv = self.embedder.embed_media(proxy, kind=it.modality,
                                               role="document")
                self._put("media", it, mv, text=it.caption)

    def _put(self, branch: str, item: MediaItem, vector, *, text: str) -> None:
        # reserved keys win over item metadata on collision; the payload is
        # what a real store keeps for display/filter/citation (4.1)
        meta = {**dict(item.metadata), "branch": branch, "item_id": item.id,
                "modality": item.modality, "media_ref": item.media_ref}
        self.store.upsert([VectorRecord(
            id=f"{item.id}:{branch}", vector=tuple(vector), text=text,
            metadata=meta)])

    @staticmethod
    def _rrf(rank_lists: list[list[ScoredRecord]], k: int = 60) -> dict[str, float]:
        scores: dict[str, float] = {}
        for lst in rank_lists:
            for rank, sr in enumerate(lst, start=1):
                item_id = sr.record.metadata["item_id"]
                scores[item_id] = scores.get(item_id, 0.0) + 1.0 / (k + rank)
        return scores

    def search(self, query: str, *, query_kind: str = "text", top_k: int = 5,
               branches: Sequence[str] = ("caption", "media"),
               filters: Mapping[str, Any] | None = None) -> list[MediaHit]:
        """query_kind: 'text' (default) or a media modality for visual search —
        'image', 'pdf_page', 'video_segment', 'audio_segment'."""
        per_branch: dict[str, list[ScoredRecord]] = {}
        for branch in branches:
            if query_kind == "text":
                qv = self.embedder.embed_query(query)
            else:
                qv = self.embedder.embed_media(query, kind=query_kind,
                                               role="query")
            f = {**dict(filters or {}), "branch": branch}
            per_branch[branch] = self.store.query(qv, top_k=top_k * 3, filters=f)
        fused = self._rrf(list(per_branch.values()))
        best_by_id: dict[str, ScoredRecord] = {}
        for lst in per_branch.values():
            for sr in lst:
                iid = sr.record.metadata["item_id"]
                if iid not in best_by_id or sr.similarity > best_by_id[iid].similarity:
                    best_by_id[iid] = sr
        out = []
        for item_id, rrf in sorted(fused.items(), key=lambda kv: -kv[1])[:top_k]:
            rec = best_by_id[item_id].record
            out.append(MediaHit(item=self._items[item_id],
                                branch=rec.metadata["branch"],
                                rank=len(out) + 1, score=rrf))
        return out


CATALOGUE = [
    MediaItem("p001", "image", media_ref="img/p001.jpg",
              metadata={"sku": "SHO-101", "price": 89.0}),
    MediaItem("p002", "image", media_ref="img/p002.jpg",
              metadata={"sku": "BAG-220", "price": 120.0}),
    MediaItem("p003", "image", media_ref="img/p003.jpg",
              metadata={"sku": "BAG-118", "price": 45.0}),
    MediaItem("p004", "image", media_ref="img/p004.jpg",
              metadata={"sku": "HAT-07", "price": 25.0}),
    MediaItem("p005", "image", media_ref="img/p005.jpg",
              metadata={"sku": "JKT-90", "price": 210.0}),
    # pre-captioned upstream (e.g. by the OCR pipeline) — the Captioner is
    # only called when caption is empty
    MediaItem("p006", "pdf_page", caption="invoice INV-2042 total due",
              media_ref="pdf/inv2042.pdf#page=1", metadata={"page": 1}),
]

if __name__ == "__main__":
    svc = MultimodalSearchService(FakeMediaEmbedder(), captioner=FakeCaptioner())
    svc.ingest(CATALOGUE)
    print(f"indexed {len(svc.store)} vectors "
          f"({len(CATALOGUE)} items -> caption+media branches)")
    for q in ["red running shoes", "bags for school", "invoice total"]:
        print(f"\nquery: {q!r}")
        for hit in svc.search(q, top_k=3):
            it = hit.item
            print(f"  {hit.score:.4f}  {it.id:5s} [{hit.branch:7s}] "
                  f"{it.caption!r}  sku={it.metadata.get('sku','-')}")
    print("\nquery: image upload (visual search, query_kind='image')")
    for hit in svc.search("red shoe product photo", query_kind="image", top_k=3):
        it = hit.item
        print(f"  {hit.score:.4f}  {it.id:5s} [{hit.branch:7s}] "
              f"{it.caption!r}  sku={it.metadata.get('sku','-')}")

Run it — this is the real output:

text
indexed 12 vectors (6 items -> caption+media branches)

query: 'red running shoes'
  0.0328  p001  [caption] 'red running shoe side view'  sku=SHO-101
  0.0323  p005  [media  ] 'navy Harrington jacket'  sku=JKT-90
  0.0317  p003  [media  ] 'green canvas tote bag'  sku=BAG-118

query: 'bags for school'
  0.0328  p002  [caption] 'blue leather backpack'  sku=BAG-220
  0.0323  p003  [caption] 'green canvas tote bag'  sku=BAG-118
  0.0317  p005  [media  ] 'navy Harrington jacket'  sku=JKT-90

query: 'invoice total'
  0.0328  p006  [caption] 'invoice INV-2042 total due'  sku=-
  0.0323  p001  [caption] 'red running shoe side view'  sku=SHO-101
  0.0317  p004  [caption] 'black baseball cap'  sku=HAT-07

query: image upload (visual search, query_kind='image')
  0.0328  p001  [media  ] 'red running shoe side view'  sku=SHO-101
  0.0320  p004  [media  ] 'black baseball cap'  sku=HAT-07
  0.0318  p006  [media  ] 'invoice INV-2042 total due'  sku=-

Read the output honestly: the correct item is always rank 1 (p001 shoes, p002/p003 bags, p006 invoice), and the margin over rank 2 is thin — because the fake embedder is deliberately crude and its toy modality offset handicaps the media branch on text queries (exactly the gap effect from Part 2). Note the branch labels: on text queries the caption branch wins; on the image upload (query_kind="image") the media branch takes over — the same plumbing, different query modality. Five captions came from FakeCaptioner, p006's was pre-filled — the caption or captioner.caption(...) fallback worked as designed. What the demo does prove: the MediaEmbedder/VectorStore/Captioner seams, the two-channel indexing, the RRF fusion and the payload plumbing all work — swap FakeMediaEmbedder for a provider adapter and the service is unchanged.

7.3 The provider adapters (illustrative)#

Each adapter implements the same MediaEmbedder protocol — embed_documents/embed_query for text, embed_media(content, kind, role) for media — around the verified APIs from Part 1, so the service never knows which provider produced a vector. role is where each provider's query/document asymmetry lives.

python
# adapters.py — ILLUSTRATIVE: each needs its provider key in .env.
# Written against official docs as of November 2026; outputs will differ.
import base64

KIND_MIME = {"image": "image/jpeg", "pdf_page": "image/png",
             "video_segment": "video/mp4", "audio_segment": "audio/mpeg"}


def _data_url(raw: bytes, mime: str) -> str:
    return f"data:{mime};base64,{base64.b64encode(raw).decode()}"


class GeminiEmbedder:
    """gemini-embedding-2: text/image/audio/video/pdf in one 8,192-token space.
    embedding-2 has NO task_type field — retrieval wants text prefixes instead:
    queries 'task: search result | query: ...', documents
    'title: none | text: ...' ('none' when untitled). For a SINGLE multimodal
    item Google recommends NOT prefixing — ai.google.dev/gemini-api/docs/embeddings."""
    @property
    def model_id(self) -> str:
        return "gemini-embedding-2"

    @property
    def dimensions(self) -> int:
        return 768    # output_dimensionality chosen at index time — record it!

    def __init__(self):
        from dotenv import load_dotenv
        from google import genai
        load_dotenv()
        self._c = genai.Client()

    def _embed(self, contents) -> list[list[float]]:
        from google.genai import types
        res = self._c.models.embed_content(
            model=self.model_id,
            contents=contents,
            config=types.EmbedContentConfig(output_dimensionality=self.dimensions),
        )
        return [list(e.values) for e in res.embeddings]

    @staticmethod
    def _one(parts):
        from google.genai import types
        return types.Content(parts=parts)

    def embed_documents(self, texts):
        from google.genai import types
        # one Content per text -> one vector per input; a bare list of parts in
        # ONE Content aggregates to a single vector (06.1 failure gallery)
        return self._embed([self._one([types.Part.from_text(
            text=f"title: none | text: {t}")]) for t in texts])

    def embed_query(self, text: str) -> list[float]:
        from google.genai import types
        return self._embed([self._one([types.Part.from_text(
            text=f"task: search result | query: {text}")])])[0]

    def embed_media(self, content: bytes, *, kind: str = "image",
                    role: str = "document") -> list[float]:
        from google.genai import types
        if not isinstance(content, (bytes, bytearray)):
            raise TypeError("embed_media takes raw bytes — fetch media_ref "
                            "from storage / the Files API first (03.6)")
        mime = KIND_MIME.get(kind, "application/octet-stream")
        # role unused here: Google's guidance is no task prefix on single
        # multimodal items — query and document media embed identically
        return self._embed([self._one([types.Part.from_bytes(
            data=bytes(content), mime_type=mime)])])[0]


class VoyageEmbedder:
    """voyage-multimodal-3.5: interleaved text/image/video, 32k ctx, pixel
    pricing. input_type 'query'/'document' makes Voyage prepend its retrieval
    prompts; embeddings with and without it stay compatible (docs)."""
    @property
    def model_id(self) -> str:
        return "voyage-multimodal-3.5"

    @property
    def dimensions(self) -> int:
        return 1024    # default; 256/512/2048 via output_dimension (SDK arg)

    def __init__(self):
        import os
        import voyageai
        from dotenv import load_dotenv
        load_dotenv()
        self._c = voyageai.Client(api_key=os.environ["VOYAGE_API_KEY"])

    @staticmethod
    def _role(role: str):
        return {"document": "document", "query": "query"}.get(role)

    def _embed(self, inputs, role: str) -> list[list[float]]:
        res = self._c.multimodal_embed(
            model=self.model_id, inputs=inputs,
            input_type=self._role(role),
            output_dimension=self.dimensions)
        return [list(e) for e in res.embeddings]

    def embed_documents(self, texts):
        # list-of-lists form: each inner list is one input of text pieces
        return self._embed([[t] for t in texts], role="document")

    def embed_query(self, text: str) -> list[float]:
        return self._embed([[text]], role="query")[0]

    def embed_media(self, content: bytes | str, *, kind: str = "image",
                    role: str = "document") -> list[float]:
        if kind not in ("image", "pdf_page", "video_segment"):
            raise NotImplementedError(
                f"kind {kind!r}: voyage-multimodal-3.5 covers text/image/video "
                "only — no audio (1.4)")
        base = "image" if kind in ("image", "pdf_page") else "video"
        if isinstance(content, (bytes, bytearray)):
            ptype, val = f"{base}_base64", _data_url(bytes(content),
                                                  KIND_MIME[kind])
        elif isinstance(content, str) and content.startswith(("http://", "https://")):
            ptype, val = f"{base}_url", content      # value is a PLAIN string
        else:
            raise TypeError("embed_media takes raw bytes or an http(s) URL")
        # {"content": [...]} dict form == the REST schema; a request must use
        # _base64 or _url pieces exclusively — each call sends one piece
        return self._embed([{"content": [{"type": ptype, ptype: val}]}],
                           role=role)[0]


class CohereEmbedder:
    """embed-v5.0-fast: text/images/fused inputs; input_type required for v3+.
    role maps to input_type: 'search_document' corpus-side, 'search_query'
    query-side — mismatched types silently degrade retrieval."""
    @property
    def model_id(self) -> str:
        return "embed-v5.0-fast"

    @property
    def dimensions(self) -> int:
        return 1024    # output_dimension chosen at index time

    def __init__(self):
        import os
        import cohere
        from dotenv import load_dotenv
        load_dotenv()
        self._c = cohere.ClientV2(api_key=os.environ["COHERE_API_KEY"])

    @staticmethod
    def _input_type(role: str) -> str:
        return "search_query" if role == "query" else "search_document"

    def embed_documents(self, texts):
        res = self._c.embed(model=self.model_id, texts=list(texts),
                            input_type="search_document",
                            output_dimension=self.dimensions,
                            embedding_types=["float"])
        return [list(v) for v in res.embeddings.float]

    def embed_query(self, text: str) -> list[float]:
        res = self._c.embed(model=self.model_id, texts=[text],
                            input_type="search_query",
                            output_dimension=self.dimensions,
                            embedding_types=["float"])
        return list(res.embeddings.float[0])

    def embed_media(self, content: bytes, *, kind: str = "image",
                    role: str = "document") -> list[float]:
        if kind not in ("image", "pdf_page"):
            raise NotImplementedError(
                "Cohere Embed takes text + images only — no video/audio (1.2); "
                "pdf_page goes as a rendered page image")
        if not isinstance(content, (bytes, bytearray)):
            raise TypeError("embed_media takes raw bytes")
        # OpenAI-style nested url — Cohere's own shape, NOT Voyage's flat string
        piece = {"type": "image_url",
                 "image_url": {"url": _data_url(bytes(content), KIND_MIME[kind])}}
        # prepend {"type":"text","text":...} to fuse caption + page image (1.4)
        res = self._c.embed(model=self.model_id,
                            inputs=[{"content": [piece]}],
                            input_type=self._input_type(role),
                            output_dimension=self.dimensions,
                            embedding_types=["float"])
        return list(res.embeddings.float[0])


class VlmCaptioner:
    """The real Pattern-2 front end for images: a VLM reads the media and
    writes the caption the caption channel embeds. Covers image-like kinds;
    pdf_page needs a page render first (09.2), A/V need STT/OCR (05.4/09.4)."""
    name = "vlm-captioner-gemini"

    def __init__(self, model: str = "gemini-3.8-flash"):
        from dotenv import load_dotenv
        from google import genai
        load_dotenv()
        self._model = model
        self._c = genai.Client()

    def caption(self, item) -> str:    # item: MediaItem from multimodal_search.py
        from pathlib import Path
        from google.genai import types
        data = Path(item.media_ref).read_bytes()   # local path; fetch URLs first
        mime = KIND_MIME.get(item.modality, "application/octet-stream")
        resp = self._c.models.generate_content(
            model=self._model,
            contents=[
                types.Part.from_bytes(data=data, mime_type=mime),
                "Describe this for search indexing in one sentence: visible "
                "objects, colours, legible text. No preamble.",
            ],
        )
        return resp.text.strip()

Notes that matter in production:

  • model_id + dimensions are the contract's identity. They feed the 06.1 version guard and must match the store's dimension — record embedder, dim and spec version in every row's metadata, and re-embed everything if you change it (02.3, 10.5).
  • role is not optional decoration. Cohere requires input_type for v3+ and silently degrades on mismatches; Voyage prepends different retrieval prompts for query vs document; Gemini-2 wants task prefixes on text (task: search result | query: vs title: ... | text:) but not on single multimodal items. The protocol's role parameter is what carries this — an adapter that ignores it produces document-flavoured query vectors, exactly the retrieval degradation 2.2 warns about.
  • Media content is bytes | str, and str means different things per provider: Voyage accepts an http(s) URL (*_url pieces — note the value is a plain string, and a request must use _base64 or _url pieces exclusively), while Cohere and Gemini want inline bytes (Cohere wraps them in a data: URI, Gemini uses Part.from_bytes). The service's text-proxy stand-in only works with the fake — production ingest fetches media_ref from object storage first.
  • Provider modality coverage is uneven: Voyage has no audio, Cohere has no video/audio, Gemini covers all five but bills video per frame. kind routing — and fallbacks like caption-first for unsupported modalities — is a service-level concern the protocol surfaces via NotImplementedError.
  • OpenAI and Anthropic can't fill this protocol for media. OpenAI embeddings are text-only and Anthropic has no embeddings API (1.5). For them, Pattern 2 applies: caption with VlmCaptioner or the chat model, embed the caption via Voyage or a text route.

7.4 What the skeleton deliberately omits#

Named so you know what production adds (all covered elsewhere): batching and resumable ingestion (06.2), the embedding cache keyed on content hash (06.2, Part 5), real vector stores and payload filtering (06.5, 06.6), the keyword channel (06.7), learned fusion weights (06.8, Part 5), the VLM rerank stage (5.4), async query APIs, rate-limit handling (03.8), and eval harnesses (6.5). Two more worth naming: multi-embedder Pattern-3 deployments — separate text and media models live in different spaces, so they need one VectorStore per space rather than the single shared-space store used here; and the byte pipeline — production ingest fetches media_ref from object storage and passes real bytes/URLs to embed_media, where this skeleton passes a text proxy.


Part 8: Applications#

Reference

The patterns above show up in recognisable products. For each: the pattern, the query types, and the trap.

Application Pattern Query types The trap
Product visual search (e-commerce) 1+3 text→image, image→image, image+text colour/attribute precision — filter metadata, don't trust the vector for "exactly navy"
Design asset library (figma exports, icons, brand kit) 1+3 text→image, image→similar near-duplicates flood results — dedup with phash at ingest (4.5)
Scanned document archive (invoices, contracts, letters) 2+4 text→page OCR errors become permanent; keep page images for VLM verification (6.2)
Video/lecture search 2 (+1 on keyframes) text→segment one vector per hour-long video is useless — segment first (4.3); transcript channel carries the recall
Podcast/audio search 2 text→segment speaker attribution and timestamps must survive chunking
Visual question answering over docs 4→VLM text→page→answer late-interaction index size; budget the VLM context (6.4)
Near-duplicate / plagiarism detection phash + embeddings image→image perceptual hash for "same picture", embedding distance for "same content different picture" — different jobs
Content moderation by similarity 1 image→blocklist blocklist vectors are sensitive — see Part 9
Medical-style image retrieval (research/triage aid) 1 image→image caution: retrieval is not diagnosis; regulatory and consent constraints are severe — human review mandatory, link Module 12
Reverse image search ("what is this?") 1 image→web/catalogue copyright on reference images; rate-limit abuse

Two cross-cutting rules: the caption channel is your friend for recall, your enemy for precision (it inherits every captioning error), and every application needs its per-modality-pair eval set before launch (6.5).


Part 9: Operations and privacy#

Deep-dive

9.1 Storage and serving costs#

  • Media storage dominates. Vectors are cheap (768–2,048 floats ≈ 3–8 KB each uncompressed, ~10× less quantized); the images, PDFs, thumbnails and video segments are not. Store originals in object storage with lifecycle rules, serve thumbnails from a CDN, and keep only media_ref pointers in the vector payload (Part 9 of 03.6's world and Module 11A own the serving side).
  • Index size for late interaction is the outlier — hundreds of vectors per page (3.4). Budget storage and memory for it explicitly.
  • Re-embedding is a batch job, not an event. Model upgrades, dim changes and preprocessing changes all require full re-embeds (05.9 owns incremental pipelines; 06.2, 7.4 prices it). Keep embed_spec_version in every row so old and new vectors never silently mix — vectors from different models are incomparable (02.3, 7.5).

9.2 Failure modes specific to multimodal retrieval#

Failure Cause Detection Fix
Right item never retrieved modality gap + global threshold per-pair score distributions (6.5) per-pair thresholds; caption channel backup
Wrong modality wins same-modality bias in two-tower models branch-level recall metrics single-backbone model; hybrid fusion; rerank
Embedding silently truncated >8,192 shared tokens (Gemini) or per-model cap token accounting per item (1.4) pre-count; chunk pages/segments
Caption hallucination poisons recall VLM invented a detail caption QA sampling; keep raw media human-review caption pipeline; Pattern 1 for critical items
Near-duplicates crowd top-k re-uploads, burst photos phash dedup at ingest dedup before embedding (4.5)
Index/model version skew re-embed partially failed version column vs embed_spec atomic re-embed + flip (05.9, 3.4)
VLM rerank hallucination reranker "sees" what isn't there logged reasons + score distributions bounded N, human spot-checks, fallback to embedding order
Face/biometric leakage faces embedded & stored privacy review see 9.3

Multimodal corpora are more sensitive than text corpora — a photo contains faces, documents contain signatures, audio contains voices. The rules:

  • Faces are biometric-adjacent data. Embedding a face photo creates a vector that can be inverted or matched — treat face vectors with the same access control, retention and deletion discipline as the images themselves (02.3, 10.7: embeddings are not anonymised). If you don't need faces for the task, blur or crop them before embedding — the vector then can't leak identity.
  • EXIF/GPS metadata is a privacy leak independent of embeddings. Strip it at ingest (09.1 covers EXIF stripping); a "harmless" product photo with GPS coordinates is a tracking risk.
  • Consent for media you didn't create. User uploads need clear terms; scraped or licensed imagery needs licence checks; voice/audio needs recording consent (jurisdiction-dependent — awareness, not legal advice; 09.4 and Module 12 own the depth).
  • Provider data policies apply to media too. Sending an image to a hosted embedder is a data transfer — check retention/training terms per provider (02.9 Part 9; note Gemini's free tier may train on content while paid tier does not). For sensitive corpora, self-hosted open weights (1.3) are the compliant path.
  • Deletion must cascade. Deleting a document deletes its caption, its vectors in every branch, its thumbnails, its phash entries and its cache entries — 06.6 owns the ACL/isolation machinery; media adds the extra surfaces above.
  • Access control on media ≠ access control on text. A thumbnail URL is a bearer token to the image; use signed URLs with expiry, per-tenant prefixes, and never expose media_ref raw (9.1).

9.4 Access control on media#

06.6 owns tenant isolation for vectors; multimodal adds two wrinkles:

  1. The payload points at sensitive bytes. Filtering the vector result isn't enough if media_ref leaks — signed URLs and per-tenant storage prefixes are mandatory.
  2. Caption text can itself be sensitive. A VLM caption of a medical image or a contract page may contain more explicit detail than the image pixels suggest — apply the same redaction rules to captions as to source text before they enter the keyword index.

Symptom Most likely cause First check
Text query returns no images at all one global threshold across modality pairs score distribution per pair (6.5)
Images rank below irrelevant text chunks same-modality bias (two-tower model) branch-level recall; try single-backbone model
"Find the invoice" misses scanned PDFs pages never embedded as images; only OCR text indexed does the pipeline render pages? (4.3)
Costs 10× the estimate video segmented per-scene + image queries priced as documents 4.4 with real query mix
Duplicate results everywhere no phash dedup; burst uploads 4.5
Answers cite the wrong page page-level vector too coarse for multi-topic pages smaller page regions / tiles; VLM rerank
Latency spikes at query time N×VLM rerank calls serially concurrency + smaller N + cached rerank scores
Quality dropped after "upgrade" new embedder/model mixed with old vectors embed_spec_version column; full re-embed
User uploads a NSFW/CSAM image no upload screening moderation gate before embedding — Module 12

Common misconceptions#

Misconception Reality
"One shared embedding space means all modalities score the same way." The space is shared but lumpy — the modality gap means text→text and text→image scores sit on different scales. Calibrate per modality pair (Part 2).
"Embed the image and you're done." Embeddings capture gist, not detail. Exact attributes (SKU, colour name, fine print) need the caption/BM25 channel or metadata filters (3.5).
"Caption first, embed text — that's all RAG needs." The caption inherits every VLM/OCR error. For visual documents, page-image retrieval sees what text extraction loses (6.2).
"Vector arithmetic can do 'like this but blue'." Largely unreliable across the modality gap; use attribute filters + text-channel queries + VLM rerank (5.3).
"OpenAI can embed images through the chat API." text-embedding-3-* is text-only; there is no image input on the embeddings endpoint. Caption first or use another provider (1.5).
"Anthropic has a multimodal embedding model." Anthropic has no embeddings API at all — use Voyage for embeddings, Claude for captioning/reranking.
"Perceptual hashing finds similar products." It finds near-identical files (dedup), not visual similarity. Similarity is the embedding's job (4.5).
"Embedding a video is one API call, one vector." Providers sample frames (32 for Gemini/Jina); long videos need segmentation first, and each segment costs its own embedding (4.3, 4.4).
"Vectors are anonymous, so face embeddings are safe." Embeddings can be inverted and matched; treat them with the same controls as the source media (9.3).
"A higher cosine score means a better match." Scores aren't comparable across modality pairs, models, or even query types — evaluate per pair on your own labelled set (6.5).
"The embedding model handles the whole retrieval problem." It's the cheap recall stage. Precision comes from hybrid channels, reranking and — for answers — a VLM that sees the actual pixels (Part 6).

Key takeaways#

  • Multimodal embeddings put text, images, audio, video and PDF pages in one vector space — but "one space" has a modality gap: calibrate thresholds per modality pair, never globally.
  • The landscape (Nov 2026): Gemini gemini-embedding-2 (all five modalities, 8,192 shared tokens), Voyage voyage-multimodal-3.5 (text+image+video, pixel pricing), Cohere Embed v4/v5 (text+image, fused inputs), Jina v5-omni (open weights, text-identical to v5-text), open weights (CLIP/SigLIP/Qwen3-VL-Embedding/ColPali-ColQwen). OpenAI: text-only. Anthropic: none.
  • Four design patterns: embed raw media, describe-then-embed, hybrid both, late-interaction page retrieval — pick with the 3.5 decision table, not by default.
  • Index the payload, not just the vector: media URL, thumbnail, caption, page/bbox/timestamp, modality, content hash, embed-spec version — everything the result UI and citation need.
  • Chunk media like you chunk text: pages, tiles, video/audio segments; store each segment's transcript slice for the keyword channel.
  • Cost is per-modality: Gemini bills modality tokens, Voyage bills clamped pixels, Cohere bills image tokens — run the 4.4 calculator with your real mix before committing.
  • Dedup with perceptual hashes at ingest (aHash/dHash); reserve embeddings for actual similarity.
  • Query types multiply: text→media, media→media, media→text, image+text — each needs its own eval slice.
  • "Like this but blue" is a filter + rerank problem, not vector arithmetic.
  • Multimodal RAG = cheap multimodal retrieval + expensive VLM reading. Budget images like the expensive tokens they are; cite pages/regions/timestamps.
  • Privacy is stricter for media: faces, EXIF/GPS, voice, consent, signed URLs, cascading deletes, and provider data policies all apply to pixels as much as to text.

Terms introduced in this lesson#

Term One-line definition
Multimodal embedding A vector representing content from more than one modality (text, image, audio, video, page) in a shared space
Shared embedding space The property that vectors from different modalities can be compared with the same similarity function
Modality gap The geometric separation between modality clusters in a shared space, which shifts score distributions per modality pair
Two-tower model A multimodal embedder with separate encoders per modality (CLIP-style), prone to modality gap and same-modality bias
Single-backbone model A multimodal embedder where one transformer reads interleaved text and media tokens
Late interaction Retrieval where query and document keep token-level vectors and match via MaxSim instead of one pooled vector
ColPali / ColQwen / ColQwen3 Late-interaction models that embed page images as patch-vector sets for visual document retrieval
ViDoRe The visual document retrieval benchmark the ColPali line was built for
Perceptual hash (aHash/dHash) A 64-bit image fingerprint robust to resize/recompress, used for near-duplicate detection
Hamming distance Number of differing bits between two hashes; the dedup threshold metric
Media chunk The retrieval unit for non-text content: page, tile, video segment or audio segment
Branch One retrieval channel in a hybrid multimodal index (media vector, caption vector, keyword)
Cross-modal reranker A VLM that scores (query, candidate media) pairs after embedding recall
Page-image RAG Answering questions by retrieving page images and reading them with a VLM, no OCR required
Embed spec version The recorded (model, dims, preprocessing) tuple that makes vectors comparable; change ⇒ re-embed
MediaEmbedder The multimodal extension of Module 06's Embedder: embed_documents/embed_query for text, embed_media(content, kind, role) for media — role carries the query/document asymmetry
Captioner The Pattern-2 seam: turns raw media into caption/OCR/transcript text for the caption channel

All terms are also collected in the glossary.


Exercises#

  1. Modality gap (2.2): rerun modality_gap_demo.py with GAP[16] = 0.0 (no gap) and with 0.9. At what gap size does the correct image drop below rank 2? What does that tell you about threshold-setting?
  2. Cost model (4.4): extend media_embed_cost.py with your own catalogue: N images at your resolution, M audio hours, K video hours segmented at your window size. Which term dominates? At what query volume does query cost overtake index cost?
  3. Perceptual hashing (4.5): take 20 real product photos (your own or generated), apply resize/rotate/brightness/JPEG recompress, and find the Hamming threshold that separates "same image" from "different product" on your data. Does dHash or aHash win?
  4. Design patterns (3.5): for three corpora you know (a photo library, a PDF archive, a podcast feed), pick a pattern and justify it against the decision table. Where does each pattern fail?
  5. Service (7.2): add a keyword channel to MultimodalSearchService.search() that substring-matches captions over self._items and feeds the result into _rrf as another rank list. Does the invoice query improve? Why does RRF still matter?
  6. Query types (5.3): implement the "like this but blue" flow as attribute-filter + caption-channel query on the fake service. Where would it break on a real catalogue?
  7. Keyless eval (6.5): write recall_at_k for the service: mark which catalogue items are relevant to five queries, run search(), and report recall@3 per branch (caption vs media) separately. What does the gap do to media-branch recall?
  8. Provider adapters (7.3): write a JinaOmniEmbedder for jina-embeddings-v5-omni — check the Jina embeddings API reference for how typed modality objects/URLs are passed — and explain why VoyageEmbedder.embed_media raises NotImplementedError for audio_segment and which provider in 1.2 could take over that branch.
Hints and worked answers
  1. In the toy, the image vector for item 0 scores about 1 / sqrt(1 + g²) (0.74 at g = 0.9, 1.0 at g = 0), while unrelated items hover around 0.0–0.1. So it stays at rank 2 (right behind the matching text vector) until g is on the order of 10. The ranking survives almost any gap; a fixed 0.8 threshold already drops the image match once g passes about 0.75. Ranking and thresholding fail at different gap sizes, which is why you calibrate thresholds per pair.
  2. Per-query cost for a 20-token text query on gemini-embedding-2 is about 20 × 0.20 / 1e6 = $0.000004; for an image query it is 258 × 0.45 / 1e6 ≈ $0.000116. Against a $5.80 index build, text queries overtake it after about 1.45 million queries, image queries after about 50,000. Re-run it with your own mix.
  3. Compute the Hamming distance for every (original, transform) pair and every (product A, product B) pair, then pick a threshold between the largest "same" distance you accept and the smallest "different" distance you must not merge. Run aHash and dHash separately and compare their error counts; neither wins everywhere (the lesson's table shows them disagreeing on the moved object).
  4. Compare your answers with 3.5: photo library → Pattern 1 (+3 if SKUs matter), PDF archive → 2 or 4, podcast feed → 2 (transcript segments). The failure of each pattern is in its "Costs and catches" list.
  5. Build a list of items whose lowercase caption contains a query word, keep their insertion order as the rank, and append it to the list passed to _rrf. RRF matters because a substring match has no comparable score: only ranks can be fused.
  6. Filter on {"price": {"$lt": 100}} or another tagged attribute first, then call search("blue version of red running shoe", branches=("caption",)). It breaks whenever colour is not in metadata or the caption (an untagged catalogue) and on multi-colour products.
  7. For each query keep a set of relevant item ids, call svc.search(q, top_k=3, branches=("caption",)) and again with ("media",), and compute len(found & relevant) / len(relevant). On text queries the media branch scores lower because of MODALITY_OFFSET, mirroring the real modality gap.
  8. Check the Jina embeddings API reference and model card for the request shape. VoyageEmbedder raises for audio because voyage-multimodal-3.5 has no audio input; gemini-embedding-2 (audio up to 180 s) or Jina v5-omni could take over that branch.

Check yourself#

  1. What does "shared embedding space" promise, and what does the modality gap break?
  2. Why can't you reuse one similarity threshold across text→text and text→image queries?
  3. Name the four design patterns and the situation each wins.
  4. Why is late-interaction page retrieval expensive to store, and what kind of database does it need?
  5. OpenAI and Anthropic both "lack" something here — what exactly, and what's the workaround?
  6. Your catalogue has 50k images at 2000×2000 px. Roughly what does embedding them cost on Gemini gemini-embedding-2 vs Voyage voyage-multimodal-3.5, and why the difference?
  7. When does segmenting a video increase retrieval quality but also multiply cost?
  8. What three channels make up the strongest general-purpose multimodal index, and why is BM25 still needed?
  9. "Find images like this one but blue" — list the approaches in order of reliability and say why vector arithmetic is last.
  10. In multimodal RAG, why is the embedding stage cheap and the VLM stage expensive — and what does that imply for k?
  11. What citation fields must your media payload carry for pages, regions and timestamps?
  12. Why is a face photo's embedding a privacy problem even though it's "just numbers"?
  13. What must be true before you can swap gemini-embedding-2 for voyage-multimodal-3.5 in a running index?
  14. Which query type is usually most reliable and why?
  15. Why does MediaEmbedder have embed_documents/embed_query/embed_media instead of one embed() — what does role buy you?

Further resources#

← 09.8 — Video Understanding | Module 09 overview | 09.10 — Building, Evaluating and Operating Multimodal Products →

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