adeshboudh16 commited on
Commit
cfd62b3
Β·
1 Parent(s): f8b04c3

test and docs

Browse files
Files changed (2) hide show
  1. docs/RAG.md +635 -0
  2. scripts/score_reranker.py +104 -0
docs/RAG.md ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CivicSetu β€” RAG Techniques Reference
2
+
3
+ **Version:** 2.0 β€” Phase 8 (RAGAS Evaluation)
4
+ **Last Updated:** April 2026
5
+
6
+ This document covers every retrieval-augmented generation technique used in CivicSetu,
7
+ why each decision was made, and what it costs when it goes wrong.
8
+
9
+ ---
10
+
11
+ ## 1. System Overview
12
+
13
+ CivicSetu is a **legal domain RAG system** over five Indian RERA jurisdictions.
14
+ The core challenge: legal text is highly structured (section numbers, cross-references,
15
+ state vs central hierarchy) and users ask imprecise plain-English questions that need
16
+ precise legal citations. Standard RAG fails here because:
17
+
18
+ - Dense embeddings miss entity distinctions ("promoter" vs "agent" look similar at 768 dims)
19
+ - Query strings rarely contain the exact legal keywords in the source text
20
+ - Single-source retrieval misses the two-law comparison needed for conflict queries
21
+ - Generator LLMs "fill in the gaps" with legal reasoning not present in context
22
+
23
+ Every technique below addresses one of these failure modes.
24
+
25
+ ---
26
+
27
+ ## 2. Ingestion Pipeline
28
+
29
+ ### 2.1 PDF Parsing
30
+
31
+ `ingestion/parser.py` uses **PyMuPDF** for text extraction. Key guards:
32
+ - `max_pages` per document β€” UP Rules truncate at page 24 (pages 25–52 are government forms),
33
+ Tamil Nadu at page 15 (pages 16–101 are Forms A–O)
34
+ - Scanned page detection β€” Karnataka's official PDF is a 19MB image scan; NAREDCO mirror used instead
35
+ - `total_pages` in metadata reflects the capped count, not the PDF total
36
+
37
+ ### 2.2 Section Boundary Chunking
38
+
39
+ `ingestion/chunker.py` applies **six regex patterns** in priority order. First match per line wins.
40
+
41
+ | # | Pattern | Example | Jurisdiction |
42
+ |---|---|---|---|
43
+ | 1 | `\n{id}.\n{title}` | `\n3.\nRegistration` | MahaRERA |
44
+ | 2 | `{id}. {title}.β€”` | `3. Registration.β€”` | MahaRERA |
45
+ | 3 | `Rule {id} - {title}` | `Rule 3 - Application` | Generic |
46
+ | 4 | `{id}. {title}.–` | `3. Application.–` | Karnataka, Tamil Nadu |
47
+ | 5 | `{id}-(1)\n{title}` | `3-(1)\nApplication` | UP RERA (multi-clause) |
48
+ | 6 | `{id}-\n{title}` | `3-\nApplication` | UP RERA (single-clause) |
49
+
50
+ `DocType.ACT` uses a separate pattern set. Fallback: paragraph split on double newlines,
51
+ logged as `fallback_paragraph_chunking`.
52
+
53
+ **Chunk size limits:**
54
+
55
+ ```
56
+ MIN_CHARS = 100 β€” discard page headers, footnotes, empty sections
57
+ MAX_CHARS = 1500 β€” split large sections at subsection markers
58
+ ```
59
+
60
+ **Large section splitting priority:**
61
+ 1. Subsection markers: `\n\s*\((?:\d+|[a-z]{1,3})\)\s+`
62
+ 2. Sentence boundary near MAX_CHARS: `rfind('. ')`
63
+ 3. Hard cut at MAX_CHARS (last resort, logs a warning)
64
+
65
+ Sub-chunks get IDs like `"11(1)"`, `"11(2)"` β€” the base section becomes `"11"`.
66
+
67
+ ### 2.3 Deterministic Chunk IDs
68
+
69
+ `chunk_id` is a **UUID5 hash** of `(doc_id, section_id, chunk_index)`. This makes
70
+ re-ingestion idempotent β€” the same section always gets the same UUID, so `ON CONFLICT DO UPDATE`
71
+ replaces rather than duplicates. Earlier versions used random UUIDs; re-ingest doubled the corpus.
72
+
73
+ ### 2.4 Section Title Prepended to Embeddings
74
+
75
+ `ingestion/pipeline.py` prepends `section_title` to the text before embedding:
76
+
77
+ ```python
78
+ texts = [
79
+ f"{c['section_title']}\n{c['text']}" if c.get('section_title') else c['text']
80
+ for c in raw_chunks
81
+ ]
82
+ ```
83
+
84
+ **Why:** Sub-chunks (e.g. `S.11(2)`, `S.11(3)`) split off from a parent section carry
85
+ the body text but lose the section header. Without prepending, a query for
86
+ "obligations of promoter" cannot match sub-chunks of Section 11 via cosine similarity
87
+ because the phrase "obligations of promoter" never appears in their raw text.
88
+ After prepending, every sub-chunk embeds: `"Obligations of promoter\n[sub-clause text]"`.
89
+
90
+ Note: the **reranker** still receives raw `chunk.text` (without the title prefix),
91
+ so it scores on the actual legal text content.
92
+
93
+ ### 2.5 Embedding Model
94
+
95
+ **Model:** `nomic-embed-text-v1.5` via `sentence-transformers` (local, no Ollama required)
96
+ **Dimension:** 768
97
+ **Asymmetric prefixes** (MTEB/nomic-embed requirement):
98
+
99
+ ```
100
+ Ingestion: "search_document: {section_title}\n{text}"
101
+ Query: "search_query: {rewritten_query}"
102
+ ```
103
+
104
+ Using the wrong prefix at query time causes ~10–15% recall degradation.
105
+
106
+ **Truncation guard:**
107
+ ```python
108
+ MAX_EMBED_CHARS = 4000 # ~1000 tokens
109
+ text = text[:MAX_EMBED_CHARS] # BEFORE adding prefix
110
+ prefixed = f"search_document: {text.strip()}"
111
+ ```
112
+
113
+ ---
114
+
115
+ ## 3. Query Pipeline
116
+
117
+ ### 3.1 Query Classification and Rewriting
118
+
119
+ `agent/nodes.py::classifier_node` calls an LLM with `CLASSIFIER_PROMPT` to produce:
120
+
121
+ ```json
122
+ {
123
+ "query_type": "fact_lookup | cross_reference | temporal | penalty_lookup | conflict_detection",
124
+ "rewritten_query": "expanded query for better retrieval"
125
+ }
126
+ ```
127
+
128
+ **Classification rules (first match wins):**
129
+
130
+ | Type | Trigger | Retrieval Route |
131
+ |---|---|---|
132
+ | `conflict_detection` | Keywords: conflict, contradict, inconsistent, override, vs | `hybrid_retrieval` |
133
+ | `penalty_lookup` | Fine, jail, imprisonment, consequences | `graph_retrieval` |
134
+ | `temporal` | Timeline, deadline, days, months, period, within, stage-wise | `graph_retrieval` |
135
+ | `cross_reference` | Explicit section number ("Section 18", "Rule 3") | `graph_retrieval` |
136
+ | `fact_lookup` | Everything else | `vector_retrieval` |
137
+
138
+ **Query rewriting** expands the query to include legal keywords that appear in source text.
139
+ Key use case: temporal queries. "What is the timeline for project registration?" becomes
140
+ `"grant or reject registration within thirty days deemed registered period"` β€” now FTS
141
+ can match Section 5 which uses exactly those words.
142
+
143
+ **Fallback:** if classifier fails to parse JSON, defaults to `fact_lookup` with original query.
144
+
145
+ ### 3.2 LLM Routing and Fallback Chain
146
+
147
+ All LLM calls go through `_llm_call()` which tries models in order:
148
+
149
+ ```
150
+ 1. gemini/gemini-2.5-flash-lite (Gemini API, GEMINI_API_KEY)
151
+ 2. openrouter/meta-llama/llama-3.3-70b-instruct:free (OpenRouter, OPENROUTER_API_KEY)
152
+ 3. groq/llama-3.3-70b-versatile (Groq, GROQ_API_KEY)
153
+ ```
154
+
155
+ **Gemini temperature quirk:** Gemini 3.x models degrade below `temperature=1.0`. The
156
+ fallback chain auto-sets `effective_temp = 1.0 if "gemini-3" in model else 0.0`.
157
+
158
+ All legal reasoning uses `temperature=0.0` β€” determinism over creativity.
159
+
160
+ ---
161
+
162
+ ## 4. Hybrid Retrieval β€” `_rrf_retrieve()`
163
+
164
+ The core retrieval function is `_rrf_retrieve()` (shared across all retrieval nodes).
165
+ It combines **three retrieval signals** into one ranked list:
166
+
167
+ ### 4.1 Vector Similarity Search
168
+
169
+ ```python
170
+ vector_results = await VectorStore.similarity_search(
171
+ query_embedding=embed_query(rewritten_query),
172
+ top_k=top_k * 3, # fetch 3Γ— to give RRF enough candidates
173
+ jurisdiction=filter
174
+ )
175
+ ```
176
+
177
+ **Index:** HNSW with cosine similarity on 768-dim vectors.
178
+ **Strengths:** Catches semantic matches β€” "penalties for building without approval" matches
179
+ "consequence of non-registration" even without keyword overlap.
180
+ **Weakness:** Embeddings for sub-clauses of large sections lose their section context.
181
+ Fixed by section title prepending during ingestion (Β§2.4).
182
+
183
+ ### 4.2 Full-Text Search (PostgreSQL `tsvector`)
184
+
185
+ ```python
186
+ fts_results = await VectorStore.full_text_search(
187
+ query=rewritten_query,
188
+ top_k=top_k * 2,
189
+ jurisdiction=filter
190
+ )
191
+ ```
192
+
193
+ **Query operator:** `websearch_to_tsquery` in OR mode β€” each word becomes an independent
194
+ FTS term. Changed from `plainto_tsquery` (AND-mode) because legal queries contain
195
+ both relevant and irrelevant words; AND-mode required all words to match, excluding
196
+ relevant sections that only matched most words.
197
+
198
+ **Strengths:** Exact entity matches β€” "Section 59" or "promoter" finds the right chunks
199
+ even when semantic similarity is ambiguous.
200
+ **Weakness:** Misses synonyms, paraphrased text, and queries whose words don't appear
201
+ verbatim in the legal text.
202
+
203
+ ### 4.3 Reciprocal Rank Fusion (RRF)
204
+
205
+ `_rrf_merge()` merges vector and FTS results:
206
+
207
+ ```python
208
+ RRF_K = 60 # standard constant β€” higher = smoother blending
209
+
210
+ rrf_score(chunk) = 1/(K + rank_in_vector) + 1/(K + rank_in_fts)
211
+ ```
212
+
213
+ Chunks appearing in **both** result sets score highest (both terms add). A chunk at
214
+ rank 1 in vector but absent from FTS scores `1/(60+1) β‰ˆ 0.016`. A chunk at rank 3
215
+ in both scores `1/63 + 1/63 β‰ˆ 0.032` β€” higher than vector-only rank 1.
216
+
217
+ **Effect:** Sections that both semantically match AND contain the right legal keywords
218
+ float to the top. Pure vector or pure FTS results that lack overlap with the other
219
+ signal drop naturally.
220
+
221
+ ### 4.4 Section Family Expansion
222
+
223
+ After RRF merge, the top-3 results trigger **family expansion**:
224
+
225
+ ```python
226
+ for rc in merged[:3]:
227
+ sid = rc.chunk.section_id # e.g. "5(4)"
228
+ base_sid = re.sub(r'\([^)]*\)$', '', sid).strip() # β†’ "5"
229
+ for expand_sid in {sid, base_sid}:
230
+ family = await VectorStore.get_section_family(
231
+ section_id=expand_sid, jurisdiction=jur
232
+ )
233
+ # adds parent section + all sibling sub-sections
234
+ ```
235
+
236
+ `get_section_family` queries: `section_id = '5'` OR `section_id LIKE '5(%'` β€” returns
237
+ the base section plus all sub-sections (`5(1)`, `5(2)`, `5(3)`, `5(4)`, `5(5)`).
238
+
239
+ **Guard:** if `section_id` already contains `(`, expansion is skipped to avoid double-expanding
240
+ sub-sections. The code strips the parenthetical suffix first (`"5(4)"` β†’ `"5"`) before calling
241
+ expansion, so sub-sections found by RRF still trigger their parent section's family.
242
+
243
+ **Why this matters:** Large sections (S.11 "Obligations of promoter") are split into 10+
244
+ sub-chunks. If only `S.11(3)` appears in the RRF top-10, family expansion pulls in
245
+ `S.11` (main), `S.11(1)`, `S.11(2)` etc. β€” the full context the generator needs.
246
+
247
+ **Cap:** `_MAX_VECTOR_EXPANDED = 40` β€” prevents excessive reranker load.
248
+
249
+ ---
250
+
251
+ ## 5. Graph-Based Retrieval
252
+
253
+ Used for `cross_reference`, `penalty_lookup`, `temporal` query types.
254
+
255
+ ### 5.1 Section ID Extraction
256
+
257
+ ```python
258
+ section_pattern = re.compile(r'\b(?:section|sec\.?|s\.)\s*(\d+[A-Z]?)\b', re.IGNORECASE)
259
+ rule_pattern = re.compile(r'\bRule\s+(\d+[A-Z]?)\b', re.IGNORECASE)
260
+ ```
261
+
262
+ If no section ID found in query, falls back to `_rrf_retrieve()` (hybrid retrieval).
263
+
264
+ ### 5.2 Neo4j Traversal
265
+
266
+ For each detected section ID, across all relevant jurisdictions:
267
+
268
+ ```
269
+ 1. Source section chunks β€” exact section_id match β†’ is_pinned=True
270
+ 2. REFERENCES outgoing β€” sections the source cites (depth=2)
271
+ 3. REFERENCES incoming β€” sections that cite the source
272
+ 4. DERIVED_FROM outgoing β€” Act sections this State Rule derives from
273
+ 5. DERIVED_FROM incoming β€” State Rule sections implementing this Act section
274
+ ```
275
+
276
+ **DERIVED_FROM** is the cross-jurisdiction link. When user asks about Maharashtra Rule 3,
277
+ traversal follows `DERIVED_FROM` to RERA Act Section 4 β€” so both jurisdictions appear
278
+ in context without needing to explicitly mention both.
279
+
280
+ ### 5.3 Pinning Rule
281
+
282
+ Exact `section_id` matches get `is_pinned=True`. Pinned chunks are prepended to
283
+ reranker output β€” they bypass score-based ordering. This prevents a highly relevant
284
+ source section from being demoted if the cross-encoder scores some related section higher.
285
+
286
+ ---
287
+
288
+ ## 6. Reranking
289
+
290
+ ### 6.1 FlashRank Cross-Encoder
291
+
292
+ `retrieval/reranker.py` uses **FlashRank** with `rank-T5-flan`:
293
+
294
+ ```python
295
+ from flashrank import Ranker, RerankRequest
296
+ ranker = Ranker(model_name="rank-T5-flan", cache_dir=".cache/flashrank")
297
+
298
+ passages = [{"text": c.chunk.text} for c in non_pinned]
299
+ request = RerankRequest(query=state["query"], passages=passages)
300
+ results = ranker.rerank(request)
301
+ ```
302
+
303
+ The cross-encoder reads the **query** and **chunk text** together in a single forward pass,
304
+ producing a relevance score (0.0–1.0). This is far more accurate than cosine similarity
305
+ but ~10Γ— slower β€” hence the `_MAX_VECTOR_EXPANDED=40` cap upstream.
306
+
307
+ **Inputs:** raw `chunk.text` β€” NOT the section-title-prefixed version used at embedding time.
308
+ The title prefix is for embedding quality; the cross-encoder scores on the actual legal text.
309
+
310
+ ### 6.2 Score Gap Filter β€” `_apply_score_gap()`
311
+
312
+ ```python
313
+ def _apply_score_gap(chunks, gap=0.6):
314
+ """Drop chunks after the first score cliff β‰₯ gap."""
315
+ for i in range(1, len(chunks)):
316
+ if chunks[i - 1].rerank_score - chunks[i].rerank_score >= gap:
317
+ return chunks[:i]
318
+ return chunks
319
+ ```
320
+
321
+ **Purpose:** Stop including chunks once there is a large quality drop. A top chunk at
322
+ score 0.98 followed by a chunk at 0.30 represents a genuine relevance cliff β€” the 0.30
323
+ chunk is noise, not context.
324
+
325
+ **Threshold values:**
326
+ - `reranker_score_threshold = 0.1` β€” minimum score to enter candidate pool (filters near-zero)
327
+ - `reranker_score_gap = 0.6` β€” cliff threshold
328
+
329
+ **Tuning history:** Original values were `threshold=0.3, gap=0.35`. The gap of 0.35
330
+ was too aggressive β€” a chunk scoring 0.52 after one scoring 0.88 was cut (gap=0.36 β‰₯ 0.35),
331
+ leaving only 1 context chunk for the generator. Increasing to 0.6 keeps reasonable
332
+ secondary chunks while still cutting genuine noise.
333
+
334
+ ### 6.3 Final Context Assembly
335
+
336
+ ```python
337
+ slots_for_ranked = max(0, 5 - len(pinned))
338
+ reranked = pinned + gap_filtered[:slots_for_ranked]
339
+ ```
340
+
341
+ Maximum 5 context chunks: pinned first, then reranker-scored chunks. This is the input
342
+ to the generator prompt as numbered blocks `[1]`, `[2]`, ..., `[5]`.
343
+
344
+ ---
345
+
346
+ ## 7. Generation
347
+
348
+ ### 7.1 Generator Prompt Structure
349
+
350
+ `prompts/generator.py` β€” the generator is instructed to:
351
+
352
+ 1. Open with plain-English summary (1–3 sentences, no jargon)
353
+ 2. Bulleted key points using only information from provided context
354
+ 3. Note connections, contradictions, exceptions
355
+ 4. Close with section references
356
+
357
+ **Output schema:**
358
+ ```json
359
+ {
360
+ "answer": "<markdown>",
361
+ "confidence_score": 0.0-1.0,
362
+ "cited_chunks": [1, 3],
363
+ "amendment_notice": null,
364
+ "conflict_warnings": []
365
+ }
366
+ ```
367
+
368
+ ### 7.2 Grounding Rules
369
+
370
+ Critical rules that prevent hallucination on sparse contexts:
371
+
372
+ - **Only use context** β€” never external legal knowledge or training data
373
+ - **Sparse context handling** β€” if context lacks the answer, say "Based on the available context: [X]" and explicitly note "The context does not contain sufficient information to determine [Y]"
374
+ - **Conflict detection grounding** β€” only assert a conflict exists if BOTH conflicting provisions appear in the context. If only one side is present: "The context contains [jurisdiction X's position] but does not include [jurisdiction Y's position] to confirm or deny a conflict"
375
+ - **No invented citations** β€” never invent section numbers, legal provisions, or figures not in context
376
+ - **Confidence calibration** β€” if `cited_chunks` is empty, `confidence_score` must be < 0.3
377
+
378
+ ### 7.3 Tone Hints per Query Type
379
+
380
+ Each query type receives a tone instruction injected into the generator system prompt:
381
+
382
+ | Type | Tone hint |
383
+ |---|---|
384
+ | `fact_lookup` | Give a direct answer and include one helpful analogy |
385
+ | `penalty_lookup` | Lead with the consequence, then explain why it applies |
386
+ | `cross_reference` | Explain the connection between sections as a narrative |
387
+ | `conflict_detection` | Only flag contradiction if BOTH sides appear in context; never infer precedence |
388
+ | `temporal` | Explain what changed, when, and why it matters |
389
+
390
+ ### 7.4 Citation Extraction
391
+
392
+ The generator returns 1-based indices (`cited_chunks: [1, 3]`) into the numbered context
393
+ blocks. The agent extracts `CivicSetuResponse.citations` from only those positions β€”
394
+ not all retrieved chunks. This ensures citations are grounded in what the LLM actually read.
395
+
396
+ ---
397
+
398
+ ## 8. Validation
399
+
400
+ ### 8.1 Validator Node
401
+
402
+ `nodes.py::validator_node` sends the answer back to an LLM with the same numbered context
403
+ blocks the generator used, asking:
404
+
405
+ - Is each claim in the answer supported by the provided context?
406
+ - Confidence score: 0.0–1.0
407
+ - `hallucination_flag`: True if any claim is not grounded
408
+
409
+ **Context format matters:** The validator must receive context in the same `[N] doc β€” section: title\ntext`
410
+ format the generator used. Early versions passed raw `chunk.text` β€” the validator couldn't
411
+ match "Section 11(1)" claims to source chunks that never contained "Section 11(1)" in their text,
412
+ causing spurious `hallucination=True` flags and retry loops.
413
+
414
+ ### 8.2 Retry Logic
415
+
416
+ ```
417
+ confidence >= 0.5 AND not hallucinated β†’ END
418
+ (confidence < 0.5 OR hallucinated) AND retry_count < 2 β†’ retry β†’ classifier
419
+ retry_count >= 2 β†’ END (low confidence answer)
420
+ ```
421
+
422
+ Max 2 retries. On retry, the classifier runs again with the original query β€” a different
423
+ model in the fallback chain may produce a better rewrite.
424
+
425
+ ### 8.3 Output Guardrails
426
+
427
+ `guardrails/output_guard.py`:
428
+ - Confidence floor: 0.30 β€” below this threshold, returns `InsufficientInfoResponse`
429
+ - Disclaimer injection: always appended to every response
430
+ - PII check not repeated (done at input)
431
+
432
+ ---
433
+
434
+ ## 9. RAGAS Evaluation Pipeline
435
+
436
+ ### 9.1 Architecture β€” Two-Phase with Caching
437
+
438
+ Phase 1 (slow, ~2–3 min): invoke the RAG graph for every query β†’ save to `eval_phase1_results.json`
439
+ Phase 2 (fast, ~1 min): score cached results with RAGAS β†’ save to `eval_results.json`
440
+
441
+ This separation allows iterating on RAGAS scoring (prompt changes, judge model changes)
442
+ without re-invoking the full RAG pipeline. Phase 1 cache is invalidated manually via `make eval-reset`.
443
+
444
+ ```bash
445
+ make eval-smoke-p1 # Phase 1: run graph for 5-row smoke dataset
446
+ make eval-smoke-p2 # Phase 2: score the 5 cached rows
447
+ make eval-reset # Clear both caches (re-runs everything)
448
+ make eval-p1 # Phase 1: full 31-row golden dataset
449
+ make eval-p2 # Phase 2: score all 31 rows
450
+ ```
451
+
452
+ ### 9.2 Golden Dataset
453
+
454
+ `eval/golden_dataset.jsonl` β€” 31 rows across 5 jurisdictions and all 5 query types.
455
+
456
+ Each row:
457
+ ```json
458
+ {
459
+ "id": "CENTRAL-FACT-001",
460
+ "jurisdiction": "CENTRAL",
461
+ "query_type": "fact_lookup",
462
+ "query": "What are the obligations of a promoter under RERA?",
463
+ "ground_truth": "Under Section 11...",
464
+ "expected_section_ids": ["Section 11", "Section 4"],
465
+ "tags": ["promoter", "obligations"]
466
+ }
467
+ ```
468
+
469
+ **Coverage:**
470
+
471
+ | Jurisdiction | fact | xref | temporal | penalty | conflict | Total |
472
+ |---|---|---|---|---|---|---|
473
+ | CENTRAL | 2 | 1 | 1 | 1 | 1 | 6 |
474
+ | MAHARASHTRA | 1 | 1 | 1 | 1 | 1 | 5 |
475
+ | UTTAR_PRADESH | 1 | 1 | 1 | 1 | 1 | 5 |
476
+ | KARNATAKA | 1 | 1 | 1 | 1 | 1 | 5 |
477
+ | TAMIL_NADU | 1 | 1 | 1 | 1 | 1 | 5 |
478
+ | MULTI (null jur) | 1 | 1 | 1 | 1 | 1 | 5 |
479
+ | **Total** | | | | | | **31** |
480
+
481
+ ### 9.3 RAGAS Metrics
482
+
483
+ Three metrics computed per row:
484
+
485
+ **Faithfulness** β€” are all claims in the answer grounded in the retrieved contexts?
486
+ ```
487
+ faithfulness = (claims supported by context) / (total claims in answer)
488
+ ```
489
+ Score 1.0 = fully grounded. Score 0.0 = complete hallucination.
490
+
491
+ **Answer Relevancy** β€” does the answer actually address the question?
492
+ ```
493
+ answer_relevancy = similarity(answer, question) averaged over generated question variants
494
+ ```
495
+ RAGAS generates N paraphrased questions from the answer, embeds them, and measures cosine
496
+ similarity to the original question. High score = answer stays on topic.
497
+
498
+ **Context Precision** β€” are the retrieved contexts ranked in order of usefulness?
499
+ ```
500
+ context_precision = precision@k averaged over ranks
501
+ ```
502
+ Each context is scored by a judge LLM: "Is this context useful for answering the question
503
+ given the ground truth?" Contexts marked useful at rank 1 weight higher than rank 3.
504
+ A precision of 0.0 means none of the retrieved contexts were useful β€” retrieval failure.
505
+
506
+ ### 9.4 Judge LLM
507
+
508
+ RAGAS uses an LLM judge for faithfulness and context precision verdicts. Supported providers:
509
+
510
+ ```bash
511
+ JUDGE_PROVIDER=groq JUDGE_MODEL=llama-3.3-70b-versatile # default
512
+ JUDGE_PROVIDER=gemini JUDGE_MODEL=gemini/gemma-4-31b-it
513
+ JUDGE_PROVIDER=osmapi JUDGE_MODEL=qwen3.5-397b-a17b
514
+ ```
515
+
516
+ Judge API key can be rotated independently of the graph LLM:
517
+ ```bash
518
+ JUDGE_GEMINI_API_KEY=<alternate_key> make eval-smoke-p2
519
+ ```
520
+
521
+ **Rate limiting:** RAGAS calls the judge LLM once per context per row. With 3 contexts Γ— 31 rows,
522
+ that is ~93 judge calls. Free-tier APIs (Gemini 2.0 Flash: 10 RPM, 200 RPD) may be exhausted.
523
+ `PHASE2_DELAY_SEC=5` adds a delay between rows; `PHASE2_MAX_RETRIES=4` retries on 429.
524
+
525
+ ### 9.5 Context Trimming for Judge
526
+
527
+ Raw legal chunks can be 1500 chars. RAGAS judge prompt with 5 chunks Γ— 1500 chars exceeds
528
+ context limits. Trimming applied before Phase 2:
529
+
530
+ ```
531
+ RAGAS_MAX_CONTEXTS = 3 β€” only score top-3 contexts (not all 5)
532
+ RAGAS_CONTEXT_CHAR_LIMIT = 800 β€” trim each context to 800 chars
533
+ RAGAS_ANSWER_CHAR_LIMIT = 800 β€” trim answer to 800 chars
534
+ RAGAS_REFERENCE_CHAR_LIMIT = 600 β€” trim ground truth to 600 chars
535
+ ```
536
+
537
+ ### 9.6 Current Eval Results (5-row smoke, April 2026)
538
+
539
+ | Row | Query Type | Faithfulness | Relevancy | Prec | Root Issue |
540
+ |---|---|---|---|---|---|
541
+ | CENTRAL-FACT-001 | fact_lookup | 0.50 | ~0.80 | 0.00 | S.11 main demoted by reranker; sub-sections rank higher |
542
+ | CENTRAL-FACT-002 | fact_lookup | 0.62 | ~0.82 | 0.33 | S.19 at rank 3; judge awards partial credit |
543
+ | CENTRAL-XREF-001 | cross_reference | 0.50 | ~0.80 | 1.00 | S.18 at rank 1; garbage financial doc removed |
544
+ | CENTRAL-CONF-001 | conflict_detection | 0.62 | ~0.85 | 0.00 | Only central RERA retrieved; state rule missing |
545
+ | CENTRAL-TEMP-001 | temporal | 1.00 | ~0.72 | 0.00 | Generator says "insufficient info" β€” S.5 not in top-5 |
546
+
547
+ Overall: faithfulness=0.650, context_precision=0.267, pass_rate=0% (threshold=0.7)
548
+
549
+ ---
550
+
551
+ ## 10. Known Failure Modes
552
+
553
+ ### 10.1 Sub-Section Demotion (FACT-001)
554
+
555
+ **Symptom:** S.11 main ("Obligations of promoter") gets demoted by the cross-encoder even
556
+ though it's the target section. The cross-encoder scores S.11(2) and S.11(3) higher because
557
+ their body text contains specific duty clauses more directly relevant to the query.
558
+
559
+ **Why:** S.11 main's first sentence is procedural ("log in to the website with credentials..."),
560
+ not about obligations. Cross-encoder scores it lower.
561
+
562
+ **Mitigation options:**
563
+ - Pin parent section when any sub-section is retrieved (aggressive pinning)
564
+ - Rewrite the section text during ingestion to deduplicate procedural preambles
565
+ - Ask the generator to synthesize from all S.11 sub-sections even without S.11 main
566
+
567
+ ### 10.2 Single-Jurisdiction Retrieval for Conflict Detection (CONF-001)
568
+
569
+ **Symptom:** "How do state RERA rules differ from central RERA on registration?" retrieves
570
+ central RERA chunks but not the relevant state rule chunk. Faithfulness=0.62 (generator
571
+ uses hedging language), context_precision=0.00 (state rule not in context at all).
572
+
573
+ **Root cause:** `conflict_detection` routes to `hybrid_retrieval`, which does a single
574
+ RRF search. A query about "state vs central" is ambiguous β€” the embedding similarity
575
+ pulls toward whichever jurisdiction dominates the corpus.
576
+
577
+ **Planned fix:** Multi-query decomposition β€” run two separate RRF queries (one biased
578
+ toward central, one toward each state) and merge before reranking.
579
+
580
+ ### 10.3 Temporal Query FTS Miss (TEMP-001)
581
+
582
+ **Symptom:** Query "What is the timeline for project registration?" should retrieve S.5
583
+ (30-day rule). S.5 IS found by RRF and scores 0.99 on the cross-encoder, but sometimes
584
+ doesn't appear in the final top-5 due to S.4 family expansion filling pool slots.
585
+
586
+ **Root cause:** S.4(14) appears in the RRF top-10, which triggers expansion of the entire
587
+ S.4 family (14 sub-sections). These fill the `_MAX_VECTOR_EXPANDED=40` pool before
588
+ reranking, and after gap filtering S.4 sub-sections at low scores may still occupy slots
589
+ that S.5 would have used.
590
+
591
+ **Partial fix applied:** Classifier now rewrites temporal queries to include legal time
592
+ keywords ("grant or reject registration within thirty days deemed registered") β€” this
593
+ improves FTS recall of S.5.
594
+
595
+ ---
596
+
597
+ ## 11. Configuration Reference
598
+
599
+ All RAG parameters in `config/settings.py`:
600
+
601
+ | Parameter | Default | Effect |
602
+ |---|---|---|
603
+ | `reranker_model` | `rank-T5-flan` | Cross-encoder model |
604
+ | `reranker_score_threshold` | `0.1` | Min score to enter candidate pool |
605
+ | `reranker_score_gap` | `0.6` | Score cliff threshold for gap filter |
606
+ | `embedding_model` | `nomic-embed-text` | Sentence-transformers model name |
607
+ | `embedding_dimension` | `768` | pgvector index dimension |
608
+
609
+ Environment overrides for eval:
610
+
611
+ | Env Var | Effect |
612
+ |---|---|
613
+ | `EVAL_LIMIT` | Limit eval to first N rows (default: all) |
614
+ | `EVAL_PHASE` | "1" = phase 1 only, "2" = phase 2 only |
615
+ | `JUDGE_PROVIDER` | `groq` / `gemini` / `osmapi` |
616
+ | `JUDGE_MODEL` | Judge LLM model name |
617
+ | `JUDGE_GEMINI_API_KEY` | Alternate Gemini key for judge only |
618
+ | `PASS_THRESHOLD` | RAGAS pass threshold (default: 0.7) |
619
+ | `PHASE2_DELAY_SEC` | Delay between judge calls (default: 5) |
620
+ | `RAGAS_MAX_CONTEXTS` | Max contexts passed to judge (default: 3) |
621
+ | `RAGAS_CONTEXT_CHAR_LIMIT` | Char trim per context (default: 800) |
622
+
623
+ ---
624
+
625
+ ## 12. Implementation Checklist
626
+
627
+ When adding a new jurisdiction or document corpus:
628
+
629
+ - [ ] Add `DocumentSpec` to `document_registry.py` with correct `max_pages` to exclude forms
630
+ - [ ] Verify PDF is born-digital (not scanned) β€” use `pdffonts` or PyMuPDF `get_text()` check
631
+ - [ ] Run `make ingest --jurisdiction <JUR>` β€” check `fallback_paragraph_chunking` logs
632
+ - [ ] Verify chunk count in PostgreSQL (`SELECT COUNT(*), jurisdiction FROM legal_chunks GROUP BY 2`)
633
+ - [ ] Run `make eval-smoke-p1` and inspect retrieved contexts for new jurisdiction queries
634
+ - [ ] Add rows to `eval/golden_dataset.jsonl` covering all 5 query types for new jurisdiction
635
+ - [ ] Run `make eval-p1 && make eval-p2` β€” check context_precision for new rows β‰₯ 0.40
scripts/score_reranker.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Quick diagnostic: score specific chunks against a query using current reranker.
3
+ Usage: uv run python scripts/score_reranker.py
4
+ """
5
+ from flashrank import Ranker, RerankRequest
6
+
7
+ MODELS = ["rank-T5-flan", "ms-marco-MiniLM-L-12-v2"]
8
+ CACHE = ".cache/flashrank"
9
+
10
+ QUERY = "What does Section 18 say about refund obligations when a promoter fails to give possession?"
11
+
12
+ # Chunks to score β€” Section 18 relevant + Karnataka-13 irrelevant
13
+ PASSAGES = [
14
+ {
15
+ "id": 0,
16
+ "label": "Section 18 - return of amount and compensation",
17
+ "text": (
18
+ "Section 18. Return of amount and compensation. "
19
+ "(1) If the promoter fails to complete or is unable to give possession of an apartment, "
20
+ "plot or building,β€” (a) in accordance with the terms of the agreement for sale or, "
21
+ "as the case may be, duly completed by the date specified therein; or (b) due to "
22
+ "discontinuance of his business as a developer on account of suspension or revocation "
23
+ "of the registration under this Act or for any other reason, the promoter shall be "
24
+ "liable on demand to the allottees, in case the allottee wishes to withdraw from the "
25
+ "project, without prejudice to any other remedy available, to return the amount "
26
+ "received by him in respect of that apartment, plot, building, as the case may be, "
27
+ "with interest at such rate as may be prescribed in this behalf including compensation "
28
+ "in the manner as provided under this Act."
29
+ ),
30
+ },
31
+ {
32
+ "id": 1,
33
+ "label": "Section 18(2) - interest on delayed possession",
34
+ "text": (
35
+ "Section 18(2) Where an allottee does not intend to withdraw from the project, "
36
+ "he shall be paid, by the promoter, interest for every month of delay, till the "
37
+ "handing over of the possession, at such rate as may be prescribed."
38
+ ),
39
+ },
40
+ {
41
+ "id": 2,
42
+ "label": "Karnataka Rule 13 - Maintenance of books of accounts (IRRELEVANT)",
43
+ "text": (
44
+ "Rule 13. Maintenance and preservation of books of accounts, records and documents. "
45
+ "Every promoter shall maintain proper books of accounts, records and documents in "
46
+ "relation to each registered real estate project, separately, and such books of "
47
+ "accounts, records and documents shall be preserved for a period of not less than "
48
+ "five years after the completion of the project."
49
+ ),
50
+ },
51
+ {
52
+ "id": 3,
53
+ "label": "Section 19 - rights of allottees (somewhat related)",
54
+ "text": (
55
+ "Section 19. Rights and duties of allottees. (1) The allottee shall be entitled "
56
+ "to obtain the information relating to sanctioned plans, layout plans along with "
57
+ "the specifications, approved by the competent authority and such other information "
58
+ "as provided under this Act or the rules and regulations made thereunder. "
59
+ "(4) The allottee shall be entitled to claim the possession of apartment, plot or "
60
+ "building, as the case may be, and the promoter shall be liable to pay interest "
61
+ "for any delay in handing over such possession at the rate specified under the Act."
62
+ ),
63
+ },
64
+ ]
65
+
66
+
67
+ def score_model(model_name: str):
68
+ print(f"\n{'='*80}")
69
+ print(f"Model: {model_name}")
70
+ print(f"{'='*80}")
71
+ ranker = Ranker(model_name=model_name, cache_dir=CACHE)
72
+
73
+ passages = [{"id": p["id"], "text": p["text"]} for p in PASSAGES]
74
+ request = RerankRequest(query=QUERY, passages=passages)
75
+ results = ranker.rerank(request)
76
+
77
+ id_to_label = {p["id"]: p["label"] for p in PASSAGES}
78
+
79
+ print(f"{'Score':>8} {'ID':>3} Label")
80
+ print("-" * 80)
81
+ for r in sorted(results, key=lambda x: x["score"], reverse=True):
82
+ score = round(float(r["score"]), 4)
83
+ label = id_to_label[r["id"]]
84
+ marker = " ← IRRELEVANT" if r["id"] == 2 else ""
85
+ print(f"{score:>8.4f} {r['id']:>3} {label}{marker}")
86
+
87
+ karnataka_score = next(round(float(r["score"]), 4) for r in results if r["id"] == 2)
88
+ sec18_score = next(round(float(r["score"]), 4) for r in results if r["id"] == 0)
89
+ print(f"\nKarnataka-13: {karnataka_score} | Section 18: {sec18_score}")
90
+ if karnataka_score > sec18_score:
91
+ print("βœ— FAIL β€” irrelevant chunk ranked ABOVE Section 18")
92
+ else:
93
+ gap = round(sec18_score - karnataka_score, 4)
94
+ print(f"βœ“ PASS β€” Section 18 ranks above Karnataka-13 (gap={gap})")
95
+
96
+
97
+ def main():
98
+ print(f"Query: {QUERY}")
99
+ for model in MODELS:
100
+ score_model(model)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()