Spaces:
Sleeping
Sleeping
Commit Β·
83087ed
1
Parent(s): fc60784
fix: use .get() for all config access + add CLAUDE.md and docs to repo
Browse files- src/ingest.py: replace cfg["paths"]["vector_db"] and
cfg["paths"]["knowledge_base"] with .get() + defaults
- src/llm/__init__.py: replace cfg["llm"]["provider"] and
cfg["llm"].get(...) with safe llm_cfg = cfg.get("llm", {})
- src/search/__init__.py: replace r['authors'], r['title'], etc.
with .get() + defaults in web results formatter
- app_web.py: respect max_clarifications config (was hardcoded to
allow 1 round regardless of config)
- tests/test_setup.py: add missing assertions for retrieval.top_k
and retrieval.max_distance
- Add CLAUDE.md, docs/plans/, docs/WORKLOG.md to the repository
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- CLAUDE.md +147 -0
- app_web.py +2 -1
- docs/WORKLOG.md +326 -0
- docs/plans/2026-03-04-rag-research-chatbot-design.md +594 -0
- docs/plans/2026-03-04-rag-research-chatbot-implementation.md +0 -0
- docs/plans/2026-03-05-query-understanding-design.md +293 -0
- src/ingest.py +2 -2
- src/llm/__init__.py +5 -4
- src/search/__init__.py +3 -3
- tests/test_setup.py +2 -0
CLAUDE.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md β Project Instructions for Claude Code
|
| 2 |
+
|
| 3 |
+
## Project Overview
|
| 4 |
+
|
| 5 |
+
**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.
|
| 6 |
+
|
| 7 |
+
## Architecture
|
| 8 |
+
|
| 9 |
+
- **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.
|
| 10 |
+
- **RAG pipeline**: ingest β chunk β embed (ChromaDB) β **query understanding** β retrieve β generate β verify (6-layer stack)
|
| 11 |
+
- **Config**: `config.yaml` (generated by `setup.py` wizard) + `.env` (API keys, gitignored). Env vars override config values.
|
| 12 |
+
|
| 13 |
+
## Key Design Decisions
|
| 14 |
+
|
| 15 |
+
### Query Understanding Layer
|
| 16 |
+
|
| 17 |
+
Pre-retrieval step that uses the LLM to improve retrieval quality:
|
| 18 |
+
|
| 19 |
+
- **Reformulation**: Rewrites user queries into search-optimized forms (expand abbreviations, add domain keywords, resolve pronouns from conversation history)
|
| 20 |
+
- **Clarification**: When a query is genuinely ambiguous (high bar), asks the user ONE clarification question before searching
|
| 21 |
+
- **Conversation history**: Uses last N messages (default 6) to resolve follow-up references like "what about 2023?" or "they"
|
| 22 |
+
- **Transparency**: Shows the reformulated query to the user (`Searching for: "..."`)
|
| 23 |
+
- **Key principle**: Reformulated query is used ONLY for retrieval. The original query is preserved for response generation
|
| 24 |
+
- **Graceful degradation**: Falls back to raw query if LLM call fails. Can be disabled via `query_understanding.enabled: false`
|
| 25 |
+
- **No anti-hallucination impact**: Operates before retrieval; the 6-layer stack is unchanged
|
| 26 |
+
|
| 27 |
+
### Anti-Hallucination is Priority #1
|
| 28 |
+
|
| 29 |
+
The 6-layer verification stack is the core differentiator. Never weaken these guardrails:
|
| 30 |
+
|
| 31 |
+
- **Layer 0**: No-source early exit β LLM is NEVER called if retrieval returns zero results
|
| 32 |
+
- **Layer 1**: System prompt with zero-tolerance hallucination rules
|
| 33 |
+
- **Layer 2**: Soft max-token cap proportional to context size
|
| 34 |
+
- **Layer 3**: LLM self-verification with iterative correction loop (max 3 iterations)
|
| 35 |
+
- **Layer 4**: Term-overlap semantic similarity check (advisory flags)
|
| 36 |
+
- **Layer 5**: Warning-phrase scanner (advisory flags)
|
| 37 |
+
|
| 38 |
+
### Over-Refusal Prevention
|
| 39 |
+
|
| 40 |
+
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.
|
| 41 |
+
|
| 42 |
+
### Citation Format
|
| 43 |
+
|
| 44 |
+
- Every factual claim must have a numbered endnote like `[1]`, `[2]`, etc.
|
| 45 |
+
- Do NOT use `[N]` as a placeholder β always use actual numbers
|
| 46 |
+
- Direct quotes (3+ consecutive words from source) must be in quotation marks
|
| 47 |
+
- Every response ends with a **References** section split into **Local Sources (Primary)** and **Web Sources (Supplementary)**
|
| 48 |
+
- References must show actual file names/paths/page numbers β NOT chunk IDs (CHUNK-LOCAL-001)
|
| 49 |
+
- Local knowledge base ALWAYS takes priority over web sources
|
| 50 |
+
|
| 51 |
+
### Chunk ID Anchoring
|
| 52 |
+
|
| 53 |
+
- Local chunks: `[CHUNK-LOCAL-NNN]`
|
| 54 |
+
- Web chunks: `[CHUNK-WEB-NNN]`
|
| 55 |
+
- These IDs appear in the context block for internal anchoring only β they must NOT appear in user-facing references
|
| 56 |
+
|
| 57 |
+
### Retrieval Strategy
|
| 58 |
+
|
| 59 |
+
- Uses **distance-threshold retrieval** instead of fixed top_k
|
| 60 |
+
- Queries up to `top_k` (default 50) candidates from ChromaDB
|
| 61 |
+
- Keeps only chunks with cosine distance below `max_distance` (default 0.55)
|
| 62 |
+
- Broad queries get more chunks; narrow queries get fewer β all based on relevance
|
| 63 |
+
|
| 64 |
+
## Project Structure
|
| 65 |
+
|
| 66 |
+
```
|
| 67 |
+
βββ setup.py # Setup wizard β generates config.yaml + .env
|
| 68 |
+
βββ ingest.py # Entry point: python ingest.py
|
| 69 |
+
βββ app_cli.py # CLI interface (Rich)
|
| 70 |
+
βββ app_web.py # Web UI (Streamlit)
|
| 71 |
+
βββ config.yaml # Generated by wizard (gitignored pattern optional)
|
| 72 |
+
βββ .env # API keys (gitignored)
|
| 73 |
+
βββ requirements.txt
|
| 74 |
+
βββ knowledge_base/ # User drops documents here
|
| 75 |
+
βββ chroma_db/ # Vector DB (auto-generated, gitignored)
|
| 76 |
+
βββ src/
|
| 77 |
+
β βββ config_loader.py # Loads config.yaml + .env
|
| 78 |
+
β βββ query_engine.py # Query understanding: reformulation + clarification
|
| 79 |
+
β βββ ingest.py # Ingestion pipeline + ChromaDB
|
| 80 |
+
β βββ retriever.py # Dual retriever (local + web) with distance threshold
|
| 81 |
+
β βββ prompts.py # System, verification, and query understanding prompts
|
| 82 |
+
β βββ verifier.py # 6-layer anti-hallucination stack
|
| 83 |
+
β βββ llm/ # Provider registry (openai, anthropic, gemini)
|
| 84 |
+
β βββ search/ # Search backend registry (semantic_scholar, none)
|
| 85 |
+
β βββ readers/ # File reader registry (15 extensions)
|
| 86 |
+
βββ tests/ # pytest test suite (59 tests)
|
| 87 |
+
βββ docs/plans/ # Design doc + implementation plan
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
## Config Field Names (IMPORTANT)
|
| 91 |
+
|
| 92 |
+
The `config.yaml` must use these exact field names β the codebase reads them with `.get()`:
|
| 93 |
+
|
| 94 |
+
| Section | Key | Used By |
|
| 95 |
+
|---|---|---|
|
| 96 |
+
| `paths.vector_db` | `src/ingest.py` | NOT `vector_store` |
|
| 97 |
+
| `web_search.backend` | `src/retriever.py` | NOT `provider` |
|
| 98 |
+
| `verification.max_iterations` | `src/verifier.py` | NOT `layers` |
|
| 99 |
+
| `verification.strict_mode` | `src/verifier.py` | boolean |
|
| 100 |
+
| `retrieval.chunk_size` | `src/ingest.py` | default 1000 |
|
| 101 |
+
| `retrieval.chunk_overlap` | `src/ingest.py` | default 100 |
|
| 102 |
+
| `retrieval.top_k` | `src/retriever.py` | default 50 (candidate pool cap) |
|
| 103 |
+
| `retrieval.max_distance` | `src/retriever.py` | default 0.55 (relevance threshold) |
|
| 104 |
+
| `embeddings.provider` | `src/ingest.py` | `"local"` or `"openai"` |
|
| 105 |
+
| `query_understanding.enabled` | `src/query_engine.py` | default true |
|
| 106 |
+
| `query_understanding.max_history` | `src/query_engine.py` | default 6 |
|
| 107 |
+
| `query_understanding.max_clarifications` | `app_cli.py`, `app_web.py` | default 1 |
|
| 108 |
+
|
| 109 |
+
## Commands
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
python setup.py # Interactive setup wizard
|
| 113 |
+
python ingest.py # Ingest documents from knowledge_base/
|
| 114 |
+
python app_cli.py # Run CLI chatbot
|
| 115 |
+
streamlit run app_web.py # Run web UI
|
| 116 |
+
python -m pytest tests/ # Run test suite
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
## Testing
|
| 120 |
+
|
| 121 |
+
- 59 tests across 13 test files
|
| 122 |
+
- All tests should pass: `python -m pytest tests/ -v`
|
| 123 |
+
- Known warning: PyPDF2 deprecation (cosmetic, not a bug)
|
| 124 |
+
|
| 125 |
+
## Code Style
|
| 126 |
+
|
| 127 |
+
- Python 3.11β3.13 (Python 3.14+ not supported due to ChromaDB/Pydantic compatibility)
|
| 128 |
+
- Type hints on public APIs
|
| 129 |
+
- No unnecessary abstractions β registry dicts over class hierarchies
|
| 130 |
+
- `.get()` with defaults for all config access (graceful degradation)
|
| 131 |
+
- Tests use `tmp_path` fixture and `pytest.importorskip` for optional deps
|
| 132 |
+
|
| 133 |
+
## Git
|
| 134 |
+
|
| 135 |
+
- **Repo**: `https://github.com/LIANJie-Jason/chatbotsample_api` (private)
|
| 136 |
+
- **Branch**: `master`
|
| 137 |
+
- Commit style: `feat:`, `fix:`, `refactor:`, `test:`, `docs:`, `style:`
|
| 138 |
+
|
| 139 |
+
## Do NOT
|
| 140 |
+
|
| 141 |
+
- Weaken anti-hallucination guardrails without explicit user approval
|
| 142 |
+
- Remove citation requirements from prompts
|
| 143 |
+
- Allow the LLM to be called when no sources are retrieved (Layer 0)
|
| 144 |
+
- Use `[N]` as a placeholder in prompts β the LLM copies it literally
|
| 145 |
+
- Show chunk IDs (CHUNK-LOCAL-001) in user-facing references
|
| 146 |
+
- Change config field names without updating ALL consumers + setup wizard + tests
|
| 147 |
+
- Commit `.env` files or API keys
|
app_web.py
CHANGED
|
@@ -154,6 +154,7 @@ def render_chat():
|
|
| 154 |
|
| 155 |
search_query = combined
|
| 156 |
response_query = combined # query passed to verify_and_respond
|
|
|
|
| 157 |
|
| 158 |
if qu_enabled:
|
| 159 |
# Exclude the just-appended user message to avoid sending
|
|
@@ -168,7 +169,7 @@ def render_chat():
|
|
| 168 |
except Exception:
|
| 169 |
qu_result = {"action": "search", "search_query": combined, "original_query": combined}
|
| 170 |
|
| 171 |
-
if qu_result["action"] == "clarify" and pending is None:
|
| 172 |
# Ask clarification β store original query, show question
|
| 173 |
st.session_state.pending_clarification = original_query
|
| 174 |
clarification_msg = f"**Before I search, could you clarify?** {qu_result['clarification_question']}"
|
|
|
|
| 154 |
|
| 155 |
search_query = combined
|
| 156 |
response_query = combined # query passed to verify_and_respond
|
| 157 |
+
max_clarifications = qu_cfg.get("max_clarifications", 1)
|
| 158 |
|
| 159 |
if qu_enabled:
|
| 160 |
# Exclude the just-appended user message to avoid sending
|
|
|
|
| 169 |
except Exception:
|
| 170 |
qu_result = {"action": "search", "search_query": combined, "original_query": combined}
|
| 171 |
|
| 172 |
+
if qu_result["action"] == "clarify" and pending is None and max_clarifications > 0:
|
| 173 |
# Ask clarification β store original query, show question
|
| 174 |
st.session_state.pending_clarification = original_query
|
| 175 |
clarification_msg = f"**Before I search, could you clarify?** {qu_result['clarification_question']}"
|
docs/WORKLOG.md
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Work Log β RAG Research Chatbot Template
|
| 2 |
+
|
| 3 |
+
## 2026-03-04 β Initial Design & Implementation
|
| 4 |
+
|
| 5 |
+
### Design Phase
|
| 6 |
+
|
| 7 |
+
- Brainstormed architecture with user (registry pattern, 6-layer anti-hallucination stack)
|
| 8 |
+
- Key decisions made:
|
| 9 |
+
- Target audience: academics (primary) + general users
|
| 10 |
+
- Interfaces: CLI (Rich) + Web UI (Streamlit)
|
| 11 |
+
- LLM providers: OpenAI, Anthropic, Google Gemini with live model fetching
|
| 12 |
+
- Web search: pluggable (Semantic Scholar default, swappable/disable)
|
| 13 |
+
- Anti-hallucination: #1 priority β 6-layer verification stack
|
| 14 |
+
- Config: interactive setup wizard β `config.yaml` + `.env`
|
| 15 |
+
- Embeddings: free local default (ChromaDB), OpenAI upgrade option
|
| 16 |
+
- File formats: 15 extensions (PDF, DOCX, XLSX, XLS, CSV, TAB, TSV, DTA, SAV, RDS, RDA, TXT, MD, JSON, DO)
|
| 17 |
+
- Design doc saved: `docs/plans/2026-03-04-rag-research-chatbot-design.md`
|
| 18 |
+
- Implementation plan saved: `docs/plans/2026-03-04-rag-research-chatbot-implementation.md`
|
| 19 |
+
|
| 20 |
+
### Implementation Phase (Subagent-Driven Development)
|
| 21 |
+
|
| 22 |
+
15 tasks implemented with TDD, dispatched as parallel subagents where independent:
|
| 23 |
+
|
| 24 |
+
1. **Scaffold** β project structure, requirements.txt, .gitignore (`415e4e8`)
|
| 25 |
+
2. **File readers** β PDF + text readers with registry (`c1d9ad3`)
|
| 26 |
+
3. **Config loader** β YAML + .env loading (`94515d4`)
|
| 27 |
+
4. **DOCX/Excel/CSV readers** β Word, Excel (xlsx+xls), CSV/TSV readers (`7cdd0f2`)
|
| 28 |
+
5. **LLM providers** β OpenAI, Anthropic, Gemini with fallback models (`3aabf2e`)
|
| 29 |
+
6. **Ingestion pipeline** β recursive chunking, ChromaDB storage (`d8edd70`)
|
| 30 |
+
7. **Search backends** β Semantic Scholar with retry logic (`e3d44b5`)
|
| 31 |
+
8. **Stat readers** β Stata, SPSS, R data readers (`d8b70fa`)
|
| 32 |
+
9. **Prompts** β system prompt + verification prompt templates (`8a653d8`)
|
| 33 |
+
10. **Retriever** β dual retrieval with local priority, chunk ID anchoring (`d641d21`)
|
| 34 |
+
11. **Verifier** β 6-layer anti-hallucination stack (`1719478`)
|
| 35 |
+
12. **CLI app** β Rich-powered terminal chatbot with slash commands (`a5f1274`)
|
| 36 |
+
13. **Setup wizard** β interactive 5-step flow with model fetching (`24c097e`)
|
| 37 |
+
14. **Web UI** β Streamlit with sidebar controls and chat interface (`e3ae940`)
|
| 38 |
+
15. **Docker + docs** β Dockerfile, docker-compose, README, LICENSE (`af76fb1`)
|
| 39 |
+
|
| 40 |
+
**Test suite**: 49 tests across 12 test files β all passing.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
## 2026-03-05 β Full Code Audit & Bug Fixes
|
| 45 |
+
|
| 46 |
+
### Audit
|
| 47 |
+
|
| 48 |
+
Performed line-by-line review of all source files against the design document.
|
| 49 |
+
|
| 50 |
+
### Bugs Found & Fixed
|
| 51 |
+
|
| 52 |
+
**CRITICAL β `setup.py:generate_config()` wrong config field names**
|
| 53 |
+
|
| 54 |
+
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"]`.
|
| 55 |
+
|
| 56 |
+
| Generated (wrong) | Expected (correct) | Impact |
|
| 57 |
+
|---|---|---|
|
| 58 |
+
| `paths.vector_store` | `paths.vector_db` | KeyError crash |
|
| 59 |
+
| `web_search.provider` | `web_search.backend` | Silent fallback |
|
| 60 |
+
| `verification.layers: [list]` | `verification.max_iterations` + `strict_mode` | Silent fallback |
|
| 61 |
+
| `embeddings.model` only | `embeddings.provider` + `openai_model` | Silent fallback |
|
| 62 |
+
| Missing `retrieval.chunk_size` | needed (default 1000) | Silent fallback |
|
| 63 |
+
| Missing `retrieval.chunk_overlap` | needed (default 100) | Silent fallback |
|
| 64 |
+
|
| 65 |
+
**BUG β `setup.py:165` wrong run command**
|
| 66 |
+
- Said `python -m src.cli` β fixed to `python app_cli.py`
|
| 67 |
+
|
| 68 |
+
**BUG β `app_cli.py:207` dead code**
|
| 69 |
+
- Removed `if False` ternary from input prompt
|
| 70 |
+
|
| 71 |
+
**TEST β `tests/test_setup.py` strengthened**
|
| 72 |
+
- Added assertions for all config field names to prevent this class of bug from recurring
|
| 73 |
+
|
| 74 |
+
### Verified Correct (no issues)
|
| 75 |
+
|
| 76 |
+
- `src/config_loader.py`, `src/readers/` (all 8 modules + registry)
|
| 77 |
+
- `src/llm/` (registry + 3 providers), `src/search/` (registry + Semantic Scholar)
|
| 78 |
+
- `src/ingest.py`, `src/retriever.py`, `src/prompts.py`, `src/verifier.py`
|
| 79 |
+
- `app_cli.py`, `app_web.py`, `ingest.py` (root entry point)
|
| 80 |
+
- `Dockerfile`, `docker-compose.yml`, `.gitignore`, `README.md`, `LICENSE`
|
| 81 |
+
- All 12 test files (49 tests pass, 1 PyPDF2 deprecation warning)
|
| 82 |
+
|
| 83 |
+
### Added
|
| 84 |
+
|
| 85 |
+
- `CLAUDE.md` β project instructions for Claude Code
|
| 86 |
+
- `docs/WORKLOG.md` β this working log
|
| 87 |
+
|
| 88 |
+
---
|
| 89 |
+
|
| 90 |
+
## 2026-03-05 β Second Full Re-Audit
|
| 91 |
+
|
| 92 |
+
### Scope
|
| 93 |
+
|
| 94 |
+
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`).
|
| 95 |
+
|
| 96 |
+
### Verified Correct
|
| 97 |
+
|
| 98 |
+
All 6 anti-hallucination layers verified in correct execution order:
|
| 99 |
+
- **Layer 0**: No-source refusal (pre-LLM gate) β `verifier.py:213-219`
|
| 100 |
+
- **Layer 1**: System prompt guardrails β `prompts.py:8-60`
|
| 101 |
+
- **Layer 2**: Soft max-token cap β `verifier.py:47-65`
|
| 102 |
+
- **Layer 3**: LLM self-verification with iterative correction β `verifier.py:250-336`
|
| 103 |
+
- **Layer 4**: Term-overlap similarity check β `verifier.py:100-148`
|
| 104 |
+
- **Layer 5**: Warning-phrase scanner (8 phrases) β `verifier.py:24-33`
|
| 105 |
+
|
| 106 |
+
All config field names verified consistent across every `.get()` call in the codebase.
|
| 107 |
+
All 4 retrieval scenarios (local+web, local-only, web-only, no-sources) verified.
|
| 108 |
+
Chunk ID anchoring (`[CHUNK-LOCAL-NNN]`, `[CHUNK-WEB-NNN]`) verified.
|
| 109 |
+
Citation format (endnotes, direct quotes, References section) verified in system prompt.
|
| 110 |
+
All 15 file format readers verified present and functional.
|
| 111 |
+
Registry pattern verified in `src/llm/`, `src/search/`, `src/readers/`.
|
| 112 |
+
Setup wizard generates correct config field names (verified by contract test in `tests/test_setup.py`).
|
| 113 |
+
|
| 114 |
+
### Bug Found & Fixed
|
| 115 |
+
|
| 116 |
+
**BUG β `src/search/semantic_scholar.py:38` β `None` authors crash**
|
| 117 |
+
|
| 118 |
+
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`.
|
| 119 |
+
|
| 120 |
+
- Line 37 already handled this correctly: `(paper.get("authors") or [])[:3]`
|
| 121 |
+
- Line 38 did NOT: `len(paper.get("authors", []))` β crashes on `None`
|
| 122 |
+
- **Fix**: Changed to `len(paper.get("authors") or [])` β consistent with line 37
|
| 123 |
+
|
| 124 |
+
### Test Suite
|
| 125 |
+
|
| 126 |
+
49 tests, all passing after fix.
|
| 127 |
+
|
| 128 |
+
---
|
| 129 |
+
|
| 130 |
+
## 2026-03-05 β GitHub Repo & README Rewrite
|
| 131 |
+
|
| 132 |
+
- Created private GitHub repo: `LIANJie-Jason/chatbotsample_api`
|
| 133 |
+
- Rewrote README as a detailed usage guide for social scientists without coding backgrounds
|
| 134 |
+
- 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
|
| 135 |
+
- Multiple rounds of README corrections (example output accuracy, clone URL, folder names)
|
| 136 |
+
- Added Python 3.11β3.13 environment setup instructions after discovering Python 3.14 incompatibility with ChromaDB/Pydantic
|
| 137 |
+
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
## 2026-03-05 β Third Full Audit & Live Testing Fixes
|
| 141 |
+
|
| 142 |
+
### Third Audit
|
| 143 |
+
|
| 144 |
+
Complete re-read of all source files, design doc, and README. All 49 tests pass.
|
| 145 |
+
|
| 146 |
+
**README fix**: Prerequisites said "Python 3.11 or later" β corrected to "Python 3.11β3.13" (Python 3.14+ not supported).
|
| 147 |
+
|
| 148 |
+
### Live Testing β Issues Found & Fixed
|
| 149 |
+
|
| 150 |
+
User tested the chatbot with real Amnesty International PDFs and CSV data. Several issues discovered:
|
| 151 |
+
|
| 152 |
+
**FIX β Over-refusal when relevant sources exist** (`src/prompts.py`)
|
| 153 |
+
|
| 154 |
+
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.
|
| 155 |
+
|
| 156 |
+
- Added: "If the context contains relevant information, you MUST provide what you can, even if the answer is incomplete."
|
| 157 |
+
- Added: "An incomplete answer grounded in sources is ALWAYS better than a refusal."
|
| 158 |
+
- Changed refusal to: "ONLY refuse if the context contains NO relevant information at all."
|
| 159 |
+
- This matches the design doc's principle: "An incomplete answer is always better than a fabricated one."
|
| 160 |
+
|
| 161 |
+
**FIX β References showed chunk IDs instead of file paths** (`src/prompts.py`)
|
| 162 |
+
|
| 163 |
+
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.
|
| 164 |
+
|
| 165 |
+
- Added explicit instruction: "Do NOT use chunk IDs (CHUNK-LOCAL-001, CHUNK-WEB-001, etc.) in the reference list."
|
| 166 |
+
- Added: "Extract the ACTUAL file name, path, and page number from the From: and Path: lines in the context."
|
| 167 |
+
- Added concrete examples of correct local and web reference formatting.
|
| 168 |
+
|
| 169 |
+
**FIX β LLM output literal `[N]` alongside real citation numbers** (`src/prompts.py`)
|
| 170 |
+
|
| 171 |
+
The citation rules used `[N]` as a placeholder example. The LLM copied it literally, producing `[N][1]`.
|
| 172 |
+
|
| 173 |
+
- Replaced `[N]` with plain English: "numbered endnote like [1], [2], etc."
|
| 174 |
+
- Added: "Do NOT output the literal text [N] β always use actual numbers."
|
| 175 |
+
- Also fixed the last `[N]` in the verification prompt template (9-point checklist item 1).
|
| 176 |
+
|
| 177 |
+
**FIX β Retrieval missed relevant chunks with fixed top_k** (`src/retriever.py`)
|
| 178 |
+
|
| 179 |
+
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.
|
| 180 |
+
|
| 181 |
+
- Replaced fixed top_k retrieval with **distance-threshold retrieval**.
|
| 182 |
+
- Now queries up to 50 candidates from ChromaDB, then filters to keep only chunks with cosine distance below `max_distance` (default 0.55).
|
| 183 |
+
- Broad queries with lots of relevant content get many chunks; narrow queries get fewer.
|
| 184 |
+
- New config fields: `retrieval.top_k` (candidate pool cap, default 50), `retrieval.max_distance` (relevance threshold, default 0.55).
|
| 185 |
+
|
| 186 |
+
**FEAT β Personal welcome message with web search status** (`app_cli.py`)
|
| 187 |
+
|
| 188 |
+
- Added chatbot self-introduction: "Hi! I'm your research assistant on {domain}..."
|
| 189 |
+
- Shows web search status (ON in green / OFF in red) with toggle instructions.
|
| 190 |
+
|
| 191 |
+
**STYLE β Hidden distance scores from `/sources` output** (`app_cli.py`)
|
| 192 |
+
|
| 193 |
+
- Removed `(distance: 0.539)` from `/sources` β internal metric not useful for end users.
|
| 194 |
+
|
| 195 |
+
### Updated Files
|
| 196 |
+
|
| 197 |
+
| File | Changes |
|
| 198 |
+
|---|---|
|
| 199 |
+
| `src/prompts.py` | Over-refusal fix, reference format fix, `[N]` removal |
|
| 200 |
+
| `src/retriever.py` | Distance-threshold retrieval |
|
| 201 |
+
| `app_cli.py` | Welcome message, web search status, hide distance scores |
|
| 202 |
+
| `setup.py` | New config defaults (top_k=50, max_distance=0.55) |
|
| 203 |
+
| `README.md` | Python version fix, config reference updated |
|
| 204 |
+
| `tests/test_prompts.py` | Updated assertions for new prompt wording |
|
| 205 |
+
|
| 206 |
+
### Test Suite
|
| 207 |
+
|
| 208 |
+
49 tests, all passing after all fixes.
|
| 209 |
+
|
| 210 |
+
---
|
| 211 |
+
|
| 212 |
+
## 2026-03-05 β Query Understanding Layer
|
| 213 |
+
|
| 214 |
+
### Design
|
| 215 |
+
|
| 216 |
+
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`.
|
| 217 |
+
|
| 218 |
+
**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.
|
| 219 |
+
|
| 220 |
+
**Solution:** Before retrieval, an LLM call analyzes the user's query and either:
|
| 221 |
+
1. **Reformulates** it into a search-optimized form (expanded keywords, resolved pronouns, domain-aware terms)
|
| 222 |
+
2. **Asks clarification** when the query is genuinely ambiguous (high bar β most queries get reformulated)
|
| 223 |
+
|
| 224 |
+
### Key Design Decisions
|
| 225 |
+
|
| 226 |
+
- **Reformulated query β retrieval only.** The original query is preserved for response generation
|
| 227 |
+
- **Conversation history** (last 6 messages by default) enables pronoun/reference resolution
|
| 228 |
+
- **Transparency:** Shows `Searching for: "reformulated query"` to the user
|
| 229 |
+
- **Graceful degradation:** Falls back to raw query if LLM fails. Configurable via `query_understanding.enabled`
|
| 230 |
+
- **No anti-hallucination impact:** Operates before retrieval; the 6-layer stack is unchanged
|
| 231 |
+
- **Max clarifications:** After `max_clarifications` rounds (default 1), forces a search
|
| 232 |
+
|
| 233 |
+
### Implementation
|
| 234 |
+
|
| 235 |
+
| File | Action | Description |
|
| 236 |
+
|---|---|---|
|
| 237 |
+
| `src/query_engine.py` | CREATE | `understand_query()` + `_parse_qu_result()` with JSON parsing and fallback |
|
| 238 |
+
| `src/prompts.py` | MODIFY | Added `QUERY_UNDERSTANDING_PROMPT_TEMPLATE` + `build_query_understanding_prompt()` |
|
| 239 |
+
| `app_cli.py` | MODIFY | Query understanding step, clarification flow, conversation history tracking |
|
| 240 |
+
| `app_web.py` | MODIFY | Query understanding step, `pending_clarification` state for Streamlit |
|
| 241 |
+
| `setup.py` | MODIFY | Added `query_understanding` config defaults |
|
| 242 |
+
| `tests/test_query_engine.py` | CREATE | 8 tests covering reformulation, clarification, disabled, error fallback, JSON parsing |
|
| 243 |
+
| `tests/test_prompts.py` | MODIFY | 2 tests for new prompt template |
|
| 244 |
+
| `tests/test_setup.py` | MODIFY | Assertions for new config section |
|
| 245 |
+
|
| 246 |
+
### Pipeline Flow (Updated)
|
| 247 |
+
|
| 248 |
+
```
|
| 249 |
+
User query β understand_query(query, history, cfg)
|
| 250 |
+
β [if CLARIFY: ask user, loop back, max 1 round]
|
| 251 |
+
β [if SEARCH: use reformulated query]
|
| 252 |
+
β retrieve(reformulated_query)
|
| 253 |
+
β verify_and_respond(original_query, results)
|
| 254 |
+
β Display
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
### Config
|
| 258 |
+
|
| 259 |
+
```yaml
|
| 260 |
+
query_understanding:
|
| 261 |
+
enabled: true # false to skip (use raw query)
|
| 262 |
+
max_history: 6 # conversation messages for context
|
| 263 |
+
max_clarifications: 1 # max clarification rounds before forcing search
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
### Test Suite
|
| 267 |
+
|
| 268 |
+
59 tests across 13 test files β all passing.
|
| 269 |
+
|
| 270 |
+
---
|
| 271 |
+
|
| 272 |
+
## 2026-03-05 β Fourth Full Audit & .get() Safety Fixes
|
| 273 |
+
|
| 274 |
+
### Scope
|
| 275 |
+
|
| 276 |
+
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.
|
| 277 |
+
|
| 278 |
+
### Bugs Found & Fixed
|
| 279 |
+
|
| 280 |
+
**BUG β `src/ingest.py:115,148` β Direct dict access crashes on missing config**
|
| 281 |
+
|
| 282 |
+
Used `cfg["paths"]["vector_db"]` and `cfg["paths"]["knowledge_base"]` instead of `.get()` with defaults. Raises `KeyError` if config is malformed or incomplete.
|
| 283 |
+
|
| 284 |
+
- Fix: `cfg.get("paths", {}).get("vector_db", "chroma_db")` and `cfg.get("paths", {}).get("knowledge_base", "knowledge_base")`
|
| 285 |
+
|
| 286 |
+
**BUG β `src/llm/__init__.py:15,21-24` β Direct dict access on `cfg["llm"]`**
|
| 287 |
+
|
| 288 |
+
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.
|
| 289 |
+
|
| 290 |
+
- Fix: Extract `llm_cfg = cfg.get("llm", {})` once, then use `llm_cfg.get(...)` for all accesses.
|
| 291 |
+
|
| 292 |
+
**BUG β `src/search/__init__.py:22-24` β Direct key access on result dicts**
|
| 293 |
+
|
| 294 |
+
Used `r['authors']`, `r['title']`, `r['url']`, `r['abstract']` instead of `.get()`. Would crash if any key missing from a search result.
|
| 295 |
+
|
| 296 |
+
- Fix: `r.get('authors', 'Unknown')`, `r.get('title', 'Untitled')`, `r.get('url', 'N/A')`, `r.get('abstract', 'N/A')`
|
| 297 |
+
|
| 298 |
+
**BUG β `app_web.py:171` β Clarification ignores `max_clarifications` config**
|
| 299 |
+
|
| 300 |
+
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.
|
| 301 |
+
|
| 302 |
+
- Fix: Added `and max_clarifications > 0` condition to the clarification check.
|
| 303 |
+
|
| 304 |
+
### Test Improvement
|
| 305 |
+
|
| 306 |
+
- Added missing assertions for `retrieval.top_k` (50) and `retrieval.max_distance` (0.55) in `tests/test_setup.py`
|
| 307 |
+
|
| 308 |
+
### Documentation
|
| 309 |
+
|
| 310 |
+
- Committed CLAUDE.md, docs/plans/, and docs/WORKLOG.md to the git repo (previously only existed in working copy)
|
| 311 |
+
- Fixed CLAUDE.md: `max_clarifications` now correctly lists both `app_cli.py` and `app_web.py` as consumers
|
| 312 |
+
|
| 313 |
+
### Test Suite
|
| 314 |
+
|
| 315 |
+
59 tests across 13 test files β all passing.
|
| 316 |
+
|
| 317 |
+
---
|
| 318 |
+
|
| 319 |
+
## Pending / Next Steps
|
| 320 |
+
|
| 321 |
+
- [x] ~~Create GitHub repo~~ β `LIANJie-Jason/chatbotsample_api` (private)
|
| 322 |
+
- [x] ~~End-to-end test with real documents and a real API key~~
|
| 323 |
+
- [x] ~~Query understanding layer for better retrieval~~
|
| 324 |
+
- [ ] Replace PyPDF2 with pypdf (PyPDF2 is deprecated)
|
| 325 |
+
- [ ] Consider adding provider switching in setup wizard (currently only one provider per config)
|
| 326 |
+
- [ ] Tune `max_distance` threshold based on more user testing
|
docs/pl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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RAG Research Chatbot Template β Design Document
|
| 2 |
+
|
| 3 |
+
**Date:** 2026-03-04
|
| 4 |
+
**Author:** Jie Lian
|
| 5 |
+
**Status:** Approved
|
| 6 |
+
|
| 7 |
+
## 1. Overview
|
| 8 |
+
|
| 9 |
+
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.
|
| 10 |
+
|
| 11 |
+
**Target audience:** Both academics (primary) and general users with domain-specific documents.
|
| 12 |
+
|
| 13 |
+
**Distribution:** GitHub template repository with a quickstart setup wizard.
|
| 14 |
+
|
| 15 |
+
## 2. Requirements Summary
|
| 16 |
+
|
| 17 |
+
| Decision | Choice |
|
| 18 |
+
|---|---|
|
| 19 |
+
| Audience | General-purpose, marketed to academics |
|
| 20 |
+
| Interface | CLI + Web UI (Streamlit) |
|
| 21 |
+
| Web search | Pluggable (Semantic Scholar default, swappable/disable) |
|
| 22 |
+
| LLM providers | OpenAI + Anthropic + Google Gemini |
|
| 23 |
+
| Model selection | Live fetch from provider API, fallback to defaults |
|
| 24 |
+
| Configuration | Interactive setup wizard + config.yaml |
|
| 25 |
+
| Embeddings | Free local default (ChromaDB), OpenAI upgrade option |
|
| 26 |
+
| Distribution | GitHub template repo + quickstart script |
|
| 27 |
+
| Setup | pip install primary, Docker optional |
|
| 28 |
+
| Anti-hallucination | #1 priority β 6-layer verification stack |
|
| 29 |
+
|
| 30 |
+
## 3. Supported File Formats
|
| 31 |
+
|
| 32 |
+
| Format | Extension | Library |
|
| 33 |
+
|---|---|---|
|
| 34 |
+
| PDF | `.pdf` | PyPDF2 |
|
| 35 |
+
| Word | `.docx` | python-docx |
|
| 36 |
+
| Excel | `.xlsx`, `.xls` | openpyxl, xlrd |
|
| 37 |
+
| CSV | `.csv` | stdlib csv |
|
| 38 |
+
| Tab-delimited | `.tab`, `.tsv` | stdlib csv |
|
| 39 |
+
| Stata | `.dta` | pyreadstat |
|
| 40 |
+
| R data | `.rds`, `.rda` | pyreadr |
|
| 41 |
+
| SPSS | `.sav` | pyreadstat |
|
| 42 |
+
| Plain text | `.txt`, `.md` | stdlib |
|
| 43 |
+
| JSON | `.json` | stdlib json |
|
| 44 |
+
| Stata do-files | `.do` | stdlib (plain text) |
|
| 45 |
+
|
| 46 |
+
## 4. Architecture
|
| 47 |
+
|
| 48 |
+
### 4.1 Project Structure
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
rag-research-chatbot/
|
| 52 |
+
βββ setup.py # Interactive setup wizard
|
| 53 |
+
βββ ingest.py # Entry point: python ingest.py
|
| 54 |
+
βββ app_cli.py # Entry point: python app_cli.py
|
| 55 |
+
βββ app_web.py # Entry point: python app_web.py (streamlit)
|
| 56 |
+
βββ config.yaml # Generated by setup wizard
|
| 57 |
+
βββ .env # API keys (generated by wizard, gitignored)
|
| 58 |
+
βββ requirements.txt
|
| 59 |
+
βββ Dockerfile
|
| 60 |
+
βββ docker-compose.yml
|
| 61 |
+
βββ .gitignore
|
| 62 |
+
βββ README.md
|
| 63 |
+
βββ LICENSE
|
| 64 |
+
β
|
| 65 |
+
βββ knowledge_base/ # User drops files here
|
| 66 |
+
β βββ .gitkeep
|
| 67 |
+
β
|
| 68 |
+
βββ chroma_db/ # Vector DB (auto-generated, gitignored)
|
| 69 |
+
β
|
| 70 |
+
βββ src/
|
| 71 |
+
βββ __init__.py
|
| 72 |
+
βββ config_loader.py # Loads config.yaml + .env, exposes settings
|
| 73 |
+
βββ ingest.py # Multi-format ingestion pipeline
|
| 74 |
+
βββ retriever.py # Orchestrates local + web retrieval
|
| 75 |
+
βββ prompts.py # System prompt builder (adapts to scenario)
|
| 76 |
+
βββ verifier.py # Anti-hallucination verification loop
|
| 77 |
+
β
|
| 78 |
+
βββ llm/
|
| 79 |
+
β βββ __init__.py # Registry: PROVIDERS dict + generate()
|
| 80 |
+
β βββ openai.py
|
| 81 |
+
β βββ anthropic.py
|
| 82 |
+
β βββ gemini.py
|
| 83 |
+
β
|
| 84 |
+
βββ search/
|
| 85 |
+
β βββ __init__.py # Registry: BACKENDS dict + search()
|
| 86 |
+
β βββ semantic_scholar.py
|
| 87 |
+
β
|
| 88 |
+
βββ readers/
|
| 89 |
+
βββ __init__.py # Registry: READERS dict by extension
|
| 90 |
+
βββ pdf.py
|
| 91 |
+
βββ docx.py
|
| 92 |
+
βββ excel.py # .xlsx and .xls
|
| 93 |
+
βββ csv_tab.py # .csv, .tab, .tsv
|
| 94 |
+
βββ stata.py # .dta via pyreadstat
|
| 95 |
+
βββ spss.py # .sav via pyreadstat
|
| 96 |
+
βββ rdata.py # .rds, .rda via pyreadr
|
| 97 |
+
βββ text.py # .txt, .md, .json, .do
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
### 4.2 Registry Pattern
|
| 101 |
+
|
| 102 |
+
LLM providers, search backends, and file readers each use a simple dict registry in their `__init__.py`:
|
| 103 |
+
|
| 104 |
+
```python
|
| 105 |
+
# src/llm/__init__.py
|
| 106 |
+
PROVIDERS = {
|
| 107 |
+
"openai": openai_generate,
|
| 108 |
+
"anthropic": anthropic_generate,
|
| 109 |
+
"gemini": gemini_generate,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
def generate(system_prompt, user_message, provider=None):
|
| 113 |
+
provider = provider or config.LLM_PROVIDER
|
| 114 |
+
if provider not in PROVIDERS:
|
| 115 |
+
raise ValueError(f"Unknown provider: {provider}")
|
| 116 |
+
return PROVIDERS[provider](system_prompt, user_message)
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
Same pattern for `src/search/__init__.py` (BACKENDS dict) and `src/readers/__init__.py` (READERS dict mapping extensions to reader functions).
|
| 120 |
+
|
| 121 |
+
Adding a new provider/format = write one file + add one line to the registry.
|
| 122 |
+
|
| 123 |
+
### 4.3 Data Flow
|
| 124 |
+
|
| 125 |
+
```
|
| 126 |
+
User query
|
| 127 |
+
|
|
| 128 |
+
v
|
| 129 |
+
retrieve() --> ChromaDB vector search (ALWAYS runs first)
|
| 130 |
+
--> Web search (optional, if enabled)
|
| 131 |
+
|
|
| 132 |
+
v
|
| 133 |
+
build_prompt() --> inject context + anti-hallucination guardrails
|
| 134 |
+
| (adapts to 4 scenarios: local+web, local-only,
|
| 135 |
+
| web-only, no-sources)
|
| 136 |
+
v
|
| 137 |
+
generate() --> LLM provider (from registry)
|
| 138 |
+
|
|
| 139 |
+
v
|
| 140 |
+
verify() --> 6-layer anti-hallucination stack
|
| 141 |
+
|
|
| 142 |
+
v
|
| 143 |
+
Display cited response with reference list
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
## 5. Retrieval Strategy
|
| 147 |
+
|
| 148 |
+
### 5.1 Web Search Toggle
|
| 149 |
+
|
| 150 |
+
- **Setup wizard:** asks user whether to enable web search (Step 5)
|
| 151 |
+
- **CLI runtime:** `/websearch on|off` command
|
| 152 |
+
- **Web UI runtime:** sidebar toggle switch
|
| 153 |
+
|
| 154 |
+
### 5.2 Priority Logic (Non-Negotiable)
|
| 155 |
+
|
| 156 |
+
Local knowledge base is ALWAYS the primary authority, regardless of web search setting.
|
| 157 |
+
|
| 158 |
+
| Scenario | Behavior |
|
| 159 |
+
|---|---|
|
| 160 |
+
| Local + Web | Local sources = PRIMARY. Web = supplementary. Web never overrides local. |
|
| 161 |
+
| Local only | Only local sources used. |
|
| 162 |
+
| Web only (no local docs ingested) | Web results used with warning: "No local knowledge base found." |
|
| 163 |
+
| No sources at all | LLM is NOT called. Hardcoded refusal returned. |
|
| 164 |
+
|
| 165 |
+
### 5.3 Chunk ID Anchoring
|
| 166 |
+
|
| 167 |
+
Each retrieved chunk gets a unique anchor ID in the context block:
|
| 168 |
+
|
| 169 |
+
```
|
| 170 |
+
[CHUNK-LOCAL-001] From: Chenoweth_2011.pdf (p.23)
|
| 171 |
+
Path: knowledge_base/NAVCO 2.0/Chenoweth_2011.pdf
|
| 172 |
+
"Nonviolent campaigns succeeded 53% of the time..."
|
| 173 |
+
|
| 174 |
+
[CHUNK-WEB-001] From: Nepstad (2011). "Nonviolent Revolutions"
|
| 175 |
+
URL: https://doi.org/10.xxxx/yyyy
|
| 176 |
+
Abstract: ...
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
The LLM must cite by these anchor IDs. The verifier checks that every citation maps to a real chunk.
|
| 180 |
+
|
| 181 |
+
## 6. Anti-Hallucination System (6-Layer Stack)
|
| 182 |
+
|
| 183 |
+
This is the most critical part of the design. Anti-hallucination is the #1 priority.
|
| 184 |
+
|
| 185 |
+
### Layer 0: No-Context Early Exit
|
| 186 |
+
|
| 187 |
+
If retrieval returns zero local chunks AND zero web results, the LLM is **never called**. A hardcoded Python string is returned:
|
| 188 |
+
|
| 189 |
+
```
|
| 190 |
+
"I don't have any information on this topic in my knowledge base.
|
| 191 |
+
No relevant local documents or web sources were found.
|
| 192 |
+
Please try a different question, or add relevant materials to
|
| 193 |
+
the knowledge_base/ folder and run ingestion again."
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
Zero hallucination risk β no LLM involvement.
|
| 197 |
+
|
| 198 |
+
### Layer 1: System Prompt β Hard Refusal of Memory
|
| 199 |
+
|
| 200 |
+
The system prompt contains an absolute, non-negotiable directive:
|
| 201 |
+
|
| 202 |
+
```
|
| 203 |
+
## ABSOLUTE RULE β ZERO TOLERANCE FOR HALLUCINATION
|
| 204 |
+
|
| 205 |
+
You are a retrieval-only assistant. You MUST:
|
| 206 |
+
- ONLY use information from the PROVIDED CONTEXT below.
|
| 207 |
+
- NEVER use your training data, general knowledge, or memory to answer.
|
| 208 |
+
- NEVER infer, guess, or "fill in gaps" with plausible-sounding information.
|
| 209 |
+
- If a user asks something not covered by the context: REFUSE to answer.
|
| 210 |
+
Say: "I don't have information on this in my knowledge base."
|
| 211 |
+
- Do NOT say "Based on my knowledge..." or "Generally speaking..." β
|
| 212 |
+
these phrases indicate you are drawing from memory, not sources.
|
| 213 |
+
|
| 214 |
+
There are NO exceptions. An incomplete answer is always better than
|
| 215 |
+
a fabricated one. Silence is always better than a guess.
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
Additional Layer 1 directives:
|
| 219 |
+
- **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.
|
| 220 |
+
- **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.
|
| 221 |
+
|
| 222 |
+
### Layer 2: Response Length Cap (Soft)
|
| 223 |
+
|
| 224 |
+
Dynamically adjusts `max_tokens` based on retrieved context size:
|
| 225 |
+
|
| 226 |
+
```python
|
| 227 |
+
context_chars = len(combined_context)
|
| 228 |
+
if context_chars < 500:
|
| 229 |
+
max_tokens = 1024
|
| 230 |
+
elif context_chars < 2000:
|
| 231 |
+
max_tokens = 1536
|
| 232 |
+
else:
|
| 233 |
+
max_tokens = config.max_tokens # default 2048
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
This is a soft suggestion, not a hard cutoff. The system prompt also encourages proportional response length.
|
| 237 |
+
|
| 238 |
+
### Layer 3: LLM Self-Verification Loop
|
| 239 |
+
|
| 240 |
+
After generation, a second LLM call verifies the response against the provided sources:
|
| 241 |
+
|
| 242 |
+
**Verification prompt:**
|
| 243 |
+
|
| 244 |
+
```
|
| 245 |
+
Verify the following response against ONLY the provided sources.
|
| 246 |
+
|
| 247 |
+
For each factual claim, check:
|
| 248 |
+
1. Is this claim directly supported by a source in the context?
|
| 249 |
+
2. Is the citation correct (right source, right page/URL)?
|
| 250 |
+
3. Is any information added that does NOT appear in the context?
|
| 251 |
+
4. Do direct quotes actually appear in the cited source chunk?
|
| 252 |
+
5. Are any claims flagged by the advisory warnings below unsupported?
|
| 253 |
+
|
| 254 |
+
Advisory flags from automated checks:
|
| 255 |
+
{phrase_flags}
|
| 256 |
+
{similarity_flags}
|
| 257 |
+
|
| 258 |
+
Report as JSON:
|
| 259 |
+
{
|
| 260 |
+
"errors": [
|
| 261 |
+
{"claim": "...", "issue": "not found in sources | wrong citation | from model memory"},
|
| 262 |
+
],
|
| 263 |
+
"error_count": <int>,
|
| 264 |
+
"pass": true | false
|
| 265 |
+
}
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
**Iterative correction logic:**
|
| 269 |
+
|
| 270 |
+
```
|
| 271 |
+
Generate response
|
| 272 |
+
|
|
| 273 |
+
v
|
| 274 |
+
Verify against sources
|
| 275 |
+
|
|
| 276 |
+
βββ pass=true --> Show to user
|
| 277 |
+
|
|
| 278 |
+
βββ pass=false
|
| 279 |
+
βββ β€2 errors: Correct once --> Re-verify
|
| 280 |
+
| βββ pass=true --> Show to user
|
| 281 |
+
| βββ pass=false --> REFUSE to answer
|
| 282 |
+
|
|
| 283 |
+
βββ >2 errors: Correct --> Re-verify --> still errors?
|
| 284 |
+
--> Correct again (loop until clean, max 3 iterations)
|
| 285 |
+
--> Still errors after max? --> REFUSE to answer
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
**Refusal message:**
|
| 289 |
+
|
| 290 |
+
```
|
| 291 |
+
"I was unable to produce a verified answer from my knowledge base.
|
| 292 |
+
Please try rephrasing your question."
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
**9-point verifier checklist:**
|
| 296 |
+
|
| 297 |
+
1. Every factual claim has at least one `[N]` citation
|
| 298 |
+
2. Every `[N]` in text appears in the reference list
|
| 299 |
+
3. Every reference list entry is used in the text
|
| 300 |
+
4. Local source paths match real chunks from context
|
| 301 |
+
5. Web source URLs/DOIs match search backend results
|
| 302 |
+
6. Direct quotes actually appear in the cited source chunk
|
| 303 |
+
7. No banned phrases without adjacent citations (from Layer 5 flags)
|
| 304 |
+
8. Claims flagged by semantic similarity are re-examined (from Layer 4 flags)
|
| 305 |
+
9. No information added that doesn't appear in context
|
| 306 |
+
|
| 307 |
+
### Layer 4: Semantic Similarity Post-Check
|
| 308 |
+
|
| 309 |
+
A non-LLM verification step using embeddings:
|
| 310 |
+
|
| 311 |
+
```python
|
| 312 |
+
claim_embedding = embed(claim_text)
|
| 313 |
+
cited_chunk_embedding = embed(cited_source_chunk)
|
| 314 |
+
similarity = cosine_similarity(claim_embedding, cited_chunk_embedding)
|
| 315 |
+
|
| 316 |
+
if similarity < 0.6:
|
| 317 |
+
flag_as_advisory(claim) # passed to Layer 3 as context
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
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.
|
| 321 |
+
|
| 322 |
+
### Layer 5: Soft Phrase Warning Filter
|
| 323 |
+
|
| 324 |
+
Scans for phrases that may indicate the model is drawing from memory. These are **advisory flags**, not automatic errors:
|
| 325 |
+
|
| 326 |
+
```python
|
| 327 |
+
WARNING_PHRASES = [
|
| 328 |
+
"based on my knowledge",
|
| 329 |
+
"generally speaking",
|
| 330 |
+
"it is well known",
|
| 331 |
+
"as we all know",
|
| 332 |
+
"it is widely accepted",
|
| 333 |
+
"common understanding suggests",
|
| 334 |
+
"from what I know",
|
| 335 |
+
"I recall that",
|
| 336 |
+
]
|
| 337 |
+
```
|
| 338 |
+
|
| 339 |
+
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.
|
| 340 |
+
|
| 341 |
+
### Execution Order
|
| 342 |
+
|
| 343 |
+
```
|
| 344 |
+
User query
|
| 345 |
+
|
|
| 346 |
+
v
|
| 347 |
+
Layer 0: No-context early exit
|
| 348 |
+
| (zero sources --> hardcoded refusal, STOP, LLM never called)
|
| 349 |
+
v
|
| 350 |
+
Layer 2: Set soft max_tokens cap based on context size
|
| 351 |
+
|
|
| 352 |
+
v
|
| 353 |
+
[Generate response from LLM]
|
| 354 |
+
|
|
| 355 |
+
v
|
| 356 |
+
Layer 5: Soft phrase warning scan <-- cheapest, no API cost
|
| 357 |
+
| (advisory flags)
|
| 358 |
+
v
|
| 359 |
+
Layer 4: Semantic similarity check <-- embedding cost only
|
| 360 |
+
| (advisory flags)
|
| 361 |
+
v
|
| 362 |
+
Layer 3: LLM self-verification <-- most expensive
|
| 363 |
+
| (receives Layer 4+5 flags as context)
|
| 364 |
+
| (iterative correction if errors found)
|
| 365 |
+
|
|
| 366 |
+
βββ PASS --> Show to user
|
| 367 |
+
βββ FAIL after max iterations --> REFUSE to answer
|
| 368 |
+
```
|
| 369 |
+
|
| 370 |
+
### Cost Configuration
|
| 371 |
+
|
| 372 |
+
```yaml
|
| 373 |
+
verification:
|
| 374 |
+
enabled: true
|
| 375 |
+
max_iterations: 3
|
| 376 |
+
strict_mode: true # if true, refuse on any remaining error
|
| 377 |
+
# if false, show answer with warning
|
| 378 |
+
```
|
| 379 |
+
|
| 380 |
+
## 7. Citation & Reference Format
|
| 381 |
+
|
| 382 |
+
### 7.1 Inline Citations (Endnote Style)
|
| 383 |
+
|
| 384 |
+
Every factual claim gets a bracketed endnote number:
|
| 385 |
+
|
| 386 |
+
```
|
| 387 |
+
The success rate of nonviolent campaigns was approximately twice that
|
| 388 |
+
of violent insurgencies between 1900 and 2006. [1] Economic boycotts
|
| 389 |
+
were among the most frequently employed tactics. [2][3]
|
| 390 |
+
```
|
| 391 |
+
|
| 392 |
+
### 7.2 Direct Quote Anchoring
|
| 393 |
+
|
| 394 |
+
Key findings include a direct quote from the source:
|
| 395 |
+
|
| 396 |
+
```
|
| 397 |
+
As stated in [1]: "nonviolent campaigns succeeded 53% of the time
|
| 398 |
+
compared to 26% for violent insurgencies."
|
| 399 |
+
```
|
| 400 |
+
|
| 401 |
+
### 7.3 Reference List
|
| 402 |
+
|
| 403 |
+
Every response ends with a structured reference list:
|
| 404 |
+
|
| 405 |
+
```
|
| 406 |
+
## References
|
| 407 |
+
|
| 408 |
+
**Local Sources (Primary):**
|
| 409 |
+
[1] Chenoweth_Stephan_2011.pdf (p. 23)
|
| 410 |
+
-- knowledge_base/NAVCO 2.0/Chenoweth_Stephan_2011.pdf
|
| 411 |
+
[2] NAVCO2JPRcodebook2013.pdf (p. 7)
|
| 412 |
+
-- knowledge_base/NAVCO 2.0/NAVCO2JPRcodebook2013.pdf
|
| 413 |
+
|
| 414 |
+
**Web Sources (Supplementary):**
|
| 415 |
+
[3] Chenoweth, E. & Stephan, M. (2011). "Why Civil Resistance Works."
|
| 416 |
+
DOI: https://doi.org/10.7312/chen15682
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
### 7.4 Format Rules
|
| 420 |
+
|
| 421 |
+
| Element | Local Source | Web Source |
|
| 422 |
+
|---|---|---|
|
| 423 |
+
| Identifier | `[N]` endnote | `[N]` endnote |
|
| 424 |
+
| Name | Original filename | Author (Year). "Title" |
|
| 425 |
+
| Location | Page/sheet/row range | DOI (preferred) or URL |
|
| 426 |
+
| Path | Full relative path from `knowledge_base/` | Full link |
|
| 427 |
+
| Priority | **Primary** | **Supplementary** |
|
| 428 |
+
|
| 429 |
+
## 8. System Prompt Adaptation
|
| 430 |
+
|
| 431 |
+
The system prompt adapts to four retrieval scenarios:
|
| 432 |
+
|
| 433 |
+
| Scenario | Prompt Behavior |
|
| 434 |
+
|---|---|
|
| 435 |
+
| Local + Web | "Local sources are PRIMARY. Web sources are supplementary only. Never let web override local." |
|
| 436 |
+
| Local only | "ONLY use the local sources below. Do not add any outside knowledge." |
|
| 437 |
+
| Web only (no local docs) | "All sources are from web search. Cite every claim with URL. State clearly you have no curated local sources." |
|
| 438 |
+
| No sources | LLM is NOT called. Hardcoded refusal. |
|
| 439 |
+
|
| 440 |
+
## 9. Setup Wizard
|
| 441 |
+
|
| 442 |
+
### 9.1 Interactive Flow
|
| 443 |
+
|
| 444 |
+
```
|
| 445 |
+
$ python setup.py
|
| 446 |
+
|
| 447 |
+
RAG Research Chatbot -- Setup Wizard
|
| 448 |
+
|
| 449 |
+
Step 1/5: What would you like to name your chatbot?
|
| 450 |
+
> My Research Assistant
|
| 451 |
+
|
| 452 |
+
Step 2/5: Describe your chatbot's domain:
|
| 453 |
+
> Political science and nonviolent resistance research
|
| 454 |
+
|
| 455 |
+
Step 3/5: Choose your LLM provider:
|
| 456 |
+
[1] OpenAI [2] Anthropic [3] Google Gemini
|
| 457 |
+
> 1
|
| 458 |
+
|
| 459 |
+
Step 3b: Fetching available models from OpenAI...
|
| 460 |
+
[1] gpt-4o
|
| 461 |
+
[2] gpt-4o-mini
|
| 462 |
+
[3] gpt-4.1
|
| 463 |
+
... (live list from API)
|
| 464 |
+
> 1
|
| 465 |
+
|
| 466 |
+
Step 4/5: Enter your API key for OpenAI:
|
| 467 |
+
> sk-... (hidden)
|
| 468 |
+
|
| 469 |
+
Step 5/5: Enable web search to supplement local knowledge base?
|
| 470 |
+
[1] Yes -- Semantic Scholar (academic papers)
|
| 471 |
+
[2] No -- local knowledge base only
|
| 472 |
+
> 1
|
| 473 |
+
|
| 474 |
+
Config saved to config.yaml
|
| 475 |
+
Created knowledge_base/ folder
|
| 476 |
+
|
| 477 |
+
Next steps:
|
| 478 |
+
1. Drop your files into knowledge_base/
|
| 479 |
+
2. Run: python ingest.py
|
| 480 |
+
3. Run: python app_cli.py (or: streamlit run app_web.py)
|
| 481 |
+
```
|
| 482 |
+
|
| 483 |
+
### 9.2 Model Fetching
|
| 484 |
+
|
| 485 |
+
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.
|
| 486 |
+
|
| 487 |
+
### 9.3 Generated config.yaml
|
| 488 |
+
|
| 489 |
+
```yaml
|
| 490 |
+
# -- Chatbot Identity --
|
| 491 |
+
chatbot:
|
| 492 |
+
name: "My Research Assistant"
|
| 493 |
+
domain: "Political science and nonviolent resistance research"
|
| 494 |
+
|
| 495 |
+
# -- LLM Provider --
|
| 496 |
+
llm:
|
| 497 |
+
provider: "openai"
|
| 498 |
+
model: "gpt-4o"
|
| 499 |
+
temperature: 0.0
|
| 500 |
+
max_tokens: 2048
|
| 501 |
+
|
| 502 |
+
# -- API Keys (can also use environment variables) --
|
| 503 |
+
# Keys are stored in .env, not here. Env vars take precedence.
|
| 504 |
+
api_keys:
|
| 505 |
+
openai: ""
|
| 506 |
+
anthropic: ""
|
| 507 |
+
gemini: ""
|
| 508 |
+
|
| 509 |
+
# -- Embeddings --
|
| 510 |
+
embeddings:
|
| 511 |
+
provider: "local" # local (free) | openai
|
| 512 |
+
openai_model: "text-embedding-3-small"
|
| 513 |
+
|
| 514 |
+
# -- Retrieval --
|
| 515 |
+
retrieval:
|
| 516 |
+
chunk_size: 1000
|
| 517 |
+
chunk_overlap: 100
|
| 518 |
+
top_k: 5
|
| 519 |
+
|
| 520 |
+
# -- Web Search --
|
| 521 |
+
web_search:
|
| 522 |
+
enabled: true
|
| 523 |
+
backend: "semantic_scholar"
|
| 524 |
+
max_results: 5
|
| 525 |
+
|
| 526 |
+
# -- Anti-Hallucination --
|
| 527 |
+
verification:
|
| 528 |
+
enabled: true
|
| 529 |
+
max_iterations: 3
|
| 530 |
+
strict_mode: true
|
| 531 |
+
|
| 532 |
+
# -- Paths --
|
| 533 |
+
paths:
|
| 534 |
+
knowledge_base: "knowledge_base"
|
| 535 |
+
vector_db: "chroma_db"
|
| 536 |
+
```
|
| 537 |
+
|
| 538 |
+
API keys are written to `.env` (gitignored), not config.yaml.
|
| 539 |
+
|
| 540 |
+
## 10. CLI Interface
|
| 541 |
+
|
| 542 |
+
Rich-powered terminal chatbot.
|
| 543 |
+
|
| 544 |
+
**Commands:**
|
| 545 |
+
- `/quit` β exit
|
| 546 |
+
- `/sources` β show sources from last response
|
| 547 |
+
- `/ingest` β re-index knowledge_base/
|
| 548 |
+
- `/model` β show current model, switch provider/model
|
| 549 |
+
- `/websearch on|off` β toggle web search
|
| 550 |
+
- `/help` β show help
|
| 551 |
+
|
| 552 |
+
## 11. Web UI (Streamlit)
|
| 553 |
+
|
| 554 |
+
### Layout
|
| 555 |
+
|
| 556 |
+
- **Header:** chatbot name
|
| 557 |
+
- **Sidebar:** provider dropdown, model dropdown (updates on provider change), web search toggle, knowledge base stats (files, chunks, last ingestion), re-ingest button
|
| 558 |
+
- **Chat area:** message history with markdown rendering
|
| 559 |
+
- **Footer:** persistent banner: "All answers sourced from local knowledge base. Web sources are supplementary only."
|
| 560 |
+
|
| 561 |
+
### Behaviors
|
| 562 |
+
|
| 563 |
+
- Chat history maintained in session (not persisted across refreshes)
|
| 564 |
+
- During verification loop, spinner: "Verifying answer against sources..."
|
| 565 |
+
- Model/provider switch is session-only (does not overwrite config.yaml)
|
| 566 |
+
|
| 567 |
+
## 12. Dependencies
|
| 568 |
+
|
| 569 |
+
```
|
| 570 |
+
# Core
|
| 571 |
+
chromadb>=0.4.0
|
| 572 |
+
PyPDF2>=3.0.0
|
| 573 |
+
python-docx>=1.0.0
|
| 574 |
+
openpyxl>=3.0.0
|
| 575 |
+
xlrd>=2.0.0
|
| 576 |
+
pyreadstat>=1.2.0
|
| 577 |
+
pyreadr>=0.5.0
|
| 578 |
+
requests>=2.28.0
|
| 579 |
+
rich>=13.0.0
|
| 580 |
+
pyyaml>=6.0
|
| 581 |
+
python-dotenv>=1.0.0
|
| 582 |
+
|
| 583 |
+
# LLM providers
|
| 584 |
+
openai>=1.0.0
|
| 585 |
+
anthropic>=0.20.0
|
| 586 |
+
google-generativeai>=0.5.0
|
| 587 |
+
|
| 588 |
+
# Web UI
|
| 589 |
+
streamlit>=1.30.0
|
| 590 |
+
```
|
| 591 |
+
|
| 592 |
+
## 13. Docker (Optional)
|
| 593 |
+
|
| 594 |
+
`Dockerfile` and `docker-compose.yml` provided for users who prefer containerized setup. Not the primary installation path.
|
docs/plans/2026-03-04-rag-research-chatbot-implementation.md
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/plans/2026-03-05-query-understanding-design.md
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Query Understanding Layer β Design Document
|
| 2 |
+
|
| 3 |
+
**Date:** 2026-03-05
|
| 4 |
+
**Author:** Jie Lian (with Claude)
|
| 5 |
+
**Status:** Approved & Implemented
|
| 6 |
+
|
| 7 |
+
## 1. Problem
|
| 8 |
+
|
| 9 |
+
Short, vague, or ambiguous user queries produce poor retrieval results. Examples:
|
| 10 |
+
|
| 11 |
+
| User Query | Problem | What Retrieval Needs |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| "China in 2024?" | Too short, embedding doesn't match long document chunks | "China human rights situation developments 2024" |
|
| 14 |
+
| "what about 2023?" | Missing context from prior conversation | "China human rights 2023" (from conversation history) |
|
| 15 |
+
| "AI stuff" | Vague | Clarification: "Are you asking about AI surveillance, AI in governance, or AI and civil resistance?" |
|
| 16 |
+
| "How did they respond?" | Pronouns unresolved | Needs prior context to resolve "they" |
|
| 17 |
+
|
| 18 |
+
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.
|
| 19 |
+
|
| 20 |
+
## 2. Solution: Query Understanding Layer
|
| 21 |
+
|
| 22 |
+
Add a pre-retrieval step that uses the LLM to:
|
| 23 |
+
|
| 24 |
+
1. **Reformulate** β Rewrite the query into a search-optimized form (expanded, keyword-rich, domain-aware)
|
| 25 |
+
2. **Clarify** β When the query is genuinely ambiguous, ask the user a targeted question before searching
|
| 26 |
+
|
| 27 |
+
### Pipeline Change
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
BEFORE:
|
| 31 |
+
User query β retrieve(query) β verify_and_respond(query, results) β Display
|
| 32 |
+
|
| 33 |
+
AFTER:
|
| 34 |
+
User query β understand_query(query, history, cfg)
|
| 35 |
+
β [if CLARIFY: ask user, get answer, call understand_query again]
|
| 36 |
+
β [if SEARCH: use reformulated query for retrieval]
|
| 37 |
+
β retrieve(reformulated_query) β verify_and_respond(original_query, results) β Display
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**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.
|
| 41 |
+
|
| 42 |
+
## 3. New Module: `src/query_engine.py`
|
| 43 |
+
|
| 44 |
+
### 3.1 Function Signature
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
def understand_query(
|
| 48 |
+
user_query: str,
|
| 49 |
+
cfg: dict,
|
| 50 |
+
conversation_history: list[dict] | None = None,
|
| 51 |
+
) -> dict:
|
| 52 |
+
"""
|
| 53 |
+
Analyze and reformulate a user query for better retrieval.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
user_query: Raw user input.
|
| 57 |
+
cfg: App config (provides domain, LLM settings).
|
| 58 |
+
conversation_history: List of {"role": "user"|"assistant", "content": "..."}
|
| 59 |
+
from the current session. Used to resolve pronouns/references.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
{
|
| 63 |
+
"action": "search" | "clarify",
|
| 64 |
+
"search_query": "reformulated query for embedding search",
|
| 65 |
+
"original_query": "user's original text",
|
| 66 |
+
"clarification_question": "..." (only if action == "clarify"),
|
| 67 |
+
}
|
| 68 |
+
"""
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
### 3.2 LLM Prompt
|
| 72 |
+
|
| 73 |
+
```
|
| 74 |
+
You are a query reformulation assistant for a {domain} research chatbot.
|
| 75 |
+
|
| 76 |
+
Your job is to analyze the user's question and decide:
|
| 77 |
+
1. SEARCH β if the question is clear enough, rewrite it as an optimized search query
|
| 78 |
+
2. CLARIFY β if the question is genuinely ambiguous, ask ONE clarification question
|
| 79 |
+
|
| 80 |
+
RULES for SEARCH:
|
| 81 |
+
- Expand abbreviations and acronyms (e.g., "HR" β "human rights")
|
| 82 |
+
- Resolve pronouns using conversation history (e.g., "they" β the entity from prior turn)
|
| 83 |
+
- Add relevant domain-specific keywords that would match document content
|
| 84 |
+
- Keep the reformulated query concise (15-40 words)
|
| 85 |
+
- Preserve the user's original intent β do NOT change what they're asking about
|
| 86 |
+
- If the query is already clear and specific, return it with minimal changes
|
| 87 |
+
|
| 88 |
+
RULES for CLARIFY:
|
| 89 |
+
- ONLY ask for clarification when the question is genuinely ambiguous
|
| 90 |
+
(could mean 2+ clearly different things)
|
| 91 |
+
- Ask ONE specific, short question
|
| 92 |
+
- Provide 2-3 options when possible
|
| 93 |
+
- Do NOT ask for clarification on clear questions β even if they are broad
|
| 94 |
+
- A broad question is NOT the same as an ambiguous question
|
| 95 |
+
|
| 96 |
+
CONVERSATION HISTORY:
|
| 97 |
+
{history}
|
| 98 |
+
|
| 99 |
+
USER'S QUESTION: {query}
|
| 100 |
+
|
| 101 |
+
Respond in JSON:
|
| 102 |
+
{
|
| 103 |
+
"action": "search" or "clarify",
|
| 104 |
+
"search_query": "reformulated search query" (only if action is "search"),
|
| 105 |
+
"clarification_question": "question to ask" (only if action is "clarify"),
|
| 106 |
+
"reasoning": "one sentence explaining your choice"
|
| 107 |
+
}
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
### 3.3 Clarification Threshold
|
| 111 |
+
|
| 112 |
+
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:
|
| 113 |
+
|
| 114 |
+
| Query | Action | Why |
|
| 115 |
+
|---|---|---|
|
| 116 |
+
| "China" | SEARCH β "China human rights developments" | Broad but not ambiguous β search and let the user refine |
|
| 117 |
+
| "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 |
|
| 118 |
+
| "what about 2023?" | SEARCH β "China human rights 2023" (from history) | Pronoun resolved from conversation context |
|
| 119 |
+
| "How effective is NVR?" | SEARCH β "effectiveness nonviolent resistance campaigns success rate" | Abbreviation expanded, terms added |
|
| 120 |
+
|
| 121 |
+
### 3.4 Conversation History
|
| 122 |
+
|
| 123 |
+
The query engine receives the last N turns of conversation (default: last 3 user-assistant pairs = 6 messages). This lets it resolve:
|
| 124 |
+
|
| 125 |
+
- Pronouns: "they", "it", "that"
|
| 126 |
+
- Follow-ups: "what about 2023?", "and in Asia?"
|
| 127 |
+
- Refinements: "more detail on the third point"
|
| 128 |
+
|
| 129 |
+
The history is passed as text in the prompt, NOT as separate LLM conversation turns (cheaper, simpler).
|
| 130 |
+
|
| 131 |
+
## 4. Integration Points
|
| 132 |
+
|
| 133 |
+
### 4.1 CLI (`app_cli.py`)
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
# In the main loop, before retrieve():
|
| 137 |
+
from src.query_engine import understand_query
|
| 138 |
+
|
| 139 |
+
# Build conversation history from state
|
| 140 |
+
history = state.get("conversation_history", [])
|
| 141 |
+
|
| 142 |
+
# Query understanding
|
| 143 |
+
qu_result = understand_query(user_input, effective_cfg, history)
|
| 144 |
+
|
| 145 |
+
if qu_result["action"] == "clarify":
|
| 146 |
+
# Show clarification question
|
| 147 |
+
console.print(f"\n[bold yellow]Clarification needed:[/bold yellow] {qu_result['clarification_question']}")
|
| 148 |
+
try:
|
| 149 |
+
clarification = input("You> ").strip()
|
| 150 |
+
except (EOFError, KeyboardInterrupt):
|
| 151 |
+
continue
|
| 152 |
+
if not clarification:
|
| 153 |
+
continue
|
| 154 |
+
# Re-run with clarification appended
|
| 155 |
+
combined = f"{user_input} β {clarification}"
|
| 156 |
+
qu_result = understand_query(combined, effective_cfg, history)
|
| 157 |
+
|
| 158 |
+
# Use reformulated query for retrieval, original for response
|
| 159 |
+
search_query = qu_result["search_query"]
|
| 160 |
+
original_query = qu_result["original_query"]
|
| 161 |
+
|
| 162 |
+
retrieval_result = retrieve(search_query, effective_cfg)
|
| 163 |
+
result = verify_and_respond(original_query, retrieval_result, effective_cfg)
|
| 164 |
+
|
| 165 |
+
# Update conversation history
|
| 166 |
+
history.append({"role": "user", "content": user_input})
|
| 167 |
+
history.append({"role": "assistant", "content": result["response"]})
|
| 168 |
+
# Keep last 6 messages (3 turns)
|
| 169 |
+
state["conversation_history"] = history[-6:]
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
### 4.2 Web UI (`app_web.py`)
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
# In render_chat(), before retrieve():
|
| 176 |
+
from src.query_engine import understand_query
|
| 177 |
+
|
| 178 |
+
history = [
|
| 179 |
+
{"role": m["role"], "content": m["content"]}
|
| 180 |
+
for m in st.session_state.messages[-6:]
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
qu_result = understand_query(prompt, cfg, history)
|
| 184 |
+
|
| 185 |
+
if qu_result["action"] == "clarify":
|
| 186 |
+
# Show clarification as assistant message
|
| 187 |
+
st.session_state.messages.append({
|
| 188 |
+
"role": "assistant",
|
| 189 |
+
"content": f"**Before I search, could you clarify?** {qu_result['clarification_question']}"
|
| 190 |
+
})
|
| 191 |
+
st.rerun()
|
| 192 |
+
return # Wait for user's next input as clarification
|
| 193 |
+
|
| 194 |
+
# Use reformulated query for retrieval
|
| 195 |
+
retrieval_result = retrieve(qu_result["search_query"], cfg)
|
| 196 |
+
result = verify_and_respond(prompt, retrieval_result, cfg)
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
### 4.3 Status Display
|
| 200 |
+
|
| 201 |
+
Show the reformulated query to the user so they understand what was searched:
|
| 202 |
+
|
| 203 |
+
**CLI:**
|
| 204 |
+
```
|
| 205 |
+
[dim]Searching for: "China human rights situation developments 2024"[/dim]
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
**Web UI:**
|
| 209 |
+
```
|
| 210 |
+
Status: Searching for "China human rights situation developments 2024"...
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
This is important for transparency β the user should know how their query was interpreted.
|
| 214 |
+
|
| 215 |
+
## 5. Config
|
| 216 |
+
|
| 217 |
+
New section in `config.yaml`:
|
| 218 |
+
|
| 219 |
+
```yaml
|
| 220 |
+
query_understanding:
|
| 221 |
+
enabled: true # set to false to skip reformulation (use raw query)
|
| 222 |
+
max_history: 6 # number of recent messages to include as context
|
| 223 |
+
max_clarifications: 1 # max clarification rounds before forcing a search
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
Default: enabled. Can be disabled for users who want raw pass-through behavior.
|
| 227 |
+
|
| 228 |
+
### Setup Wizard Addition
|
| 229 |
+
|
| 230 |
+
No new wizard step needed β `query_understanding` defaults to enabled. Advanced users can disable in `config.yaml`.
|
| 231 |
+
|
| 232 |
+
The setup wizard's `generate_config()` adds:
|
| 233 |
+
|
| 234 |
+
```python
|
| 235 |
+
"query_understanding": {
|
| 236 |
+
"enabled": True,
|
| 237 |
+
"max_history": 6,
|
| 238 |
+
"max_clarifications": 1,
|
| 239 |
+
},
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
## 6. Cost Analysis
|
| 243 |
+
|
| 244 |
+
| Component | LLM Calls Before | LLM Calls After |
|
| 245 |
+
|---|---|---|
|
| 246 |
+
| Query understanding | 0 | 1 (small, ~100 tokens out) |
|
| 247 |
+
| Response generation | 1 | 1 (unchanged) |
|
| 248 |
+
| Verification | 1-3 | 1-3 (unchanged) |
|
| 249 |
+
| Clarification | 0 | 0-1 (only when ambiguous) |
|
| 250 |
+
| **Total** | **2-4** | **3-5** |
|
| 251 |
+
|
| 252 |
+
The query understanding call is cheap: short prompt, short response (~100 tokens). The improved retrieval quality is worth the extra call.
|
| 253 |
+
|
| 254 |
+
## 7. Anti-Hallucination Impact
|
| 255 |
+
|
| 256 |
+
**No weakening.** The query understanding layer operates BEFORE retrieval and does NOT affect the 6-layer verification stack:
|
| 257 |
+
|
| 258 |
+
- Layer 0 (no-source gate): Still works β if reformulated query finds nothing, LLM is never called
|
| 259 |
+
- Layer 1-5: Unchanged β the response is still verified against retrieved sources
|
| 260 |
+
- The original query is preserved for response generation β the LLM answers what the user actually asked, not a reformulated version
|
| 261 |
+
|
| 262 |
+
## 8. Edge Cases
|
| 263 |
+
|
| 264 |
+
| Case | Handling |
|
| 265 |
+
|---|---|
|
| 266 |
+
| Query understanding disabled | Skip entirely, use raw query (current behavior) |
|
| 267 |
+
| LLM call fails | Fall back to raw query, log warning |
|
| 268 |
+
| Clarification on first message (no history) | Works fine β history is empty |
|
| 269 |
+
| User skips clarification (empty input) | Skip, use raw query |
|
| 270 |
+
| Very long query (paragraph) | Still reformulate β LLM extracts the core question |
|
| 271 |
+
| Multi-part question | LLM reformulates the primary question; may suggest focusing |
|
| 272 |
+
|
| 273 |
+
## 9. Files to Create/Modify
|
| 274 |
+
|
| 275 |
+
| File | Action | Description |
|
| 276 |
+
|---|---|---|
|
| 277 |
+
| `src/query_engine.py` | **CREATE** | Query understanding module |
|
| 278 |
+
| `src/prompts.py` | **MODIFY** | Add `QUERY_UNDERSTANDING_PROMPT_TEMPLATE` and `build_query_understanding_prompt()` |
|
| 279 |
+
| `app_cli.py` | **MODIFY** | Add query understanding step + conversation history + clarification flow |
|
| 280 |
+
| `app_web.py` | **MODIFY** | Add query understanding step + clarification flow |
|
| 281 |
+
| `setup.py` | **MODIFY** | Add `query_understanding` config defaults |
|
| 282 |
+
| `tests/test_query_engine.py` | **CREATE** | Tests for query engine |
|
| 283 |
+
| `tests/test_prompts.py` | **MODIFY** | Test for new prompt template |
|
| 284 |
+
|
| 285 |
+
## 10. Test Plan
|
| 286 |
+
|
| 287 |
+
1. `test_understand_query_reformulates` β Clear query returns action="search" with reformulated query
|
| 288 |
+
2. `test_understand_query_clarifies` β Ambiguous query returns action="clarify"
|
| 289 |
+
3. `test_understand_query_preserves_original` β Original query always in result
|
| 290 |
+
4. `test_understand_query_with_history` β Pronoun resolution using conversation history
|
| 291 |
+
5. `test_understand_query_disabled` β When disabled, returns raw query passthrough
|
| 292 |
+
6. `test_understand_query_fallback_on_error` β LLM failure falls back to raw query
|
| 293 |
+
7. `test_build_query_understanding_prompt` β Prompt template includes domain and history
|
src/ingest.py
CHANGED
|
@@ -112,7 +112,7 @@ def discover_files(documents_dir: str) -> list[tuple[Path, str]]:
|
|
| 112 |
|
| 113 |
def get_chroma_collection(cfg: dict):
|
| 114 |
"""Get or create the ChromaDB collection with embeddings."""
|
| 115 |
-
db_path = cfg
|
| 116 |
if not os.path.isabs(db_path):
|
| 117 |
db_path = os.path.join(os.path.dirname(os.path.abspath("config.yaml")), db_path)
|
| 118 |
|
|
@@ -145,7 +145,7 @@ def ingest_documents(cfg: dict = None, documents_dir: str = None) -> int:
|
|
| 145 |
cfg = load_config()
|
| 146 |
|
| 147 |
if documents_dir is None:
|
| 148 |
-
documents_dir = cfg
|
| 149 |
if not os.path.isabs(documents_dir):
|
| 150 |
documents_dir = os.path.join(
|
| 151 |
os.path.dirname(os.path.abspath("config.yaml")), documents_dir
|
|
|
|
| 112 |
|
| 113 |
def get_chroma_collection(cfg: dict):
|
| 114 |
"""Get or create the ChromaDB collection with embeddings."""
|
| 115 |
+
db_path = cfg.get("paths", {}).get("vector_db", "chroma_db")
|
| 116 |
if not os.path.isabs(db_path):
|
| 117 |
db_path = os.path.join(os.path.dirname(os.path.abspath("config.yaml")), db_path)
|
| 118 |
|
|
|
|
| 145 |
cfg = load_config()
|
| 146 |
|
| 147 |
if documents_dir is None:
|
| 148 |
+
documents_dir = cfg.get("paths", {}).get("knowledge_base", "knowledge_base")
|
| 149 |
if not os.path.isabs(documents_dir):
|
| 150 |
documents_dir = os.path.join(
|
| 151 |
os.path.dirname(os.path.abspath("config.yaml")), documents_dir
|
src/llm/__init__.py
CHANGED
|
@@ -12,16 +12,17 @@ PROVIDERS = {
|
|
| 12 |
|
| 13 |
def generate(system_prompt: str, user_message: str, cfg: dict,
|
| 14 |
provider: str = None, max_tokens: int = None) -> str:
|
| 15 |
-
|
|
|
|
| 16 |
if provider not in PROVIDERS:
|
| 17 |
raise ValueError(f"Unknown provider: {provider}. Available: {list(PROVIDERS.keys())}")
|
| 18 |
api_key = get_api_key(cfg, provider)
|
| 19 |
if not api_key:
|
| 20 |
raise ValueError(f"API key not set for {provider}. Set it in .env or config.yaml.")
|
| 21 |
-
model =
|
| 22 |
-
temperature =
|
| 23 |
if max_tokens is None:
|
| 24 |
-
max_tokens =
|
| 25 |
return PROVIDERS[provider].generate(
|
| 26 |
system_prompt=system_prompt, user_message=user_message,
|
| 27 |
api_key=api_key, model=model, temperature=temperature, max_tokens=max_tokens,
|
|
|
|
| 12 |
|
| 13 |
def generate(system_prompt: str, user_message: str, cfg: dict,
|
| 14 |
provider: str = None, max_tokens: int = None) -> str:
|
| 15 |
+
llm_cfg = cfg.get("llm", {})
|
| 16 |
+
provider = provider or llm_cfg.get("provider", "openai")
|
| 17 |
if provider not in PROVIDERS:
|
| 18 |
raise ValueError(f"Unknown provider: {provider}. Available: {list(PROVIDERS.keys())}")
|
| 19 |
api_key = get_api_key(cfg, provider)
|
| 20 |
if not api_key:
|
| 21 |
raise ValueError(f"API key not set for {provider}. Set it in .env or config.yaml.")
|
| 22 |
+
model = llm_cfg.get("model", "")
|
| 23 |
+
temperature = llm_cfg.get("temperature", 0.0)
|
| 24 |
if max_tokens is None:
|
| 25 |
+
max_tokens = llm_cfg.get("max_tokens", 2048)
|
| 26 |
return PROVIDERS[provider].generate(
|
| 27 |
system_prompt=system_prompt, user_message=user_message,
|
| 28 |
api_key=api_key, model=model, temperature=temperature, max_tokens=max_tokens,
|
src/search/__init__.py
CHANGED
|
@@ -19,8 +19,8 @@ def format_web_results_as_context(results: list[dict]) -> str:
|
|
| 19 |
for i, r in enumerate(results, 1):
|
| 20 |
year_str = f" ({r['year']})" if r.get("year") else ""
|
| 21 |
parts.append(
|
| 22 |
-
f"[CHUNK-WEB-{i:03d}] From: {r
|
| 23 |
-
f" URL: {r
|
| 24 |
-
f" Abstract: {r
|
| 25 |
)
|
| 26 |
return "\n".join(parts)
|
|
|
|
| 19 |
for i, r in enumerate(results, 1):
|
| 20 |
year_str = f" ({r['year']})" if r.get("year") else ""
|
| 21 |
parts.append(
|
| 22 |
+
f"[CHUNK-WEB-{i:03d}] From: {r.get('authors', 'Unknown')}{year_str}. \"{r.get('title', 'Untitled')}\"\n"
|
| 23 |
+
f" URL: {r.get('url', 'N/A')}\n"
|
| 24 |
+
f" Abstract: {r.get('abstract', 'N/A')}\n"
|
| 25 |
)
|
| 26 |
return "\n".join(parts)
|
tests/test_setup.py
CHANGED
|
@@ -21,6 +21,8 @@ def test_generate_config_yaml():
|
|
| 21 |
assert cfg["verification"]["strict_mode"] is True
|
| 22 |
assert cfg["retrieval"]["chunk_size"] == 1000
|
| 23 |
assert cfg["retrieval"]["chunk_overlap"] == 100
|
|
|
|
|
|
|
| 24 |
assert cfg["embeddings"]["provider"] == "local"
|
| 25 |
# Query understanding config
|
| 26 |
assert cfg["query_understanding"]["enabled"] is True
|
|
|
|
| 21 |
assert cfg["verification"]["strict_mode"] is True
|
| 22 |
assert cfg["retrieval"]["chunk_size"] == 1000
|
| 23 |
assert cfg["retrieval"]["chunk_overlap"] == 100
|
| 24 |
+
assert cfg["retrieval"]["top_k"] == 50
|
| 25 |
+
assert cfg["retrieval"]["max_distance"] == 0.55
|
| 26 |
assert cfg["embeddings"]["provider"] == "local"
|
| 27 |
# Query understanding config
|
| 28 |
assert cfg["query_understanding"]["enabled"] is True
|