Souheil007/Rag_Full_Version

Production-grade Document RAG with IBM Docling AST parsing, automated VLM table repair (Pixtral), dual-representation serialization, hybrid RRF retrieval, and sub- 2s latency.

Python

6

65 commits

updated Oct 16, 2026

See the code

See what people are saying

README

โšก Production-Grade Document RAG Engine

Enterprise-grade Document RAG with IBM Docling AST parsing, automated VLM table repair (Pixtral-12B), dual-representation serialization, hybrid RRF retrieval, deterministic guardrails, and sub-2s latency.

Python 3.11+ Docling AST Mistral Pixtral Hybrid Search Docker Ready Benchmark Accuracy Median Latency License: MIT


๐ŸŽฏ Architectural Philosophy: First-Principles over Heavy Frameworks

This project intentionally avoids heavy wrapper abstractions (like LangChain or LlamaIndex) in favor of First-Principles AI Engineering:

  • ๐Ÿ” Full Transparency & Zero "Black Box": Every algorithmโ€”from Okapi BM25 scoring and Reciprocal Rank Fusion (RRF) to cross-encoder re-ranking and semantic cachingโ€”is implemented natively without layers of obscure wrapper classes.
  • โšก High Performance & Low Latency: Native Python and direct official SDKs eliminate framework overhead, resulting in sub-millisecond local execution and lightning-fast test suites.
  • ๐Ÿ› ๏ธ Production Debuggability: Traceability is straightforward: no hidden prompt injections, memory leaks, or unhandled exceptions buried deep within third-party abstractions.
  • ๐Ÿ”Œ Framework-Agnostic & Agent-Ready: Every module is a typed, standalone component that can easily plug into orchestration frameworks (e.g., LangGraph, AutoGen) if complex cyclic workflows are needed.

๐Ÿ”„ End-to-End Workflow & System Architecture

Here is the exact flow of data and component execution across the two main pipelines: Document Ingestion and RAG Query Execution.

๐Ÿ“Š Visual Architecture Diagram

%%{init: {'theme': 'neutral', 'themeVariables': { 'fontSize': '13px', 'lineColor': '#2b7fff', 'edgeLabelBackground': '#ffffff', 'textColor': '#1f2937' }, 'flowchart': { 'nodeSpacing': 30, 'rankSpacing': 40, 'padding': 15, 'useMaxWidth': true } } }%%
flowchart TD
    subgraph Ingestion ["๐Ÿ“ฅ 1. DOCUMENT INGESTION & DUAL INDEXING"]
        A1["๐Ÿ“„ Complex Documents<br/>(PDF, DOCX, TXT)"] --> A2["๐ŸŒณ Layout Parser<br/>(Docling AST & doc_tree)"]
        A2 --> A3{"๐Ÿฉบ TableSanityChecker<br/>Health >= 0.70?"}
        A3 -->|"Needs Repair"| A4["โœจ VLM Table Repair<br/>(Mistral Pixtral-12B)"]
        A3 -->|"Healthy"| A5["โœ‚๏ธ Block-Type Chunker<br/>(Atomic & Row-Groups)"]
        A4 --> A5
        A5 --> A6["๐Ÿ”„ Dual Serializer<br/>(KV Embeddings & Markdown)"]
        A6 --> A7[("๐Ÿ—„๏ธ ChromaDB Store")]
        A6 --> A8[("๐Ÿ“Š Okapi BM25 Index")]
    end

    subgraph Retrieval ["โšก 2. HYBRID RETRIEVAL & RE-RANKING"]
        B1["โ“ User Query"] --> B2["๐Ÿ” Hybrid Retriever"]
        B2 --> B3[("๐Ÿ—„๏ธ ChromaDB")]
        B2 --> B4[("๐Ÿ“Š Okapi BM25")]
        B3 --> B5["๐Ÿ”€ Reciprocal Rank Fusion"]
        B4 --> B5
        B5 --> B6["๐ŸŽฏ Cross-Encoder Reranker"]
        B6 --> B7["๐Ÿงฉ Hit Collapser & Deduplicator<br/>(Token Budget & Prose Link)"]
        B7 --> B8["๐Ÿ“ Prompt Formatter"]
    end

    subgraph Generation ["๐Ÿค– 3. GENERATION & GUARDRAILS"]
        B8 --> C1["๐Ÿ’ฌ LLM Provider"]
        C1 --> C2["๐Ÿ“ Raw Output"]
        C2 --> G1["๐Ÿ” Tier 1: Citation Verifier"]
        G1 --> G2["๐Ÿง  Tier 2: Jev Entailment Engine"]
        G2 --> G3["๐Ÿ›ก๏ธ Tier 3: Fallback Handler"]
        G3 --> C3["๐Ÿ’ก Verified Safe Response"]

        C1 -.-> D1["๐Ÿ“Š Langfuse Tracing"]
        C1 -.-> D2["๐Ÿšจ Sentry APM"]
        C1 -.-> D3["๐Ÿ“ Local JSONL Logs"]
    end

๐Ÿ—บ๏ธ Text Architecture Overview

===================================================================================
                       RAG SYSTEM ARCHITECTURE & DATAFLOW
===================================================================================

 ๐Ÿ“ฅ INGESTION:   [ ๐Ÿ“„ Documents ] โ”€โ”€โ–บ [ ๐ŸŒณ Docling Layout AST ] โ”€โ”€โ–บ [ ๐Ÿฉบ TableSanityChecker ]
                                                                             โ”‚
                                           โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                           โ–ผ                                                                   โ–ผ
                                  [ Needs Repair (<0.70) ]                                                [ Healthy ]
                                           โ”‚                                                                   โ”‚
                                           โ–ผ                                                                   โ”‚
                              [ โœจ Mistral Pixtral VLM ]                                                       โ”‚
                                           โ”‚                                                                   โ”‚
                                           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                                             โ–ผ
                                                                  [ โœ‚๏ธ BlockChunker ]
                                                                  (Atomic & Row-Groups)
                                                                             โ”‚
                                                                             โ–ผ
                                                                [ ๐Ÿ”„ Dual Serializer ]
                                                                (KV Text & Clean MD)
                                                                             โ”‚
                                                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                                       โ–ผ                                           โ–ผ
                                             [ ๐Ÿ—„๏ธ ChromaDB Store ]                       [ ๐Ÿ“Š Okapi BM25 Index ]
                                                   (Dense)                                       (Sparse)
 โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”‚ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”‚ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€
                                                       โ–ผ                                           โ–ผ
 โšก QUERYING:    [ โ“ User Query ] โ”€โ”€โ–บ [ ๐Ÿ” Hybrid Search & RRF Fusion ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐ŸŽฏ Cross-Encoder Reranker ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿงฉ HitCollapser & Sibling Deduplicator ]
                                              (Context Budgeting & Story Linking)
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿ“ Prompt Formatter ]
                                                       โ”‚
                                                       โ–ผ
 ๐Ÿค– GENERATION:                               [ ๐Ÿ’ฌ LLM (Mistral/Gemini) ]
                                                       โ”‚
                                                       โ–ผ
 ๐Ÿ›ก๏ธ GUARDRAILS:                               [ ๐Ÿ” Tier 1: Citation Verifier ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿง  Tier 2: Jev Entailment Engine ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿšจ Tier 3: Safe Fallback Handler ]
                                                       โ”‚
                              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                              โ–ผ                                                 โ–ผ
                       [ ๐Ÿ’ก Verified Safe Response ]             [ ๐Ÿ“Š Telemetry & Monitoring ]
                                                                 โ”œโ”€โ–บ Langfuse (Traces & Costs)
                                                                 โ”œโ”€โ–บ Sentry (Exceptions & APM)
                                                                 โ””โ”€โ–บ Local JSONL Logs
===================================================================================

โš™๏ธ Step-by-Step Breakdown

1. Ingestion & Indexing Phase (POST /index & DELETE /index)

  • Docling Layout Analysis & AST Building: LayoutParser extracts structural blocks (SectionHeaderItem, TableItem, TextItem, CodeItem) into a typed hierarchy (DocumentTree) with section breadcrumbs and table-to-prose linkages.
  • Extraction & Table Health Sanity Checks:
    • ExtractionQualityScorer calculates $Q_{score} \in [0.0, 1.0]$ based on text cleanliness and character noise.
    • TableSanityChecker inspects table column alignment, missing cell voids, and jagged row lengths.
  • VLM Table Repairer: If a table fails sanity checks (e.g., column-swapped borderless grid), it routes page images to Mistral's pixtral-12b-2409 multimodal model to visually transcribe the exact table into pristine Markdown.
  • Block-Type Chunking: BlockChunker keeps small tables ($\le 25$ rows) atomic and slices oversized tables into row-groups with replicated schema headers.
  • Dual Representation Serialization: TableSerializer produces linearized Key-Value sentences for vector embeddings and Markdown tables for LLM prompt context.
  • Dual Indexing: Upserts dense representations into ChromaDB and sparse lexical statistics into Okapi BM25.

2. Querying, Caching & Generation Phase (POST /query)

  1. Semantic Cache Lookup: Evaluates query cosine similarity against cached vectors (similarity_threshold >= 0.95). If a verified cached response exists, returns immediately ($0 LLM cost, ~5-15ms latency).
  2. Tracing Started: Tracer creates a unique trace_id for distributed observability.
  3. Hybrid Retrieval (Retriever):
    • Runs Dense Vector Search and Sparse BM25 Search in parallel.
    • Reciprocal Rank Fusion (RRF) combines candidate lists into a unified score array.
    • Cross-Encoder Reranker scores top candidates jointly with the query.
  4. Hit Collapser & Sibling Deduplication: HitCollapser groups sibling row-chunks belonging to the same table ID, pulls introductory prose (preceding_prose_id), and caps context within token budgets.
  5. Prompt Formatting: format_rag_prompt() injects structured Markdown tables and prose into strict grounding templates.
  6. LLM Generation: LLMClient calls the selected provider (Mistral, Gemini, OpenAI, or Anthropic) to generate the raw response.
  7. Multi-Tier Guardrail Verification:
    • Tier 1 (Citation Verifier): Deterministic regex parsing validating that numeric citations ([1], [2]) and file sources exist within context.
    • Tier 2 (Hallucination Detector & Jev): Decomposes assertions into claims and verifies entailment via the Jev discriminative decision engine.
    • Tier 3 (Fallback Handler): In strict mode, intercepts citation failures or ungrounded statements and returns a safe refusal message.
  8. Cache Storage: Verified, approved answers are saved into the bounded LRU semantic cache with TTL.

3. Observability & Monitoring Phase

  • Langfuse Tracing: Exports hierarchical trace trees (retrieval duration, prompt payload, generation latency, guardrail execution, and token counts) to Langfuse.
  • Sentry Error Monitoring: Intercepts unhandled ASGI exceptions and logs APM profiling sessions to Sentry.
  • Local JSONL Logging: Appends execution logs locally in logs/traces.jsonl.

๐Ÿ—บ๏ธ Production Roadmap

The repository follows a structured engineering roadmap detailed in the plans/ directory:

PlanTitleStatusDescription
Plan 1Advanced Hybrid Retrieval & Re-rankingโœ… CompleteSparse BM25 + Dense Vector search with Reciprocal Rank Fusion (RRF), Cross-Encoder Re-ranking, and Contextual Sentence Compression.
Plan 2Evaluation Engine (LLM-as-a-Judge)โœ… CompletePrecision@K, Recall@K, Hit Rate, MRR, Faithfulness / Groundedness, and automated Golden Dataset benchmarking.
Plan 3Failure Modes & Guardrails (Jev)โœ… CompleteMulti-tiered guardrails with deterministic citation bounds checking, statement entailment via Jev discriminative decision model, and safe fallback handling.
Plan 6Observability & Sentry Error Monitoringโœ… CompleteEnd-to-end span tracing (Tracer), operational metrics (MetricsCollector), Langfuse observability, and Sentry APM error monitoring.
Plan 4Cost & Latency Optimizationโœ… CompleteSemantic vector query cache ($0 repeat cost), query complexity router (Flash vs. Pro), and token/latency profiler.
Plan 7Complex Document Ingestion & Chunkingโœ… CompleteDocling layout AST engine, TableSanityChecker, Pixtral VLM table repair fallback, dual serialization (KV & MD), and runtime HitCollapser.
Plan 5System Design & 100x Scaling (ADRs)โณ PendingArchitecture Decision Records (RAG vs. Fine-Tuning, 100x scale sharding), and Senior AI Interview Cheat Sheet.

๐Ÿ“ Project Structure

Rag_Full_Version/
โ”œโ”€โ”€ README.md                      # Project description, philosophy, and setup guide
โ”œโ”€โ”€ requirements.txt               # Dependencies (FastAPI, Docling, ChromaDB, Mistral, etc.)
โ”œโ”€โ”€ Dockerfile                     # Multi-stage security-hardened container specification
โ”œโ”€โ”€ docker-compose.yml             # Container orchestration with persistent volumes
โ”œโ”€โ”€ .dockerignore                  # Docker build context exclusions
โ”œโ”€โ”€ .env / .env.example            # Environment variables and API keys
โ”œโ”€โ”€ .gitignore                     # Git ignore definitions
โ”œโ”€โ”€ config.yaml                    # Central configuration file
โ”œโ”€โ”€ AGENTS.md                      # Coding standards & agent instructions
โ”œโ”€โ”€ main.py                        # Service entry point
โ”œโ”€โ”€ docs/                          # Comprehensive architectural guides & benchmarks
โ”‚   โ”œโ”€โ”€ CHUNKING_AND_INGESTION_ARCHITECTURE.md # 7-stage block chunking & dual serialization
โ”‚   โ”œโ”€โ”€ DOCLING_VS_MISTRAL_OCR.md         # Docling vs Mistral OCR trade-offs, pricing & hybrid VLM
โ”‚   โ”œโ”€โ”€ GUARDRAILS_AND_FALLBACK_GUIDE.md  # 3-Tier guardrails, Jev entailment & fallback
โ”‚   โ”œโ”€โ”€ RETRIEVAL_METRICS_AND_SCORES.md   # Distance, BM25, RRF & Cross-Encoder scores
โ”‚   โ”œโ”€โ”€ EVALUATION_METRICS_GUIDE.md       # Precision@K, Recall@K, MRR & LLM Judge
โ”‚   โ”œโ”€โ”€ TOP_K_TUNING_GUIDE.md             # Two-stage retrieval sizing & cost tuning
โ”‚   โ””โ”€โ”€ OBSERVABILITY_VS_MONITORING.md    # Langfuse semantic tracing vs Sentry APM
โ”œโ”€โ”€ plans/                         # Step-by-step engineering plans
โ”‚   โ”œโ”€โ”€ plan1.md                   # Plan 1: Hybrid Retrieval & Re-ranking (Done)
โ”‚   โ”œโ”€โ”€ plan2.md                   # Plan 2: Evaluation & Metrics Engine (Done)
โ”‚   โ”œโ”€โ”€ plan3.md                   # Plan 3: Failure Modes & Guardrails (Done)
โ”‚   โ”œโ”€โ”€ plan4.md                   # Plan 4: Cost & Latency Optimization (Done)
โ”‚   โ”œโ”€โ”€ plan5.md                   # Plan 5: System Design & Scaling ADRs
โ”‚   โ”œโ”€โ”€ plan6.md                   # Plan 6: Observability & Sentry Monitoring (Done)
โ”‚   โ””โ”€โ”€ plan7.md                   # Plan 7: Complex Document Ingestion & Table Chunking (Done)
โ”œโ”€โ”€ scripts/                       # Operational scripts & benchmarking CLIs
โ”‚   โ”œโ”€โ”€ test_pdf_chunking.py       # PDF layout inspection, table sanity & chunk provenance CLI
โ”‚   โ””โ”€โ”€ eval_chunking_benchmark.py # 25-question retrieval benchmark on complex tables
โ”œโ”€โ”€ .agents/
โ”‚   โ””โ”€โ”€ skills/
โ”‚       โ””โ”€โ”€ rag-conventions/
โ”‚           โ””โ”€โ”€ SKILL.md           # Custom skill for naming conventions and docstrings
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ ingestion/                 # Document layout extraction & tree modeling
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ doc_tree.py            # Hierarchical DocumentNode AST & section breadcrumbs
โ”‚   โ”‚   โ”œโ”€โ”€ layout_parser.py       # Dedicated Docling layout engine & disambiguation
โ”‚   โ”‚   โ”œโ”€โ”€ quality_scorer.py      # Q_score extraction scorer & TableSanityChecker
โ”‚   โ”‚   โ””โ”€โ”€ loader.py              # Directory file loader
โ”‚   โ”œโ”€โ”€ chunking/                  # Block-type chunking & table serializers
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ block_chunker.py       # Atomic small tables & row-grouping with replicated headers
โ”‚   โ”‚   โ”œโ”€โ”€ table_parser.py        # Multi-row fill-down & headerless page stitcher
โ”‚   โ”‚   โ”œโ”€โ”€ table_serializer.py    # KV linearization for embeddings & Markdown for LLM
โ”‚   โ”‚   โ”œโ”€โ”€ table_repairer.py      # VLM table repair fallback (Mistral Pixtral-12B)
โ”‚   โ”‚   โ”œโ”€โ”€ chunker.py             # Recursive text chunker (fallback/baseline)
โ”‚   โ”‚   โ””โ”€โ”€ compression.py         # Contextual sentence compressor
โ”‚   โ”œโ”€โ”€ embeddings/                # Vector embeddings (SentenceTransformers, OpenAI, Gemini)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ embedder.py
โ”‚   โ”œโ”€โ”€ vectordb/                  # Vector database (ChromaDB, FAISS, in-memory)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ vector_store.py
โ”‚   โ”œโ”€โ”€ retrieval/                 # Unified search engine, hybrid rankers & deduplicators
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ hit_collapser.py       # Table sibling deduplication & token budgeter
โ”‚   โ”‚   โ”œโ”€โ”€ bm25_retriever.py      # Okapi BM25 keyword search
โ”‚   โ”‚   โ”œโ”€โ”€ hybrid_retriever.py    # Reciprocal Rank Fusion (RRF)
โ”‚   โ”‚   โ”œโ”€โ”€ reranker.py            # Cross-Encoder re-ranker
โ”‚   โ”‚   โ””โ”€โ”€ retriever.py           # Unified Retriever Facade
โ”‚   โ”œโ”€โ”€ guardrails/                # Multi-tier guardrails & hallucination prevention
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ citation_verifier.py   # Tier 1 deterministic citation bounds checker
โ”‚   โ”‚   โ”œโ”€โ”€ hallucination_detector.py # Tier 2 claim-level entailment verifier
โ”‚   โ”‚   โ”œโ”€โ”€ jev_client.py          # Fast discriminative decision model client
โ”‚   โ”‚   โ””โ”€โ”€ fallback_handler.py    # Tier 3 policy enforcement & safe fallback
โ”‚   โ”œโ”€โ”€ optimization/              # Cost & latency optimization (Plan 4)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ semantic_cache.py      # Bounded LRU semantic vector cache
โ”‚   โ”‚   โ”œโ”€โ”€ query_router.py        # Complexity-based query router
โ”‚   โ”‚   โ””โ”€โ”€ profiler.py            # Latency and cost profiler
โ”‚   โ”œโ”€โ”€ prompts/                   # Prompt templates & context formatting
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ prompt_templates.py
โ”‚   โ”œโ”€โ”€ llm/                       # LLM provider clients (Mistral, Gemini, OpenAI)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ llm_client.py
โ”‚   โ”œโ”€โ”€ observability/             # Distributed tracing, APM, and metrics
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ tracer.py
โ”‚   โ”‚   โ”œโ”€โ”€ metrics_collector.py
โ”‚   โ”‚   โ”œโ”€โ”€ sentry_monitor.py
โ”‚   โ”‚   โ””โ”€โ”€ span_exporter.py
โ”‚   โ”œโ”€โ”€ api/                       # FastAPI REST endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ routes.py
โ”‚   โ””โ”€โ”€ utils/                     # Config loader, helpers, structured logger
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ””โ”€โ”€ helpers.py
โ”œโ”€โ”€ tests/                         # Unit & integration test suites
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ test_app.py
โ”‚   โ”œโ”€โ”€ test_block_chunking.py
โ”‚   โ”œโ”€โ”€ test_table_health.py
โ”‚   โ”œโ”€โ”€ test_table_repairer.py
โ”‚   โ”œโ”€โ”€ test_ugly_table_fixture.py
โ”‚   โ”œโ”€โ”€ test_guardrails.py
โ”‚   โ”œโ”€โ”€ test_hybrid_retriever.py
โ”‚   โ”œโ”€โ”€ test_evaluation.py
โ”‚   โ”œโ”€โ”€ test_observability.py
โ”‚   โ””โ”€โ”€ test_optimization.py
โ”œโ”€โ”€ reports/                       # Generated benchmark & document inspection reports
โ””โ”€โ”€ logs/                          # Application log files
    โ””โ”€โ”€ .gitkeep


๐Ÿš€ Getting Started

Run the entire RAG pipelineโ€”including IBM Docling neural layout models, ChromaDB vector persistence, and FastAPI serverโ€”inside an isolated, production-ready container with a single command:

1. Configure Environment

cp .env.example .env
# Fill in your MISTRAL_API_KEY (and optional LANGFUSE / SENTRY keys) in .env

2. Start Services via Docker Compose

docker compose up --build -d

[!TIP] The docker-compose.yml mounts ./data, ./chroma_db, and ./reports directly as host volumes. You can drop new PDFs into data/ and see index changes and reports persist immediately without rebuilding the image.


Option B: Local Python Environment

1. Installation

Create and activate a virtual environment, then install dependencies:

python -m venv .venv
# On Windows:
.venv\Scripts\activate
# On Linux/macOS:
source .venv/bin/activate

pip install -r requirements.txt

2. Configure Environment

cp .env.example .env

3. Run the Application

Start the FastAPI server:

python main.py
  • API Docs (Swagger): http://localhost:8000/docs
  • Health Check: http://localhost:8000/health

4. Inspect Document Chunking & Table Health

To inspect how any document is parsed, chunked, and validated:

python scripts/test_pdf_chunking.py data/sample-tables.pdf

This generates a detailed inspection report in reports/inspection_sample-tables.md displaying table sanity health scores, relational links, and dual representations.


๐Ÿงช Running Tests

Run the test suite using pytest:

pytest -v

๐Ÿ“š In-Depth Documentation


๐Ÿ“ Conventions & Standards

  • Naming: snake_case for modules/functions/variables, PascalCase for classes, UPPER_SNAKE_CASE for constants.
  • Docstrings: Concise Google-style Python docstrings for all functions, classes, and modules.
  • Rules & Skills: Defined in AGENTS.md and .agents/skills/rag-conventions/SKILL.md.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

bm25
chromadb
docling
guardrails
hybrid-search
mistral
production
production-ai
rag
retrieval-augmented-generation
system-design
table-extraction
vector-search

Souheil007/Rag_Full_Version

Production-grade Document RAG with IBM Docling AST parsing, automated VLM table repair (Pixtral), dual-representation serialization, hybrid RRF retrieval, and sub- 2s latency.

Python

6

65 commits

updated Oct 16, 2026

See the code

See what people are saying

README

โšก Production-Grade Document RAG Engine

Enterprise-grade Document RAG with IBM Docling AST parsing, automated VLM table repair (Pixtral-12B), dual-representation serialization, hybrid RRF retrieval, deterministic guardrails, and sub-2s latency.

Python 3.11+ Docling AST Mistral Pixtral Hybrid Search Docker Ready Benchmark Accuracy Median Latency License: MIT


๐ŸŽฏ Architectural Philosophy: First-Principles over Heavy Frameworks

This project intentionally avoids heavy wrapper abstractions (like LangChain or LlamaIndex) in favor of First-Principles AI Engineering:

  • ๐Ÿ” Full Transparency & Zero "Black Box": Every algorithmโ€”from Okapi BM25 scoring and Reciprocal Rank Fusion (RRF) to cross-encoder re-ranking and semantic cachingโ€”is implemented natively without layers of obscure wrapper classes.
  • โšก High Performance & Low Latency: Native Python and direct official SDKs eliminate framework overhead, resulting in sub-millisecond local execution and lightning-fast test suites.
  • ๐Ÿ› ๏ธ Production Debuggability: Traceability is straightforward: no hidden prompt injections, memory leaks, or unhandled exceptions buried deep within third-party abstractions.
  • ๐Ÿ”Œ Framework-Agnostic & Agent-Ready: Every module is a typed, standalone component that can easily plug into orchestration frameworks (e.g., LangGraph, AutoGen) if complex cyclic workflows are needed.

๐Ÿ”„ End-to-End Workflow & System Architecture

Here is the exact flow of data and component execution across the two main pipelines: Document Ingestion and RAG Query Execution.

๐Ÿ“Š Visual Architecture Diagram

%%{init: {'theme': 'neutral', 'themeVariables': { 'fontSize': '13px', 'lineColor': '#2b7fff', 'edgeLabelBackground': '#ffffff', 'textColor': '#1f2937' }, 'flowchart': { 'nodeSpacing': 30, 'rankSpacing': 40, 'padding': 15, 'useMaxWidth': true } } }%%
flowchart TD
    subgraph Ingestion ["๐Ÿ“ฅ 1. DOCUMENT INGESTION & DUAL INDEXING"]
        A1["๐Ÿ“„ Complex Documents<br/>(PDF, DOCX, TXT)"] --> A2["๐ŸŒณ Layout Parser<br/>(Docling AST & doc_tree)"]
        A2 --> A3{"๐Ÿฉบ TableSanityChecker<br/>Health >= 0.70?"}
        A3 -->|"Needs Repair"| A4["โœจ VLM Table Repair<br/>(Mistral Pixtral-12B)"]
        A3 -->|"Healthy"| A5["โœ‚๏ธ Block-Type Chunker<br/>(Atomic & Row-Groups)"]
        A4 --> A5
        A5 --> A6["๐Ÿ”„ Dual Serializer<br/>(KV Embeddings & Markdown)"]
        A6 --> A7[("๐Ÿ—„๏ธ ChromaDB Store")]
        A6 --> A8[("๐Ÿ“Š Okapi BM25 Index")]
    end

    subgraph Retrieval ["โšก 2. HYBRID RETRIEVAL & RE-RANKING"]
        B1["โ“ User Query"] --> B2["๐Ÿ” Hybrid Retriever"]
        B2 --> B3[("๐Ÿ—„๏ธ ChromaDB")]
        B2 --> B4[("๐Ÿ“Š Okapi BM25")]
        B3 --> B5["๐Ÿ”€ Reciprocal Rank Fusion"]
        B4 --> B5
        B5 --> B6["๐ŸŽฏ Cross-Encoder Reranker"]
        B6 --> B7["๐Ÿงฉ Hit Collapser & Deduplicator<br/>(Token Budget & Prose Link)"]
        B7 --> B8["๐Ÿ“ Prompt Formatter"]
    end

    subgraph Generation ["๐Ÿค– 3. GENERATION & GUARDRAILS"]
        B8 --> C1["๐Ÿ’ฌ LLM Provider"]
        C1 --> C2["๐Ÿ“ Raw Output"]
        C2 --> G1["๐Ÿ” Tier 1: Citation Verifier"]
        G1 --> G2["๐Ÿง  Tier 2: Jev Entailment Engine"]
        G2 --> G3["๐Ÿ›ก๏ธ Tier 3: Fallback Handler"]
        G3 --> C3["๐Ÿ’ก Verified Safe Response"]

        C1 -.-> D1["๐Ÿ“Š Langfuse Tracing"]
        C1 -.-> D2["๐Ÿšจ Sentry APM"]
        C1 -.-> D3["๐Ÿ“ Local JSONL Logs"]
    end

๐Ÿ—บ๏ธ Text Architecture Overview

===================================================================================
                       RAG SYSTEM ARCHITECTURE & DATAFLOW
===================================================================================

 ๐Ÿ“ฅ INGESTION:   [ ๐Ÿ“„ Documents ] โ”€โ”€โ–บ [ ๐ŸŒณ Docling Layout AST ] โ”€โ”€โ–บ [ ๐Ÿฉบ TableSanityChecker ]
                                                                             โ”‚
                                           โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                           โ–ผ                                                                   โ–ผ
                                  [ Needs Repair (<0.70) ]                                                [ Healthy ]
                                           โ”‚                                                                   โ”‚
                                           โ–ผ                                                                   โ”‚
                              [ โœจ Mistral Pixtral VLM ]                                                       โ”‚
                                           โ”‚                                                                   โ”‚
                                           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                                             โ–ผ
                                                                  [ โœ‚๏ธ BlockChunker ]
                                                                  (Atomic & Row-Groups)
                                                                             โ”‚
                                                                             โ–ผ
                                                                [ ๐Ÿ”„ Dual Serializer ]
                                                                (KV Text & Clean MD)
                                                                             โ”‚
                                                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                                       โ–ผ                                           โ–ผ
                                             [ ๐Ÿ—„๏ธ ChromaDB Store ]                       [ ๐Ÿ“Š Okapi BM25 Index ]
                                                   (Dense)                                       (Sparse)
 โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”‚ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”‚ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€ โ”€โ”€
                                                       โ–ผ                                           โ–ผ
 โšก QUERYING:    [ โ“ User Query ] โ”€โ”€โ–บ [ ๐Ÿ” Hybrid Search & RRF Fusion ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐ŸŽฏ Cross-Encoder Reranker ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿงฉ HitCollapser & Sibling Deduplicator ]
                                              (Context Budgeting & Story Linking)
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿ“ Prompt Formatter ]
                                                       โ”‚
                                                       โ–ผ
 ๐Ÿค– GENERATION:                               [ ๐Ÿ’ฌ LLM (Mistral/Gemini) ]
                                                       โ”‚
                                                       โ–ผ
 ๐Ÿ›ก๏ธ GUARDRAILS:                               [ ๐Ÿ” Tier 1: Citation Verifier ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿง  Tier 2: Jev Entailment Engine ]
                                                       โ”‚
                                                       โ–ผ
                                              [ ๐Ÿšจ Tier 3: Safe Fallback Handler ]
                                                       โ”‚
                              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                              โ–ผ                                                 โ–ผ
                       [ ๐Ÿ’ก Verified Safe Response ]             [ ๐Ÿ“Š Telemetry & Monitoring ]
                                                                 โ”œโ”€โ–บ Langfuse (Traces & Costs)
                                                                 โ”œโ”€โ–บ Sentry (Exceptions & APM)
                                                                 โ””โ”€โ–บ Local JSONL Logs
===================================================================================

โš™๏ธ Step-by-Step Breakdown

1. Ingestion & Indexing Phase (POST /index & DELETE /index)

  • Docling Layout Analysis & AST Building: LayoutParser extracts structural blocks (SectionHeaderItem, TableItem, TextItem, CodeItem) into a typed hierarchy (DocumentTree) with section breadcrumbs and table-to-prose linkages.
  • Extraction & Table Health Sanity Checks:
    • ExtractionQualityScorer calculates $Q_{score} \in [0.0, 1.0]$ based on text cleanliness and character noise.
    • TableSanityChecker inspects table column alignment, missing cell voids, and jagged row lengths.
  • VLM Table Repairer: If a table fails sanity checks (e.g., column-swapped borderless grid), it routes page images to Mistral's pixtral-12b-2409 multimodal model to visually transcribe the exact table into pristine Markdown.
  • Block-Type Chunking: BlockChunker keeps small tables ($\le 25$ rows) atomic and slices oversized tables into row-groups with replicated schema headers.
  • Dual Representation Serialization: TableSerializer produces linearized Key-Value sentences for vector embeddings and Markdown tables for LLM prompt context.
  • Dual Indexing: Upserts dense representations into ChromaDB and sparse lexical statistics into Okapi BM25.

2. Querying, Caching & Generation Phase (POST /query)

  1. Semantic Cache Lookup: Evaluates query cosine similarity against cached vectors (similarity_threshold >= 0.95). If a verified cached response exists, returns immediately ($0 LLM cost, ~5-15ms latency).
  2. Tracing Started: Tracer creates a unique trace_id for distributed observability.
  3. Hybrid Retrieval (Retriever):
    • Runs Dense Vector Search and Sparse BM25 Search in parallel.
    • Reciprocal Rank Fusion (RRF) combines candidate lists into a unified score array.
    • Cross-Encoder Reranker scores top candidates jointly with the query.
  4. Hit Collapser & Sibling Deduplication: HitCollapser groups sibling row-chunks belonging to the same table ID, pulls introductory prose (preceding_prose_id), and caps context within token budgets.
  5. Prompt Formatting: format_rag_prompt() injects structured Markdown tables and prose into strict grounding templates.
  6. LLM Generation: LLMClient calls the selected provider (Mistral, Gemini, OpenAI, or Anthropic) to generate the raw response.
  7. Multi-Tier Guardrail Verification:
    • Tier 1 (Citation Verifier): Deterministic regex parsing validating that numeric citations ([1], [2]) and file sources exist within context.
    • Tier 2 (Hallucination Detector & Jev): Decomposes assertions into claims and verifies entailment via the Jev discriminative decision engine.
    • Tier 3 (Fallback Handler): In strict mode, intercepts citation failures or ungrounded statements and returns a safe refusal message.
  8. Cache Storage: Verified, approved answers are saved into the bounded LRU semantic cache with TTL.

3. Observability & Monitoring Phase

  • Langfuse Tracing: Exports hierarchical trace trees (retrieval duration, prompt payload, generation latency, guardrail execution, and token counts) to Langfuse.
  • Sentry Error Monitoring: Intercepts unhandled ASGI exceptions and logs APM profiling sessions to Sentry.
  • Local JSONL Logging: Appends execution logs locally in logs/traces.jsonl.

๐Ÿ—บ๏ธ Production Roadmap

The repository follows a structured engineering roadmap detailed in the plans/ directory:

PlanTitleStatusDescription
Plan 1Advanced Hybrid Retrieval & Re-rankingโœ… CompleteSparse BM25 + Dense Vector search with Reciprocal Rank Fusion (RRF), Cross-Encoder Re-ranking, and Contextual Sentence Compression.
Plan 2Evaluation Engine (LLM-as-a-Judge)โœ… CompletePrecision@K, Recall@K, Hit Rate, MRR, Faithfulness / Groundedness, and automated Golden Dataset benchmarking.
Plan 3Failure Modes & Guardrails (Jev)โœ… CompleteMulti-tiered guardrails with deterministic citation bounds checking, statement entailment via Jev discriminative decision model, and safe fallback handling.
Plan 6Observability & Sentry Error Monitoringโœ… CompleteEnd-to-end span tracing (Tracer), operational metrics (MetricsCollector), Langfuse observability, and Sentry APM error monitoring.
Plan 4Cost & Latency Optimizationโœ… CompleteSemantic vector query cache ($0 repeat cost), query complexity router (Flash vs. Pro), and token/latency profiler.
Plan 7Complex Document Ingestion & Chunkingโœ… CompleteDocling layout AST engine, TableSanityChecker, Pixtral VLM table repair fallback, dual serialization (KV & MD), and runtime HitCollapser.
Plan 5System Design & 100x Scaling (ADRs)โณ PendingArchitecture Decision Records (RAG vs. Fine-Tuning, 100x scale sharding), and Senior AI Interview Cheat Sheet.

๐Ÿ“ Project Structure

Rag_Full_Version/
โ”œโ”€โ”€ README.md                      # Project description, philosophy, and setup guide
โ”œโ”€โ”€ requirements.txt               # Dependencies (FastAPI, Docling, ChromaDB, Mistral, etc.)
โ”œโ”€โ”€ Dockerfile                     # Multi-stage security-hardened container specification
โ”œโ”€โ”€ docker-compose.yml             # Container orchestration with persistent volumes
โ”œโ”€โ”€ .dockerignore                  # Docker build context exclusions
โ”œโ”€โ”€ .env / .env.example            # Environment variables and API keys
โ”œโ”€โ”€ .gitignore                     # Git ignore definitions
โ”œโ”€โ”€ config.yaml                    # Central configuration file
โ”œโ”€โ”€ AGENTS.md                      # Coding standards & agent instructions
โ”œโ”€โ”€ main.py                        # Service entry point
โ”œโ”€โ”€ docs/                          # Comprehensive architectural guides & benchmarks
โ”‚   โ”œโ”€โ”€ CHUNKING_AND_INGESTION_ARCHITECTURE.md # 7-stage block chunking & dual serialization
โ”‚   โ”œโ”€โ”€ DOCLING_VS_MISTRAL_OCR.md         # Docling vs Mistral OCR trade-offs, pricing & hybrid VLM
โ”‚   โ”œโ”€โ”€ GUARDRAILS_AND_FALLBACK_GUIDE.md  # 3-Tier guardrails, Jev entailment & fallback
โ”‚   โ”œโ”€โ”€ RETRIEVAL_METRICS_AND_SCORES.md   # Distance, BM25, RRF & Cross-Encoder scores
โ”‚   โ”œโ”€โ”€ EVALUATION_METRICS_GUIDE.md       # Precision@K, Recall@K, MRR & LLM Judge
โ”‚   โ”œโ”€โ”€ TOP_K_TUNING_GUIDE.md             # Two-stage retrieval sizing & cost tuning
โ”‚   โ””โ”€โ”€ OBSERVABILITY_VS_MONITORING.md    # Langfuse semantic tracing vs Sentry APM
โ”œโ”€โ”€ plans/                         # Step-by-step engineering plans
โ”‚   โ”œโ”€โ”€ plan1.md                   # Plan 1: Hybrid Retrieval & Re-ranking (Done)
โ”‚   โ”œโ”€โ”€ plan2.md                   # Plan 2: Evaluation & Metrics Engine (Done)
โ”‚   โ”œโ”€โ”€ plan3.md                   # Plan 3: Failure Modes & Guardrails (Done)
โ”‚   โ”œโ”€โ”€ plan4.md                   # Plan 4: Cost & Latency Optimization (Done)
โ”‚   โ”œโ”€โ”€ plan5.md                   # Plan 5: System Design & Scaling ADRs
โ”‚   โ”œโ”€โ”€ plan6.md                   # Plan 6: Observability & Sentry Monitoring (Done)
โ”‚   โ””โ”€โ”€ plan7.md                   # Plan 7: Complex Document Ingestion & Table Chunking (Done)
โ”œโ”€โ”€ scripts/                       # Operational scripts & benchmarking CLIs
โ”‚   โ”œโ”€โ”€ test_pdf_chunking.py       # PDF layout inspection, table sanity & chunk provenance CLI
โ”‚   โ””โ”€โ”€ eval_chunking_benchmark.py # 25-question retrieval benchmark on complex tables
โ”œโ”€โ”€ .agents/
โ”‚   โ””โ”€โ”€ skills/
โ”‚       โ””โ”€โ”€ rag-conventions/
โ”‚           โ””โ”€โ”€ SKILL.md           # Custom skill for naming conventions and docstrings
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ ingestion/                 # Document layout extraction & tree modeling
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ doc_tree.py            # Hierarchical DocumentNode AST & section breadcrumbs
โ”‚   โ”‚   โ”œโ”€โ”€ layout_parser.py       # Dedicated Docling layout engine & disambiguation
โ”‚   โ”‚   โ”œโ”€โ”€ quality_scorer.py      # Q_score extraction scorer & TableSanityChecker
โ”‚   โ”‚   โ””โ”€โ”€ loader.py              # Directory file loader
โ”‚   โ”œโ”€โ”€ chunking/                  # Block-type chunking & table serializers
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ block_chunker.py       # Atomic small tables & row-grouping with replicated headers
โ”‚   โ”‚   โ”œโ”€โ”€ table_parser.py        # Multi-row fill-down & headerless page stitcher
โ”‚   โ”‚   โ”œโ”€โ”€ table_serializer.py    # KV linearization for embeddings & Markdown for LLM
โ”‚   โ”‚   โ”œโ”€โ”€ table_repairer.py      # VLM table repair fallback (Mistral Pixtral-12B)
โ”‚   โ”‚   โ”œโ”€โ”€ chunker.py             # Recursive text chunker (fallback/baseline)
โ”‚   โ”‚   โ””โ”€โ”€ compression.py         # Contextual sentence compressor
โ”‚   โ”œโ”€โ”€ embeddings/                # Vector embeddings (SentenceTransformers, OpenAI, Gemini)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ embedder.py
โ”‚   โ”œโ”€โ”€ vectordb/                  # Vector database (ChromaDB, FAISS, in-memory)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ vector_store.py
โ”‚   โ”œโ”€โ”€ retrieval/                 # Unified search engine, hybrid rankers & deduplicators
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ hit_collapser.py       # Table sibling deduplication & token budgeter
โ”‚   โ”‚   โ”œโ”€โ”€ bm25_retriever.py      # Okapi BM25 keyword search
โ”‚   โ”‚   โ”œโ”€โ”€ hybrid_retriever.py    # Reciprocal Rank Fusion (RRF)
โ”‚   โ”‚   โ”œโ”€โ”€ reranker.py            # Cross-Encoder re-ranker
โ”‚   โ”‚   โ””โ”€โ”€ retriever.py           # Unified Retriever Facade
โ”‚   โ”œโ”€โ”€ guardrails/                # Multi-tier guardrails & hallucination prevention
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ citation_verifier.py   # Tier 1 deterministic citation bounds checker
โ”‚   โ”‚   โ”œโ”€โ”€ hallucination_detector.py # Tier 2 claim-level entailment verifier
โ”‚   โ”‚   โ”œโ”€โ”€ jev_client.py          # Fast discriminative decision model client
โ”‚   โ”‚   โ””โ”€โ”€ fallback_handler.py    # Tier 3 policy enforcement & safe fallback
โ”‚   โ”œโ”€โ”€ optimization/              # Cost & latency optimization (Plan 4)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ semantic_cache.py      # Bounded LRU semantic vector cache
โ”‚   โ”‚   โ”œโ”€โ”€ query_router.py        # Complexity-based query router
โ”‚   โ”‚   โ””โ”€โ”€ profiler.py            # Latency and cost profiler
โ”‚   โ”œโ”€โ”€ prompts/                   # Prompt templates & context formatting
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ prompt_templates.py
โ”‚   โ”œโ”€โ”€ llm/                       # LLM provider clients (Mistral, Gemini, OpenAI)
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ llm_client.py
โ”‚   โ”œโ”€โ”€ observability/             # Distributed tracing, APM, and metrics
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ tracer.py
โ”‚   โ”‚   โ”œโ”€โ”€ metrics_collector.py
โ”‚   โ”‚   โ”œโ”€โ”€ sentry_monitor.py
โ”‚   โ”‚   โ””โ”€โ”€ span_exporter.py
โ”‚   โ”œโ”€โ”€ api/                       # FastAPI REST endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ routes.py
โ”‚   โ””โ”€โ”€ utils/                     # Config loader, helpers, structured logger
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ””โ”€โ”€ helpers.py
โ”œโ”€โ”€ tests/                         # Unit & integration test suites
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ test_app.py
โ”‚   โ”œโ”€โ”€ test_block_chunking.py
โ”‚   โ”œโ”€โ”€ test_table_health.py
โ”‚   โ”œโ”€โ”€ test_table_repairer.py
โ”‚   โ”œโ”€โ”€ test_ugly_table_fixture.py
โ”‚   โ”œโ”€โ”€ test_guardrails.py
โ”‚   โ”œโ”€โ”€ test_hybrid_retriever.py
โ”‚   โ”œโ”€โ”€ test_evaluation.py
โ”‚   โ”œโ”€โ”€ test_observability.py
โ”‚   โ””โ”€โ”€ test_optimization.py
โ”œโ”€โ”€ reports/                       # Generated benchmark & document inspection reports
โ””โ”€โ”€ logs/                          # Application log files
    โ””โ”€โ”€ .gitkeep


๐Ÿš€ Getting Started

Run the entire RAG pipelineโ€”including IBM Docling neural layout models, ChromaDB vector persistence, and FastAPI serverโ€”inside an isolated, production-ready container with a single command:

1. Configure Environment

cp .env.example .env
# Fill in your MISTRAL_API_KEY (and optional LANGFUSE / SENTRY keys) in .env

2. Start Services via Docker Compose

docker compose up --build -d

[!TIP] The docker-compose.yml mounts ./data, ./chroma_db, and ./reports directly as host volumes. You can drop new PDFs into data/ and see index changes and reports persist immediately without rebuilding the image.


Option B: Local Python Environment

1. Installation

Create and activate a virtual environment, then install dependencies:

python -m venv .venv
# On Windows:
.venv\Scripts\activate
# On Linux/macOS:
source .venv/bin/activate

pip install -r requirements.txt

2. Configure Environment

cp .env.example .env

3. Run the Application

Start the FastAPI server:

python main.py
  • API Docs (Swagger): http://localhost:8000/docs
  • Health Check: http://localhost:8000/health

4. Inspect Document Chunking & Table Health

To inspect how any document is parsed, chunked, and validated:

python scripts/test_pdf_chunking.py data/sample-tables.pdf

This generates a detailed inspection report in reports/inspection_sample-tables.md displaying table sanity health scores, relational links, and dual representations.


๐Ÿงช Running Tests

Run the test suite using pytest:

pytest -v

๐Ÿ“š In-Depth Documentation


๐Ÿ“ Conventions & Standards

  • Naming: snake_case for modules/functions/variables, PascalCase for classes, UPPER_SNAKE_CASE for constants.
  • Docstrings: Concise Google-style Python docstrings for all functions, classes, and modules.
  • Rules & Skills: Defined in AGENTS.md and .agents/skills/rag-conventions/SKILL.md.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

bm25
chromadb
docling
guardrails
hybrid-search
mistral
production
production-ai
rag
retrieval-augmented-generation
system-design
table-extraction
vector-search