Spaces:
Sleeping
Sleeping
Commit Β·
e5f51c4
1
Parent(s): c0a76c4
chore: remove CLAUDE.md and docs/ from repo, add to .gitignore
Browse filesThese are private design documents kept only in the local working copy.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (6)
- .gitignore+2
- CLAUDE.mdDeleted-153
- docs/WORKLOG.mdDeleted-332
- docs/plans/2026-03-04-rag-research-chatbot-design.mdDeleted-594
- docs/plans/2026-03-04-rag-research-chatbot-implementation.mdDeleted
- docs/plans/2026-03-05-query-understanding-design.mdDeleted-293
8 unmodified lines910118 unmodified lines.pytest_cache/knowledge_base/*!knowledge_base/.gitkeep8 unmodified lines9101112138 unmodified lines.pytest_cache/knowledge_base/*!knowledge_base/.gitkeepCLAUDE.mddocs/
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153# CLAUDE.md β Project Instructions for Claude Code
## Project Overview
**RAG Research Chatbot Template** β A reusable, citation-verified research assistant chatbot grounded in a local knowledge base. Users download the template, provide an API key, drop documents into `knowledge_base/`, and get a chatbot with strong anti-hallucination guardrails.
## Architecture
- **Registry pattern**: LLM providers (`src/llm/`), search backends (`src/search/`), and file readers (`src/readers/`) each use a dict registry in their `__init__.py`. Adding a new provider/format = write one file + add one line to the registry.- **Ingestion pipeline**: ingest β chunk β embed β store (ChromaDB)- **Query pipeline**: query understanding β retrieve β generate β verify (6-layer stack)- **Config**: `config.yaml` (generated by `setup.py` wizard) + `.env` (API keys, gitignored). Env vars override config values.
## Key Design Decisions
### Query Understanding Layer
Pre-retrieval step that uses the LLM to improve retrieval quality:
- **Reformulation**: Rewrites user queries into search-optimized forms (expand abbreviations, add domain keywords, resolve pronouns from conversation history)- **Clarification**: When a query is genuinely ambiguous (high bar), asks the user ONE clarification question before searching- **Conversation history**: Uses last N messages (default 6) to resolve follow-up references like "what about 2023?" or "they"- **Transparency**: Shows the reformulated query to the user (`Searching for: "..."`)- **Key principle**: Reformulated query is used ONLY for retrieval. The original query is preserved for response generation- **Graceful degradation**: Falls back to raw query if LLM call fails. Can be disabled via `query_understanding.enabled: false`- **No anti-hallucination impact**: Operates before retrieval; the 6-layer stack is unchanged
### Anti-Hallucination is Priority #1
The 6-layer verification stack is the core differentiator. Never weaken these guardrails:
- **Layer 0**: No-source early exit β LLM is NEVER called if retrieval returns zero results- **Layer 1**: System prompt with zero-tolerance hallucination rules- **Layer 2**: Soft max-token cap proportional to context size- **Layer 3**: LLM self-verification with iterative correction loop (max 3 iterations)- **Layer 4**: Term-overlap semantic similarity check (advisory flags)- **Layer 5**: Warning-phrase scanner (advisory flags)
### Over-Refusal Prevention
The system prompt distinguishes between "no relevant info" (refuse) and "some relevant info" (provide what's available). An incomplete answer grounded in sources is always better than a refusal when relevant chunks exist.
### Citation Format
- Every factual claim must have a numbered endnote like `[1]`, `[2]`, etc.- Do NOT use `[N]` as a placeholder β always use actual numbers- Direct quotes (3+ consecutive words from source) must be in quotation marks- Every response ends with a **References** section split into **Local Sources (Primary)** and **Web Sources (Supplementary)**- References must show actual file names/paths/page numbers β NOT chunk IDs (CHUNK-LOCAL-001)- Local knowledge base ALWAYS takes priority over web sources
### Chunk ID Anchoring
- Local chunks: `[CHUNK-LOCAL-NNN]`- Web chunks: `[CHUNK-WEB-NNN]`- These IDs appear in the context block for internal anchoring only β they must NOT appear in user-facing references
### Retrieval Strategy
- Uses **distance-threshold retrieval** instead of fixed top_k- Queries up to `top_k` (default 50) candidates from ChromaDB- Keeps only chunks with cosine distance below `max_distance` (default 0.55)- Broad queries get more chunks; narrow queries get fewer β all based on relevance
## Project Structure
```βββ CLAUDE.md # Project instructions for Claude Codeβββ setup.py # Setup wizard β generates config.yaml + .envβββ ingest.py # Entry point: python ingest.pyβββ app_cli.py # CLI interface (Rich)βββ app_web.py # Web UI (Streamlit)βββ config.yaml # Generated by wizard (gitignored pattern optional)βββ .env # API keys (gitignored)βββ requirements.txtβββ knowledge_base/ # User drops documents hereβββ chroma_db/ # Vector DB (auto-generated, gitignored)βββ src/β βββ config_loader.py # Loads config.yaml + .envβ βββ query_engine.py # Query understanding: reformulation + clarificationβ βββ ingest.py # Ingestion pipeline + ChromaDBβ βββ retriever.py # Dual retriever (local + web) with distance thresholdβ βββ prompts.py # System, verification, and query understanding promptsβ βββ verifier.py # 6-layer anti-hallucination stackβ βββ llm/ # Provider registry (openai, anthropic, gemini)β βββ search/ # Search backend registry (semantic_scholar, none)β βββ readers/ # File reader registry (15 extensions)βββ tests/ # pytest test suite (59 tests, 13 files)βββ docs/ βββ WORKLOG.md # Development log βββ plans/ # Design docs + implementation plan```
## Config Field Names (IMPORTANT)
The `config.yaml` must use these exact field names β the codebase reads them with `.get()`:
| Config Path | Read By | Notes ||---|---|---|| `paths.vector_db` | `src/ingest.py` | NOT `vector_store` || `paths.knowledge_base` | `src/ingest.py` | default `"knowledge_base"` || `web_search.backend` | `src/retriever.py` | NOT `provider` || `verification.max_iterations` | `src/verifier.py` | NOT `layers` || `verification.strict_mode` | `src/verifier.py` | boolean || `retrieval.chunk_size` | `src/ingest.py` | default 1000 || `retrieval.chunk_overlap` | `src/ingest.py` | default 100 || `retrieval.top_k` | `src/retriever.py` | default 50 (candidate pool cap) || `retrieval.max_distance` | `src/retriever.py` | default 0.55 (relevance threshold) || `embeddings.provider` | `src/ingest.py` | `"local"` or `"openai"` || `query_understanding.enabled` | `src/query_engine.py` | default true || `query_understanding.max_history` | `src/query_engine.py` | default 6 || `query_understanding.max_clarifications` | `app_cli.py`, `app_web.py` | default 1 |
## Commands
```bashpython setup.py # Interactive setup wizardpython ingest.py # Ingest documents from knowledge_base/python app_cli.py # Run CLI chatbotstreamlit run app_web.py # Run web UIpython -m pytest tests/ # Run test suite```
## Testing
- 59 tests across 13 test files- All tests should pass: `python -m pytest tests/ -v`- Known warning: PyPDF2 deprecation (cosmetic, not a bug)
## Code Style
- Python 3.11β3.13 (Python 3.14+ not supported due to ChromaDB/Pydantic compatibility)- Type hints on public APIs- No unnecessary abstractions β registry dicts over class hierarchies- `.get()` with defaults for all config access (graceful degradation)- Tests use `tmp_path` fixture and `pytest.importorskip` for optional deps
## Git
- **Repo**: `https://github.com/LIANJie-Jason/chatbotsample_api` (private)- **Branch**: `master`- Commit style: `feat:`, `fix:`, `refactor:`, `test:`, `docs:`, `style:`
## Do NOT
- Weaken anti-hallucination guardrails without explicit user approval- Remove citation requirements from prompts- Allow the LLM to be called when no sources are retrieved (Layer 0)- Use `[N]` as a placeholder in prompts β the LLM copies it literally- Show chunk IDs (CHUNK-LOCAL-001) in user-facing references- Use direct dict access (`cfg["key"]`) for config β always use `.get()` with defaults- Change config field names without updating ALL consumers + setup wizard + tests- Commit `.env` files or API keys123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332# Work Log β RAG Research Chatbot Template
## 2026-03-04 β Initial Design & Implementation
### Design Phase
- Brainstormed architecture with user (registry pattern, 6-layer anti-hallucination stack)- Key decisions made: - Target audience: academics (primary) + general users - Interfaces: CLI (Rich) + Web UI (Streamlit) - LLM providers: OpenAI, Anthropic, Google Gemini with live model fetching - Web search: pluggable (Semantic Scholar default, swappable/disable) - Anti-hallucination: #1 priority β 6-layer verification stack - Config: interactive setup wizard β `config.yaml` + `.env` - Embeddings: free local default (ChromaDB), OpenAI upgrade option - File formats: 15 extensions (PDF, DOCX, XLSX, XLS, CSV, TAB, TSV, DTA, SAV, RDS, RDA, TXT, MD, JSON, DO)- Design doc saved: `docs/plans/2026-03-04-rag-research-chatbot-design.md`- Implementation plan saved: `docs/plans/2026-03-04-rag-research-chatbot-implementation.md`
### Implementation Phase (Subagent-Driven Development)
15 tasks implemented with TDD, dispatched as parallel subagents where independent:
1. **Scaffold** β project structure, requirements.txt, .gitignore (`415e4e8`)2. **File readers** β PDF + text readers with registry (`c1d9ad3`)3. **Config loader** β YAML + .env loading (`94515d4`)4. **DOCX/Excel/CSV readers** β Word, Excel (xlsx+xls), CSV/TSV readers (`7cdd0f2`)5. **LLM providers** β OpenAI, Anthropic, Gemini with fallback models (`3aabf2e`)6. **Ingestion pipeline** β recursive chunking, ChromaDB storage (`d8edd70`)7. **Search backends** β Semantic Scholar with retry logic (`e3d44b5`)8. **Stat readers** β Stata, SPSS, R data readers (`d8b70fa`)9. **Prompts** β system prompt + verification prompt templates (`8a653d8`)10. **Retriever** β dual retrieval with local priority, chunk ID anchoring (`d641d21`)11. **Verifier** β 6-layer anti-hallucination stack (`1719478`)12. **CLI app** β Rich-powered terminal chatbot with slash commands (`a5f1274`)13. **Setup wizard** β interactive 5-step flow with model fetching (`24c097e`)14. **Web UI** β Streamlit with sidebar controls and chat interface (`e3ae940`)15. **Docker + docs** β Dockerfile, docker-compose, README, LICENSE (`af76fb1`)
**Test suite**: 49 tests across 12 test files β all passing.
---
## 2026-03-05 β Full Code Audit & Bug Fixes
### Audit
Performed line-by-line review of all source files against the design document.
### Bugs Found & Fixed
**CRITICAL β `setup.py:generate_config()` wrong config field names**
The setup wizard generated a `config.yaml` with field names that didn't match what the rest of the codebase reads. This would cause a **KeyError crash** at runtime when accessing `paths["vector_db"]`.
| Generated (wrong) | Expected (correct) | Impact ||---|---|---|| `paths.vector_store` | `paths.vector_db` | KeyError crash || `web_search.provider` | `web_search.backend` | Silent fallback || `verification.layers: [list]` | `verification.max_iterations` + `strict_mode` | Silent fallback || `embeddings.model` only | `embeddings.provider` + `openai_model` | Silent fallback || Missing `retrieval.chunk_size` | needed (default 1000) | Silent fallback || Missing `retrieval.chunk_overlap` | needed (default 100) | Silent fallback |
**BUG β `setup.py:165` wrong run command**- Said `python -m src.cli` β fixed to `python app_cli.py`
**BUG β `app_cli.py:207` dead code**- Removed `if False` ternary from input prompt
**TEST β `tests/test_setup.py` strengthened**- Added assertions for all config field names to prevent this class of bug from recurring
### Verified Correct (no issues)
- `src/config_loader.py`, `src/readers/` (all 8 modules + registry)- `src/llm/` (registry + 3 providers), `src/search/` (registry + Semantic Scholar)- `src/ingest.py`, `src/retriever.py`, `src/prompts.py`, `src/verifier.py`- `app_cli.py`, `app_web.py`, `ingest.py` (root entry point)- `Dockerfile`, `docker-compose.yml`, `.gitignore`, `README.md`, `LICENSE`- All 12 test files (49 tests pass, 1 PyPDF2 deprecation warning)
### Added
- `CLAUDE.md` β project instructions for Claude Code- `docs/WORKLOG.md` β this working log
---
## 2026-03-05 β Second Full Re-Audit
### Scope
Complete re-read of every source file (38 Python files + Dockerfile, docker-compose.yml, requirements.txt, .gitignore, LICENSE, README) against the design document (`docs/plans/2026-03-04-rag-research-chatbot-design.md`).
### Verified Correct
All 6 anti-hallucination layers verified in correct execution order:- **Layer 0**: No-source refusal (pre-LLM gate) β `verifier.py:213-219`- **Layer 1**: System prompt guardrails β `prompts.py:8-60`- **Layer 2**: Soft max-token cap β `verifier.py:47-65`- **Layer 3**: LLM self-verification with iterative correction β `verifier.py:250-336`- **Layer 4**: Term-overlap similarity check β `verifier.py:100-148`- **Layer 5**: Warning-phrase scanner (8 phrases) β `verifier.py:24-33`
All config field names verified consistent across every `.get()` call in the codebase.All 4 retrieval scenarios (local+web, local-only, web-only, no-sources) verified.Chunk ID anchoring (`[CHUNK-LOCAL-NNN]`, `[CHUNK-WEB-NNN]`) verified.Citation format (endnotes, direct quotes, References section) verified in system prompt.All 15 file format readers verified present and functional.Registry pattern verified in `src/llm/`, `src/search/`, `src/readers/`.Setup wizard generates correct config field names (verified by contract test in `tests/test_setup.py`).
### Bug Found & Fixed
**BUG β `src/search/semantic_scholar.py:38` β `None` authors crash**
If the Semantic Scholar API returns a paper with `"authors": null`, `paper.get("authors", [])` returns `None` (key exists with value `None`; default only applies when key is missing). `len(None)` raises `TypeError`.
- Line 37 already handled this correctly: `(paper.get("authors") or [])[:3]`- Line 38 did NOT: `len(paper.get("authors", []))` β crashes on `None`- **Fix**: Changed to `len(paper.get("authors") or [])` β consistent with line 37
### Test Suite
49 tests, all passing after fix.
---
## 2026-03-05 β GitHub Repo & README Rewrite
- Created private GitHub repo: `LIANJie-Jason/chatbotsample_api`- Rewrote README as a detailed usage guide for social scientists without coding backgrounds- README includes: step-by-step installation, supported file formats, CLI/web usage, how it works, anti-hallucination explanation, config reference, Docker, 9 advantages, 9 limitations, troubleshooting- Multiple rounds of README corrections (example output accuracy, clone URL, folder names)- Added Python 3.11β3.13 environment setup instructions after discovering Python 3.14 incompatibility with ChromaDB/Pydantic
---
## 2026-03-05 β Third Full Audit & Live Testing Fixes
### Third Audit
Complete re-read of all source files, design doc, and README. All 49 tests pass.
**README fix**: Prerequisites said "Python 3.11 or later" β corrected to "Python 3.11β3.13" (Python 3.14+ not supported).
### Live Testing β Issues Found & Fixed
User tested the chatbot with real Amnesty International PDFs and CSV data. Several issues discovered:
**FIX β Over-refusal when relevant sources exist** (`src/prompts.py`)
The system prompt had a binary rule: "If the answer is NOT in the context β REFUSE." The LLM refused even when relevant chunks were retrieved (e.g., 5 chunks about China at distances 0.368β0.459) because the question was broad and the data was sparse.
- Added: "If the context contains relevant information, you MUST provide what you can, even if the answer is incomplete."- Added: "An incomplete answer grounded in sources is ALWAYS better than a refusal."- Changed refusal to: "ONLY refuse if the context contains NO relevant information at all."- This matches the design doc's principle: "An incomplete answer is always better than a fabricated one."
**FIX β References showed chunk IDs instead of file paths** (`src/prompts.py`)
The LLM output `[1] CHUNK-LOCAL-001` instead of actual file names. The prompt said "source title or chunk ID" and the LLM took the easy route.
- Added explicit instruction: "Do NOT use chunk IDs (CHUNK-LOCAL-001, CHUNK-WEB-001, etc.) in the reference list."- Added: "Extract the ACTUAL file name, path, and page number from the From: and Path: lines in the context."- Added concrete examples of correct local and web reference formatting.
**FIX β LLM output literal `[N]` alongside real citation numbers** (`src/prompts.py`)
The citation rules used `[N]` as a placeholder example. The LLM copied it literally, producing `[N][1]`.
- Replaced `[N]` with plain English: "numbered endnote like [1], [2], etc."- Added: "Do NOT output the literal text [N] β always use actual numbers."- Also fixed the last `[N]` in the verification prompt template (9-point checklist item 1).
**FIX β Retrieval missed relevant chunks with fixed top_k** (`src/retriever.py`)
With `top_k=5`, short queries like "China in 2024?" retrieved generic intro pages (pages 1, 3, 11) but missed the China-specific page 410.
- Replaced fixed top_k retrieval with **distance-threshold retrieval**.- Now queries up to 50 candidates from ChromaDB, then filters to keep only chunks with cosine distance below `max_distance` (default 0.55).- Broad queries with lots of relevant content get many chunks; narrow queries get fewer.- New config fields: `retrieval.top_k` (candidate pool cap, default 50), `retrieval.max_distance` (relevance threshold, default 0.55).
**FEAT β Personal welcome message with web search status** (`app_cli.py`)
- Added chatbot self-introduction: "Hi! I'm your research assistant on {domain}..."- Shows web search status (ON in green / OFF in red) with toggle instructions.
**STYLE β Hidden distance scores from `/sources` output** (`app_cli.py`)
- Removed `(distance: 0.539)` from `/sources` β internal metric not useful for end users.
### Updated Files
| File | Changes ||---|---|| `src/prompts.py` | Over-refusal fix, reference format fix, `[N]` removal || `src/retriever.py` | Distance-threshold retrieval || `app_cli.py` | Welcome message, web search status, hide distance scores || `setup.py` | New config defaults (top_k=50, max_distance=0.55) || `README.md` | Python version fix, config reference updated || `tests/test_prompts.py` | Updated assertions for new prompt wording |
### Test Suite
49 tests, all passing after all fixes.
---
## 2026-03-05 β Query Understanding Layer
### Design
Added a pre-retrieval query understanding layer that uses the LLM to reformulate user queries for better embedding search. Design doc: `docs/plans/2026-03-05-query-understanding-design.md`.
**Problem:** Short/vague queries like "China in 2024?" produce weak embeddings that miss relevant chunks, even when the knowledge base has the answer. Follow-up questions like "what about 2023?" lose context.
**Solution:** Before retrieval, an LLM call analyzes the user's query and either:1. **Reformulates** it into a search-optimized form (expanded keywords, resolved pronouns, domain-aware terms)2. **Asks clarification** when the query is genuinely ambiguous (high bar β most queries get reformulated)
### Key Design Decisions
- **Reformulated query β retrieval only.** The original query is preserved for response generation- **Conversation history** (last 6 messages by default) enables pronoun/reference resolution- **Transparency:** Shows `Searching for: "reformulated query"` to the user- **Graceful degradation:** Falls back to raw query if LLM fails. Configurable via `query_understanding.enabled`- **No anti-hallucination impact:** Operates before retrieval; the 6-layer stack is unchanged- **Max clarifications:** After `max_clarifications` rounds (default 1), forces a search
### Implementation
| File | Action | Description ||---|---|---|| `src/query_engine.py` | CREATE | `understand_query()` + `_parse_qu_result()` with JSON parsing and fallback || `src/prompts.py` | MODIFY | Added `QUERY_UNDERSTANDING_PROMPT_TEMPLATE` + `build_query_understanding_prompt()` || `app_cli.py` | MODIFY | Query understanding step, clarification flow, conversation history tracking || `app_web.py` | MODIFY | Query understanding step, `pending_clarification` state for Streamlit || `setup.py` | MODIFY | Added `query_understanding` config defaults || `tests/test_query_engine.py` | CREATE | 8 tests covering reformulation, clarification, disabled, error fallback, JSON parsing || `tests/test_prompts.py` | MODIFY | 2 tests for new prompt template || `tests/test_setup.py` | MODIFY | Assertions for new config section |
### Pipeline Flow (Updated)
```User query β understand_query(query, history, cfg) β [if CLARIFY: ask user, loop back, max 1 round] β [if SEARCH: use reformulated query] β retrieve(reformulated_query) β verify_and_respond(original_query, results) β Display```
### Config
```yamlquery_understanding: enabled: true # false to skip (use raw query) max_history: 6 # conversation messages for context max_clarifications: 1 # max clarification rounds before forcing search```
### Test Suite
59 tests across 13 test files β all passing.
---
## 2026-03-05 β Fourth Full Audit & .get() Safety Fixes
### Scope
Complete re-audit of all 40+ source files by 6 parallel subagents, covering: design doc consistency, core pipeline code, app entry points, registry modules, full test suite (59/59 pass), and README/Docker/CLAUDE.md accuracy.
### Bugs Found & Fixed
**BUG β `src/ingest.py:115,148` β Direct dict access crashes on missing config**
Used `cfg["paths"]["vector_db"]` and `cfg["paths"]["knowledge_base"]` instead of `.get()` with defaults. Raises `KeyError` if config is malformed or incomplete.
- Fix: `cfg.get("paths", {}).get("vector_db", "chroma_db")` and `cfg.get("paths", {}).get("knowledge_base", "knowledge_base")`
**BUG β `src/llm/__init__.py:15,21-24` β Direct dict access on `cfg["llm"]`**
Line 15 used `cfg["llm"]["provider"]`; lines 21-24 used `cfg["llm"].get(...)` where the outer `cfg["llm"]` could still crash. All violate CLAUDE.md's `.get()` with defaults requirement.
- Fix: Extract `llm_cfg = cfg.get("llm", {})` once, then use `llm_cfg.get(...)` for all accesses.
**BUG β `src/search/__init__.py:22-24` β Direct key access on result dicts**
Used `r['authors']`, `r['title']`, `r['url']`, `r['abstract']` instead of `.get()`. Would crash if any key missing from a search result.
- Fix: `r.get('authors', 'Unknown')`, `r.get('title', 'Untitled')`, `r.get('url', 'N/A')`, `r.get('abstract', 'N/A')`
**BUG β `app_web.py:171` β Clarification ignores `max_clarifications` config**
Web UI always allowed 1 clarification round regardless of `max_clarifications` config value. Setting `max_clarifications: 0` in config would not disable clarification in the web UI.
- Fix: Added `and max_clarifications > 0` condition to the clarification check.
### Test Improvement
- Added missing assertions for `retrieval.top_k` (50) and `retrieval.max_distance` (0.55) in `tests/test_setup.py`
### Documentation
- Committed CLAUDE.md, docs/plans/, and docs/WORKLOG.md to the git repo (previously only existed in working copy)- Fixed CLAUDE.md: `max_clarifications` now correctly lists both `app_cli.py` and `app_web.py` as consumers- Refined CLAUDE.md: - Separated ingestion pipeline and query pipeline in architecture description - Fixed config table column headers (`Config Path | Read By | Notes`) - Added `paths.knowledge_base` to config table (was missing) - Updated project structure to include `CLAUDE.md` and `docs/` - Added `.get()` rule to "Do NOT" section to prevent future direct-access bugs
### Test Suite
59 tests across 13 test files β all passing.
---
## Pending / Next Steps
- [x] ~~Create GitHub repo~~ β `LIANJie-Jason/chatbotsample_api` (private)- [x] ~~End-to-end test with real documents and a real API key~~- [x] ~~Query understanding layer for better retrieval~~- [ ] Replace PyPDF2 with pypdf (PyPDF2 is deprecated)- [ ] Consider adding provider switching in setup wizard (currently only one provider per config)- [ ] Tune `max_distance` threshold based on more user testing123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594# RAG Research Chatbot Template β Design Document
**Date:** 2026-03-04**Author:** Jie Lian**Status:** Approved
## 1. Overview
A reusable, open-source chatbot template that lets users build a research assistant grounded in their own local knowledge base. Users download the template from GitHub, provide an API key, drop their documents into a `knowledge_base/` folder, and get a citation-verified chatbot with strong anti-hallucination guardrails.
**Target audience:** Both academics (primary) and general users with domain-specific documents.
**Distribution:** GitHub template repository with a quickstart setup wizard.
## 2. Requirements Summary
| Decision | Choice ||---|---|| Audience | General-purpose, marketed to academics || Interface | CLI + Web UI (Streamlit) || Web search | Pluggable (Semantic Scholar default, swappable/disable) || LLM providers | OpenAI + Anthropic + Google Gemini || Model selection | Live fetch from provider API, fallback to defaults || Configuration | Interactive setup wizard + config.yaml || Embeddings | Free local default (ChromaDB), OpenAI upgrade option || Distribution | GitHub template repo + quickstart script || Setup | pip install primary, Docker optional || Anti-hallucination | #1 priority β 6-layer verification stack |
## 3. Supported File Formats
| Format | Extension | Library ||---|---|---|| PDF | `.pdf` | PyPDF2 || Word | `.docx` | python-docx || Excel | `.xlsx`, `.xls` | openpyxl, xlrd || CSV | `.csv` | stdlib csv || Tab-delimited | `.tab`, `.tsv` | stdlib csv || Stata | `.dta` | pyreadstat || R data | `.rds`, `.rda` | pyreadr || SPSS | `.sav` | pyreadstat || Plain text | `.txt`, `.md` | stdlib || JSON | `.json` | stdlib json || Stata do-files | `.do` | stdlib (plain text) |
## 4. Architecture
### 4.1 Project Structure
```rag-research-chatbot/βββ setup.py # Interactive setup wizardβββ ingest.py # Entry point: python ingest.pyβββ app_cli.py # Entry point: python app_cli.pyβββ app_web.py # Entry point: python app_web.py (streamlit)βββ config.yaml # Generated by setup wizardβββ .env # API keys (generated by wizard, gitignored)βββ requirements.txtβββ Dockerfileβββ docker-compose.ymlβββ .gitignoreβββ README.mdβββ LICENSEββββ knowledge_base/ # User drops files hereβ βββ .gitkeepββββ chroma_db/ # Vector DB (auto-generated, gitignored)ββββ src/ βββ __init__.py βββ config_loader.py # Loads config.yaml + .env, exposes settings βββ ingest.py # Multi-format ingestion pipeline βββ retriever.py # Orchestrates local + web retrieval βββ prompts.py # System prompt builder (adapts to scenario) βββ verifier.py # Anti-hallucination verification loop β βββ llm/ β βββ __init__.py # Registry: PROVIDERS dict + generate() β βββ openai.py β βββ anthropic.py β βββ gemini.py β βββ search/ β βββ __init__.py # Registry: BACKENDS dict + search() β βββ semantic_scholar.py β βββ readers/ βββ __init__.py # Registry: READERS dict by extension βββ pdf.py βββ docx.py βββ excel.py # .xlsx and .xls βββ csv_tab.py # .csv, .tab, .tsv βββ stata.py # .dta via pyreadstat βββ spss.py # .sav via pyreadstat βββ rdata.py # .rds, .rda via pyreadr βββ text.py # .txt, .md, .json, .do```
### 4.2 Registry Pattern
LLM providers, search backends, and file readers each use a simple dict registry in their `__init__.py`:
```python# src/llm/__init__.pyPROVIDERS = { "openai": openai_generate, "anthropic": anthropic_generate, "gemini": gemini_generate,}
def generate(system_prompt, user_message, provider=None): provider = provider or config.LLM_PROVIDER if provider not in PROVIDERS: raise ValueError(f"Unknown provider: {provider}") return PROVIDERS[provider](system_prompt, user_message)```
Same pattern for `src/search/__init__.py` (BACKENDS dict) and `src/readers/__init__.py` (READERS dict mapping extensions to reader functions).
Adding a new provider/format = write one file + add one line to the registry.
### 4.3 Data Flow
```User query | vretrieve() --> ChromaDB vector search (ALWAYS runs first) --> Web search (optional, if enabled) | vbuild_prompt() --> inject context + anti-hallucination guardrails | (adapts to 4 scenarios: local+web, local-only, | web-only, no-sources) vgenerate() --> LLM provider (from registry) | vverify() --> 6-layer anti-hallucination stack | vDisplay cited response with reference list```
## 5. Retrieval Strategy
### 5.1 Web Search Toggle
- **Setup wizard:** asks user whether to enable web search (Step 5)- **CLI runtime:** `/websearch on|off` command- **Web UI runtime:** sidebar toggle switch
### 5.2 Priority Logic (Non-Negotiable)
Local knowledge base is ALWAYS the primary authority, regardless of web search setting.
| Scenario | Behavior ||---|---|| Local + Web | Local sources = PRIMARY. Web = supplementary. Web never overrides local. || Local only | Only local sources used. || Web only (no local docs ingested) | Web results used with warning: "No local knowledge base found." || No sources at all | LLM is NOT called. Hardcoded refusal returned. |
### 5.3 Chunk ID Anchoring
Each retrieved chunk gets a unique anchor ID in the context block:
```[CHUNK-LOCAL-001] From: Chenoweth_2011.pdf (p.23) Path: knowledge_base/NAVCO 2.0/Chenoweth_2011.pdf "Nonviolent campaigns succeeded 53% of the time..."
[CHUNK-WEB-001] From: Nepstad (2011). "Nonviolent Revolutions" URL: https://doi.org/10.xxxx/yyyy Abstract: ...```
The LLM must cite by these anchor IDs. The verifier checks that every citation maps to a real chunk.
## 6. Anti-Hallucination System (6-Layer Stack)
This is the most critical part of the design. Anti-hallucination is the #1 priority.
### Layer 0: No-Context Early Exit
If retrieval returns zero local chunks AND zero web results, the LLM is **never called**. A hardcoded Python string is returned:
```"I don't have any information on this topic in my knowledge base.No relevant local documents or web sources were found.Please try a different question, or add relevant materials tothe knowledge_base/ folder and run ingestion again."```
Zero hallucination risk β no LLM involvement.
### Layer 1: System Prompt β Hard Refusal of Memory
The system prompt contains an absolute, non-negotiable directive:
```## ABSOLUTE RULE β ZERO TOLERANCE FOR HALLUCINATION
You are a retrieval-only assistant. You MUST:- ONLY use information from the PROVIDED CONTEXT below.- NEVER use your training data, general knowledge, or memory to answer.- NEVER infer, guess, or "fill in gaps" with plausible-sounding information.- If a user asks something not covered by the context: REFUSE to answer. Say: "I don't have information on this in my knowledge base."- Do NOT say "Based on my knowledge..." or "Generally speaking..." β these phrases indicate you are drawing from memory, not sources.
There are NO exceptions. An incomplete answer is always better thana fabricated one. Silence is always better than a guess.```
Additional Layer 1 directives:- **Direct quote anchoring:** For key findings, include a direct quote from the source material. If you cannot find a direct quote to support a claim, do NOT make that claim.- **Response length guidance:** Response length should generally be proportional to available evidence. If only 1-2 sources, keep the answer focused and concise. Brief synthesis is allowed, but do not pad beyond what sources support.
### Layer 2: Response Length Cap (Soft)
Dynamically adjusts `max_tokens` based on retrieved context size:
```pythoncontext_chars = len(combined_context)if context_chars < 500: max_tokens = 1024elif context_chars < 2000: max_tokens = 1536else: max_tokens = config.max_tokens # default 2048```
This is a soft suggestion, not a hard cutoff. The system prompt also encourages proportional response length.
### Layer 3: LLM Self-Verification Loop
After generation, a second LLM call verifies the response against the provided sources:
**Verification prompt:**
```Verify the following response against ONLY the provided sources.
For each factual claim, check:1. Is this claim directly supported by a source in the context?2. Is the citation correct (right source, right page/URL)?3. Is any information added that does NOT appear in the context?4. Do direct quotes actually appear in the cited source chunk?5. Are any claims flagged by the advisory warnings below unsupported?
Advisory flags from automated checks:{phrase_flags}{similarity_flags}
Report as JSON:{ "errors": [ {"claim": "...", "issue": "not found in sources | wrong citation | from model memory"}, ], "error_count": <int>, "pass": true | false}```
**Iterative correction logic:**
```Generate response | vVerify against sources | βββ pass=true --> Show to user | βββ pass=false βββ β€2 errors: Correct once --> Re-verify | βββ pass=true --> Show to user | βββ pass=false --> REFUSE to answer | βββ >2 errors: Correct --> Re-verify --> still errors? --> Correct again (loop until clean, max 3 iterations) --> Still errors after max? --> REFUSE to answer```
**Refusal message:**
```"I was unable to produce a verified answer from my knowledge base.Please try rephrasing your question."```
**9-point verifier checklist:**
1. Every factual claim has at least one `[N]` citation2. Every `[N]` in text appears in the reference list3. Every reference list entry is used in the text4. Local source paths match real chunks from context5. Web source URLs/DOIs match search backend results6. Direct quotes actually appear in the cited source chunk7. No banned phrases without adjacent citations (from Layer 5 flags)8. Claims flagged by semantic similarity are re-examined (from Layer 4 flags)9. No information added that doesn't appear in context
### Layer 4: Semantic Similarity Post-Check
A non-LLM verification step using embeddings:
```pythonclaim_embedding = embed(claim_text)cited_chunk_embedding = embed(cited_source_chunk)similarity = cosine_similarity(claim_embedding, cited_chunk_embedding)
if similarity < 0.6: flag_as_advisory(claim) # passed to Layer 3 as context```
This is a mathematical check β no LLM judgment involved. Catches cases where the LLM cites a source but says something the source doesn't support.
### Layer 5: Soft Phrase Warning Filter
Scans for phrases that may indicate the model is drawing from memory. These are **advisory flags**, not automatic errors:
```pythonWARNING_PHRASES = [ "based on my knowledge", "generally speaking", "it is well known", "as we all know", "it is widely accepted", "common understanding suggests", "from what I know", "I recall that",]```
Flagged phrases are passed to the Layer 3 verifier as advisory context: "pay extra attention to these sections." A flagged phrase followed by a proper citation `[N]` passes fine. Only if the section genuinely lacks source support does it become an error through normal verification.
### Execution Order
```User query | vLayer 0: No-context early exit | (zero sources --> hardcoded refusal, STOP, LLM never called) vLayer 2: Set soft max_tokens cap based on context size | v[Generate response from LLM] | vLayer 5: Soft phrase warning scan <-- cheapest, no API cost | (advisory flags) vLayer 4: Semantic similarity check <-- embedding cost only | (advisory flags) vLayer 3: LLM self-verification <-- most expensive | (receives Layer 4+5 flags as context) | (iterative correction if errors found) | βββ PASS --> Show to user βββ FAIL after max iterations --> REFUSE to answer```
### Cost Configuration
```yamlverification: enabled: true max_iterations: 3 strict_mode: true # if true, refuse on any remaining error # if false, show answer with warning```
## 7. Citation & Reference Format
### 7.1 Inline Citations (Endnote Style)
Every factual claim gets a bracketed endnote number:
```The success rate of nonviolent campaigns was approximately twice thatof violent insurgencies between 1900 and 2006. [1] Economic boycottswere among the most frequently employed tactics. [2][3]```
### 7.2 Direct Quote Anchoring
Key findings include a direct quote from the source:
```As stated in [1]: "nonviolent campaigns succeeded 53% of the timecompared to 26% for violent insurgencies."```
### 7.3 Reference List
Every response ends with a structured reference list:
```## References
**Local Sources (Primary):**[1] Chenoweth_Stephan_2011.pdf (p. 23) -- knowledge_base/NAVCO 2.0/Chenoweth_Stephan_2011.pdf[2] NAVCO2JPRcodebook2013.pdf (p. 7) -- knowledge_base/NAVCO 2.0/NAVCO2JPRcodebook2013.pdf
**Web Sources (Supplementary):**[3] Chenoweth, E. & Stephan, M. (2011). "Why Civil Resistance Works." DOI: https://doi.org/10.7312/chen15682```
### 7.4 Format Rules
| Element | Local Source | Web Source ||---|---|---|| Identifier | `[N]` endnote | `[N]` endnote || Name | Original filename | Author (Year). "Title" || Location | Page/sheet/row range | DOI (preferred) or URL || Path | Full relative path from `knowledge_base/` | Full link || Priority | **Primary** | **Supplementary** |
## 8. System Prompt Adaptation
The system prompt adapts to four retrieval scenarios:
| Scenario | Prompt Behavior ||---|---|| Local + Web | "Local sources are PRIMARY. Web sources are supplementary only. Never let web override local." || Local only | "ONLY use the local sources below. Do not add any outside knowledge." || Web only (no local docs) | "All sources are from web search. Cite every claim with URL. State clearly you have no curated local sources." || No sources | LLM is NOT called. Hardcoded refusal. |
## 9. Setup Wizard
### 9.1 Interactive Flow
```$ python setup.py
RAG Research Chatbot -- Setup Wizard
Step 1/5: What would you like to name your chatbot?> My Research Assistant
Step 2/5: Describe your chatbot's domain:> Political science and nonviolent resistance research
Step 3/5: Choose your LLM provider: [1] OpenAI [2] Anthropic [3] Google Gemini> 1
Step 3b: Fetching available models from OpenAI... [1] gpt-4o [2] gpt-4o-mini [3] gpt-4.1 ... (live list from API)> 1
Step 4/5: Enter your API key for OpenAI:> sk-... (hidden)
Step 5/5: Enable web search to supplement local knowledge base? [1] Yes -- Semantic Scholar (academic papers) [2] No -- local knowledge base only> 1
Config saved to config.yamlCreated knowledge_base/ folder
Next steps: 1. Drop your files into knowledge_base/ 2. Run: python ingest.py 3. Run: python app_cli.py (or: streamlit run app_web.py)```
### 9.2 Model Fetching
Each provider exposes a `list_models(api_key)` function that calls the provider's API to get available models. If the API call fails (no internet, invalid key), a small hardcoded fallback list is used.
### 9.3 Generated config.yaml
```yaml# -- Chatbot Identity --chatbot: name: "My Research Assistant" domain: "Political science and nonviolent resistance research"
# -- LLM Provider --llm: provider: "openai" model: "gpt-4o" temperature: 0.0 max_tokens: 2048
# -- API Keys (can also use environment variables) --# Keys are stored in .env, not here. Env vars take precedence.api_keys: openai: "" anthropic: "" gemini: ""
# -- Embeddings --embeddings: provider: "local" # local (free) | openai openai_model: "text-embedding-3-small"
# -- Retrieval --retrieval: chunk_size: 1000 chunk_overlap: 100 top_k: 5
# -- Web Search --web_search: enabled: true backend: "semantic_scholar" max_results: 5
# -- Anti-Hallucination --verification: enabled: true max_iterations: 3 strict_mode: true
# -- Paths --paths: knowledge_base: "knowledge_base" vector_db: "chroma_db"```
API keys are written to `.env` (gitignored), not config.yaml.
## 10. CLI Interface
Rich-powered terminal chatbot.
**Commands:**- `/quit` β exit- `/sources` β show sources from last response- `/ingest` β re-index knowledge_base/- `/model` β show current model, switch provider/model- `/websearch on|off` β toggle web search- `/help` β show help
## 11. Web UI (Streamlit)
### Layout
- **Header:** chatbot name- **Sidebar:** provider dropdown, model dropdown (updates on provider change), web search toggle, knowledge base stats (files, chunks, last ingestion), re-ingest button- **Chat area:** message history with markdown rendering- **Footer:** persistent banner: "All answers sourced from local knowledge base. Web sources are supplementary only."
### Behaviors
- Chat history maintained in session (not persisted across refreshes)- During verification loop, spinner: "Verifying answer against sources..."- Model/provider switch is session-only (does not overwrite config.yaml)
## 12. Dependencies
```# Corechromadb>=0.4.0PyPDF2>=3.0.0python-docx>=1.0.0openpyxl>=3.0.0xlrd>=2.0.0pyreadstat>=1.2.0pyreadr>=0.5.0requests>=2.28.0rich>=13.0.0pyyaml>=6.0python-dotenv>=1.0.0
# LLM providersopenai>=1.0.0anthropic>=0.20.0google-generativeai>=0.5.0
# Web UIstreamlit>=1.30.0```
## 13. Docker (Optional)
`Dockerfile` and `docker-compose.yml` provided for users who prefer containerized setup. Not the primary installation path.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# Query Understanding Layer β Design Document
**Date:** 2026-03-05**Author:** Jie Lian (with Claude)**Status:** Approved & Implemented
## 1. Problem
Short, vague, or ambiguous user queries produce poor retrieval results. Examples:
| User Query | Problem | What Retrieval Needs ||---|---|---|| "China in 2024?" | Too short, embedding doesn't match long document chunks | "China human rights situation developments 2024" || "what about 2023?" | Missing context from prior conversation | "China human rights 2023" (from conversation history) || "AI stuff" | Vague | Clarification: "Are you asking about AI surveillance, AI in governance, or AI and civil resistance?" || "How did they respond?" | Pronouns unresolved | Needs prior context to resolve "they" |
The current pipeline passes the raw user query directly to ChromaDB embedding search. Short/vague queries produce weak embeddings that miss relevant chunks even when the knowledge base has the answer.
## 2. Solution: Query Understanding Layer
Add a pre-retrieval step that uses the LLM to:
1. **Reformulate** β Rewrite the query into a search-optimized form (expanded, keyword-rich, domain-aware)2. **Clarify** β When the query is genuinely ambiguous, ask the user a targeted question before searching
### Pipeline Change
```BEFORE:User query β retrieve(query) β verify_and_respond(query, results) β Display
AFTER:User query β understand_query(query, history, cfg) β [if CLARIFY: ask user, get answer, call understand_query again] β [if SEARCH: use reformulated query for retrieval] β retrieve(reformulated_query) β verify_and_respond(original_query, results) β Display```
**Key principle:** The reformulated query is used ONLY for retrieval (embedding search). The original user query is still passed to `verify_and_respond()` for response generation, so the LLM answers what the user actually asked.
## 3. New Module: `src/query_engine.py`
### 3.1 Function Signature
```pythondef understand_query( user_query: str, cfg: dict, conversation_history: list[dict] | None = None,) -> dict: """ Analyze and reformulate a user query for better retrieval.
Args: user_query: Raw user input. cfg: App config (provides domain, LLM settings). conversation_history: List of {"role": "user"|"assistant", "content": "..."} from the current session. Used to resolve pronouns/references.
Returns: { "action": "search" | "clarify", "search_query": "reformulated query for embedding search", "original_query": "user's original text", "clarification_question": "..." (only if action == "clarify"), } """```
### 3.2 LLM Prompt
```You are a query reformulation assistant for a {domain} research chatbot.
Your job is to analyze the user's question and decide:1. SEARCH β if the question is clear enough, rewrite it as an optimized search query2. CLARIFY β if the question is genuinely ambiguous, ask ONE clarification question
RULES for SEARCH:- Expand abbreviations and acronyms (e.g., "HR" β "human rights")- Resolve pronouns using conversation history (e.g., "they" β the entity from prior turn)- Add relevant domain-specific keywords that would match document content- Keep the reformulated query concise (15-40 words)- Preserve the user's original intent β do NOT change what they're asking about- If the query is already clear and specific, return it with minimal changes
RULES for CLARIFY:- ONLY ask for clarification when the question is genuinely ambiguous (could mean 2+ clearly different things)- Ask ONE specific, short question- Provide 2-3 options when possible- Do NOT ask for clarification on clear questions β even if they are broad- A broad question is NOT the same as an ambiguous question
CONVERSATION HISTORY:{history}
USER'S QUESTION: {query}
Respond in JSON:{ "action": "search" or "clarify", "search_query": "reformulated search query" (only if action is "search"), "clarification_question": "question to ask" (only if action is "clarify"), "reasoning": "one sentence explaining your choice"}```
### 3.3 Clarification Threshold
The LLM should have a HIGH bar for asking clarification. Most queries should be reformulated directly, not clarified. Clarification is only for genuinely ambiguous cases. Examples:
| Query | Action | Why ||---|---|---|| "China" | SEARCH β "China human rights developments" | Broad but not ambiguous β search and let the user refine || "AI" | CLARIFY β "Are you asking about AI surveillance technology, AI in governance, or AI and civil resistance?" | Genuinely ambiguous in a domain that covers all of these || "what about 2023?" | SEARCH β "China human rights 2023" (from history) | Pronoun resolved from conversation context || "How effective is NVR?" | SEARCH β "effectiveness nonviolent resistance campaigns success rate" | Abbreviation expanded, terms added |
### 3.4 Conversation History
The query engine receives the last N turns of conversation (default: last 3 user-assistant pairs = 6 messages). This lets it resolve:
- Pronouns: "they", "it", "that"- Follow-ups: "what about 2023?", "and in Asia?"- Refinements: "more detail on the third point"
The history is passed as text in the prompt, NOT as separate LLM conversation turns (cheaper, simpler).
## 4. Integration Points
### 4.1 CLI (`app_cli.py`)
```python# In the main loop, before retrieve():from src.query_engine import understand_query
# Build conversation history from statehistory = state.get("conversation_history", [])
# Query understandingqu_result = understand_query(user_input, effective_cfg, history)
if qu_result["action"] == "clarify": # Show clarification question console.print(f"\n[bold yellow]Clarification needed:[/bold yellow] {qu_result['clarification_question']}") try: clarification = input("You> ").strip() except (EOFError, KeyboardInterrupt): continue if not clarification: continue # Re-run with clarification appended combined = f"{user_input} β {clarification}" qu_result = understand_query(combined, effective_cfg, history)
# Use reformulated query for retrieval, original for responsesearch_query = qu_result["search_query"]original_query = qu_result["original_query"]
retrieval_result = retrieve(search_query, effective_cfg)result = verify_and_respond(original_query, retrieval_result, effective_cfg)
# Update conversation historyhistory.append({"role": "user", "content": user_input})history.append({"role": "assistant", "content": result["response"]})# Keep last 6 messages (3 turns)state["conversation_history"] = history[-6:]```
### 4.2 Web UI (`app_web.py`)
```python# In render_chat(), before retrieve():from src.query_engine import understand_query
history = [ {"role": m["role"], "content": m["content"]} for m in st.session_state.messages[-6:]]
qu_result = understand_query(prompt, cfg, history)
if qu_result["action"] == "clarify": # Show clarification as assistant message st.session_state.messages.append({ "role": "assistant", "content": f"**Before I search, could you clarify?** {qu_result['clarification_question']}" }) st.rerun() return # Wait for user's next input as clarification
# Use reformulated query for retrievalretrieval_result = retrieve(qu_result["search_query"], cfg)result = verify_and_respond(prompt, retrieval_result, cfg)```
### 4.3 Status Display
Show the reformulated query to the user so they understand what was searched:
**CLI:**```[dim]Searching for: "China human rights situation developments 2024"[/dim]```
**Web UI:**```Status: Searching for "China human rights situation developments 2024"...```
This is important for transparency β the user should know how their query was interpreted.
## 5. Config
New section in `config.yaml`:
```yamlquery_understanding: enabled: true # set to false to skip reformulation (use raw query) max_history: 6 # number of recent messages to include as context max_clarifications: 1 # max clarification rounds before forcing a search```
Default: enabled. Can be disabled for users who want raw pass-through behavior.
### Setup Wizard Addition
No new wizard step needed β `query_understanding` defaults to enabled. Advanced users can disable in `config.yaml`.
The setup wizard's `generate_config()` adds:
```python"query_understanding": { "enabled": True, "max_history": 6, "max_clarifications": 1,},```
## 6. Cost Analysis
| Component | LLM Calls Before | LLM Calls After ||---|---|---|| Query understanding | 0 | 1 (small, ~100 tokens out) || Response generation | 1 | 1 (unchanged) || Verification | 1-3 | 1-3 (unchanged) || Clarification | 0 | 0-1 (only when ambiguous) || **Total** | **2-4** | **3-5** |
The query understanding call is cheap: short prompt, short response (~100 tokens). The improved retrieval quality is worth the extra call.
## 7. Anti-Hallucination Impact
**No weakening.** The query understanding layer operates BEFORE retrieval and does NOT affect the 6-layer verification stack:
- Layer 0 (no-source gate): Still works β if reformulated query finds nothing, LLM is never called- Layer 1-5: Unchanged β the response is still verified against retrieved sources- The original query is preserved for response generation β the LLM answers what the user actually asked, not a reformulated version
## 8. Edge Cases
| Case | Handling ||---|---|| Query understanding disabled | Skip entirely, use raw query (current behavior) || LLM call fails | Fall back to raw query, log warning || Clarification on first message (no history) | Works fine β history is empty || User skips clarification (empty input) | Skip, use raw query || Very long query (paragraph) | Still reformulate β LLM extracts the core question || Multi-part question | LLM reformulates the primary question; may suggest focusing |
## 9. Files to Create/Modify
| File | Action | Description ||---|---|---|| `src/query_engine.py` | **CREATE** | Query understanding module || `src/prompts.py` | **MODIFY** | Add `QUERY_UNDERSTANDING_PROMPT_TEMPLATE` and `build_query_understanding_prompt()` || `app_cli.py` | **MODIFY** | Add query understanding step + conversation history + clarification flow || `app_web.py` | **MODIFY** | Add query understanding step + clarification flow || `setup.py` | **MODIFY** | Add `query_understanding` config defaults || `tests/test_query_engine.py` | **CREATE** | Tests for query engine || `tests/test_prompts.py` | **MODIFY** | Test for new prompt template |
## 10. Test Plan
1. `test_understand_query_reformulates` β Clear query returns action="search" with reformulated query2. `test_understand_query_clarifies` β Ambiguous query returns action="clarify"3. `test_understand_query_preserves_original` β Original query always in result4. `test_understand_query_with_history` β Pronoun resolution using conversation history5. `test_understand_query_disabled` β When disabled, returns raw query passthrough6. `test_understand_query_fallback_on_error` β LLM failure falls back to raw query7. `test_build_query_understanding_prompt` β Prompt template includes domain and history.gitignore+2
CLAUDE.mdDeleted-153
docs/WORKLOG.mdDeleted-332
docs/plans/2026-03-04-rag-research-chatbot-design.mdDeleted-594
docs/plans/2026-03-04-rag-research-chatbot-implementation.mdDeleted
docs/plans/2026-03-05-query-understanding-design.mdDeleted-293