Vectorizing Non-Text Information for RAG Knowledge Bases: A Practical Guide

    This article explains why document parsing determines the quality ceiling of a RAG knowledge base and how to bring images, tables, and formulas into a unified vectorization pipeline. It covers a four-layer architecture, table structure recovery and chunking, dual-channel image handling, shared versus text-projection vector spaces, hybrid retrieval, and measurable evaluation metrics, along with common pitfalls to avoid. Readers will find reusable design patterns and sample code for building retrieval systems that stay accurate and traceable on real-world documents.

    Vectorizing Non-Text Information for RAG Knowledge Bases: A Practical Guide

    In a retrieval-augmented generation (RAG) system, the quality ceiling of the knowledge base is usually set by the document parsing stage. Real business documents are rarely clean text streams: PDFs contain cross-page tables and merged cells, web pages contain infographics and screenshots, and scanned files mix formulas, stamps, and handwritten annotations. If the parsing stage discards this content as noise, the later chunking, embedding, and retrieval steps can only work with incomplete information, and the probability of answers that read fluently but contain wrong data rises sharply.

    This article takes an engineering perspective on how to bring non-text information such as images and tables into a unified vectorization pipeline, and offers reusable design patterns with sample code.

    1. The Problem: Why Non-Text Information Creates Retrieval Gaps

    Traditional embedding models take text as their only input and output vectors in a text semantic space. Non-text information carries meaning in entirely different ways:

    • Tables derive meaning from two-dimensional structure and row-column correspondence. Once extracted as a flat text stream, three cells such as “2023 / East China / 1200” are pulled into a single line, the row and column ownership is lost, and the model cannot tell which metric 1200 belongs to.
    • Images derive meaning from the visual content itself. Information in architecture diagrams, flowcharts, and UI screenshots cannot be fully recovered by OCR alone; arrow directions, color-coded regions, and indentation levels are all part of the semantics.
    • Layout carries meaning on its own. Heading levels, column order, and footnote placement determine reading order, and a wrong extraction order directly breaks contextual coherence.

    So the real issue is not “whether to support multimodality” but how to project heterogeneous information into the same comparable vector space while ensuring that a retrieval hit can be traced back to the original evidence.

    2. Overall Architecture: A Four-Layer Pipeline

    A robust design can be split into four layers, decoupled from each other by a structured intermediate representation:

    1. Parsing layer: convert carriers such as PDFs, images, and web pages into an intermediate format with layout structure (for example Markdown or structured JSON), preserving heading levels, reading order, table structure, and coordinate information.
    2. Element classification layer: split the document flow into typed elements such as text blocks, table blocks, image blocks, and formula blocks, and bind a different processing strategy to each type.
    3. Embedding layer: text goes through a text embedding model; tables go through “structured serialization + text embedding” or a dedicated table representation; images go through a joint vision-language representation, with a retrievable text description generated as a supplementary index.
    4. Retrieval and generation layer: hybrid recall combining vector retrieval and keyword retrieval; after a hit, trace back to the parent block for context, then hand it to the LLM for generation.

    A sample intermediate representation looks like this:

    1. {
    2. "page": 12,
    3. "elements": [
    4. {"type": "text", "level": 2, "content": "Annual Revenue Breakdown"},
    5. {"type": "table", "html": "<table>...</table>", "bbox": [72, 310, 520, 640]},
    6. {"type": "image", "caption": "Revenue Share by Region", "bbox": [80, 660, 500, 900]}
    7. ]
    8. }

    The value of bbox coordinates is often underestimated: they support layout reconstruction and reading-order correction, and they let retrieval results be highlighted precisely at the original location, which makes manual verification easier.

    3. Table Handling: From Two-Dimensional Structure to an Embeddable Sequence

    Tables are the most information-dense and the most error-prone elements in RAG. The recommended processing chain:

    (1) Prioritize structure recovery. You need to detect ruled and borderless tables, the row and column spans of merged cells, and the stitching of tables that continue across pages. The test is straightforward: if the recovered table can be expressed in HTML or Markdown with the same row and column counts as the original, the structure is intact.

    (2) Structured serialization. Convert the table into a linear form the model can consume. Three common approaches:

    • Markdown tables: good readability, suitable for going straight into the context;
    • HTML tables: can express merged cells, with higher fidelity;
    • Row-level natural language rendering: turn each row into a sentence like “the metric is X, the 2023 value is Y, and the year-over-year change is Z”, which noticeably improves dense retrieval recall.

    (3) Chunking strategy. When splitting a large table by rows, every chunk must carry the header and the table title so that each chunk is semantically self-contained:

    1. def chunk_table(rows, header, chunk_size=20, title=""):
    2. chunks = []
    3. for i in range(0, len(rows), chunk_size):
    4. body = rows[i:i + chunk_size]
    5. md = f"### {title}\n| " + " | ".join(header) + " |\n"
    6. md += "| " + " | ".join(["---"] * len(header)) + " |\n"
    7. for r in body:
    8. md += "| " + " | ".join(r) + " |\n"
    9. chunks.append({"text": md, "meta": {"type": "table", "rows": body}})
    10. return chunks

    (4) Supplementary index for numeric Q&A. For metric tables, you can additionally generate “question-answer” pseudo-documents (for example, “What was East China’s 2023 revenue? 1200”) and store them together with the table chunks, compensating for the weakness of dense vectors on exact numeric values.

    4. Image Handling: A Dual Channel of Visual Representation and Text Description

    Images cannot be treated uniformly. Classify them by semantic role first, then route them:

    • Informative images (architecture diagrams, flowcharts, trend charts): use a vision-language model to generate a structured description that explicitly states the entities, levels, and relationships in the image; also keep a reference to the original image so it can be passed back as a multimodal input during generation.
    • Decorative images (icons, separators, backgrounds): filter them out directly to avoid polluting the vector space.
    • Images containing text (screenshots, scans): run text recognition first, then concatenate the recognized text with the image description into a single multimodal document.
    • Formulas: convert them into a readable linear form (such as LaTeX) and embed them together with the surrounding paragraph.

    The key benefit of the dual channel is explainability and graceful degradation: even if the retrieval service only supports text vectors, the image descriptions still make the information retrievable; when the upper-layer model accepts image input, the original image can be handed to the model for direct reading.

    5. A Unified Vector Space and Hybrid Retrieval

    Multimodal information ultimately has to land on the same retrieval interface. There are two mainstream engineering paths:

    • Shared vector space: use a multimodal embedding model to map text and images into the same space, enabling true cross-modal retrieval. Before adopting it, verify how well the model supports Chinese documents and business terminology.
    • Text projection (recommended as the baseline): convert every non-text element into a high-quality text description first, then run everything through text embedding. It is simple to implement, highly controllable, and sufficient for most enterprise knowledge base scenarios.

    On the retrieval side, a hybrid strategy is recommended: dense vectors handle semantic similarity, sparse keywords handle exact matching of IDs, model numbers, and proper nouns, and a reranking model performs a second pass over the candidate set. During generation, expand the context using “retrieve on sub-blocks, feed the parent block” to reduce the semantic loss caused by truncated tables.

    6. Quality Evaluation: Turning Parsing Quality into Measurable Metrics

    A parsing pipeline without evaluation cannot be iterated. Cover at least four metric groups:

    • Structure fidelity: the match rate of table row and column counts, and the accuracy of merged-cell recovery;
    • Reading-order accuracy: the proportion of correctly ordered blocks in multi-column and mixed-layout documents;
    • Retrieval hit rate: build a business Q&A set and measure whether the Top-K contains the correct evidence block;
    • End-to-end accuracy: factual accuracy on numeric questions and the traceability rate of citations.

    In engineering terms, you can build document parsing, chunking and embedding, and storage and retrieval into a pipeline, run the parsing service on a container platform, keep original documents and parsing artifacts in object storage, use a message queue to absorb spikes and support batch re-parsing, and use logs plus monitoring alerts to locate low-quality batches. In scenarios like this, Baidu AI Cloud is typically built from the same combination of general-purpose capabilities described above.

    7. Common Pitfalls

    1. Doing OCR only, without layout analysis: the text is complete but the order is scrambled, so retrieval quality stays poor.
    2. Chunking all tables at a fixed length: the header is lost and chunks are no longer semantically self-contained.
    3. Discarding coordinate information: results cannot be traced back to the source, and answers cannot be verified.
    4. Ignoring incremental updates: after a document changes, re-parse and re-embed at element granularity instead of rebuilding the whole index.
    5. Over-relying on a single embedding model: numeric and ID-style queries should keep a keyword channel as a fallback.

    Conclusion

    Vectorizing non-text information comes down to treating “layout structure” as a first-class citizen: preserve structure at parsing time, preserve self-containedness at chunking time, preserve alignment at embedding time, and preserve traceability at retrieval time. Following this four-layer pipeline and driving iteration with measurable evaluation is what allows a RAG knowledge base to produce trustworthy answers reliably in real document environments.