Skip to content
manukothari

Production RAG

Building a Multimodal RAG Pipeline for Semantic Image Search using Gemini 2.5

A practical walkthrough of using Gemini 2.5 Pro, multimodal embeddings, vector storage, and cosine similarity to build a semantic photo retrieval system.

7 min read

Part 1 of 4 · Production RAG
  1. Building a Multimodal RAG Pipeline for Semantic Image Search using Gemini 2.5
  2. Beyond Naive RAG: Five Retrieval Patterns That Actually Work in Production
  3. Building Agentic RAG with Google's Agent Development Kit
  4. Evaluating RAG Pipelines: Building a Gemini-Powered LLM-as-Judge System
On this page

The photos on your phone are searchable today only because someone — Apple, Google, or you — paid the cost of labeling them. That labeling is brittle. It collapses a rich visual scene into a handful of keywords (beach, dog, sunset) and throws everything else away. So a query like "the photo where my niece is reaching for the cake but hasn't grabbed it yet" returns nothing useful, even though every detail you described is sitting right there in the pixels.

Multimodal embeddings fix this. Instead of describing an image with text, you let a vision-language model project the image and your query into the same high-dimensional vector space, then you ask: which image vectors point closest to the query vector? It's RAG, but the "documents" are pictures.

This post walks through a working pipeline end-to-end. We'll use Google's multimodal embedding endpoint to project images and queries into a shared vector space, and Gemini 2.5 Pro when we need a generative model in the loop (re-ranking, query rewriting, caption augmentation). We'll cover the architecture, generate embeddings, store them, query them, and then talk about what changes when you go from prototype to production.

A note on which Gemini does what: there are two models in play. gemini-embedding-2 is the multimodal embedding endpoint — it takes text, images, video, audio, or documents in and returns vectors in a single shared space. gemini-2.5-pro is the generative multimodal model — images in, text out — which is useful when you want to re-rank results, rewrite queries, or generate captions to augment your index. The two are commonly confused because they share the Gemini brand.

Architecture overview

The system is two paths bolted to the same vector store.

text
INGEST                                       QUERY
──────                                       ─────
images/   ─┐                       text   ─┐
            ├─► gemini-embedding-2 ──► vec ──┐  ├─► gemini-embedding-2 ──► vec
metadata ─┘                              │                          │
                                         ▼                          ▼
                                   ┌──────────────────────────────────┐
                                   │  Vector store (NumPy / FAISS /   │
                                   │  pgvector)                       │
                                   └──────────────────────────────────┘
                                                   │
                                                   ▼
                                            top-k by cosine

The crucial property: ingestion and query both pass through the same embedding model, so the vectors live in a shared geometry. A photo of a labrador on a beach and the query "golden dog on sand" end up near each other not because of shared keywords, but because the model learned that they describe the same kind of scene.

What you control is everything around the model: how images get in, how vectors get stored, how queries get rewritten, and how results get ranked. The model itself is a black box you call over the network.

Generating embeddings with gemini-embedding-2

Install the new Google GenAI SDK and set your API key as GEMINI_API_KEY. The SDK auto-discovers the env var when you instantiate the client.

python
import os
from google import genai
from PIL import Image
 
client = genai.Client()
 
EMBED_MODEL = "gemini-embedding-2"
 
def embed_image(path: str) -> list[float]:
    img = Image.open(path)
    result = client.models.embed_content(
        model=EMBED_MODEL,
        contents=img,
        config={"task_type": "RETRIEVAL_DOCUMENT"},
    )
    return result.embeddings[0].values

gemini-embedding-2 accepts a PIL Image directly; you don't need to base64-encode it yourself. By default the model returns a 3072-dimensional vector. We pass task_type: "RETRIEVAL_DOCUMENT" so the model optimizes the embedding geometry for asymmetric retrieval (short query → rich document).

For the text query side, the SDK uses a corresponding task_type to tell the model you're embedding a search query, not a document:

python
def embed_query(text: str) -> list[float]:
    result = client.models.embed_content(
        model=EMBED_MODEL,
        contents=text,
        config={"task_type": "RETRIEVAL_QUERY"},
    )
    return result.embeddings[0].values

The RETRIEVAL_QUERY vs RETRIEVAL_DOCUMENT distinction matters. It tells the model to optimize for asymmetric similarity — short queries matching against rich content. In practice we've seen Recall@10 lift by 5–8% over un-typed embeddings on photo libraries, so it's worth the one extra config line.

For a real ingestion run you want concurrency, rate-limit handling, and resumability. A minimal version with asyncio and a semaphore looks like this:

python
import asyncio
from pathlib import Path
 
CONCURRENCY = 8
 
async def embed_batch(paths: list[Path]) -> dict[str, list[float]]:
    sem = asyncio.Semaphore(CONCURRENCY)
 
    async def one(p: Path):
        async with sem:
            for attempt in range(5):
                try:
                    return p.name, await asyncio.to_thread(embed_image, str(p))
                except Exception as e:
                    wait = 2 ** attempt
                    print(f"retry {p.name} in {wait}s: {e}")
                    await asyncio.sleep(wait)
            return p.name, None
 
    results = await asyncio.gather(*(one(p) for p in paths))
    return {name: vec for name, vec in results if vec is not None}

The exponential backoff covers the two failure modes you'll actually hit: 429s when you exceed your per-minute quota, and transient 503s when Google rebalances. Anything beyond five retries usually means the image is corrupt or the API key is wrong, and you want those to surface, not silently retry forever.

If you're embedding a large library all at once, the Batch API is cheaper and avoids quota pressure. The async loop above is the right shape for streaming uploads where you need fresh vectors immediately.

Vector storage

For under ~50K vectors, NumPy plus a pickle is enough. The whole index fits in memory, the search is a single matmul, and you skip a whole class of operational problems.

python
import numpy as np
import pickle
 
def build_index(embeddings: dict[str, list[float]], out: str) -> None:
    names = list(embeddings.keys())
    matrix = np.array([embeddings[n] for n in names], dtype=np.float32)
    with open(out, "wb") as f:
        pickle.dump({"names": names, "matrix": matrix}, f)

gemini-embedding-2 returns vectors that are already L2-normalized — including truncated dimensions (768, 1536), which the model auto-renormalizes. That means cosine similarity collapses to a plain dot product at query time without any pre-processing on your end. If you ever switch to a model that doesn't normalize (older text-embedding-004 truncated outputs, for instance), add matrix /= np.linalg.norm(matrix, axis=1, keepdims=True) here.

Past 50K vectors, three things start to bite: the matmul slows linearly, the pickle gets ugly to update incrementally, and you start wanting to filter by metadata (date range, album, person). Two upgrade paths:

  • FAISS if your data lives on one machine and you want sub-millisecond search with approximate-nearest-neighbor indexes (IndexHNSWFlat is a sane default).
  • pgvector if you already run Postgres and you want metadata filtering, transactional updates, and replication for free. The latency is higher (~10-50ms vs <1ms) but the operational story is dramatically simpler.

Don't reach for these on day one. The prototype-to-production gap is where most of these projects die, and you'll learn more about your actual query patterns from the NumPy version than from a premature pgvector deployment.

With normalized vectors, the query path is a few lines of NumPy:

python
def search(query: str, index: dict, k: int = 10) -> list[tuple[str, float]]:
    result = client.models.embed_content(
        model=EMBED_MODEL,
        contents=query,
        config={"task_type": "RETRIEVAL_QUERY"},
    )
    q = np.array(result.embeddings[0].values, dtype=np.float32)
 
    scores = index["matrix"] @ q  # (N,) cosine similarities
    top = np.argpartition(-scores, k)[:k]
    top = top[np.argsort(-scores[top])]
    return [(index["names"][i], float(scores[i])) for i in top]

argpartition followed by a small argsort is meaningfully faster than a full argsort once your index has more than a few thousand entries — you're sorting k items, not N. With k=10 and N=100,000 it's roughly 30x faster on my laptop.

The score is in [-1, 1]. In practice cross-modal cosine scores cluster much tighter than that (often 0.15 to 0.35 for any reasonable hit), so don't bother with absolute thresholds — rank, then trust the top of the list.

Productionization notes

A few things to keep in mind when you're ready to put this in front of users:

Cache embeddings aggressively. Image embeddings cost money and don't change. Keep the (image_hash → vector) mapping in a key-value store and only call Gemini for new uploads. A SHA-256 of the file bytes works fine; you don't need a perceptual hash unless you're trying to dedupe re-encodings of the same photo.

Consider dimension reduction. gemini-embedding-2 defaults to 3072 dimensions but is trained with Matryoshka Representation Learning, so you can request 1536 or 768 dimensions via output_dimensionality without retraining. Smaller vectors cut storage and search time linearly with the dimension ratio, and the model auto-renormalizes truncated outputs so cosine math stays correct. Run a Recall@10 comparison on your own data before committing — for most photo libraries 1536 holds up; 768 is more aggressive.

python
result = client.models.embed_content(
    model=EMBED_MODEL,
    contents=img,
    config={
        "task_type": "RETRIEVAL_DOCUMENT",
        "output_dimensionality": 1536,
    },
)

Measure recall, not vibes. Build a small evaluation set of (query, expected images) pairs by hand — a hundred is plenty to start. Track Recall@10 and MRR (mean reciprocal rank) over time. Without this you have no way to tell whether a change to the prompt, the chunking, or the model actually improved things or just shifted which queries are broken.

Watch the cost shape. Embedding costs scale with ingestion (one-time per image), not with queries (cheap text embeddings on each search). If your images grow at a steady rate, costs are predictable. If you ever re-embed everything because of a model upgrade, that's a budgeting event — plan for it.

Conclusion

Multimodal RAG is one of those rare cases where the architecture is genuinely simple and the model does the hard part. The whole working system is fewer than 100 lines of Python on top of Gemini's embedding endpoint. The interesting engineering happens at the edges: keeping the index fresh, evaluating quality, and choosing when to graduate from NumPy to a real vector store.

If you want to dig deeper:

The next post in this series will cover hybrid retrieval — combining the dense vector search above with a sparse BM25 layer to recover the queries where keyword matching still wins.