Skip to main content

Overview

A RAG system is only as good as its knowledge base. The data pipeline transforms raw medical documents into a searchable vector store that enables fast, semantically-aware retrieval.
Pipeline GoalConvert unstructured medical PDFs into semantically searchable chunks with rich metadata, stored in a vector database for efficient retrieval.

Pipeline Architecture


Stage 1: Raw Documents

Source Material

The Obstetrics RAG Benchmark uses clinical practice guidelines for pregnancy and childbirth:
  • Document: Guía de Práctica Clínica para el cuidado prenatal
  • Format: PDF documents with text and tables
  • Language: Spanish (medical terminology)
  • Size: Multiple pages of dense medical content

Storage Structure


Stage 2: Document Extraction

Text Extraction Process

PDF documents are parsed to extract text content while preserving structure:

Challenges Addressed

Medical documents often use multi-column layouts. Extraction preserves reading order to maintain coherence.
Clinical guidelines contain structured data (dosage tables, recommendation lists). These are extracted while maintaining relationships.
Page numbers, headers, and footers are identified and handled appropriately to avoid noise.
Medical terminology includes special characters and accented text (Spanish). Proper encoding ensures correct representation.

Stage 3: Text Cleaning

Preprocessing Steps

Extracted text undergoes cleaning to improve retrieval quality:
  1. Whitespace normalization: Remove excessive spaces and newlines
  2. Special character handling: Preserve medical symbols, remove artifacts
  3. Encoding fixes: Ensure proper UTF-8 encoding
  4. Paragraph reconstruction: Merge split paragraphs from PDF extraction
  5. Reference cleanup: Handle citations and footnotes appropriately

Quality Checks

  • Character validation: Ensure no corrupted characters
  • Language detection: Verify Spanish content
  • Length validation: Flag suspiciously short/long pages
  • Encoding verification: Check for mojibake and encoding errors

Stage 4: Text Chunking

Why Chunking Matters

LLMs have context limits, and retrieval systems need focused, relevant pieces of information. Chunking breaks documents into semantic units that:
  • Fit within embedding model limits (8,191 tokens for text-embedding-3-small)
  • Capture coherent semantic concepts
  • Provide focused context for answer generation
  • Enable precise retrieval granularity

Chunking Strategy

The system uses semantic chunking with overlap:

Chunk Size

~500-1000 characters per chunkLarge enough for semantic coherence, small enough for focused retrieval

Overlap

100-200 characters overlapEnsures context isn’t lost at chunk boundaries

Chunking Implementation

Splitting Logic

Hierarchical separators (in priority order):
  1. Double newlines (\n\n) - Paragraph boundaries
  2. Single newlines (\n) - Sentence groups
  3. Periods (. ) - Sentence boundaries
  4. Spaces ( ) - Word boundaries
  5. Characters ("") - Last resort
This ensures chunks break at natural semantic boundaries rather than mid-sentence.

Example Chunks

Note the overlap between chunks: “El inicio temprano permite…” appears in both chunks, ensuring context continuity.

Stage 5: Metadata Enrichment

Why Metadata Matters

Metadata enables:
  • Source attribution: Know where information came from
  • Filtered retrieval: Search within specific pages or sections
  • Result ranking: Prefer recent or authoritative sources
  • Explainability: Show users the source of information

Metadata Schema

Metadata Uses in Retrieval


Stage 6: Embedding Generation

What Are Embeddings?

Embeddings are dense vector representations of text that capture semantic meaning. Similar texts have similar embeddings, enabling semantic search.

Embedding Model

The benchmark uses OpenAI’s text-embedding-3-small:

Dimensions

1536 dimensionsCaptures nuanced semantic relationships

Context Length

8191 tokensHandles long medical passages

Cost

$0.02 / 1M tokensVery cost-effective for knowledge bases

Performance

SOTA multilingualExcellent for Spanish medical text

Embedding Generation Script

Run the script:
Output:

Embedding Process

  1. Batch Processing: Chunks are embedded in batches for efficiency
  2. API Calls: Text sent to OpenAI API for embedding generation
  3. Vector Storage: Embeddings stored alongside original text and metadata
  4. Indexing: Vector store creates efficient search indices

Stage 7: ChromaDB Vector Store

Why ChromaDB?

ChromaDB is an open-source vector database optimized for embedding storage and retrieval:
Embeddings are saved to disk and persist between runs. No need to regenerate embeddings each time.
Uses HNSW (Hierarchical Navigable Small World) algorithm for efficient approximate nearest neighbor search.
Supports filtering results by metadata (e.g., source, page number) before or during search.
Organize embeddings into collections (e.g., different document sets).

Vector Store Structure

Retrieval Operations

Similarity Search:
Similarity Search with Scores:
Filtered Search:

Pipeline Execution

One-Time Setup

The data pipeline is typically run once to create the vector store:

Verification

Check that the pipeline completed successfully:
Expected output:

Pipeline Optimization

Chunking Strategy Tuning

Smaller Chunks

Pros: More precise retrieval, better for specific factsCons: May lose context, requires higher k for coverage

Larger Chunks

Pros: More context per chunk, fewer retrieval callsCons: Less precise, may include irrelevant information
Experimentation:
The benchmark uses medium chunks (800 chars) as the optimal balance for medical Q&A.

Embedding Model Selection

The benchmark uses text-embedding-3-small for the best cost-performance ratio.

Data Quality Considerations

Garbage In, Garbage OutRAG quality is fundamentally limited by knowledge base quality. Poor chunking, noisy text, or incomplete extraction will degrade retrieval performance no matter how sophisticated the RAG architecture.

Quality Checklist

  • Clean extraction: No corrupted characters or encoding issues
  • Semantic chunks: Chunks break at natural boundaries
  • Appropriate size: Not too small (fragments) or too large (unfocused)
  • Sufficient overlap: Context preserved across chunk boundaries
  • Rich metadata: Enable filtering and source attribution
  • Complete coverage: All relevant information from source docs
  • Consistent format: Standardized structure across chunks

Next Steps

RAG Architectures

See how different retrieval strategies use this vector store

Running Evaluations

Evaluate RAG performance with your vector store

Customizing Data

Add your own medical documents to the knowledge base

Troubleshooting

Resolve common data pipeline issues