Most Retrieval-Augmented Generation (RAG) pipelines fail the moment your users drop a system architecture diagram, a mobile UI screenshot, or a PDF containing a mix of text and sparse flowchart boxes into the prompt.
Standard text-only chunking treats images as dead air. It passes an empty string or drops the asset entirely. If you fall back on a basic multi-modal embedding model like CLIP, you quickly discover that it is brilliant at matching broad visual aesthetics (finding "a photo of a red sports car"), but it utterly fails at locating a specific Kubernetes ingress YAML snippet embedded inside a complex, highly technical whiteboard photo.
If you are building developer tooling, documentation copilots, or internal enterprise search, text alone is only half the surface area of your data. Technical documentation lives in architectural diagrams, Jira screenshots, wireframes, and error stack traces burned into PNGs.
This guide breaks down how to build a production-grade Multimodal RAG system that ingests, indexes, and semantically searches across screenshots, diagrams, and technical text using modern embedding models, vision-language models (VLMs), and hybrid retrieval strategies.
📋 Table of Contents
- The Real Problem With Text-Only RAG in Technical Workspaces
- 1. Ingesting Visual Assets: Resolution, Cropping, and Normalization
- 2. The Dual-Representation Strategy: Dense Vision Embeddings vs. VLM Captions
- 3. Semantic Chunking for Mixed Documents (PDFs, Markdown, and Slides)
- 4. Unified Vector Indexing With ColPali and Late Interaction Models
- 5. Hybrid Retrieval: Combining BM25 Text Search With Vector Vision Spaces
- 6. Re-Ranking Multimodal Results With Vision-Language Cross-Encoders
- 7. Context Assembly and Token Budgeting for the Generation Step
- Production Architecture and Operational Trade-offs
The Real Problem With Text-Only RAG in Technical Workspaces
Scenario: A developer queries your internal knowledge base: "Where is the fallback mechanism configured for our payment gateway microservice?"
Why it matters: The answer does not exist in plain Markdown files. It lives inside a legacy sequence diagram drawn in Miro, exported as a 4K PNG, and dropped into a Confluence page three years ago. A traditional text-based RAG pipeline—which strips out images during parsing—sees only the surrounding text: "See diagram below." The retriever returns nothing useful, the LLM hallucinates an answer based on generic payment architecture, and the developer loses trust in your system.
[ User Query: "Where is the payment fallback?" ]
│
┌───────────┴───────────┐
▼ ▼
[ Text RAG Pipeline ] [ Multimodal Pipeline ]
│ │
(Misses PNG diagram) (Extracts, OCRs, & Embeds PNG)
│ │
▼ ▼
"No results found." Returns Miro Sequence Diagram + Code Snippet
To solve this, you cannot simply slap a standard text embedding model on top of an OCR script. OCR strips spatial layout, ignores visual hierarchies (like arrows pointing from Service A to Service B), and garbles multi-column tables. True multimodal RAG requires treating images and text as first-class citizens throughout ingestion, embedding, indexing, and retrieval.
1. Ingesting Visual Assets: Resolution, Cropping, and Normalization
Scenario: Your ingestion script pulls down 500 engineering PDFs, each containing embedded architecture diagrams alongside dense paragraphs. When you pass full pages directly to a vision encoder, tiny architecture boxes become unreadable thumbnails.
Why it matters:
Vision-language models and visual embedding models have fixed context windows and image resolution caps (typically 448x448 or 512x512 pixels). If you downsample a massive system diagram to fit that window, text labels like auth-service-v2.internal:8080 turn into unreadable pixel sludge.
Solution: Implement a pre-processing pipeline that detects embedded figures in PDFs, crops bounding boxes around visual regions, and splits oversized architectural diagrams into overlapping visual tiles while preserving their aspect ratio.
import fitz # PyMuPDF
from PIL import Image
import io
def extract_and_normalize_images(pdf_path: str, output_dir: str, min_width: int = 300, min_height: int = 300):
doc = fitz.open(pdf_path)
extracted_images = []
for page_index in range(len(doc)):
page = doc[page_index]
image_list = page.get_images(full=True)
for img_index, img in enumerate(image_list):
xref = img[0]
base_image = doc.extract_image(xref)
image_bytes = base_image["image"]
image_ext = base_image["ext"]
image = Image.open(io.BytesIO(image_bytes))
width, height = image.size
# Filter out tiny icons, decorative bullets, and spacer images
if width < min_width or height < min_height:
continue
# Normalize color space and format
if image.mode != "RGB":
image = image.convert("RGB")
filename = f"page_{page_index}_img_{img_index}.{image_ext}"
save_path = f"{output_dir}/{filename}"
image.save(save_path, optimize=True, quality=95)
extracted_images.append({"path": save_path, "page": page_index, "dims": (width, height)})
return extracted_images
Why this works: Filtering out sub-300px icons keeps your vector database clean of useless UI chrome, logos, and spacers. Normalizing to RGB ensures downstream vision encoders don't throw dimension mismatch errors on CMYK or grayscale palette variants.
💡 Practical note: When dealing with massive engineering blueprints or sprawling CI/CD pipeline graphs, consider splitting the image into a $2 \times 2$ grid with 15% overlap. This allows patch-based vision models to retain high-frequency text readability across boundaries.
2. The Dual-Representation Strategy: Dense Vision Embeddings vs. VLM Captions
Scenario: You need to index both UI screenshots of your React dashboard and dense database schema diagrams. A developer might search for "user settings modal component" or "foreign key relationship between users and orders."
Why it matters: No single embedding approach handles both raw visual layout similarity and deep conceptual textual queries equally well. Pure vision models struggle with abstract conceptual queries, while pure text captions generated by a VLM miss exact visual positioning and UI aesthetics.
Solution: Adopt a Dual-Representation Strategy. For every ingested image, generate two distinct artifacts and store them linked in your database:
- A dense visual embedding (via models like ColPali or CLIP-variant encoders) capturing spatial layout, colors, and structural shapes.
- A structured VLM caption / OCR transcript generated by a model like Claude 3.5 Sonnet, GPT-4o, or Llama-3.2-Vision, capturing explicit text, semantic intent, and component relationships.
from openai import OpenAI
import base64
client = OpenAI()
def generate_vlm_caption(image_path: str) -> str:
with open(image_path, "rb") as image_file:
encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this technical image. Provide a detailed description including: 1) All visible text, error codes, or UI labels, 2) The structural layout or architecture flow, 3) Any specific configuration values or code snippets visible."
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{encoded_image}"
}
}
]
}
],
max_tokens=500
)
return response.choices[0].message.content
Why this works: When a user searches using natural language ("show me where the Redis cache sits in the auth flow"), the text query matches against the VLM-generated caption and OCR transcript via standard dense text search. When a user queries with a visual concept or structural layout, the visual embedding handles the similarity space.
3. Semantic Chunking for Mixed Documents (PDFs, Markdown, and Slides)
Scenario: Your technical documentation consists of 100-page PDF specifications where text paragraphs flow directly into large architectural diagrams, followed by bullet points and tables.
Why it matters: Traditional fixed-size chunking (e.g., splitting every 500 characters) will slice an architecture diagram right down the middle, separating the visual nodes from their explanatory caption and rendering both useless.
Solution: Implement a layout-aware semantic chunking algorithm that parses document object models (DOM) or PDF bounding boxes, grouping images, tables, and adjacent text headers into cohesive atomic chunks.
class MixedContentChunk:
def __init__(self, chunk_id: str, text_content: str, images: list, metadata: dict):
self.chunk_id = chunk_id
self.text_content = text_content
self.images = images
self.metadata = metadata
def build_layout_chunks(parsed_elements: list) -> list[MixedContentChunk]:
chunks = []
current_text = []
current_images = []
chunk_counter = 0
for element in parsed_elements:
if element["type"] == "heading" and (current_text or current_images):
# Flush existing chunk on new major heading
chunks.append(MixedContentChunk(
chunk_id=f"chunk_{chunk_counter}",
text_content="\n".join(current_text),
images=current_images,
metadata={"source_page": element["page"]}
))
chunk_counter += 1
current_text = [element["content"]]
current_images = []
elif element["type"] == "text":
current_text.append(element["content"])
elif element["type"] == "image":
current_images.append(element["path"])
# Flush final buffer
if current_text or current_images:
chunks.append(MixedContentChunk(
chunk_id=f"chunk_{chunk_counter}",
text_content="\n".join(current_text),
images=current_images,
metadata={"source_page": parsed_elements[-1]["page"]}
))
return chunks
Why this works: By keeping images tied to their surrounding header context and sibling paragraphs within the same semantic block, you ensure that retrieval pulls the diagram along with the paragraph that references it.
4. Unified Vector Indexing With ColPali and Late Interaction Models
Scenario: You’ve generated visual embeddings and text captions, but you're tired of maintaining separate vector spaces, disparate search indexes, and complex routing logic to decide whether to query the text index or the image index.
Why it matters:
Standard bi-encoders compress an entire image or document into a single 1536-dimensional vector. This massive compression bottleneck causes fine-grained details—such as a tiny port number 5432 on a database node in a complex diagram—to vanish entirely.
Solution: Adopt ColPali (Contextualized Late Interaction over Patches for Image Retrieval). Instead of compressing an image into a single vector, ColPali leverages a Vision Transformer (ViT) to output a matrix of patch-level embeddings (e.g., $N \times 128$), preserving fine-grained spatial and textual tokens across the image.
from colpali_engine.models import ColPali, ColPaliProcessor
from torch.utils.data import DataLoader
import torch
# Initialize model and processor (ensure GPU availability)
model_name = "vidore/colpali-v1.2"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ColPali.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map=device
)
processor = ColPaliProcessor.from_pretrained(model_name)
def encode_images_colpali(image_paths: list[str]):
images = [Image.open(p).convert("RGB") for p in image_paths]
dataloader = DataLoader(
images,
batch_size=4,
shuffle=False,
collate_fn=lambda x: processor.process_images(x)
)
all_embeddings = []
model.eval()
with torch.no_grad():
for batch in dataloader:
batch = {k: v.to(device) for k, v in batch.items()}
embeddings = model(**batch)
all_embeddings.append(embeddings.cpu())
return torch.cat(all_embeddings, dim=0)
Why this works: ColPali uses MaxSim (Maximum Similarity) late interaction scoring during retrieval. It computes the token-to-patch similarity matrix between your text query and the image patches, meaning a query for "Postgres configuration" will explicitly match against the visual patches containing the word "Postgres" or the database icon inside the image.
🚨 Production warning: ColPali generates significantly larger index footprints than standard single-vector embeddings because it stores multi-vector patch embeddings per page. Ensure your vector database or storage tier has sufficient RAM and disk IOPS allocated for late interaction indexing.
5. Hybrid Retrieval: Combining BM25 Text Search With Vector Vision Spaces
Scenario:
A user searches for an exact function name: processWebhookEventV2(). While vector models excel at semantic intent, they often struggle with exact keyword matches, symbol names, and exact error hashes.
Why it matters: If your search relies solely on vector similarity, exact code symbols, stack traces, and variable names can get lost in the embedding space. Developers expect exact string matching when hunting for code or configuration keys.
Solution: Build a hybrid retrieval pipeline that executes BM25 lexical search over your VLM captions and OCR text in parallel with your dense vector/ColPali retrieval, fusing the results using Reciprocal Rank Fusion (RRF).
from rank_bm25 import BM25Okapi
import numpy as np
class HybridMultimodalRetriever:
def __init__(self, corpus_texts: list[str], image_paths: list[str], vector_store):
tokenized_corpus = [doc.lower().split(" ") for doc in corpus_texts]
self.bm25 = BM25Okapi(tokenized_corpus)
self.corpus_texts = corpus_texts
self.image_paths = image_paths
self.vector_store = vector_store
def search(self, query: str, query_embedding: list[float], top_k: int = 5) -> list[dict]:
# 1. Lexical BM25 Search
tokenized_query = query.lower().split(" ")
bm25_scores = self.bm25.get_scores(tokenized_query)
top_bm25_indices = np.argsort(bm25_scores)[::-1][:top_k]
# 2. Vector / Dense Search
vector_results = self.vector_store.similarity_search(query_embedding, k=top_k)
# 3. Reciprocal Rank Fusion (RRF)
fusion_scores = {}
k_val = 60 # RRF constant
for rank, idx in enumerate(top_bm25_indices):
fusion_scores[idx] = fusion_scores.get(idx, 0.0) + 1.0 / (k_val + rank + 1)
for rank, res in enumerate(vector_results):
idx = res["metadata"]["internal_id"]
fusion_scores[idx] = fusion_scores.get(idx, 0.0) + 1.0 / (k_val + rank + 1)
sorted_results = sorted(fusion_scores.items(), key=lambda x: x[1], reverse=True)
return [{"id": item[0], "score": item[1], "path": self.image_paths[item[0]]}
for item in sorted_results[:top_k]]
Why this works: RRF is parameter-free and robust. It doesn't require normalizing scores across wildly different distance metrics (like Cosine distance vs. BM25 score scales), preventing lexical search or vector search from dominating the result set entirely.
6. Re-Ranking Multimodal Results With Vision-Language Cross-Encoders
Scenario: Your hybrid retriever returns 20 candidate documents consisting of text snippets, UI screenshots, and architecture diagrams. However, 12 of those images are irrelevant noise that share a few overlapping keywords.
Why it matters: Passing 20 raw images into an LLM context window will instantly blow up your token budget, introduce massive latency, and degrade reasoning quality due to the "lost in the middle" attention phenomenon.
Solution: Add a cross-encoder re-ranker specifically trained on multimodal pairs (such as Jina CLIP Reorder or a custom Vision Cross-Encoder) to re-evaluate the top candidate pool before passing them to the generator.
from transformers import AutoModelForSequenceClassification, AutoProcessor
import torch
class MultimodalReranker:
def __init__(self, model_name: str = "jinaai/jina-colbert-v2"):
# Utilizing state-of-the-art cross-encoder or late-interaction reranker
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = AutoModelForSequenceClassification.from_pretrained(model_name).to(self.device)
self.processor = AutoProcessor.from_pretrained(model_name)
def rerank(self, query: str, candidates: list[dict], top_n: int = 3) -> list[dict]:
scored_candidates = []
for candidate in candidates:
image = Image.open(candidate["path"]).convert("RGB")
inputs = self.processor(text=[query], images=[image], return_tensors="pt", padding=True).to(self.device)
with torch.no_grad():
outputs = self.model(**inputs)
score = outputs.logits.item()
scored_candidates.append({**candidate, "rerank_score": score})
scored_candidates.sort(key=lambda x: x["rerank_score"], reverse=True)
return scored_candidates[:top_n]
Why this works: Cross-encoders evaluate the query and the image/text pair simultaneously through full self-attention layers, capturing deep semantic alignment that simple bi-encoder cosine similarity misses.
7. Context Assembly and Token Budgeting for the Generation Step
Scenario: You have successfully retrieved the top 3 items: an architecture diagram (PNG), a technical specification sheet (Markdown), and an error log screenshot (PNG). You now need to format them into a prompt for your LLM.
Why it matters:
Different vision-capable LLMs handle image inputs differently. Claude 3.5 Sonnet and GPT-4o expect base64-encoded image parts inline within message arrays, while local models like LLaVA require specific prompt template tokens (<image>). Mismanaging your image payload sizes will trigger HTTP 413 Payload Too Large or API rate limit errors.
Solution: Implement dynamic image resizing and payload assembly that formats mixed text and visual chunks into a clean, structured prompt payload.
import base64
from io import BytesIO
def prepare_vlm_prompt(query: str, retrieved_chunks: list[dict]) -> list[dict]:
content_payload = []
# Add context instructions
content_payload.append({
"type": "text",
"text": f"You are an expert technical assistant. Answer the user query using ONLY the provided context documents, code snippets, and diagrams.\n\nUser Query: {query}\n\nContext:"
})
for i, chunk in enumerate(retrieved_chunks):
content_payload.append({
"type": "text",
"text": f"\n--- Document Source {i+1} (Text) ---\n{chunk.get('text_content', '')}"
})
if "image_path" in chunk:
image = Image.open(chunk["image_path"])
# Resize image to save tokens if dimensions exceed 1024x1024
image.thumbnail((1024, 1024))
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
content_payload.append({
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_str}",
"detail": "high"
}
})
messages = [{"role": "user", "content": content_payload}]
return messages
Why this works: Resizing images to a maximum bounding box of $1024 \times 1024$ prevents massive 4K diagrams from consuming thousands of unnecessary vision tokens while keeping critical text labels crisp enough for the VLM to parse accurately.
Production Architecture and Operational Trade-offs
Building a production-ready multimodal RAG pipeline requires balancing ingestion compute costs, index storage footprint, and query latency. The table below outlines how different components stack up in real-world deployment:
| Component / Layer | Recommended Choice | Complexity | Latency Impact | Cost / Resource Trade-off |
|---|---|---|---|---|
| Image Extraction | PyMuPDF (fitz) + Custom Filtering |
Low | Low (<50ms/page) | Minimal CPU overhead; filters noise early. |
| Caption Generation | GPT-4o / Claude 3.5 Sonnet | Medium | High (Async queue needed) | API costs per ingested image; essential for text-query matching. |
| Vector Indexing | ColPali / Multi-Vector Store | High | Medium (GPU required) | High memory footprint; provides unmatched spatial retrieval accuracy. |
| Hybrid Search | BM25 + Vector RRF | Medium | Low (<20ms) | Requires maintaining dual indexes (text + vector). |
| Re-ranking | Jina-ColBERT / Cross-Encoder | High | Medium (100–300ms) | Adds latency at query time; drastically cuts down hallucination rates. |
Final Architectural Observation
Never build a multimodal RAG system by treating images as an afterthought bolted onto an existing text database. Design your ingestion pipeline from day one to extract, normalize, caption, and index visual artifacts alongside text. By combining ColPali late interaction embeddings for structural visual search with BM25 lexical retrieval for code symbols and exact names, you bridge the gap between human visual documentation and machine reasoning.