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
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.
This project intentionally avoids heavy wrapper abstractions (like LangChain or LlamaIndex) in favor of First-Principles AI Engineering:
Here is the exact flow of data and component execution across the two main pipelines: Document Ingestion and RAG Query Execution.
%%{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
===================================================================================
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
===================================================================================
POST /index & DELETE /index)LayoutParser extracts structural blocks (SectionHeaderItem, TableItem, TextItem, CodeItem) into a typed hierarchy (DocumentTree) with section breadcrumbs and table-to-prose linkages.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.pixtral-12b-2409 multimodal model to visually transcribe the exact table into pristine Markdown.BlockChunker keeps small tables ($\le 25$ rows) atomic and slices oversized tables into row-groups with replicated schema headers.TableSerializer produces linearized Key-Value sentences for vector embeddings and Markdown tables for LLM prompt context.ChromaDB and sparse lexical statistics into Okapi BM25.POST /query)similarity_threshold >= 0.95). If a verified cached response exists, returns immediately ($0 LLM cost, ~5-15ms latency).Tracer creates a unique trace_id for distributed observability.Retriever):
HitCollapser groups sibling row-chunks belonging to the same table ID, pulls introductory prose (preceding_prose_id), and caps context within token budgets.format_rag_prompt() injects structured Markdown tables and prose into strict grounding templates.LLMClient calls the selected provider (Mistral, Gemini, OpenAI, or Anthropic) to generate the raw response.[1], [2]) and file sources exist within context.logs/traces.jsonl.The repository follows a structured engineering roadmap detailed in the plans/ directory:
| Plan | Title | Status | Description |
|---|---|---|---|
| Plan 1 | Advanced Hybrid Retrieval & Re-ranking | โ Complete | Sparse BM25 + Dense Vector search with Reciprocal Rank Fusion (RRF), Cross-Encoder Re-ranking, and Contextual Sentence Compression. |
| Plan 2 | Evaluation Engine (LLM-as-a-Judge) | โ Complete | Precision@K, Recall@K, Hit Rate, MRR, Faithfulness / Groundedness, and automated Golden Dataset benchmarking. |
| Plan 3 | Failure Modes & Guardrails (Jev) | โ Complete | Multi-tiered guardrails with deterministic citation bounds checking, statement entailment via Jev discriminative decision model, and safe fallback handling. |
| Plan 6 | Observability & Sentry Error Monitoring | โ Complete | End-to-end span tracing (Tracer), operational metrics (MetricsCollector), Langfuse observability, and Sentry APM error monitoring. |
| Plan 4 | Cost & Latency Optimization | โ Complete | Semantic vector query cache ($0 repeat cost), query complexity router (Flash vs. Pro), and token/latency profiler. |
| Plan 7 | Complex Document Ingestion & Chunking | โ Complete | Docling layout AST engine, TableSanityChecker, Pixtral VLM table repair fallback, dual serialization (KV & MD), and runtime HitCollapser. |
| Plan 5 | System Design & 100x Scaling (ADRs) | โณ Pending | Architecture Decision Records (RAG vs. Fine-Tuning, 100x scale sharding), and Senior AI Interview Cheat Sheet. |
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
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:
cp .env.example .env
# Fill in your MISTRAL_API_KEY (and optional LANGFUSE / SENTRY keys) in .env
docker compose up --build -d
docker compose logs -fdocker compose down[!TIP] The
docker-compose.ymlmounts./data,./chroma_db, and./reportsdirectly as host volumes. You can drop new PDFs intodata/and see index changes and reports persist immediately without rebuilding the image.
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
cp .env.example .env
Start the FastAPI server:
python main.py
http://localhost:8000/docshttp://localhost:8000/healthTo 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.
Run the test suite using pytest:
pytest -v
distance, score, bm25_score, rrf_score, and rerank_score, including mathematical formulas, healthy ranges, and real-world interpretations.snake_case for modules/functions/variables, PascalCase for classes, UPPER_SNAKE_CASE for constants.AGENTS.md and .agents/skills/rag-conventions/SKILL.md.This project is licensed under the MIT License - see the LICENSE file for details.
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
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.
This project intentionally avoids heavy wrapper abstractions (like LangChain or LlamaIndex) in favor of First-Principles AI Engineering:
Here is the exact flow of data and component execution across the two main pipelines: Document Ingestion and RAG Query Execution.
%%{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
===================================================================================
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
===================================================================================
POST /index & DELETE /index)LayoutParser extracts structural blocks (SectionHeaderItem, TableItem, TextItem, CodeItem) into a typed hierarchy (DocumentTree) with section breadcrumbs and table-to-prose linkages.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.pixtral-12b-2409 multimodal model to visually transcribe the exact table into pristine Markdown.BlockChunker keeps small tables ($\le 25$ rows) atomic and slices oversized tables into row-groups with replicated schema headers.TableSerializer produces linearized Key-Value sentences for vector embeddings and Markdown tables for LLM prompt context.ChromaDB and sparse lexical statistics into Okapi BM25.POST /query)similarity_threshold >= 0.95). If a verified cached response exists, returns immediately ($0 LLM cost, ~5-15ms latency).Tracer creates a unique trace_id for distributed observability.Retriever):
HitCollapser groups sibling row-chunks belonging to the same table ID, pulls introductory prose (preceding_prose_id), and caps context within token budgets.format_rag_prompt() injects structured Markdown tables and prose into strict grounding templates.LLMClient calls the selected provider (Mistral, Gemini, OpenAI, or Anthropic) to generate the raw response.[1], [2]) and file sources exist within context.logs/traces.jsonl.The repository follows a structured engineering roadmap detailed in the plans/ directory:
| Plan | Title | Status | Description |
|---|---|---|---|
| Plan 1 | Advanced Hybrid Retrieval & Re-ranking | โ Complete | Sparse BM25 + Dense Vector search with Reciprocal Rank Fusion (RRF), Cross-Encoder Re-ranking, and Contextual Sentence Compression. |
| Plan 2 | Evaluation Engine (LLM-as-a-Judge) | โ Complete | Precision@K, Recall@K, Hit Rate, MRR, Faithfulness / Groundedness, and automated Golden Dataset benchmarking. |
| Plan 3 | Failure Modes & Guardrails (Jev) | โ Complete | Multi-tiered guardrails with deterministic citation bounds checking, statement entailment via Jev discriminative decision model, and safe fallback handling. |
| Plan 6 | Observability & Sentry Error Monitoring | โ Complete | End-to-end span tracing (Tracer), operational metrics (MetricsCollector), Langfuse observability, and Sentry APM error monitoring. |
| Plan 4 | Cost & Latency Optimization | โ Complete | Semantic vector query cache ($0 repeat cost), query complexity router (Flash vs. Pro), and token/latency profiler. |
| Plan 7 | Complex Document Ingestion & Chunking | โ Complete | Docling layout AST engine, TableSanityChecker, Pixtral VLM table repair fallback, dual serialization (KV & MD), and runtime HitCollapser. |
| Plan 5 | System Design & 100x Scaling (ADRs) | โณ Pending | Architecture Decision Records (RAG vs. Fine-Tuning, 100x scale sharding), and Senior AI Interview Cheat Sheet. |
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
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:
cp .env.example .env
# Fill in your MISTRAL_API_KEY (and optional LANGFUSE / SENTRY keys) in .env
docker compose up --build -d
docker compose logs -fdocker compose down[!TIP] The
docker-compose.ymlmounts./data,./chroma_db, and./reportsdirectly as host volumes. You can drop new PDFs intodata/and see index changes and reports persist immediately without rebuilding the image.
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
cp .env.example .env
Start the FastAPI server:
python main.py
http://localhost:8000/docshttp://localhost:8000/healthTo 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.
Run the test suite using pytest:
pytest -v
distance, score, bm25_score, rrf_score, and rerank_score, including mathematical formulas, healthy ranges, and real-world interpretations.snake_case for modules/functions/variables, PascalCase for classes, UPPER_SNAKE_CASE for constants.AGENTS.md and .agents/skills/rag-conventions/SKILL.md.This project is licensed under the MIT License - see the LICENSE file for details.