🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Multi-Modal RAG for Images, Tables and Code

RAGopsMulti-Modal RetrievalđŸŸĸ Free Lesson

Text-only retrieval loses most of the document

Enterprise corpora are rarely prose. A product manual interleaves instructions with wiring diagrams. A quarterly review is half narrative and half financial tables. An incident report embeds screenshots of logs and a screenshot of the dashboard that first caught the regression. A text-only pipeline extracts the paragraphs and silently discards the evidence that users are actually asking about — which is why questions about "the chart on page twelve" return confident answers about the surrounding caption instead.

Multi-modal retrieval-augmented generation closes that gap by parsing each content type, embedding it into a shared or aligned vector space, and reassembling mixed context for the generator. The design questions are practical rather than exotic: which modality to keep, how to represent it for the retriever, and what the generator can actually consume at answer time.

The honest constraint is that most generators accept text and images only in restricted forms, and vision tokens are expensive. Most working systems therefore use a hybrid representation: images are captioned or described in detail at ingestion time and both the image and its description are indexed, while tables are serialised into structured text and optionally kept as structured objects for exact lookup. Retrieval then runs mostly in text space, and modality-specific paths are used only where they measurably improve results.

Parsing mixed-content documents

A multi-modal parser walks each page and classifies blocks by type. Text blocks come out with bounding boxes that let you preserve reading order and associate a caption with the figure above it. Embedded images are extracted at native resolution, with format and size recorded so downstream steps can decide whether to run OCR, captioning, or both. Tables need explicit detection — they arrive as drawn cells, as spacing-only layouts, or as embedded images of spreadsheets, and each requires a different extractor.

Two details decide whether the output is usable. First, keep page-level provenance on every extracted item: a caption without its page number cannot be cited, and a table without its section heading loses the context that disambiguates similar columns. Second, deduplicate repeated artefacts. Logos, headers, and decorative figures appear on hundreds of pages and will happily consume the entire embedding budget while adding nothing.

python
import re
from dataclasses import dataclass, field


@dataclass
class ContentItem:
    kind: str          # text | image | table
    payload: str | bytes
    page: int
    provenance: str
    metadata: dict = field(default_factory=dict)


class MixedDocumentParser:
    NOISE_PATTERNS = [
        re.compile(r"^\s*page \d+ of \d+\s*$", re.I),
        re.compile(r"^\s*confidential\b", re.I),
    ]

    def parse(self, page_iter, source: str) -> list[ContentItem]:
        items = []
        for page_number, page in enumerate(page_iter, start=1):
            for block in page.text_blocks():
                if self._is_noise(block.text):
                    continue
                items.append(ContentItem(
                    kind="text", payload=block.text.strip(), page=page_number,
                    provenance=source,
                    metadata={"bbox": block.bbox, "section": block.section},
                ))
            for image in page.images(min_width=120, min_height=120):
                items.append(ContentItem(
                    kind="image", payload=image.bytes, page=page_number,
                    provenance=source,
                    metadata={"format": image.format, "caption": image.caption},
                ))
            for table in page.tables():
                items.append(ContentItem(
                    kind="table", payload=table.rows, page=page_number,
                    provenance=source,
                    metadata={"caption": table.caption, "n_rows": len(table.rows)},
                ))
        return items

    def _is_noise(self, text: str) -> bool:
        stripped = text.strip()
        return len(stripped) < 20 or any(p.match(stripped) for p in self.NOISE_PATTERNS)

Rejecting noise at parse time is cheaper than discovering it later in the vector index, where every duplicate logo is one more false neighbour for an unrelated query.

Embedding images alongside text

Two embedding strategies compete. A joint vision-language encoder maps images and text into one space, so a text query can retrieve an image directly — the standard approach when the questions are visual ("show me the topology diagram"). A pipeline approach captions each image with a vision model, then embeds the caption with a conventional text encoder — cheaper, fully indexable with existing infrastructure, and better when the questions are about what the image means in context rather than what it looks like.

Most production systems keep both: the joint encoder for visual similarity, the caption for semantic retrieval and as the fallback the generator actually reads. Store the caption alongside the image record so a retrieved image can always be rendered as text if the generation path cannot accept images.

ModalityRetrieval representationGenerator inputFailure mode if skipped
ProseChunk textTextBaseline behaviour
FigureCaption + visual embeddingCaption, optionally imageVisual evidence invisible
TableSerialised rowsSerialised textNumbers misattributed
CodeLanguage-tagged chunkFenced textSnippets split mid-function

Tables: serialise, summarise, or both

Tables are where multi-modal pipelines most often fail silently. A naive converter emits comma-separated values with no header association, and the generator then pairs a number with the wrong column. Serialisation should be row-oriented and header-aware: "Region: EMEA; Revenue: 4.2M; Growth: 11%" is unambiguous, greppable, and embeds better than a raw grid.

For wide tables, add a generated summary line with the table's topic and its most salient statistics, and index the summary as well as the serialised rows. Retrieval often matches the summary while the answer needs the exact row, so returning both keeps the generator grounded. Preserve the original structured form in metadata so an exact-value question can be answered by lookup instead of by generation, which eliminates a whole class of arithmetic hallucinations.

python
class TableSerialiser:
    """Turn a grid of cells into unambiguous, embeddable text."""

    def __init__(self, max_rows: int = 25):
        self.max_rows = max_rows

    def to_text(self, rows: list[list[str]]) -> str:
        if not rows:
            return ""
        headers = [h.strip() for h in rows[0]]
        lines = [f"Table columns: {', '.join(headers)}"]
        for row in rows[1:self.max_rows + 1]:
            pairs = [
                f"{header}: {cell.strip()}"
                for header, cell in zip(headers, row)
                if cell.strip()
            ]
            if pairs:
                lines.append("; ".join(pairs))
        remaining = max(len(rows) - 1 - self.max_rows, 0)
        if remaining:
            lines.append(f"({remaining} further rows omitted)")
        return "\n".join(lines)

    def lookup(self, rows: list[list[str]], column: str, key: str) -> str | None:
        if not rows:
            return None
        headers = [h.strip() for h in rows[0]]
        if column not in headers:
            return None
        col = headers.index(column)
        for row in rows[1:]:
            if row and row[0].strip() == key and len(row) > col:
                return row[col].strip()
        return None

The lookup method is the point of keeping structure around: an exact-value question is answered by a table scan, and only the softer comparative questions fall through to generation.

Fusing modalities in the context window

Once retrieval returns a mixed list, assembly determines what the model sees. Keep each item labelled by kind — text, image description, table — and keep each item's provenance attached, because models cite more carefully when citations are available. Order items by relevance but group them by source document so the model can read one document's contributions together rather than interleaving fragments.

Budget explicitly. Vision inputs and long table serialisations both expand quickly; cap per-item tokens and prefer several short, on-point items over one enormous context block. When the retrieved set is mostly images and the generation path is text-only, the caption becomes the authoritative representation and should be written to stand alone — describing axis labels, units, and trends rather than saying "see chart above".

Evaluating across modalities

Retrieval evaluation extends naturally: label relevance per item regardless of kind, then compute recall and precision as before. Generation evaluation needs modality-aware checks. For table questions, verify numeric answers against the structured original rather than against the prose. For figure questions, check that claims appear in the caption or in an OCR pass over the image. Cross-modal faithfulness — is every claim supported by some item in the mixed context — catches the characteristic failure of answering a table question from a nearby paragraph that discusses a different quarter.

Cost and latency realities

Captioning every image at ingestion is a one-time cost per document and is almost always worth it. Running a vision encoder per query is a recurring cost and rarely is: index images once, embed the query as text, and invoke the vision path only when text-first retrieval misses. Measure the per-modality hit rate — how often the winning evidence came from an image, a table, or prose — before expanding the multi-modal budget, because that number tells you which parsing investments pay rent.

Best Practices

  • Keep page-level provenance and captions on every extracted item so answers remain citable across modalities.
  • Deduplicate logos, headers, and decorative figures at parse time before they pollute the vector index.
  • Index both the image and its caption; let text-first retrieval lead and invoke vision paths only on a miss.
  • Serialise tables row-wise with explicit headers, and keep the structured original for exact-value lookup.
  • Label every context item by kind and source so the generator can attribute claims correctly.
  • Measure per-modality retrieval hit rate before spending more on captioning or vision encoding.

Key Takeaways

  • Most enterprise evidence lives in tables and figures, so text-only retrieval systematically loses the questions users ask.
  • Parse each page into typed items with provenance, and reject noise before it reaches the embedding stage.
  • Joint vision-language encoders answer visual similarity questions; captions answer semantic ones — keep both representations.
  • Table serialisation must be header-aware and row-oriented, or the generator pairs numbers with the wrong columns.
  • Context assembly should group by source, label by kind, and cap per-item tokens to protect the generator's attention.
  • Evaluate numeric answers against structured originals, not against the prose that happens to sit nearby.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement