axiom-coding-agent-setup 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,316 +1,316 @@
1
- # AdaptiveRAG — Project Plan & Progress Tracker
2
-
3
- > Master checklist for the entire build. Update status markers as work completes. See `ARCHITECTURE.md` for design rationale.
4
-
5
- **Status legend:** ✅ done · 🚧 in progress · ⬜ pending · ⏸️ deferred · ❌ cancelled
6
-
7
- ---
8
-
9
- ## Phase 0 — Project Setup ✅
10
-
11
- - Repo initialized (`.git`, `.gitignore`, `.gitattributes`)
12
- - Python 3.14 + `uv` package manager
13
- - `pyproject.toml` with core deps
14
- - `.env` for API keys (`OPENAI_API_KEY`, `QWEN_API_KEY`)
15
- - `AGENTS.md` engineering principles
16
- - `ARCHITECTURE.md` system design
17
- - `PROJECT_PLAN.md` (this file)
18
- - `.env.example` template
19
-
20
- ---
21
-
22
- ## Phase 1 — Document → Markdown (Docling baseline) ✅
23
-
24
- **Goal:** Upload a document, get clean markdown back. Docling-only.
25
-
26
- - `src/core/file_detector.py` — extension/MIME detection
27
- - `src/core/converter.py` — Docling wrapper
28
- - `src/ui/markdown_converter_ui.py` — Gradio upload/preview/download UI
29
- - `app.py` — entry point
30
- - Docling model warm-up on startup
31
-
32
- **Acceptance:** Upload PDF/DOCX/PPTX, see markdown rendered, download `.md` file.
33
-
34
- ---
35
-
36
- ## Phase 2 — Parser Router + Qwen3-VL OCR Fallback 🚧
37
-
38
- **Goal:** Route per-file-type. Use Docling for digital formats, Qwen3-VL for images and scanned PDFs. Add caching so iteration doesn't burn API credits.
39
-
40
- ### Cleanup
41
-
42
- - Trim `file_detector.py` to common formats only (drop ASCIIDOC, LaTeX, XML, JSON, audio/video, VTT, BMP, TIFF, format variants like `.dotx`/`.docm`/etc.)
43
-
44
- ### New modules
45
-
46
- - `src/utils/pdf_inspector.py`
47
- - `is_scanned_pdf(path) -> bool` heuristic (sample first 3 pages, threshold by extracted text length)
48
- - `render_pdf_pages(path, dpi=150) -> Iterator[bytes]` (PNG bytes via `pypdfium2`)
49
- - `src/cache/ocr_cache.py` — SHA256-keyed disk cache for OCR results
50
- - `src/core/qwen_parser.py`
51
- - `QwenParser.extract_image(path) -> str`
52
- - `QwenParser.extract_pdf_pages(path) -> str` (per-page caching, concat)
53
- - Tenacity retry on rate limits / network errors
54
- - Deterministic OCR prompt
55
- - `src/core/docling_parser.py` — Docling-only parser (extracted from `converter.py`)
56
- - `src/core/parser_router.py` — dispatches:
57
- ```
58
- .md / .txt → passthrough (read file)
59
- .png / .jpg / .webp → Qwen
60
- .pdf scanned → Qwen (per page, cached)
61
- .pdf born-digital → Docling
62
- .docx / .pptx / .xlsx / .html / .csv → Docling
63
- ```
64
-
65
- ### Refactor
66
-
67
- - `src/core/converter.py` — slim down to public API, delegate to `parser_router`
68
- - `src/core/__init__.py` — update exports
69
-
70
- ### UI
71
-
72
- - Toggle: "Force Qwen3-VL OCR for PDFs" (override born-digital heuristic)
73
- - Progress indicator for multi-page scanned PDFs
74
- - Show parser used (`docling` / `qwen3-vl` / `passthrough`) in status
75
-
76
- ### Dependencies
77
-
78
- - Add `pypdfium2>=4.30` (PDF inspection + rendering)
79
- - Add `tenacity>=9.0` (retry)
80
- - Add `pillow>=10` (PIL image handling — also Docling transitive but pin explicit)
81
-
82
- **Acceptance:**
83
-
84
- 1. Upload a born-digital PDF → routes to Docling → markdown returned in seconds.
85
- 2. Upload a scanned PDF → routes to Qwen → markdown with preserved tables.
86
- 3. Upload a `.png` of a table → routes to Qwen → markdown table.
87
- 4. Re-upload same file → returns from cache (< 100ms, no API call).
88
- 5. Upload `.docx` / `.pptx` / `.xlsx` / `.html` → Docling, no Qwen call.
89
- 6. Upload `.md` / `.txt` → passthrough, instant.
90
-
91
- ---
92
-
93
- ## Phase 3 — Chunking + Indexing ✅
94
-
95
- **Goal:** Header-aware chunking + hybrid (dense + BM25) indexing in Qdrant.
96
-
97
- ### Modules
98
-
99
- - `src/chunking/markdown_chunker.py`
100
- - `MarkdownHeaderTextSplitter` primary split (`#`/`##`/`###`, `strip_headers=False`)
101
- - `RecursiveCharacterTextSplitter` fallback for oversized sections (>1500 chars)
102
- - Inject `header_path`, `doc_id`, `chunk_index`, `total_chunks`, `parser`, `pages` into metadata
103
- - `src/chunking/metadata.py` — content-hash `doc_id`, deterministic `chunk_uuid` (UUID5), ingestion timestamp
104
- - `src/indexing/embeddings.py` — dense (`text-embedding-3-small`, cached) + sparse (FastEmbed `Qdrant/bm25`)
105
- - `src/indexing/qdrant_store.py` — hybrid collection (named vectors + IDF modifier), upsert, doc-level dedup, library listing, delete-by-doc
106
- - Deduplication is part of `QdrantStore` (skip / replace / count-by-doc) — no separate module needed
107
- - `src/cache/embedding_cache.py` — wraps OpenAI embeddings with `CacheBackedEmbeddings` + `LocalFileStore`
108
- - `src/indexing/pipeline.py` — convert → chunk → upsert orchestrator
109
-
110
- ### Infrastructure
111
-
112
- - `docker-compose.yml` with Qdrant (REST 6333 + gRPC 6334)
113
- - `scripts/init_qdrant.py` — verifies/creates collection, supports `--recreate`
114
-
115
- ### Dependencies
116
-
117
- - Added `qdrant-client>=1.12`
118
- - Added `fastembed>=0.4.2`
119
-
120
- ### UI
121
-
122
- - Refactored `src/ui` into tab-based composition (`main_ui.py`)
123
- - New tab: **Ingest** — multi-file upload → convert → chunk → index, with library table, refresh, and delete-by-doc-id
124
-
125
- **Acceptance:**
126
-
127
- 1. Upload doc → indexed with N chunks. ✅
128
- 2. Re-upload same doc → replaces by default (UUID5 deterministic IDs); checkbox flips to skip-if-exists. ✅
129
- 3. Qdrant has both dense + sparse vectors per chunk (named vectors). ✅
130
- 4. Each chunk has `header_path` metadata visible (e.g. `"Refund Policy > Eligibility"`). ✅
131
-
132
- **Known limitation:** `py-rust-stemmers` 0.1.5 segfaults on Python 3.14
133
- ([qdrant/py-rust-stemmers#9](https://github.com/qdrant/py-rust-stemmers/pull/9)).
134
- We pass `disable_stemmer=True` to FastEmbed BM25 as a workaround. Drop the
135
- flag in `src/indexing/embeddings.py::build_sparse_embeddings` once a fixed
136
- release is published. Quality impact is small (only stemming-sensitive
137
- queries like "running"/"runs" are affected).
138
-
139
- ---
140
-
141
- ## Phase 4 — Hybrid Retrieval + Reranker + Basic Chat ✅
142
-
143
- **Goal:** Ask questions, get answers grounded in indexed docs.
144
-
145
- ### Modules
146
-
147
- - `src/config/settings.py` — single source of truth for tunables (top-K, models, temperature, etc.) — overridable via `.env`
148
- - `src/retrieval/hybrid_search.py` — `HybridRetriever` (Qdrant `similarity_search_with_score` over the named-vector hybrid collection — server-side RRF fusion) + `RetrievalPipeline` (prefetch → rerank → trim) with `RetrievedChunk` + `RetrievalReport` dataclasses
149
- - `src/retrieval/reranker.py` — FlashRank ONNX cross-encoder wrapper (`ms-marco-MiniLM-L-12-v2` default, ~34 MB), graceful fallback if unavailable
150
- - Citations live next to retrieval (`RetrievedChunk.citation_label()`) — no dedicated `citations.py` module needed
151
- - `src/synthesis/response.py` — `GroundedAnswerer` builds a numbered-context prompt, calls `ChatOpenAI`, parses inline `[n]` citations into `Citation` objects
152
- - `src/ui/chat_ui.py` — Chatbot + textbox + sources panel + per-turn debug strip; lazy init for retrieval/reranker/LLM so the tab opens fast
153
-
154
- ### Refactor
155
-
156
- - Migrated existing modules (`indexing/embeddings.py`, `indexing/qdrant_store.py`, `chunking/markdown_chunker.py`, `core/qwen_parser.py`) to read defaults from `src.config.settings` instead of duplicated env reads / hardcoded constants
157
- - Reordered tabs (`Chat → Ingest → Convert`) so the primary workflow is front and center
158
-
159
- ### Dependencies
160
-
161
- - Added `flashrank>=0.2.9` (pure-ONNX reranker, no Torch — keeps Python 3.14 install clean)
162
- - LLM via existing `langchain-openai` (`ChatOpenAI`, model defaults to `gpt-4.1-mini`)
163
-
164
- ### UI
165
-
166
- - New tab: **Chat** — `gr.Chatbot` + submit textbox, sources accordion, per-turn debug line (model · prefetch / rerank timings)
167
-
168
- **Acceptance:**
169
-
170
- 1. Query a document, get an answer with at least one citation. ✅
171
- 2. Citation links back to the source chunk + filename + header path. ✅
172
- 3. Configurable `RERANK_TOP_K` (default 5) and `RETRIEVAL_PREFETCH_K` (default 25) via `.env`. ✅
173
- 4. Reranker reorders the hybrid candidates (verified against the indexed sample corpus). ✅
174
-
175
- ### Deferred to Phase 6
176
-
177
- - First Ragas baseline run (golden set + metrics) — moves with the other eval work in Phase 6 to keep this phase focused on the user-facing pipeline
178
-
179
- ---
180
-
181
- ## Phase 5 — Adaptive Query Router ✅
182
-
183
- **Goal:** Implement actual Adaptive RAG. Pick `no_retrieval | vector_only | sql_only | hybrid | clarify` per query.
184
-
185
- ### Routing layer
186
-
187
- - `src/routing/strategies.py` — `Strategy` `StrEnum` + label / capability sets
188
- - `src/routing/prompts.py` — router system prompt + few-shot examples + schema injection
189
- - `src/routing/adaptive_router.py` — `ChatOpenAI(...).with_structured_output(RouterDecision)` classifier; passes chat history; sanitizes (downgrades SQL strategies if backend missing, fills missing clarify question)
190
- - `src/routing/dispatcher.py` — `AdaptiveDispatcher` orchestrates router → retrieval → SQL → synthesis with per-stage timings, lazy backends, and graceful SQL fallback
191
-
192
- ### Tools
193
-
194
- - `src/tools/sql_tool.py` — schema introspection, NL→SQL via `with_structured_output(_SqlOutput)`, statement-level allowlist (only `SELECT`/`WITH`), forbidden-keyword regex, no-multi-statement guard, server-side `statement_timeout`, transaction-level `READ ONLY`, automatic `LIMIT N` injection
195
- - `src/tools/registry.py` — **dropped on purpose.** With explicit routing → dispatch we don't need a function-calling registry abstraction; `SqlTool` is just a class. Documented in code comments / decision log.
196
-
197
- ### Synthesis
198
-
199
- - Extended `GroundedAnswerer` with `answer_direct(...)` (no_retrieval) and `answer_with_sql(...)` (sql_only / hybrid). Single citation model: `[1]..[N]` for chunks, `[DB]` for SQL — parsed back out into `AnswerResponse.cited_indices` / `cited_db`.
200
-
201
- ### Demo data
202
-
203
- - `scripts/seed_demo_data.py` — deterministic e-commerce dataset (100 customers, 50 products, 500 orders, ~1300 line items, ~35 refunds). Idempotent (skips if already populated) with `--recreate` flag. Creates a dedicated read-only role `adaptive_rag_ro` with `SELECT`-only grants for the app to use.
204
-
205
- ### Infrastructure
206
-
207
- - Postgres added to `docker-compose.yml` (`postgres:17-alpine`, healthcheck, persistent volume). **Bound to host port `5433`** (not `5432`) to dodge collisions with a host-installed Postgres.
208
- - `.env.example` documents `SQL_DATABASE_URL`, `SQL_QUERY_TIMEOUT_SEC`, `SQL_ROW_LIMIT`, `ROUTER_MODEL`, `ROUTER_TEMPERATURE`, `SQL_MODEL`. All wired through `src.config.settings`.
209
-
210
- ### Dependencies
211
-
212
- - Added `sqlalchemy>=2.0.36`
213
- - Added `psycopg[binary]>=3.2.3`
214
- - Added explicit `pydantic>=2.9.0` (already a transitive dep, pinned for clarity)
215
-
216
- ### UI
217
-
218
- - Refactored `src/ui/chat_ui.py` to call `AdaptiveDispatcher`. Sources panel now shows: strategy badge + reasoning, executed SQL with first 5 result rows, and chunk citations. Per-turn debug strip shows per-stage timings.
219
-
220
- **Acceptance:**
221
-
222
- 1. ✅ "What does the indexed story say about the aliens arriving in Jakarta?" → `vector_only` (5 chunks retrieved, 5 cited, narrative answer).
223
- 2. ✅ "How many refunds last 30 days?" → `sql_only` (`SELECT COUNT(*) FROM refunds WHERE created_at >= NOW() - INTERVAL '30 days'` → "3 refunds [DB]").
224
- 3. ✅ "Summarize the indexed story and tell me total refunds in our database" → `hybrid` (chunks + SQL, blended answer).
225
- 4. ✅ "Hi there!" → `no_retrieval`.
226
- 5. ✅ "What about last quarter?" → `clarify` ("Could you specify what information about last quarter you're interested in — sales, refunds, new customers?").
227
-
228
- ### Deferred to Phase 6
229
-
230
- - Routing accuracy metric on a golden set (30-50 examples) — moves with the rest of the eval work.
231
- - Top-N products SQL with `ORDER BY ... DESC` is correct, but synthesis truncates the list when the chunk slice cuts mid-list. Worth a small system-prompt tweak in Phase 6.
232
-
233
- ### Known surprises (from smoke test)
234
-
235
- - The router will pick `no_retrieval` over `vector_only` for vague conversational openers like "What happens in the story?" without prior turns — it asks "which story?" instead of blindly searching. Defensible behavior; document the workaround (be specific, e.g. "What does the indexed story say about X").
236
-
237
- ---
238
-
239
- ## Phase 6 — Evaluation, Tracing, Polish ✅
240
-
241
- **Goal:** Make this presentable as a portfolio piece.
242
-
243
- ### Observability (Langfuse)
244
-
245
- - `src/observability/langfuse_client.py` — lazy singleton `Langfuse` client, no-op `span()` context manager when keys are missing, `CallbackHandler` factory for LangChain
246
- - `src/observability/cost_tracker.py` — read-side helper that pulls daily metrics from Langfuse's `/api/public/metrics/daily` endpoint (no separate price table to maintain)
247
- - `src/routing/dispatcher.py` — wraps every chat turn in a parent `chat.turn` span with child spans `router.classify`, `retrieval.hybrid_search`, `tool.sql_execute`, `synthesis.direct` / `synthesis.grounded`. Auto-flushes after each turn so traces appear immediately even in short-lived Gradio request cycles.
248
- - `src/routing/adaptive_router.py`, `src/synthesis/response.py`, `src/tools/sql_tool.py` — every `ChatOpenAI.invoke(...)` call now passes `config={"callbacks": get_callback_handler(), "run_name": "...", "metadata": {...}}` so token usage + cost get captured automatically.
249
-
250
- ### Evaluation
251
-
252
- - `src/eval/golden.jsonl` — **minimal smoke set** (≈5 rows, one per strategy) to avoid burning tokens; extend the file anytime you want stronger coverage.
253
- - `src/eval/run_routing_eval.py` — router-only accuracy + breakdown; **`--threshold` is opt-in** (default: print report only) so tiny goldens don’t spam failures
254
- - `src/eval/run_deepeval.py` — runs the full dispatcher on retrieval-bearing examples and scores them with DeepEval's `FaithfulnessMetric`, `AnswerRelevancyMetric`, `ContextualRelevancyMetric`. Emits both a JSON dump and a self-contained HTML report under `src/eval/reports/`.
255
- - `src/eval/__init__.py` + `src/eval/reports/` (gitignored)
256
-
257
- ### UI
258
-
259
- - New tab: **Admin** — Langfuse cost / usage dashboard with selectable window (24h / 7d / 30d), per-model breakdown, per-day breakdown. Friendly empty-state when keys aren't configured.
260
-
261
- ### Dependencies
262
-
263
- - `langfuse>=4.0.0`
264
- - `deepeval>=3.0.0`
265
-
266
- ### Configuration
267
-
268
- - `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_HOST` added to `.env`, `.env.example`, and `src/config/settings.py`. `Settings.langfuse_enabled` returns `True` only when both keys are set.
269
-
270
- **Acceptance:**
271
-
272
- 1. ✅ Routing eval prints per-strategy accuracy and writes `src/eval/reports/routing.json`. Pass `--threshold 0.85` in CI when you want a hard gate.
273
- 2. ✅ DeepEval eval emits faithfulness / answer relevancy / contextual relevancy in both JSON and HTML.
274
- 3. ✅ Every chat turn produces a Langfuse trace with router / retrieval / SQL / synthesis spans (when keys are set; otherwise the app behaves identically and the spans are no-ops).
275
- 4. ✅ Admin tab renders cost + token totals (and a friendly setup message when Langfuse is disabled).
276
-
277
- ---
278
-
279
- ## Phase 7 — Stretch Goals ⏸️
280
-
281
- Optional, only if time permits.
282
-
283
- - **C-RAG self-reflection** — grade retrieved context, fall back to web search if low relevance
284
- - **Multi-hop retrieval** — when `clarify` strategy escalates to step-by-step search
285
- - **MCP server surface** (`src/mcp_server/server.py`) — expose `search_docs` and `query_sql` tools to Cursor / Claude Desktop
286
- - **Web search fallback** — Tavily / Exa when context insufficient
287
- - **Streaming responses** — wire LLM streaming through Gradio
288
- - **Multi-collection** — split per-domain (policies, finance, technical)
289
- - **OCR of in-line images** — extract images from Docling output, OCR them, inline into markdown
290
-
291
- ---
292
-
293
- ## Currently Working On
294
-
295
- **Phase 7 — Stretch Goals** ⏸️
296
-
297
- Phase 6 is complete. Pick whichever stretch goal is most valuable next: streaming responses through Gradio, MCP server surface for Cursor / Claude Desktop, or C-RAG self-reflection with web search fallback.
298
-
299
- ---
300
-
301
- ## Quick Status
302
-
303
-
304
- | Phase | Status | % |
305
- | ----------------------- | ------ | ---- |
306
- | 0. Setup | ✅ | 100% |
307
- | 1. Docling baseline | ✅ | 100% |
308
- | 2. Parser router + Qwen | ✅ | 100% |
309
- | 3. Chunking + indexing | ✅ | 100% |
310
- | 4. Retrieval + chat | ✅ | 100% |
311
- | 5. Adaptive router | ✅ | 100% |
312
- | 6. Eval + polish | ✅ | 100% |
313
- | 7. Stretch | ⏸️ | — |
314
-
315
-
1
+ # AdaptiveRAG — Project Plan & Progress Tracker
2
+
3
+ > Master checklist for the entire build. Update status markers as work completes. See `ARCHITECTURE.md` for design rationale.
4
+
5
+ **Status legend:** ✅ done · 🚧 in progress · ⬜ pending · ⏸️ deferred · ❌ cancelled
6
+
7
+ ---
8
+
9
+ ## Phase 0 — Project Setup ✅
10
+
11
+ - Repo initialized (`.git`, `.gitignore`, `.gitattributes`)
12
+ - Python 3.14 + `uv` package manager
13
+ - `pyproject.toml` with core deps
14
+ - `.env` for API keys (`OPENAI_API_KEY`, `QWEN_API_KEY`)
15
+ - `AGENTS.md` engineering principles
16
+ - `ARCHITECTURE.md` system design
17
+ - `PROJECT_PLAN.md` (this file)
18
+ - `.env.example` template
19
+
20
+ ---
21
+
22
+ ## Phase 1 — Document → Markdown (Docling baseline) ✅
23
+
24
+ **Goal:** Upload a document, get clean markdown back. Docling-only.
25
+
26
+ - `src/core/file_detector.py` — extension/MIME detection
27
+ - `src/core/converter.py` — Docling wrapper
28
+ - `src/ui/markdown_converter_ui.py` — Gradio upload/preview/download UI
29
+ - `app.py` — entry point
30
+ - Docling model warm-up on startup
31
+
32
+ **Acceptance:** Upload PDF/DOCX/PPTX, see markdown rendered, download `.md` file.
33
+
34
+ ---
35
+
36
+ ## Phase 2 — Parser Router + Qwen3-VL OCR Fallback 🚧
37
+
38
+ **Goal:** Route per-file-type. Use Docling for digital formats, Qwen3-VL for images and scanned PDFs. Add caching so iteration doesn't burn API credits.
39
+
40
+ ### Cleanup
41
+
42
+ - Trim `file_detector.py` to common formats only (drop ASCIIDOC, LaTeX, XML, JSON, audio/video, VTT, BMP, TIFF, format variants like `.dotx`/`.docm`/etc.)
43
+
44
+ ### New modules
45
+
46
+ - `src/utils/pdf_inspector.py`
47
+ - `is_scanned_pdf(path) -> bool` heuristic (sample first 3 pages, threshold by extracted text length)
48
+ - `render_pdf_pages(path, dpi=150) -> Iterator[bytes]` (PNG bytes via `pypdfium2`)
49
+ - `src/cache/ocr_cache.py` — SHA256-keyed disk cache for OCR results
50
+ - `src/core/qwen_parser.py`
51
+ - `QwenParser.extract_image(path) -> str`
52
+ - `QwenParser.extract_pdf_pages(path) -> str` (per-page caching, concat)
53
+ - Tenacity retry on rate limits / network errors
54
+ - Deterministic OCR prompt
55
+ - `src/core/docling_parser.py` — Docling-only parser (extracted from `converter.py`)
56
+ - `src/core/parser_router.py` — dispatches:
57
+ ```
58
+ .md / .txt → passthrough (read file)
59
+ .png / .jpg / .webp → Qwen
60
+ .pdf scanned → Qwen (per page, cached)
61
+ .pdf born-digital → Docling
62
+ .docx / .pptx / .xlsx / .html / .csv → Docling
63
+ ```
64
+
65
+ ### Refactor
66
+
67
+ - `src/core/converter.py` — slim down to public API, delegate to `parser_router`
68
+ - `src/core/__init__.py` — update exports
69
+
70
+ ### UI
71
+
72
+ - Toggle: "Force Qwen3-VL OCR for PDFs" (override born-digital heuristic)
73
+ - Progress indicator for multi-page scanned PDFs
74
+ - Show parser used (`docling` / `qwen3-vl` / `passthrough`) in status
75
+
76
+ ### Dependencies
77
+
78
+ - Add `pypdfium2>=4.30` (PDF inspection + rendering)
79
+ - Add `tenacity>=9.0` (retry)
80
+ - Add `pillow>=10` (PIL image handling — also Docling transitive but pin explicit)
81
+
82
+ **Acceptance:**
83
+
84
+ 1. Upload a born-digital PDF → routes to Docling → markdown returned in seconds.
85
+ 2. Upload a scanned PDF → routes to Qwen → markdown with preserved tables.
86
+ 3. Upload a `.png` of a table → routes to Qwen → markdown table.
87
+ 4. Re-upload same file → returns from cache (< 100ms, no API call).
88
+ 5. Upload `.docx` / `.pptx` / `.xlsx` / `.html` → Docling, no Qwen call.
89
+ 6. Upload `.md` / `.txt` → passthrough, instant.
90
+
91
+ ---
92
+
93
+ ## Phase 3 — Chunking + Indexing ✅
94
+
95
+ **Goal:** Header-aware chunking + hybrid (dense + BM25) indexing in Qdrant.
96
+
97
+ ### Modules
98
+
99
+ - `src/chunking/markdown_chunker.py`
100
+ - `MarkdownHeaderTextSplitter` primary split (`#`/`##`/`###`, `strip_headers=False`)
101
+ - `RecursiveCharacterTextSplitter` fallback for oversized sections (>1500 chars)
102
+ - Inject `header_path`, `doc_id`, `chunk_index`, `total_chunks`, `parser`, `pages` into metadata
103
+ - `src/chunking/metadata.py` — content-hash `doc_id`, deterministic `chunk_uuid` (UUID5), ingestion timestamp
104
+ - `src/indexing/embeddings.py` — dense (`text-embedding-3-small`, cached) + sparse (FastEmbed `Qdrant/bm25`)
105
+ - `src/indexing/qdrant_store.py` — hybrid collection (named vectors + IDF modifier), upsert, doc-level dedup, library listing, delete-by-doc
106
+ - Deduplication is part of `QdrantStore` (skip / replace / count-by-doc) — no separate module needed
107
+ - `src/cache/embedding_cache.py` — wraps OpenAI embeddings with `CacheBackedEmbeddings` + `LocalFileStore`
108
+ - `src/indexing/pipeline.py` — convert → chunk → upsert orchestrator
109
+
110
+ ### Infrastructure
111
+
112
+ - `docker-compose.yml` with Qdrant (REST 6333 + gRPC 6334)
113
+ - `scripts/init_qdrant.py` — verifies/creates collection, supports `--recreate`
114
+
115
+ ### Dependencies
116
+
117
+ - Added `qdrant-client>=1.12`
118
+ - Added `fastembed>=0.4.2`
119
+
120
+ ### UI
121
+
122
+ - Refactored `src/ui` into tab-based composition (`main_ui.py`)
123
+ - New tab: **Ingest** — multi-file upload → convert → chunk → index, with library table, refresh, and delete-by-doc-id
124
+
125
+ **Acceptance:**
126
+
127
+ 1. Upload doc → indexed with N chunks. ✅
128
+ 2. Re-upload same doc → replaces by default (UUID5 deterministic IDs); checkbox flips to skip-if-exists. ✅
129
+ 3. Qdrant has both dense + sparse vectors per chunk (named vectors). ✅
130
+ 4. Each chunk has `header_path` metadata visible (e.g. `"Refund Policy > Eligibility"`). ✅
131
+
132
+ **Known limitation:** `py-rust-stemmers` 0.1.5 segfaults on Python 3.14
133
+ ([qdrant/py-rust-stemmers#9](https://github.com/qdrant/py-rust-stemmers/pull/9)).
134
+ We pass `disable_stemmer=True` to FastEmbed BM25 as a workaround. Drop the
135
+ flag in `src/indexing/embeddings.py::build_sparse_embeddings` once a fixed
136
+ release is published. Quality impact is small (only stemming-sensitive
137
+ queries like "running"/"runs" are affected).
138
+
139
+ ---
140
+
141
+ ## Phase 4 — Hybrid Retrieval + Reranker + Basic Chat ✅
142
+
143
+ **Goal:** Ask questions, get answers grounded in indexed docs.
144
+
145
+ ### Modules
146
+
147
+ - `src/config/settings.py` — single source of truth for tunables (top-K, models, temperature, etc.) — overridable via `.env`
148
+ - `src/retrieval/hybrid_search.py` — `HybridRetriever` (Qdrant `similarity_search_with_score` over the named-vector hybrid collection — server-side RRF fusion) + `RetrievalPipeline` (prefetch → rerank → trim) with `RetrievedChunk` + `RetrievalReport` dataclasses
149
+ - `src/retrieval/reranker.py` — FlashRank ONNX cross-encoder wrapper (`ms-marco-MiniLM-L-12-v2` default, ~34 MB), graceful fallback if unavailable
150
+ - Citations live next to retrieval (`RetrievedChunk.citation_label()`) — no dedicated `citations.py` module needed
151
+ - `src/synthesis/response.py` — `GroundedAnswerer` builds a numbered-context prompt, calls `ChatOpenAI`, parses inline `[n]` citations into `Citation` objects
152
+ - `src/ui/chat_ui.py` — Chatbot + textbox + sources panel + per-turn debug strip; lazy init for retrieval/reranker/LLM so the tab opens fast
153
+
154
+ ### Refactor
155
+
156
+ - Migrated existing modules (`indexing/embeddings.py`, `indexing/qdrant_store.py`, `chunking/markdown_chunker.py`, `core/qwen_parser.py`) to read defaults from `src.config.settings` instead of duplicated env reads / hardcoded constants
157
+ - Reordered tabs (`Chat → Ingest → Convert`) so the primary workflow is front and center
158
+
159
+ ### Dependencies
160
+
161
+ - Added `flashrank>=0.2.9` (pure-ONNX reranker, no Torch — keeps Python 3.14 install clean)
162
+ - LLM via existing `langchain-openai` (`ChatOpenAI`, model defaults to `gpt-4.1-mini`)
163
+
164
+ ### UI
165
+
166
+ - New tab: **Chat** — `gr.Chatbot` + submit textbox, sources accordion, per-turn debug line (model · prefetch / rerank timings)
167
+
168
+ **Acceptance:**
169
+
170
+ 1. Query a document, get an answer with at least one citation. ✅
171
+ 2. Citation links back to the source chunk + filename + header path. ✅
172
+ 3. Configurable `RERANK_TOP_K` (default 5) and `RETRIEVAL_PREFETCH_K` (default 25) via `.env`. ✅
173
+ 4. Reranker reorders the hybrid candidates (verified against the indexed sample corpus). ✅
174
+
175
+ ### Deferred to Phase 6
176
+
177
+ - First Ragas baseline run (golden set + metrics) — moves with the other eval work in Phase 6 to keep this phase focused on the user-facing pipeline
178
+
179
+ ---
180
+
181
+ ## Phase 5 — Adaptive Query Router ✅
182
+
183
+ **Goal:** Implement actual Adaptive RAG. Pick `no_retrieval | vector_only | sql_only | hybrid | clarify` per query.
184
+
185
+ ### Routing layer
186
+
187
+ - `src/routing/strategies.py` — `Strategy` `StrEnum` + label / capability sets
188
+ - `src/routing/prompts.py` — router system prompt + few-shot examples + schema injection
189
+ - `src/routing/adaptive_router.py` — `ChatOpenAI(...).with_structured_output(RouterDecision)` classifier; passes chat history; sanitizes (downgrades SQL strategies if backend missing, fills missing clarify question)
190
+ - `src/routing/dispatcher.py` — `AdaptiveDispatcher` orchestrates router → retrieval → SQL → synthesis with per-stage timings, lazy backends, and graceful SQL fallback
191
+
192
+ ### Tools
193
+
194
+ - `src/tools/sql_tool.py` — schema introspection, NL→SQL via `with_structured_output(_SqlOutput)`, statement-level allowlist (only `SELECT`/`WITH`), forbidden-keyword regex, no-multi-statement guard, server-side `statement_timeout`, transaction-level `READ ONLY`, automatic `LIMIT N` injection
195
+ - `src/tools/registry.py` — **dropped on purpose.** With explicit routing → dispatch we don't need a function-calling registry abstraction; `SqlTool` is just a class. Documented in code comments / decision log.
196
+
197
+ ### Synthesis
198
+
199
+ - Extended `GroundedAnswerer` with `answer_direct(...)` (no_retrieval) and `answer_with_sql(...)` (sql_only / hybrid). Single citation model: `[1]..[N]` for chunks, `[DB]` for SQL — parsed back out into `AnswerResponse.cited_indices` / `cited_db`.
200
+
201
+ ### Demo data
202
+
203
+ - `scripts/seed_demo_data.py` — deterministic e-commerce dataset (100 customers, 50 products, 500 orders, ~1300 line items, ~35 refunds). Idempotent (skips if already populated) with `--recreate` flag. Creates a dedicated read-only role `adaptive_rag_ro` with `SELECT`-only grants for the app to use.
204
+
205
+ ### Infrastructure
206
+
207
+ - Postgres added to `docker-compose.yml` (`postgres:17-alpine`, healthcheck, persistent volume). **Bound to host port `5433`** (not `5432`) to dodge collisions with a host-installed Postgres.
208
+ - `.env.example` documents `SQL_DATABASE_URL`, `SQL_QUERY_TIMEOUT_SEC`, `SQL_ROW_LIMIT`, `ROUTER_MODEL`, `ROUTER_TEMPERATURE`, `SQL_MODEL`. All wired through `src.config.settings`.
209
+
210
+ ### Dependencies
211
+
212
+ - Added `sqlalchemy>=2.0.36`
213
+ - Added `psycopg[binary]>=3.2.3`
214
+ - Added explicit `pydantic>=2.9.0` (already a transitive dep, pinned for clarity)
215
+
216
+ ### UI
217
+
218
+ - Refactored `src/ui/chat_ui.py` to call `AdaptiveDispatcher`. Sources panel now shows: strategy badge + reasoning, executed SQL with first 5 result rows, and chunk citations. Per-turn debug strip shows per-stage timings.
219
+
220
+ **Acceptance:**
221
+
222
+ 1. ✅ "What does the indexed story say about the aliens arriving in Jakarta?" → `vector_only` (5 chunks retrieved, 5 cited, narrative answer).
223
+ 2. ✅ "How many refunds last 30 days?" → `sql_only` (`SELECT COUNT(*) FROM refunds WHERE created_at >= NOW() - INTERVAL '30 days'` → "3 refunds [DB]").
224
+ 3. ✅ "Summarize the indexed story and tell me total refunds in our database" → `hybrid` (chunks + SQL, blended answer).
225
+ 4. ✅ "Hi there!" → `no_retrieval`.
226
+ 5. ✅ "What about last quarter?" → `clarify` ("Could you specify what information about last quarter you're interested in — sales, refunds, new customers?").
227
+
228
+ ### Deferred to Phase 6
229
+
230
+ - Routing accuracy metric on a golden set (30-50 examples) — moves with the rest of the eval work.
231
+ - Top-N products SQL with `ORDER BY ... DESC` is correct, but synthesis truncates the list when the chunk slice cuts mid-list. Worth a small system-prompt tweak in Phase 6.
232
+
233
+ ### Known surprises (from smoke test)
234
+
235
+ - The router will pick `no_retrieval` over `vector_only` for vague conversational openers like "What happens in the story?" without prior turns — it asks "which story?" instead of blindly searching. Defensible behavior; document the workaround (be specific, e.g. "What does the indexed story say about X").
236
+
237
+ ---
238
+
239
+ ## Phase 6 — Evaluation, Tracing, Polish ✅
240
+
241
+ **Goal:** Make this presentable as a portfolio piece.
242
+
243
+ ### Observability (Langfuse)
244
+
245
+ - `src/observability/langfuse_client.py` — lazy singleton `Langfuse` client, no-op `span()` context manager when keys are missing, `CallbackHandler` factory for LangChain
246
+ - `src/observability/cost_tracker.py` — read-side helper that pulls daily metrics from Langfuse's `/api/public/metrics/daily` endpoint (no separate price table to maintain)
247
+ - `src/routing/dispatcher.py` — wraps every chat turn in a parent `chat.turn` span with child spans `router.classify`, `retrieval.hybrid_search`, `tool.sql_execute`, `synthesis.direct` / `synthesis.grounded`. Auto-flushes after each turn so traces appear immediately even in short-lived Gradio request cycles.
248
+ - `src/routing/adaptive_router.py`, `src/synthesis/response.py`, `src/tools/sql_tool.py` — every `ChatOpenAI.invoke(...)` call now passes `config={"callbacks": get_callback_handler(), "run_name": "...", "metadata": {...}}` so token usage + cost get captured automatically.
249
+
250
+ ### Evaluation
251
+
252
+ - `src/eval/golden.jsonl` — **minimal smoke set** (≈5 rows, one per strategy) to avoid burning tokens; extend the file anytime you want stronger coverage.
253
+ - `src/eval/run_routing_eval.py` — router-only accuracy + breakdown; **`--threshold` is opt-in** (default: print report only) so tiny goldens don’t spam failures
254
+ - `src/eval/run_deepeval.py` — runs the full dispatcher on retrieval-bearing examples and scores them with DeepEval's `FaithfulnessMetric`, `AnswerRelevancyMetric`, `ContextualRelevancyMetric`. Emits both a JSON dump and a self-contained HTML report under `src/eval/reports/`.
255
+ - `src/eval/__init__.py` + `src/eval/reports/` (gitignored)
256
+
257
+ ### UI
258
+
259
+ - New tab: **Admin** — Langfuse cost / usage dashboard with selectable window (24h / 7d / 30d), per-model breakdown, per-day breakdown. Friendly empty-state when keys aren't configured.
260
+
261
+ ### Dependencies
262
+
263
+ - `langfuse>=4.0.0`
264
+ - `deepeval>=3.0.0`
265
+
266
+ ### Configuration
267
+
268
+ - `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_HOST` added to `.env`, `.env.example`, and `src/config/settings.py`. `Settings.langfuse_enabled` returns `True` only when both keys are set.
269
+
270
+ **Acceptance:**
271
+
272
+ 1. ✅ Routing eval prints per-strategy accuracy and writes `src/eval/reports/routing.json`. Pass `--threshold 0.85` in CI when you want a hard gate.
273
+ 2. ✅ DeepEval eval emits faithfulness / answer relevancy / contextual relevancy in both JSON and HTML.
274
+ 3. ✅ Every chat turn produces a Langfuse trace with router / retrieval / SQL / synthesis spans (when keys are set; otherwise the app behaves identically and the spans are no-ops).
275
+ 4. ✅ Admin tab renders cost + token totals (and a friendly setup message when Langfuse is disabled).
276
+
277
+ ---
278
+
279
+ ## Phase 7 — Stretch Goals ⏸️
280
+
281
+ Optional, only if time permits.
282
+
283
+ - **C-RAG self-reflection** — grade retrieved context, fall back to web search if low relevance
284
+ - **Multi-hop retrieval** — when `clarify` strategy escalates to step-by-step search
285
+ - **MCP server surface** (`src/mcp_server/server.py`) — expose `search_docs` and `query_sql` tools to Cursor / Claude Desktop
286
+ - **Web search fallback** — Tavily / Exa when context insufficient
287
+ - **Streaming responses** — wire LLM streaming through Gradio
288
+ - **Multi-collection** — split per-domain (policies, finance, technical)
289
+ - **OCR of in-line images** — extract images from Docling output, OCR them, inline into markdown
290
+
291
+ ---
292
+
293
+ ## Currently Working On
294
+
295
+ **Phase 7 — Stretch Goals** ⏸️
296
+
297
+ Phase 6 is complete. Pick whichever stretch goal is most valuable next: streaming responses through Gradio, MCP server surface for Cursor / Claude Desktop, or C-RAG self-reflection with web search fallback.
298
+
299
+ ---
300
+
301
+ ## Quick Status
302
+
303
+
304
+ | Phase | Status | % |
305
+ | ----------------------- | ------ | ---- |
306
+ | 0. Setup | ✅ | 100% |
307
+ | 1. Docling baseline | ✅ | 100% |
308
+ | 2. Parser router + Qwen | ✅ | 100% |
309
+ | 3. Chunking + indexing | ✅ | 100% |
310
+ | 4. Retrieval + chat | ✅ | 100% |
311
+ | 5. Adaptive router | ✅ | 100% |
312
+ | 6. Eval + polish | ✅ | 100% |
313
+ | 7. Stretch | ⏸️ | — |
314
+
315
+
316
316
  Last updated: 2026-05-15