docresolve 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
docresolve/core.py ADDED
@@ -0,0 +1,2307 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ GOV-RAG with Gemini Embeddings
4
+
5
+ This version uses Google's Gemini API for embeddings instead of
6
+ local sentence-transformers. Useful when:
7
+ - You have network/proxy issues downloading models
8
+ - You want to use GCP infrastructure
9
+ - You prefer cloud-based embeddings
10
+
11
+ All other components (authority detection, conflict resolution) remain the same.
12
+ """
13
+
14
+ import os
15
+ import time
16
+ import re
17
+ import json
18
+ import glob
19
+ from dataclasses import dataclass, asdict
20
+ from collections import defaultdict
21
+ from typing import Dict, List, Optional
22
+
23
+ import numpy as np
24
+
25
+ from .chunker import chunk_text_with_locations
26
+
27
+ # The Google SDKs are optional: the packaged pipeline defaults to a local
28
+ # embedder and an OpenAI-compatible generator (see ``providers``). The Gemini
29
+ # classes below raise a clear error only if they are actually constructed.
30
+ USE_VERTEX_AI = False
31
+ try:
32
+ import vertexai
33
+ from vertexai.language_models import TextEmbeddingModel
34
+ USE_VERTEX_AI = True
35
+ except ImportError:
36
+ vertexai = None
37
+ TextEmbeddingModel = None
38
+ try:
39
+ import google.generativeai as genai
40
+ except ImportError:
41
+ genai = None
42
+
43
+
44
+ # ============================================================
45
+ # CONFIG
46
+ # ============================================================
47
+
48
+ # Vertex AI Configuration (project-based authentication)
49
+ VERTEX_AI_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT", None)
50
+ VERTEX_AI_REGION = os.getenv("VERTEX_AI_REGION", "us-central1")
51
+ VERTEX_AI_MODEL = "text-embedding-004" # or "textembedding-gecko@003"
52
+ VERTEX_AI_GENERATION_MODEL = "gemini-2.5-pro" # Gemini 2.5 Pro
53
+
54
+ # Fallback: AI Studio API Key (if not using Vertex AI)
55
+ GEMINI_API_KEY = os.getenv("GOOGLE_API_KEY", None)
56
+
57
+ # ============================================================
58
+ # SYSTEM PROMPT FOR FINAL EVIDENCE RESOLUTION
59
+ # ============================================================
60
+
61
+ SYSTEM_PROMPT = """You answer questions using only the supplied evidence passages and optional case context.
62
+ Read full passages, including conditions and exceptions. Never infer organizational authority
63
+ as verified fact: status, document type, authority scores, and scope similarity are inferred
64
+ signals only; scope similarity is not proof of applicability. Never invent precedence.
65
+
66
+ Choose exactly one decision:
67
+ - answered: evidence supports a direct answer, including its conditions and exceptions.
68
+ - unresolved_conflict: applicable evidence disagrees and documented precedence does not resolve it.
69
+ - needs_information: relevant rules exist, but essential facts about this case are missing.
70
+ - insufficient_evidence: retrieved passages do not support an answer.
71
+
72
+ Do not force a winner between equally applicable conflicting passages. Distinguish different
73
+ scope, explicitly superseded material, supporting context, and uncertain applicability. A
74
+ document saying it "supersedes" earlier documents is not itself superseded.
75
+
76
+ Return JSON only:
77
+ {
78
+ "decision": "answered|unresolved_conflict|needs_information|insufficient_evidence",
79
+ "answer": "Readable answer with all important conditions and exceptions.",
80
+ "short_answers": ["each distinct final answer as a short span; for an unresolved conflict, each competing answer"],
81
+ "citations": [
82
+ {"chunk_id": "exact supplied chunk id", "quote": "verbatim excerpt from that passage",
83
+ "treatment": "governing|supporting|superseded|different_scope|conflicting|uncertain",
84
+ "explanation": "brief plain-language treatment"}
85
+ ],
86
+ "explanation": "Brief explanation of this decision.",
87
+ "missing_information": [],
88
+ "clarification_question": null,
89
+ "selected_source": null,
90
+ "conflict_detected": false,
91
+ "confidence": "high|medium|low"
92
+ }
93
+ For unresolved conflicts, cite each materially competing passage and explain its treatment;
94
+ selected_source must be null. For needs_information, list the missing facts and ask a useful
95
+ clarification question. Use an empty citation list if evidence cannot support any citation.
96
+ When the decision is answered, selected_source must be the filename of the governing passage the
97
+ answer is taken from (never null). selected_source must exactly match a supplied filename and
98
+ appear in citations. Numeric claim metadata is a search aid, never a citation or proof."""
99
+
100
+ # GOV-RAG "answer-and-flag" conflict policy. Same governance reasoning as
101
+ # SYSTEM_PROMPT, but when applicable passages disagree and no governance signal
102
+ # (status, supersession, scope) separates them, the model commits to the
103
+ # better-corroborated value and flags the dissent instead of abstaining.
104
+ # ``unresolved_conflict`` is reserved for genuine ties.
105
+ SYSTEM_PROMPT_ANSWER_AND_FLAG = """You answer questions using only the supplied evidence passages and optional case context.
106
+ Read full passages, including conditions and exceptions. Never infer organizational authority
107
+ as verified fact: status, document type, authority scores, and scope similarity are inferred
108
+ signals only; scope similarity is not proof of applicability. Never invent precedence.
109
+
110
+ Choose exactly one decision:
111
+ - answered: evidence supports a direct answer, including its conditions and exceptions.
112
+ - unresolved_conflict: applicable passages disagree AND the competing values are equally
113
+ supported (see the tie rule below).
114
+ - needs_information: relevant rules exist, but essential facts about this case are missing.
115
+ - insufficient_evidence: retrieved passages do not support an answer.
116
+
117
+ Resolving disagreement, in order:
118
+ 1. Governance: a passage that is explicitly superseded, out of scope, or supporting context
119
+ does not compete. A document saying it "supersedes" earlier documents is not itself superseded.
120
+ 2. Corroboration: among the passages that do compete, prefer the value supported by more
121
+ independent documents (different filenames). Treat the "Corroboration" summary, when
122
+ supplied, as a count aid only; verify it against the passages.
123
+ 3. Consistency: prefer the value that agrees with the other facts in the evidence (dates,
124
+ places, names, totals) and that comes from a more specific, internally consistent passage.
125
+ 4. Tie rule: only if the competing values are supported by the same number of independent
126
+ documents and steps 1 and 3 do not separate them, choose unresolved_conflict.
127
+
128
+ When you commit under step 2 or 3, the decision is answered, conflict_detected is true, the
129
+ dissenting passage is cited with treatment "conflicting", and the explanation names the
130
+ rejected value and why it lost. short_answers must contain only the committed answer(s), never
131
+ the rejected value. If the question is ambiguous because several distinct entities share the
132
+ same name, give the correct answer for each entity; that is not a conflict.
133
+
134
+ Return JSON only:
135
+ {
136
+ "decision": "answered|unresolved_conflict|needs_information|insufficient_evidence",
137
+ "answer": "Readable answer with all important conditions and exceptions; mention flagged dissent briefly.",
138
+ "short_answers": ["each distinct final answer as a short span; for an unresolved conflict, each competing answer"],
139
+ "citations": [
140
+ {"chunk_id": "exact supplied chunk id", "quote": "verbatim excerpt from that passage",
141
+ "treatment": "governing|supporting|superseded|different_scope|conflicting|uncertain",
142
+ "explanation": "brief plain-language treatment"}
143
+ ],
144
+ "explanation": "Brief explanation of this decision, including how any conflict was resolved.",
145
+ "missing_information": [],
146
+ "clarification_question": null,
147
+ "selected_source": null,
148
+ "conflict_detected": false,
149
+ "confidence": "high|medium|low"
150
+ }
151
+ For unresolved conflicts, cite each materially competing passage and explain its treatment;
152
+ selected_source must be null. For needs_information, list the missing facts and ask a useful
153
+ clarification question. Use an empty citation list if evidence cannot support any citation.
154
+ When the decision is answered, selected_source must be the filename of the governing passage the
155
+ answer is taken from (never null). selected_source must exactly match a supplied filename and
156
+ appear in citations. Numeric claim metadata is a search aid, never a citation or proof."""
157
+
158
+ # GOV-RAG "two-stage" policy, stage 2. Stage 1 drafts an answer with the plain
159
+ # BASELINE_SYSTEM_PROMPT over the governance-ranked passages; this prompt then
160
+ # audits that draft against the evidence and the governance signals. The draft
161
+ # stands unless the evidence gives a concrete governance reason to change it,
162
+ # so the audit adds citations and conflict flags without re-deciding answers
163
+ # the plain reader already got right.
164
+ SYSTEM_PROMPT_VERIFY = """You audit a draft answer against the supplied evidence passages and optional case context.
165
+ The draft was written by a reader who saw the same passages but no governance signals.
166
+ Read full passages, including conditions and exceptions. Never infer organizational authority
167
+ as verified fact: status, document type, authority scores, and scope similarity are inferred
168
+ signals only; scope similarity is not proof of applicability. Never invent precedence.
169
+
170
+ Keep the draft's answer and short_answers unchanged unless one of these holds:
171
+ 1. Governance: the draft relies on a passage that is explicitly superseded or out of scope
172
+ while an applicable passage gives a different value. A document saying it "supersedes"
173
+ earlier documents is not itself superseded.
174
+ 2. Corroboration: the draft's value is contradicted by more independent documents (different
175
+ filenames) than support it.
176
+ 3. Unsupported: the draft's value does not appear in, and cannot be read from, any passage.
177
+ 4. Genuine tie: applicable passages give different values, each supported by the same number of
178
+ independent documents, and nothing in the evidence separates them. Only then choose
179
+ unresolved_conflict and give each competing value in short_answers.
180
+ If none holds, the decision is answered with the draft's short_answers. If a passage disagrees
181
+ but loses under rule 1 or 2, keep or adopt the winning value, set conflict_detected to true,
182
+ cite the dissenting passage with treatment "conflicting", and name the rejected value in the
183
+ explanation. When you change the draft, say which rule applied and why.
184
+
185
+ Return JSON only:
186
+ {
187
+ "decision": "answered|unresolved_conflict|needs_information|insufficient_evidence",
188
+ "answer": "Readable answer with all important conditions and exceptions; mention flagged dissent briefly.",
189
+ "short_answers": ["each distinct final answer as a short span; for an unresolved conflict, each competing answer"],
190
+ "citations": [
191
+ {"chunk_id": "exact supplied chunk id", "quote": "verbatim excerpt from that passage",
192
+ "treatment": "governing|supporting|superseded|different_scope|conflicting|uncertain",
193
+ "explanation": "brief plain-language treatment"}
194
+ ],
195
+ "explanation": "Brief explanation: draft kept or changed, and how any conflict was resolved.",
196
+ "missing_information": [],
197
+ "clarification_question": null,
198
+ "selected_source": null,
199
+ "conflict_detected": false,
200
+ "confidence": "high|medium|low"
201
+ }
202
+ For unresolved conflicts, cite each materially competing passage and explain its treatment;
203
+ selected_source must be null. Use an empty citation list if evidence cannot support any citation.
204
+ When the decision is answered, selected_source must be the filename of the governing passage the
205
+ answer is taken from (never null). selected_source must exactly match a supplied filename and
206
+ appear in citations. Numeric claim metadata is a search aid, never a citation or proof."""
207
+
208
+
209
+ def build_verify_prompt(question, candidates, draft, context=None):
210
+ """Stage-2 user turn: the evidence with governance signals, plus the stage-1 draft."""
211
+ draft_view = {k: draft.get(k) for k in ("decision", "answer", "short_answers", "selected_source")}
212
+ return (build_user_prompt(question, candidates, context=context, include_signals=True, corroboration=True)
213
+ .rsplit("Analyze the evidence", 1)[0]
214
+ + "Draft answer to audit:\n" + json.dumps(draft_view, ensure_ascii=True)
215
+ + "\n\nAudit the draft against the evidence and return the final answer in JSON format.")
216
+
217
+
218
+ # GOV-RAG "answer-and-flag v2" (changes A + C on top of answer-and-flag):
219
+ # A: corroboration decides only factual claims; competing opinions,
220
+ # recommendations or research outcomes that governance does not separate
221
+ # are an unresolved_conflict laid out neutrally with sources named.
222
+ # C: factual ties do not abstain; they are broken by consistency, then by
223
+ # background knowledge stated openly, with the dissent cited as conflicting.
224
+ # Built from SYSTEM_PROMPT_ANSWER_AND_FLAG by exact replacements so nothing
225
+ # else differs; the asserts fail loudly if the base prompt ever changes.
226
+ def _build_answer_and_flag_v2(base):
227
+ swaps = [
228
+ ("""- unresolved_conflict: applicable passages disagree AND the competing values are equally
229
+ supported (see the tie rule below).""",
230
+ """- unresolved_conflict: applicable passages give competing opinions, recommendations or research
231
+ outcomes that can legitimately differ, and governance does not separate them. A disagreement
232
+ about a factual claim is never an unresolved_conflict."""),
233
+ ("""2. Corroboration: among the passages that do compete, prefer the value supported by more
234
+ independent documents (different filenames). Treat the "Corroboration" summary, when
235
+ supplied, as a count aid only; verify it against the passages.
236
+ 3. Consistency: prefer the value that agrees with the other facts in the evidence (dates,
237
+ places, names, totals) and that comes from a more specific, internally consistent passage.
238
+ 4. Tie rule: only if the competing values are supported by the same number of independent
239
+ documents and steps 1 and 3 do not separate them, choose unresolved_conflict.
240
+
241
+ When you commit under step 2 or 3, the decision is answered, conflict_detected is true, the
242
+ dissenting passage is cited with treatment "conflicting", and the explanation names the
243
+ rejected value and why it lost. short_answers must contain only the committed answer(s), never
244
+ the rejected value.""",
245
+ """2. Kind of disagreement: a factual claim is a number, date, name, place or event that has one
246
+ true value. Opinions, recommendations and research outcomes can legitimately differ.
247
+ 3. Opinions, recommendations, research outcomes: if step 1 does not separate them, do not pick
248
+ a side and do not count documents. Choose unresolved_conflict, lay out each position
249
+ neutrally in the answer naming the sources (filenames) that hold it, cite each with
250
+ treatment "conflicting", and list each position in short_answers.
251
+ 4. Factual claims, corroboration: prefer the value supported by more independent documents
252
+ (different filenames). Treat the "Corroboration" summary, when supplied, as a count aid
253
+ only; verify it against the passages.
254
+ 5. Factual ties: do not abstain. Break the tie by consistency: prefer the value that agrees with
255
+ the other facts in the evidence (dates, places, names, totals) and that comes from a more
256
+ specific, internally consistent passage. If that does not separate them, use your background
257
+ knowledge and say so openly in the answer and explanation.
258
+
259
+ When you commit under step 4 or 5, the decision is answered, conflict_detected is true, the
260
+ dissenting passage is cited with treatment "conflicting", and the explanation names the
261
+ rejected value and why it lost. short_answers must contain exactly one committed value for the
262
+ conflict, never the rejected value."""),
263
+ ]
264
+ for old, new in swaps:
265
+ assert base.count(old) == 1, "answer-and-flag base prompt changed; rebuild v2"
266
+ base = base.replace(old, new)
267
+ return base
268
+
269
+
270
+ SYSTEM_PROMPT_ANSWER_AND_FLAG_V2 = _build_answer_and_flag_v2(SYSTEM_PROMPT_ANSWER_AND_FLAG)
271
+
272
+
273
+ # GOV-RAG "answer-and-flag A" (change A alone on top of answer-and-flag; C reverted):
274
+ # corroboration decides only factual claims; competing opinions, recommendations
275
+ # or research outcomes that governance does not separate are an
276
+ # unresolved_conflict laid out neutrally with sources named. Factual ties keep
277
+ # the original tie rule (abstain as unresolved_conflict), and the original
278
+ # short_answers wording is kept. Same exact-replacement construction as v2.
279
+ def _build_answer_and_flag_a(base):
280
+ swaps = [
281
+ ("""- unresolved_conflict: applicable passages disagree AND the competing values are equally
282
+ supported (see the tie rule below).""",
283
+ """- unresolved_conflict: applicable passages give competing opinions, recommendations or research
284
+ outcomes that governance does not separate, or competing factual values that are equally
285
+ supported (see the tie rule below)."""),
286
+ ("""2. Corroboration: among the passages that do compete, prefer the value supported by more
287
+ independent documents (different filenames). Treat the "Corroboration" summary, when
288
+ supplied, as a count aid only; verify it against the passages.
289
+ 3. Consistency: prefer the value that agrees with the other facts in the evidence (dates,
290
+ places, names, totals) and that comes from a more specific, internally consistent passage.
291
+ 4. Tie rule: only if the competing values are supported by the same number of independent
292
+ documents and steps 1 and 3 do not separate them, choose unresolved_conflict.
293
+
294
+ When you commit under step 2 or 3,""",
295
+ """2. Kind of disagreement: a factual claim is a number, date, name, place or event that has one
296
+ true value. Opinions, recommendations and research outcomes can legitimately differ.
297
+ 3. Opinions, recommendations, research outcomes: if step 1 does not separate them, do not pick
298
+ a side and do not count documents. Choose unresolved_conflict, lay out each position
299
+ neutrally in the answer naming the sources (filenames) that hold it, cite each with
300
+ treatment "conflicting", and list each position in short_answers.
301
+ 4. Factual claims, corroboration: among the passages that do compete, prefer the value
302
+ supported by more independent documents (different filenames). Treat the "Corroboration"
303
+ summary, when supplied, as a count aid only; verify it against the passages.
304
+ 5. Factual claims, consistency: prefer the value that agrees with the other facts in the
305
+ evidence (dates, places, names, totals) and that comes from a more specific, internally
306
+ consistent passage.
307
+ 6. Factual tie rule: only if the competing factual values are supported by the same number of
308
+ independent documents and steps 1 and 5 do not separate them, choose unresolved_conflict.
309
+
310
+ When you commit under step 4 or 5,"""),
311
+ ]
312
+ for old, new in swaps:
313
+ assert base.count(old) == 1, "answer-and-flag base prompt changed; rebuild A"
314
+ base = base.replace(old, new)
315
+ return base
316
+
317
+
318
+ SYSTEM_PROMPT_ANSWER_AND_FLAG_A = _build_answer_and_flag_a(SYSTEM_PROMPT_ANSWER_AND_FLAG)
319
+
320
+
321
+ # GOV-RAG "answer-and-flag final" = A' + B + E + E' (BRIEF_final_policy.md incl. Revision 1), one prompt
322
+ # for every generator. Built from the A prompt by exact replacements:
323
+ # B (prompt part): when passages do not disagree and one addresses the question, answer it.
324
+ # (B's retrieval part, ranking conflict-free questions by retrieval score, is in
325
+ # GovRAGGemini.query; salvage after the single repair is run_generation's default.)
326
+ # E: the answer field holds the committed value(s) only; a rejected value may appear only in a
327
+ # final sentence that marks it as rejected; the dissent lives in the explanation and in the
328
+ # "conflicting" citation. Step numbers follow the A prompt (factual commits are steps 4 and 5).
329
+ def _build_answer_and_flag_final(a_prompt):
330
+ swaps = [
331
+ # A' (Revision 1): unresolved_conflict is evaluative-only; factual disagreements are
332
+ # always resolved. The brief numbers the tie rule "step 4" with steps 2/3 as
333
+ # corroboration/consistency (base prompt); in the A prompt those are steps 6, 4 and 5.
334
+ ("""- unresolved_conflict: applicable passages give competing opinions, recommendations or research
335
+ outcomes that governance does not separate, or competing factual values that are equally
336
+ supported (see the tie rule below).""",
337
+ """- unresolved_conflict: the competing passages disagree on a matter of opinion,
338
+ recommendation, interpretation or research outcome that can legitimately differ, and no
339
+ governance signal separates them. A disagreement about a fact (a number, date, name, place,
340
+ event or attribute) is never an unresolved conflict."""),
341
+ ("""6. Factual tie rule: only if the competing factual values are supported by the same number of
342
+ independent documents and steps 1 and 5 do not separate them, choose unresolved_conflict.""",
343
+ """6. Factual disagreements are always resolved: apply steps 4 and 5; if the counts are equal and
344
+ step 5 does not separate the values, commit to the value from the more specific, internally
345
+ consistent passage and set confidence to "low". Never resolve a disagreement from your own
346
+ knowledge: the committed value must appear in a supplied passage. If the passages describe
347
+ different entities that share a name, that is not a disagreement: give each entity its own
348
+ value."""),
349
+ ("""- insufficient_evidence: retrieved passages do not support an answer.
350
+ """,
351
+ """- insufficient_evidence: retrieved passages do not support an answer.
352
+
353
+ When the passages do not disagree and at least one of them addresses the question, answer it;
354
+ insufficient_evidence is for passages that are off-topic, not for passages that are merely brief.
355
+ """),
356
+ ("""When you commit under step 4 or 5, the decision is answered, conflict_detected is true, the
357
+ dissenting passage is cited with treatment "conflicting", and the explanation names the
358
+ rejected value and why it lost. short_answers must contain only the committed answer(s), never
359
+ the rejected value. If the question is ambiguous because several distinct entities share the
360
+ same name, give the correct answer for each entity; that is not a conflict.""",
361
+ """When you commit under step 4 or 5, the decision is answered, conflict_detected is true, the
362
+ dissenting passage is cited with treatment "conflicting", and the explanation names the
363
+ rejected value and why it lost. The "answer" field states the committed answer(s) only. Do not
364
+ list a rejected value in the answer as an additional figure, another possibility, or a
365
+ qualification in parentheses; a reader of the answer alone must see one value per entity. If
366
+ you mention a rejected value in the answer at all, do it in a separate final sentence that
367
+ says it is rejected and why, for example: "One source gives 12,345; that figure is rejected
368
+ because it is contradicted by the other documents." short_answers must contain only the
369
+ committed answer(s), never the rejected value. If the question is ambiguous because several
370
+ distinct entities share the same name, give the correct answer for each entity; that is not a
371
+ conflict, and each entity's value is committed in the same way."""),
372
+ (""" "answer": "Readable answer with all important conditions and exceptions; mention flagged dissent briefly.",""",
373
+ """ "answer": "Readable committed answer with all important conditions and exceptions. No rejected values except in a final sentence that marks them as rejected.","""),
374
+ (""" "explanation": "Brief explanation of this decision, including how any conflict was resolved.",""",
375
+ """ "explanation": "Brief explanation of this decision, including how any conflict was resolved and which value was rejected.",
376
+ "rejected_values": ["each value you rejected when resolving a factual disagreement, as a short span; empty if none"],"""),
377
+ ]
378
+ for old, new in swaps:
379
+ assert a_prompt.count(old) == 1, "answer-and-flag A prompt changed; rebuild final"
380
+ a_prompt = a_prompt.replace(old, new)
381
+ return a_prompt
382
+
383
+
384
+ SYSTEM_PROMPT_ANSWER_AND_FLAG_FINAL = _build_answer_and_flag_final(SYSTEM_PROMPT_ANSWER_AND_FLAG_A)
385
+
386
+
387
+ # Plain evidence-grounded RAG prompt used by the ``baseline`` mode. Same output
388
+ # schema so results are directly comparable, but no governance guidance: the
389
+ # model is simply asked to answer from the retrieved passages.
390
+ BASELINE_SYSTEM_PROMPT = """You answer questions using only the supplied evidence passages and optional case context.
391
+ Read the passages and answer the question as directly as you can from them. If the passages
392
+ disagree, use your best judgment about which answer the evidence supports.
393
+
394
+ Return JSON only:
395
+ {
396
+ "decision": "answered|unresolved_conflict|needs_information|insufficient_evidence",
397
+ "answer": "Readable answer.",
398
+ "short_answers": ["each distinct final answer as a short span"],
399
+ "citations": [
400
+ {"chunk_id": "exact supplied chunk id", "quote": "verbatim excerpt from that passage",
401
+ "treatment": "supporting|conflicting",
402
+ "explanation": "brief plain-language note"}
403
+ ],
404
+ "explanation": "Brief explanation of this answer.",
405
+ "missing_information": [],
406
+ "clarification_question": null,
407
+ "selected_source": "filename of the passage the answer is taken from, or null",
408
+ "conflict_detected": false,
409
+ "confidence": "high|medium|low"
410
+ }
411
+ Use "answered" whenever the passages support an answer. When the decision is answered,
412
+ selected_source must be the filename of the passage the answer is taken from (never null); it must
413
+ exactly match a supplied filename and must also appear in citations."""
414
+
415
+ # Closed-book control (``closedbook`` mode): no retrieved passages at all. A
416
+ # targeted few-shot chain-of-thought prompt whose worked examples match the
417
+ # task format (single answer, several answers when a name is ambiguous, and an
418
+ # honest "unknown"), so the control is a fair test of parametric knowledge.
419
+ CLOSED_BOOK_SYSTEM_PROMPT = """You answer questions from your own knowledge. No documents are provided.
420
+ Think step by step first: identify what the question refers to, recall what you know, check whether the
421
+ name could refer to several distinct things, and decide how confident you are. Then give the answer.
422
+
423
+ Rules:
424
+ - If the question is ambiguous because several distinct entities share the same name, give the correct answer
425
+ for each entity and list each one in short_answers with the entity in parentheses.
426
+ - If you do not know, say so: set decision to "insufficient_evidence" and leave short_answers empty.
427
+ Do not guess a specific value you cannot recall.
428
+ - short_answers holds each distinct final answer as a short span (a name, a number, a date, a phrase).
429
+
430
+ Return the reasoning, then JSON only:
431
+ {
432
+ "reasoning": "step-by-step thinking",
433
+ "decision": "answered|insufficient_evidence",
434
+ "answer": "Readable answer.",
435
+ "short_answers": ["short span", "..."],
436
+ "confidence": "high|medium|low"
437
+ }
438
+
439
+ Example 1
440
+ Question: Who wrote the novel Pride and Prejudice?
441
+ {
442
+ "reasoning": "Pride and Prejudice is an English novel first published in 1813. Its author is Jane Austen. The title is not shared by another well-known work, so there is one answer.",
443
+ "decision": "answered",
444
+ "answer": "Pride and Prejudice was written by Jane Austen and published in 1813.",
445
+ "short_answers": ["Jane Austen"],
446
+ "confidence": "high"
447
+ }
448
+
449
+ Example 2
450
+ Question: What is the population of Georgia?
451
+ {
452
+ "reasoning": "Georgia names two distinct places: the U.S. state and the country in the Caucasus. The question does not say which, so both answers are needed. The state had about 10.7 million residents in the 2020 census; the country has roughly 3.7 million people.",
453
+ "decision": "answered",
454
+ "answer": "The name is ambiguous. The U.S. state of Georgia had about 10.7 million residents in the 2020 census, while the country of Georgia has roughly 3.7 million people.",
455
+ "short_answers": ["about 10.7 million (U.S. state of Georgia, 2020 census)", "about 3.7 million (country of Georgia)"],
456
+ "confidence": "medium"
457
+ }
458
+
459
+ Example 3
460
+ Question: In what year was the Mill Creek covered bridge in Ashtabula County last repainted?
461
+ {
462
+ "reasoning": "This asks for a specific maintenance date for a small local structure. I have no reliable knowledge of it and guessing a year would likely be wrong.",
463
+ "decision": "insufficient_evidence",
464
+ "answer": "I do not know when that bridge was last repainted.",
465
+ "short_answers": [],
466
+ "confidence": "low"
467
+ }"""
468
+
469
+ INITIAL_RETRIEVAL_K = 30
470
+ FINAL_CONTEXT_K = 8
471
+
472
+ # Reranking weights
473
+ W_SEMANTIC = 0.30
474
+ W_AUTHORITY = 0.50
475
+ W_SCOPE = 0.20
476
+
477
+ # Relevance gate. Authority and scope bonuses only apply to chunks whose
478
+ # semantic similarity is within this margin of the most relevant retrieved
479
+ # chunk, fading linearly to zero at the margin. Without it, an authoritative
480
+ # document about an unrelated topic (similarity 0.57 vs 0.82 for the relevant
481
+ # ones) outranked every relevant passage purely on its authority score and
482
+ # filled most of the context window. Set to None to disable (pure additive).
483
+ RELEVANCE_GATE_MARGIN = 0.10
484
+
485
+
486
+ def relevance_gate(semantic, best_semantic, margin=None):
487
+ """Return a 0..1 multiplier for authority/scope bonuses."""
488
+ margin = RELEVANCE_GATE_MARGIN if margin is None else margin
489
+ if not margin or margin <= 0:
490
+ return 1.0
491
+ gate = (semantic - (best_semantic - margin)) / margin
492
+ return max(0.0, min(1.0, gate))
493
+
494
+
495
+ # ============================================================
496
+ # DATA STRUCTURES (same as original)
497
+ # ============================================================
498
+
499
+ @dataclass
500
+ class Document:
501
+ filename: str
502
+ text: str
503
+ embedding: Optional[np.ndarray] = None
504
+
505
+
506
+ @dataclass
507
+ class Candidate:
508
+ filename: str
509
+ text: str
510
+ semantic_score: float
511
+ authority_score: float
512
+ scope_score: float
513
+ claim: Optional[str]
514
+ claim_sentence: Optional[str]
515
+ status: str
516
+ doc_type: str
517
+ final_score: float = 0.0
518
+ chunk_index: Optional[int] = None
519
+ document_id: Optional[str] = None
520
+ chunk_id: Optional[str] = None
521
+ page_start: Optional[int] = None
522
+ page_end: Optional[int] = None
523
+ section: Optional[str] = None
524
+ relevance_gate: float = 1.0
525
+
526
+
527
+ @dataclass
528
+ class Chunk:
529
+ """A retrieval-unit slice of a document, preserving doc-level identity."""
530
+ filename: str
531
+ document_id: str
532
+ chunk_index: int
533
+ chunk_id: str
534
+ text: str
535
+ scope_text: Optional[str] = None
536
+ embedding: Optional[np.ndarray] = None
537
+ scope_embedding: Optional[np.ndarray] = None
538
+ page_start: Optional[int] = None
539
+ page_end: Optional[int] = None
540
+ section: Optional[str] = None
541
+
542
+
543
+ @dataclass
544
+ class DocumentMeta:
545
+ """Governance metadata computed once per whole document, reused by every chunk."""
546
+ status: str
547
+ doc_type: str
548
+ authority_raw: float
549
+
550
+
551
+ DECISIONS = {"answered", "unresolved_conflict", "needs_information", "insufficient_evidence"}
552
+ CITATION_TREATMENTS = {
553
+ "governing", "supporting", "superseded", "different_scope", "conflicting", "uncertain",
554
+ }
555
+
556
+
557
+ def format_location(page_start=None, page_end=None, section=None):
558
+ parts = []
559
+ if page_start is not None:
560
+ parts.append(f"page {page_start}" if page_start == page_end else f"pages {page_start}-{page_end}")
561
+ if section:
562
+ parts.append(f"section {section}")
563
+ return ", ".join(parts) or "chunk reference only"
564
+
565
+
566
+ def generation_failure(reason):
567
+ """A visible failure result. ``validation_error`` marks that this came from
568
+ the pipeline rejecting the model's output, not from the model deciding the
569
+ evidence was insufficient, so evaluations can tell the two apart."""
570
+ return {
571
+ "decision": "insufficient_evidence",
572
+ "answer": "No answer could be safely generated from the retrieved evidence.",
573
+ "citations": [],
574
+ "reason": reason,
575
+ "explanation": reason,
576
+ "missing_information": [],
577
+ "clarification_question": None,
578
+ "selected_source": None,
579
+ "conflict_detected": False,
580
+ "confidence": "low",
581
+ "validation_error": True,
582
+ }
583
+
584
+
585
+ # Characters that models routinely drop or alter when quoting Markdown
586
+ # passages: emphasis markers, code ticks, heading/quote markers, and
587
+ # typographic quotes/dashes. Quote verification compares both sides after
588
+ # removing or unifying them, so a verbatim quote of "**7,430 Quens**" that
589
+ # comes back as "7,430 Quens" still verifies.
590
+ _QUOTE_STRIP = re.compile(r"[*_`#>\[\]]")
591
+ _QUOTE_UNIFY = {
592
+ "‘": "'", "’": "'", "“": '"', "”": '"',
593
+ "–": "-", "—": "-", "…": "...", " ": " ",
594
+ }
595
+
596
+
597
+ def _normalized_quote(text):
598
+ text = text or ""
599
+ for src, dst in _QUOTE_UNIFY.items():
600
+ text = text.replace(src, dst)
601
+ text = _QUOTE_STRIP.sub("", text)
602
+ text = " ".join(text.split()).casefold()
603
+ # Models often wrap the quote in quotation marks or trailing ellipses.
604
+ return text.strip(" \"'.")
605
+
606
+
607
+ def quote_matches(quote, text):
608
+ """True if ``quote`` is a verbatim span of ``text`` after normalisation.
609
+
610
+ Models often shorten a long passage by joining two or more non-adjacent
611
+ spans with an ellipsis ("A ... B"). Each span is then verified separately
612
+ and must appear in the passage in the same order.
613
+ """
614
+ q = _normalized_quote(quote)
615
+ t = _normalized_quote(text)
616
+ if not q:
617
+ return False
618
+ if q in t:
619
+ return True
620
+ segments = [seg.strip(" \"'.,;:") for seg in q.split("...")]
621
+ segments = [seg for seg in segments if seg]
622
+ if len(segments) < 2:
623
+ return False
624
+ pos = 0
625
+ for seg in segments:
626
+ idx = t.find(seg, pos)
627
+ if idx < 0:
628
+ return False
629
+ pos = idx + len(seg)
630
+ return True
631
+
632
+
633
+ _REJECTION_WORDS = re.compile(r"reject|contradict", re.I)
634
+
635
+
636
+ def _norm_value_text(text):
637
+ return re.sub(r"\s+", " ", (text or "").lower().replace(",", "")).strip()
638
+
639
+
640
+ def _value_in(value, text):
641
+ """True when the normalized value occurs in the normalized text as a whole token span."""
642
+ v, t = _norm_value_text(value), _norm_value_text(text)
643
+ return bool(v) and re.search(r"(?<![\w.])" + re.escape(v) + r"(?![\w])", t) is not None
644
+
645
+
646
+ def rejected_values(result, candidates):
647
+ """E' (Revision 1, value source as decided by the user on 26 Nov): values the model itself
648
+ treats as rejected: the values it lists in "rejected_values", plus, for every citation with
649
+ treatment "conflicting", the normalized numeric claim of that chunk unless a governing or
650
+ supporting cited chunk carries the same claim; minus any value that appears in short_answers
651
+ (committed). The corroboration-summary values of the brief's
652
+ version are not used: on Gemma RAMDocs they flagged 140 answers for incidental numbers
653
+ (mostly years) against 11 for planted values."""
654
+ by_id = {c.chunk_id: c for c in candidates}
655
+ values = {v for v in (result.get("rejected_values") or []) if isinstance(v, str) and v.strip()}
656
+ cited = [(c.get("treatment"), by_id.get(c.get("chunk_id"))) for c in result.get("citations") or []]
657
+ # A conflicting chunk's extracted number is rejected only if no governing/supporting chunk the
658
+ # model cited carries the same number (the extractor often returns a shared year, e.g. "1979").
659
+ kept = {normalize_claim(cand.claim) for t, cand in cited if cand is not None and t in ("governing", "supporting")}
660
+ for t, cand in cited:
661
+ if t == "conflicting" and cand is not None and normalize_claim(cand.claim) not in kept | {"NO_CLAIM"}:
662
+ values.add(normalize_claim(cand.claim))
663
+ committed = [s for s in (result.get("short_answers") or []) if isinstance(s, str)]
664
+ return sorted(v for v in values if not any(_value_in(v, s) for s in committed))
665
+
666
+
667
+ def committed_answer_violation(result, candidates):
668
+ """Return the first rejected value the answer names outside a rejecting sentence, or None.
669
+ Applies to decision == "answered" only."""
670
+ if result.get("decision") != "answered":
671
+ return None
672
+ answer = result.get("answer") or ""
673
+ sents = [x for x in re.split(r"(?<=[.!?])\s+", answer) if x.strip()]
674
+ for value in rejected_values(result, candidates):
675
+ holding = [x for x in sents if _value_in(value, x)]
676
+ if holding and not all(_REJECTION_WORDS.search(x) for x in holding):
677
+ return value
678
+ return None
679
+
680
+
681
+ def rebuild_committed_answer(result):
682
+ """E' fallback: the answer becomes the committed values, one sentence per value."""
683
+ values = [s.strip().rstrip(".") for s in (result.get("short_answers") or []) if isinstance(s, str) and s.strip()]
684
+ rebuilt = dict(result)
685
+ if values:
686
+ rebuilt["answer"] = " ".join(f"{v}." for v in values)
687
+ rebuilt["answer_rebuilt"] = True
688
+ return rebuilt
689
+
690
+
691
+ def run_generation(complete, system_prompt, user_prompt, candidates, max_repairs=1, enforce_committed=False):
692
+ """Run a chat completion, validate it, and give the model one chance to
693
+ repair a rejected output.
694
+
695
+ ``complete(system_prompt, user_prompt) -> str`` is the provider call. On a
696
+ validator rejection the rejection reason is appended to the prompt and the
697
+ model is asked for corrected JSON. The returned result carries
698
+ ``repair_attempts`` (0 or 1) and, for a final rejection, ``validation_error``.
699
+ """
700
+ feedback = ""
701
+ for attempt in range(max_repairs + 1):
702
+ response_text = complete(system_prompt, user_prompt + feedback)
703
+ parsed = parse_json_response(response_text)
704
+ if parsed is None:
705
+ print("ERROR: JSON parsing failed")
706
+ print(f"Full response ({len(response_text)} chars):")
707
+ print(response_text)
708
+ validated = generation_failure("Generation returned invalid JSON; no answer was selected.")
709
+ else:
710
+ validated = validate_generation_result(parsed, candidates)
711
+ pending = None # E': a valid result whose answer still names a rejected value
712
+ if enforce_committed and not validated.get("validation_error"):
713
+ value = committed_answer_violation(validated, candidates)
714
+ if value is not None:
715
+ pending = validated
716
+ validated = generation_failure(
717
+ f"The answer names a rejected value ({value}). The answer must state the committed "
718
+ f"value(s) only; remove {value} from the answer or move it to one final sentence that "
719
+ "says it is rejected and why. Keep short_answers unchanged.")
720
+ validated["repair_attempts"] = attempt
721
+ if not validated.get("validation_error"):
722
+ if enforce_committed:
723
+ validated["answer_rebuilt"] = False
724
+ return validated
725
+ if attempt == max_repairs and pending is not None:
726
+ rebuilt = rebuild_committed_answer(pending)
727
+ rebuilt["repair_attempts"] = attempt
728
+ print("REBUILT: answer still named a rejected value after the repair")
729
+ return rebuilt
730
+ if attempt == max_repairs:
731
+ # Last resort: keep the answer but drop the citations that could
732
+ # not be verified, rather than discarding a well-formed answer over
733
+ # one bad quote. The number dropped is recorded for reporting.
734
+ if parsed is not None:
735
+ salvaged = validate_generation_result(parsed, candidates, drop_unverifiable=True)
736
+ if not salvaged.get("validation_error"):
737
+ salvaged["repair_attempts"] = attempt
738
+ print(f"SALVAGED: dropped {salvaged.get('dropped_citations', 0)} unverifiable citation(s)")
739
+ if enforce_committed:
740
+ if committed_answer_violation(salvaged, candidates) is not None:
741
+ salvaged = rebuild_committed_answer(salvaged)
742
+ else:
743
+ salvaged["answer_rebuilt"] = False
744
+ return salvaged
745
+ return validated
746
+ print(f"REPAIR: asking the model to fix a rejected output ({validated['reason']})")
747
+ feedback = (
748
+ "\n\nYour previous JSON response was rejected for this reason: "
749
+ f"{validated['reason']} "
750
+ "Return the complete corrected JSON only. Every citation quote must be copied "
751
+ "verbatim from the Content of the passage whose Chunk ID you cite, every "
752
+ "treatment must be one of the allowed values, and selected_source must be a "
753
+ "cited filename."
754
+ )
755
+ return validated
756
+
757
+
758
+ def format_evidence(candidates, include_signals=True):
759
+ """Format candidates as numbered evidence blocks.
760
+
761
+ ``include_signals=False`` omits the inferred status/type/authority/scope
762
+ lines so a plain-RAG baseline sees only the passages themselves.
763
+ """
764
+ parts = []
765
+
766
+ for i, c in enumerate(candidates, 1):
767
+ chunk_label = f" (chunk {c.chunk_index + 1})" if c.chunk_index is not None else ""
768
+ text = c.text if len(c.text) <= 6000 else c.text[:6000] + "..."
769
+ signal_lines = ""
770
+ if include_signals:
771
+ signal_lines = (
772
+ f"Inferred status: {c.status}\n"
773
+ f"Inferred type: {c.doc_type}\n"
774
+ f"Inferred authority signal: {c.authority_score:.3f}\n"
775
+ f"Scope similarity (not proof of applicability): {c.scope_score:.3f}\n"
776
+ )
777
+ parts.append(f"""Evidence {i}{chunk_label}:
778
+ Chunk ID: {c.chunk_id}
779
+ Document ID: {c.document_id}
780
+ Filename: {c.filename}
781
+ {signal_lines}Location: {format_location(c.page_start, c.page_end, c.section)}
782
+
783
+ Content:
784
+ {text}
785
+
786
+ {'-'*80}
787
+ """)
788
+
789
+ return "\n".join(parts)
790
+
791
+
792
+ def corroboration_summary(candidates):
793
+ """Count, per extracted numeric claim, how many distinct documents carry it.
794
+
795
+ A cheap, deterministic corroboration aid for the answer-and-flag policy:
796
+ only claim-bearing (numeric) passages are counted, by filename, so the model
797
+ can see e.g. "3,559: 2 documents; 10,000: 1 document". Returns "" when no
798
+ claim appears in more than one competing form.
799
+ """
800
+ by_claim = defaultdict(set)
801
+ for c in candidates:
802
+ key = normalize_claim(c.claim)
803
+ if key != "NO_CLAIM":
804
+ by_claim[key].add(c.filename)
805
+ if len(by_claim) < 2:
806
+ return ""
807
+ lines = sorted(((len(fs), claim) for claim, fs in by_claim.items()), reverse=True)
808
+ return "Corroboration (numeric claims, distinct documents; count aid only):\n" + "\n".join(
809
+ f"- {claim}: {n} document{'s' if n != 1 else ''}" for n, claim in lines
810
+ )
811
+
812
+
813
+ def build_user_prompt(question, candidates, context=None, include_signals=True, corroboration=False):
814
+ """Build the user turn sent to the generator (shared across providers)."""
815
+ evidence_text = format_evidence(candidates, include_signals=include_signals)
816
+ return f"""Question: {question}
817
+
818
+ Case context (user-provided, potentially incomplete):
819
+ {json.dumps(context or {}, ensure_ascii=True)}
820
+
821
+ Retrieved Evidence:
822
+
823
+ {evidence_text}
824
+ {(corroboration_summary(candidates) + chr(10) + chr(10)) if corroboration else ""}Analyze the evidence and provide your answer in JSON format."""
825
+
826
+
827
+ def parse_json_response(response_text):
828
+ """Parse a JSON object out of a model response; returns None on failure.
829
+
830
+ Tolerates markdown code fences and leading/trailing prose by falling back
831
+ to the outermost ``{...}`` span.
832
+ """
833
+ text = (response_text or "").strip()
834
+ if text.startswith("```json"):
835
+ text = text[7:]
836
+ if text.startswith("```"):
837
+ text = text[3:]
838
+ if text.endswith("```"):
839
+ text = text[:-3]
840
+ text = text.strip()
841
+ try:
842
+ return json.loads(text)
843
+ except json.JSONDecodeError:
844
+ start, end = text.find("{"), text.rfind("}")
845
+ if start == -1 or end <= start:
846
+ return None
847
+ try:
848
+ return json.loads(text[start:end + 1])
849
+ except json.JSONDecodeError:
850
+ pass
851
+ # Last resort: lenient repair (missing quotes/commas, truncated tail).
852
+ # Anything it invents is still subject to citation validation.
853
+ try:
854
+ from json_repair import repair_json
855
+ repaired = repair_json(text[start:], return_objects=True)
856
+ except Exception: # noqa: BLE001 - optional dependency / repair failure
857
+ return None
858
+ if isinstance(repaired, dict) and repaired.get("decision"):
859
+ print("WARNING: model JSON was malformed and was repaired leniently")
860
+ return repaired
861
+ return None
862
+
863
+
864
+ def validate_generation_result(result, candidates, drop_unverifiable=False):
865
+ """Reject generated citations and source names not grounded in retrieval.
866
+
867
+ On rejection the raw model output is logged so that failures can be
868
+ diagnosed from the run log instead of being silently coerced into
869
+ ``insufficient_evidence``. With ``drop_unverifiable=True`` unverifiable
870
+ citations are removed instead of rejecting the whole result; the count is
871
+ returned as ``dropped_citations``.
872
+ """
873
+ validated = _validate_generation_result(result, candidates, drop_unverifiable=drop_unverifiable)
874
+ if validated.get("validation_error"):
875
+ try:
876
+ raw = json.dumps(result, ensure_ascii=False)
877
+ except (TypeError, ValueError):
878
+ raw = repr(result)
879
+ print(f"VALIDATION REJECTED: {validated['reason']}")
880
+ print(f"Raw model output ({len(raw)} chars): {raw[:4000]}")
881
+ return validated
882
+
883
+
884
+ def _validate_generation_result(result, candidates, drop_unverifiable=False):
885
+ if not isinstance(result, dict):
886
+ return generation_failure("Generation returned an invalid structured result.")
887
+
888
+ decision = result.get("decision")
889
+ if decision not in DECISIONS:
890
+ return generation_failure("Generation returned an unsupported decision.")
891
+
892
+ candidates_by_id = {candidate.chunk_id: candidate for candidate in candidates}
893
+ # Models often cite the document id or filename instead of the full
894
+ # "<doc>:chunk:<n>" id. Accept those when they resolve to exactly one
895
+ # retrieved chunk; ambiguous or unknown ids are still rejected.
896
+ by_alias = defaultdict(list)
897
+ for candidate in candidates:
898
+ for alias in {candidate.document_id, candidate.filename,
899
+ (candidate.filename or "").rsplit(".", 1)[0]}:
900
+ if alias:
901
+ by_alias[alias].append(candidate)
902
+ for alias, matches in by_alias.items():
903
+ if alias not in candidates_by_id and len(matches) == 1:
904
+ candidates_by_id[alias] = matches[0]
905
+ citations = result.get("citations", [])
906
+ if not isinstance(citations, list):
907
+ return generation_failure("Generation returned an invalid citation list.")
908
+
909
+ verified_citations = []
910
+ problems = []
911
+ dropped = 0
912
+ for position, citation in enumerate(citations, 1):
913
+ if not isinstance(citation, dict):
914
+ return generation_failure("Generation returned a malformed citation.")
915
+ chunk_id = citation.get("chunk_id")
916
+ candidate = candidates_by_id.get(chunk_id)
917
+ quote = citation.get("quote")
918
+ problem = None
919
+ if candidate is None:
920
+ problem = f"citation {position} cites chunk_id {chunk_id!r}, which is not among the retrieved passages"
921
+ elif not isinstance(quote, str) or not quote.strip():
922
+ problem = f"citation {position} ({chunk_id}) has an empty quote"
923
+ elif not quote_matches(quote, candidate.text):
924
+ snippet = " ".join(quote.split())
925
+ if len(snippet) > 120:
926
+ snippet = snippet[:117] + "..."
927
+ problem = (
928
+ f"citation {position} ({chunk_id}) quote is not verbatim from that passage: \"{snippet}\""
929
+ )
930
+ if problem:
931
+ if drop_unverifiable:
932
+ dropped += 1
933
+ continue
934
+ problems.append(problem)
935
+ continue
936
+ treatment = citation.get("treatment", "supporting")
937
+ if treatment not in CITATION_TREATMENTS:
938
+ return generation_failure("Generation returned an unsupported evidence treatment.")
939
+ verified_citations.append({
940
+ "chunk_id": candidate.chunk_id,
941
+ "document_id": candidate.document_id,
942
+ "filename": candidate.filename,
943
+ "page_start": candidate.page_start,
944
+ "page_end": candidate.page_end,
945
+ "section": candidate.section,
946
+ "passage": candidate.text,
947
+ "quote": quote,
948
+ "treatment": treatment,
949
+ "explanation": str(citation.get("explanation") or ""),
950
+ })
951
+
952
+ if problems:
953
+ return generation_failure(
954
+ "Generation cited evidence that was not retrieved or quoted text that does not match: "
955
+ + "; ".join(problems)
956
+ + "."
957
+ )
958
+ if decision in {"answered", "unresolved_conflict", "needs_information"} and not verified_citations:
959
+ return generation_failure("Generation did not provide a verifiable evidence citation.")
960
+ if decision == "unresolved_conflict" and not any(
961
+ citation["treatment"] == "conflicting" for citation in verified_citations
962
+ ):
963
+ return generation_failure("Unresolved evidence was not identified as conflicting.")
964
+
965
+ selected_source = result.get("selected_source")
966
+ cited_filenames = {citation["filename"] for citation in verified_citations}
967
+ if selected_source is not None and selected_source not in cited_filenames:
968
+ if drop_unverifiable and dropped:
969
+ selected_source = None
970
+ else:
971
+ return generation_failure("Generation selected a source that was not cited.")
972
+ if decision == "answered" and selected_source is None:
973
+ # Some models answer and cite a single governing (or sole supporting)
974
+ # passage but leave selected_source null. Derive it from the citations
975
+ # when, and only when, that choice is unambiguous.
976
+ governing = {c["filename"] for c in verified_citations if c["treatment"] == "governing"}
977
+ supporting = {c["filename"] for c in verified_citations if c["treatment"] == "supporting"}
978
+ if len(governing) == 1:
979
+ selected_source = next(iter(governing))
980
+ elif not governing and len(supporting) == 1:
981
+ selected_source = next(iter(supporting))
982
+ if decision == "unresolved_conflict":
983
+ selected_source = None
984
+
985
+ missing = result.get("missing_information") or []
986
+ if not isinstance(missing, list) or not all(isinstance(item, str) for item in missing):
987
+ return generation_failure("Generation returned malformed missing-information details.")
988
+ clarification = result.get("clarification_question")
989
+ if clarification is not None and not isinstance(clarification, str):
990
+ return generation_failure("Generation returned a malformed clarification question.")
991
+ if decision == "needs_information" and (not missing or not clarification or not clarification.strip()):
992
+ return generation_failure(
993
+ "Generation identified missing case facts without listing them and asking a clarification question."
994
+ )
995
+
996
+ answer = result.get("answer")
997
+ # insufficient_evidence replaces the answer text below, so a null answer
998
+ # there is a valid abstention, not an unreadable one (Gemma emits that).
999
+ if decision != "insufficient_evidence" and (not isinstance(answer, str) or not answer.strip()):
1000
+ return generation_failure("Generation returned no readable answer.")
1001
+ if decision == "insufficient_evidence":
1002
+ answer = "The retrieved evidence does not support a reliable answer."
1003
+ selected_source = None
1004
+
1005
+ explanation = result.get("explanation") or result.get("reason") or ""
1006
+ confidence = result.get("confidence", "unknown")
1007
+ if confidence not in {"high", "medium", "low"}:
1008
+ confidence = "unknown"
1009
+ short_answers = result.get("short_answers") or []
1010
+ if not isinstance(short_answers, list):
1011
+ short_answers = [short_answers]
1012
+ short_answers = [str(s).strip() for s in short_answers if str(s).strip()]
1013
+ if decision == "insufficient_evidence":
1014
+ short_answers = []
1015
+
1016
+ rejected = result.get("rejected_values") or []
1017
+ if not isinstance(rejected, list):
1018
+ rejected = [rejected]
1019
+ rejected = [str(v).strip() for v in rejected if str(v).strip()]
1020
+
1021
+ return {
1022
+ "decision": decision,
1023
+ "answer": answer.strip(),
1024
+ "short_answers": short_answers,
1025
+ "rejected_values": rejected,
1026
+ "citations": verified_citations,
1027
+ "reason": str(explanation),
1028
+ "explanation": str(explanation),
1029
+ "missing_information": missing,
1030
+ "clarification_question": clarification,
1031
+ "selected_source": selected_source,
1032
+ "conflict_detected": bool(result.get("conflict_detected"))
1033
+ or decision == "unresolved_conflict",
1034
+ "confidence": confidence,
1035
+ "dropped_citations": dropped,
1036
+ }
1037
+
1038
+
1039
+ # ============================================================
1040
+ # VERTEX AI / GEMINI EMBEDDINGS
1041
+ # ============================================================
1042
+
1043
+ class GeminiEmbedder:
1044
+ def __init__(self, project_id=None, region=None, api_key=None):
1045
+ """
1046
+ Initialize embedder with Vertex AI (project-based) or AI Studio (API key).
1047
+
1048
+ Priority:
1049
+ 1. Vertex AI with project_id (recommended for GCP)
1050
+ 2. AI Studio with api_key (fallback)
1051
+ """
1052
+ self.use_vertex = False
1053
+
1054
+ # Try Vertex AI first (project-based authentication)
1055
+ if project_id or VERTEX_AI_PROJECT:
1056
+ try:
1057
+ project = project_id or VERTEX_AI_PROJECT
1058
+ location = region or VERTEX_AI_REGION
1059
+
1060
+ vertexai.init(project=project, location=location)
1061
+ self.model = TextEmbeddingModel.from_pretrained(VERTEX_AI_MODEL)
1062
+ self.use_vertex = True
1063
+
1064
+ print(f"✓ Using Vertex AI")
1065
+ print(f" Project: {project}")
1066
+ print(f" Region: {location}")
1067
+ print(f" Model: {VERTEX_AI_MODEL}")
1068
+ print(f" Auth: gcloud credentials")
1069
+ return
1070
+
1071
+ except Exception as e:
1072
+ print(f"WARNING: Vertex AI initialization failed: {e}")
1073
+ print("Falling back to AI Studio API key authentication...")
1074
+
1075
+ # Fallback to AI Studio (API key)
1076
+ if api_key or GEMINI_API_KEY:
1077
+ import google.generativeai as genai
1078
+
1079
+ key = api_key or GEMINI_API_KEY
1080
+ genai.configure(api_key=key)
1081
+ print(f"✓ Using AI Studio API (API key)")
1082
+ self.use_vertex = False
1083
+ else:
1084
+ print("\nERROR: No authentication found!")
1085
+ print("\nOption 1 - Vertex AI (Recommended):")
1086
+ print(" gcloud auth application-default login")
1087
+ print(" export GOOGLE_CLOUD_PROJECT='your-project-id'")
1088
+ print("\nOption 2 - AI Studio:")
1089
+ print(" export GOOGLE_API_KEY='your-api-key'")
1090
+ print(" Get key from: https://makersuite.google.com/app/apikey")
1091
+ raise ValueError("No authentication configured")
1092
+
1093
+ def encode(self, texts, task_type="RETRIEVAL_DOCUMENT"):
1094
+ """
1095
+ Encode texts using Vertex AI or Gemini API.
1096
+
1097
+ task_type:
1098
+ - RETRIEVAL_DOCUMENT: For indexing documents
1099
+ - RETRIEVAL_QUERY: For search queries
1100
+ """
1101
+ if isinstance(texts, str):
1102
+ texts = [texts]
1103
+
1104
+ if self.use_vertex:
1105
+ return self._encode_vertex(texts, task_type)
1106
+ else:
1107
+ return self._encode_genai(texts, task_type)
1108
+
1109
+ def _encode_vertex(self, texts, task_type):
1110
+ """Encode using Vertex AI."""
1111
+ embeddings = []
1112
+ batch_size = 5 # Vertex AI has lower batch limits
1113
+
1114
+ for i in range(0, len(texts), batch_size):
1115
+ batch = texts[i:i+batch_size]
1116
+
1117
+ try:
1118
+ # Vertex AI uses different method
1119
+ result = self.model.get_embeddings(batch)
1120
+ batch_embeddings = [emb.values for emb in result]
1121
+ embeddings.extend(batch_embeddings)
1122
+
1123
+ except Exception as e:
1124
+ print(f"Error encoding batch {i//batch_size}: {e}")
1125
+ dim = 768
1126
+ embeddings.extend([np.zeros(dim) for _ in batch])
1127
+
1128
+ embeddings = np.array(embeddings)
1129
+
1130
+ # Normalize
1131
+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
1132
+ norms = np.where(norms == 0, 1, norms)
1133
+ embeddings = embeddings / norms
1134
+
1135
+ return embeddings
1136
+
1137
+ def _encode_genai(self, texts, task_type):
1138
+ """Encode using AI Studio API."""
1139
+ import google.generativeai as genai
1140
+
1141
+ embeddings = []
1142
+ batch_size = 100
1143
+
1144
+ for i in range(0, len(texts), batch_size):
1145
+ batch = texts[i:i+batch_size]
1146
+
1147
+ try:
1148
+ result = genai.embed_content(
1149
+ model="models/text-embedding-004",
1150
+ content=batch,
1151
+ task_type=task_type
1152
+ )
1153
+
1154
+ batch_embeddings = result['embedding']
1155
+
1156
+ if isinstance(batch_embeddings[0], (int, float)):
1157
+ batch_embeddings = [batch_embeddings]
1158
+
1159
+ embeddings.extend(batch_embeddings)
1160
+
1161
+ except Exception as e:
1162
+ print(f"Error encoding batch {i//batch_size}: {e}")
1163
+ dim = 768
1164
+ embeddings.extend([np.zeros(dim) for _ in batch])
1165
+
1166
+ embeddings = np.array(embeddings)
1167
+
1168
+ # Normalize
1169
+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
1170
+ norms = np.where(norms == 0, 1, norms)
1171
+ embeddings = embeddings / norms
1172
+
1173
+ return embeddings
1174
+
1175
+
1176
+ # ============================================================
1177
+ # GEMINI GENERATOR (for final LLM-based resolution)
1178
+ # ============================================================
1179
+
1180
+ class GeminiGenerator:
1181
+ """Generate final answers using Gemini 2.5 Pro."""
1182
+
1183
+ def __init__(self, project_id=None, region=None, api_key=None):
1184
+ """Initialize Gemini generator with Vertex AI or AI Studio."""
1185
+ self.use_vertex = False
1186
+
1187
+ # Try Vertex AI first
1188
+ if project_id or VERTEX_AI_PROJECT:
1189
+ try:
1190
+ from vertexai.generative_models import GenerativeModel
1191
+
1192
+ project = project_id or VERTEX_AI_PROJECT
1193
+ location = region or VERTEX_AI_REGION
1194
+
1195
+ vertexai.init(project=project, location=location)
1196
+ # Initialize model with system instruction
1197
+ self.model = GenerativeModel(
1198
+ VERTEX_AI_GENERATION_MODEL,
1199
+ system_instruction=[SYSTEM_PROMPT]
1200
+ )
1201
+ self.use_vertex = True
1202
+
1203
+ print(f"✓ Using Vertex AI for generation")
1204
+ print(f" Model: {VERTEX_AI_GENERATION_MODEL}")
1205
+ return
1206
+
1207
+ except Exception as e:
1208
+ print(f"WARNING: Vertex AI generation init failed: {e}")
1209
+ print("Falling back to AI Studio...")
1210
+
1211
+ # Fallback to AI Studio
1212
+ if api_key or GEMINI_API_KEY:
1213
+ import google.generativeai as genai
1214
+
1215
+ key = api_key or GEMINI_API_KEY
1216
+ genai.configure(api_key=key)
1217
+ print(f"✓ Using AI Studio for generation")
1218
+ self.use_vertex = False
1219
+ else:
1220
+ raise ValueError("No authentication configured for generation")
1221
+
1222
+ def _vertex_model(self, system_prompt):
1223
+ """Return a Vertex model bound to ``system_prompt`` (cached per prompt)."""
1224
+ if system_prompt == SYSTEM_PROMPT:
1225
+ return self.model
1226
+ cache = getattr(self, "_prompt_models", None)
1227
+ if cache is None:
1228
+ cache = self._prompt_models = {}
1229
+ if system_prompt not in cache:
1230
+ from vertexai.generative_models import GenerativeModel
1231
+ cache[system_prompt] = GenerativeModel(
1232
+ VERTEX_AI_GENERATION_MODEL, system_instruction=[system_prompt]
1233
+ )
1234
+ return cache[system_prompt]
1235
+
1236
+ def generate(self, question, candidates, context=None, baseline=False):
1237
+ """
1238
+ Generate a structured decision and verify citations against retrieved chunks.
1239
+
1240
+ Args:
1241
+ question: User's question
1242
+ candidates: List of Candidate objects (top K documents)
1243
+ context: optional case facts
1244
+ baseline: use the plain-RAG prompt without governance signals
1245
+
1246
+ Returns:
1247
+ A validated decision object or a transparent insufficient-evidence result.
1248
+ """
1249
+ system_prompt = BASELINE_SYSTEM_PROMPT if baseline else SYSTEM_PROMPT
1250
+ user_prompt = build_user_prompt(
1251
+ question, candidates, context=context, include_signals=not baseline
1252
+ )
1253
+
1254
+ try:
1255
+ return run_generation(self._complete, system_prompt, user_prompt, candidates)
1256
+ except Exception as e:
1257
+ print(f"ERROR: Gemini generation failed: {e}")
1258
+ return self._fallback_resolution(question, candidates)
1259
+
1260
+ def _complete(self, system_prompt, user_prompt):
1261
+ """One chat completion; returns the raw response text."""
1262
+ if self.use_vertex:
1263
+ response = self._vertex_model(system_prompt).generate_content(
1264
+ [user_prompt],
1265
+ generation_config={
1266
+ "temperature": 0.0,
1267
+ "max_output_tokens": 4096,
1268
+ "candidate_count": 1,
1269
+ }
1270
+ )
1271
+ try:
1272
+ return response.candidates[0].content.parts[0].text
1273
+ except (IndexError, AttributeError):
1274
+ return response.text
1275
+
1276
+ # AI Studio
1277
+ import google.generativeai as genai
1278
+
1279
+ model = genai.GenerativeModel(
1280
+ model_name="gemini-2.5-pro",
1281
+ system_instruction=system_prompt
1282
+ )
1283
+ response = model.generate_content(
1284
+ user_prompt,
1285
+ generation_config=genai.GenerationConfig(
1286
+ temperature=0.0,
1287
+ max_output_tokens=4096,
1288
+ )
1289
+ )
1290
+ return response.text
1291
+
1292
+ def _format_evidence(self, candidates):
1293
+ """Kept for backward compatibility; see module-level ``format_evidence``."""
1294
+ return format_evidence(candidates, include_signals=True)
1295
+
1296
+ def _fallback_resolution(self, question, candidates):
1297
+ """Return a visible failure rather than selecting a heuristic winner."""
1298
+ return generation_failure("Generation failed; no answer was selected.")
1299
+
1300
+
1301
+ # ============================================================
1302
+ # LOAD DOCUMENTS (same as original)
1303
+ # ============================================================
1304
+
1305
+ def load_documents(folder: str) -> List[Document]:
1306
+ files = glob.glob(os.path.join(folder, "**/*.md"), recursive=True)
1307
+ docs = []
1308
+
1309
+ for path in files:
1310
+ with open(path, "r", encoding="utf-8") as f:
1311
+ text = f.read()
1312
+
1313
+ docs.append(Document(filename=os.path.basename(path), text=text))
1314
+
1315
+ print(f"Loaded {len(docs)} documents")
1316
+ return docs
1317
+
1318
+
1319
+ def governance_disabled() -> bool:
1320
+ """GOVRAG_GOVERNANCE=off runs the ablation without governance signals: every
1321
+ document gets neutral metadata (status unknown, authority 0), so ranking
1322
+ reduces to semantic + scope and the generator sees no governance cue."""
1323
+ return os.getenv("GOVRAG_GOVERNANCE", "on").strip().lower() in ("off", "0", "false", "no")
1324
+
1325
+
1326
+ def build_document_meta(documents: List[Document]) -> Dict[str, DocumentMeta]:
1327
+ """Compute governance metadata once per whole document; chunks reuse it."""
1328
+ meta = {}
1329
+ if governance_disabled():
1330
+ print("GOVERNANCE SIGNALS DISABLED (GOVRAG_GOVERNANCE=off): neutral metadata for every document")
1331
+ return {doc.filename: DocumentMeta(status="unknown", doc_type="unknown", authority_raw=0.0) for doc in documents}
1332
+ for doc in documents:
1333
+ meta[doc.filename] = DocumentMeta(
1334
+ status=detect_status(doc.text),
1335
+ doc_type=detect_doc_type(doc.text),
1336
+ authority_raw=authority_score(doc.text),
1337
+ )
1338
+ return meta
1339
+
1340
+
1341
+ def build_chunks(documents: List[Document]) -> List[Chunk]:
1342
+ """Split each document into retrieval-unit chunks (short docs -> 1 chunk)."""
1343
+ chunks = []
1344
+ for doc in documents:
1345
+ pieces = chunk_text_with_locations(doc.text)
1346
+ document_id = doc.filename.rsplit("__", 1)[-1]
1347
+ if document_id.lower().endswith(".md"):
1348
+ document_id = document_id[:-3]
1349
+ for idx, piece in enumerate(pieces):
1350
+ chunks.append(Chunk(
1351
+ filename=doc.filename,
1352
+ document_id=document_id,
1353
+ chunk_index=idx,
1354
+ chunk_id=f"{document_id}:chunk:{idx}",
1355
+ text=piece.text,
1356
+ page_start=piece.page_start,
1357
+ page_end=piece.page_end,
1358
+ section=piece.section,
1359
+ ))
1360
+ return chunks
1361
+
1362
+
1363
+ # ============================================================
1364
+ # UTILITY FUNCTIONS (same as original)
1365
+ # ============================================================
1366
+
1367
+ def cosine_similarity(a, b):
1368
+ return float(np.dot(a, b))
1369
+
1370
+
1371
+ def sentences(text):
1372
+ return [
1373
+ x.strip()
1374
+ for x in re.split(r"(?<=[.!?])\s+|\n+", text)
1375
+ if x.strip()
1376
+ ]
1377
+
1378
+
1379
+ # ============================================================
1380
+ # UTILITY FUNCTIONS (Copied from gov_rag.py to avoid dependency)
1381
+ # ============================================================
1382
+
1383
+ def sentences(text):
1384
+ """Split text into sentences"""
1385
+ return [
1386
+ x.strip()
1387
+ for x in re.split(r"(?<=[.!?])\s+|\n+", text)
1388
+ if x.strip()
1389
+ ]
1390
+
1391
+
1392
+ def keyword_overlap(question: str, sentence: str):
1393
+ """Calculate keyword overlap between question and sentence"""
1394
+ q_words = set(
1395
+ re.findall(r"[a-zA-Z]{3,}", question.lower())
1396
+ )
1397
+
1398
+ s_words = set(
1399
+ re.findall(r"[a-zA-Z]{3,}", sentence.lower())
1400
+ )
1401
+
1402
+ if not q_words:
1403
+ return 0
1404
+
1405
+ return len(q_words & s_words) / len(q_words)
1406
+
1407
+
1408
+ QUANTITY_PATTERN = re.compile(
1409
+ r"""
1410
+ (?<![A-Za-z0-9])
1411
+ (?:
1412
+ -?\d+(?:,\d{3})*(?:\.\d+)?
1413
+ \s*
1414
+ (?:
1415
+ %|
1416
+ °c|
1417
+ degrees?\s+celsius|
1418
+ minutes?|
1419
+ hours?|
1420
+ days?|
1421
+ years?|
1422
+ kilometers?|
1423
+ km|
1424
+ cases?|
1425
+ calls?|
1426
+ quens?|
1427
+ luma|
1428
+ inspection\s+points?
1429
+ )?
1430
+ )
1431
+ """,
1432
+ re.IGNORECASE | re.VERBOSE
1433
+ )
1434
+
1435
+
1436
+ # Header/first-N-characters window used to keep single ambiguous keywords
1437
+ # (e.g. "draft", "summary") from firing on incidental body-text mentions in
1438
+ # ordinary documents; strong multi-word phrases are still checked anywhere.
1439
+ HEADER_WINDOW_CHARS = 1200
1440
+
1441
+
1442
+ def get_header_window(text: str) -> str:
1443
+ return text[:HEADER_WINDOW_CHARS].lower()
1444
+
1445
+
1446
+ def extract_structured_field(text: str, field_names) -> Optional[str]:
1447
+ """Match explicit 'Label: value' lines such as 'Status: DRAFT'."""
1448
+ pattern = re.compile(
1449
+ rf"^\s*(?:{'|'.join(field_names)})\s*:\s*(.+)$",
1450
+ re.IGNORECASE | re.MULTILINE,
1451
+ )
1452
+ match = pattern.search(text)
1453
+ return match.group(1).strip().lower() if match else None
1454
+
1455
+
1456
+ def detect_status(text: str):
1457
+ """Detect document status conservatively: only trust an explicit structural
1458
+ cue (a 'Status:'/'Governing status:' line) or a strong, specific multi-word
1459
+ phrase, never a single ambiguous word (draft/archived/historical/stale)
1460
+ found anywhere in the body. Verified against all 180 ConflictBench Easy
1461
+ documents: every one of them is classified via a structured line or a
1462
+ strong phrase, so this conservative approach has zero regression there,
1463
+ while avoiding false positives on ordinary documents that happen to
1464
+ contain common words like "historical" or "propose" in their prose.
1465
+ """
1466
+ full = text.lower()
1467
+ structured = extract_structured_field(text, ["governing status", "status"])
1468
+
1469
+ if "active and authoritative" in full or "governing status: active" in full:
1470
+ return "active_authoritative"
1471
+ if structured and "authoritative" in structured:
1472
+ return "active_authoritative"
1473
+
1474
+ if any(x in full for x in ["superseded by", "withdrawn", "no longer valid"]):
1475
+ return "superseded"
1476
+ if structured and "supersed" in structured:
1477
+ return "superseded"
1478
+
1479
+ if any(x in full for x in ["legacy version"]):
1480
+ return "archived"
1481
+ if structured and any(w in structured for w in ["archived", "historical", "legacy", "stale", "obsolete"]):
1482
+ return "archived"
1483
+
1484
+ if any(x in full for x in ["draft policy", "working draft", "proposed policy", "proposed requirement", "planning brief"]):
1485
+ return "draft"
1486
+ if structured and any(w in structured for w in ["draft", "proposed"]):
1487
+ return "draft"
1488
+
1489
+ if any(x in full for x in [
1490
+ "active governing policy",
1491
+ "governing policy",
1492
+ "currently effective",
1493
+ "current policy",
1494
+ "effective immediately",
1495
+ "active policy",
1496
+ ]):
1497
+ return "active"
1498
+ if structured == "active":
1499
+ return "active"
1500
+
1501
+ return "unknown"
1502
+
1503
+
1504
+ def detect_doc_type(text: str):
1505
+ """Detect document type. Strong, specific multi-word governance terms are
1506
+ checked anywhere in the document. Weak generic words (summary/digest/
1507
+ overview) only count near the top, since a research paper's body section
1508
+ titled "Results Summary" should not make the whole document a
1509
+ secondary_summary. Falls back to a light heuristic for ordinary
1510
+ documents rather than forcing an unrelated governance type.
1511
+ """
1512
+ full = text.lower()
1513
+ header = get_header_window(text)
1514
+
1515
+ hierarchy = [
1516
+ ("governing_policy", ["governing policy", "official policy"]),
1517
+ ("policy_bulletin", ["policy bulletin"]),
1518
+ ("standard", ["official standard", "safety standard", "compliance standard"]),
1519
+ ("implementation_memo", ["implementation memo", "implementation memorandum"]),
1520
+ ("faq", ["faq", "frequently asked questions"]),
1521
+ ("training_guide", ["training guide", "training material"]),
1522
+ ("reference_card", ["reference card", "quick reference"]),
1523
+ ]
1524
+
1525
+ for name, keywords in hierarchy:
1526
+ if any(k in full for k in keywords):
1527
+ return name
1528
+
1529
+ if any(k in header for k in ["summary", "digest", "overview"]):
1530
+ return "secondary_summary"
1531
+
1532
+ # Ordinary-document fallback: sensible generic types, not governance labels.
1533
+ if "abstract" in header and any(k in full for k in ["references", "et al", "arxiv"]):
1534
+ return "research_paper"
1535
+ if any(k in header for k in ["readme", "documentation", "user guide", "getting started"]):
1536
+ return "documentation"
1537
+ if any(k in full for k in ["technical report", "specification", "architecture overview"]):
1538
+ return "technical_document"
1539
+
1540
+ return "unknown"
1541
+
1542
+
1543
+ def authority_score(text: str):
1544
+ """Calculate authority score based on text markers"""
1545
+ t = text.lower()
1546
+ # Reuse detect_status's conservative structured/strong-phrase logic rather
1547
+ # than re-implementing bare-keyword checks here (those false-positive on
1548
+ # ordinary prose - see detect_status docstring).
1549
+ status_hint = detect_status(text)
1550
+
1551
+ score = 0.0
1552
+
1553
+ # Strongest signal: explicit active and authoritative marker
1554
+ if "active and authoritative" in t:
1555
+ score += 10.0
1556
+
1557
+ if "governing status: active" in t:
1558
+ score += 8.0
1559
+
1560
+ # Supersession language
1561
+ if "supersedes all previous" in t:
1562
+ score += 4.0
1563
+ elif "supersedes earlier" in t:
1564
+ score += 4.0
1565
+ elif "supersedes previous" in t:
1566
+ score += 3.0
1567
+
1568
+ # Standard authority markers
1569
+ if "active governing policy" in t:
1570
+ score += 5.0
1571
+ elif "governing policy" in t:
1572
+ score += 4.0
1573
+
1574
+ if "current policy" in t:
1575
+ score += 3.0
1576
+
1577
+ if "currently effective" in t:
1578
+ score += 3.0
1579
+
1580
+ if "effective immediately" in t:
1581
+ score += 2.5
1582
+
1583
+ if "official policy" in t:
1584
+ score += 2.5
1585
+
1586
+ if "policy bulletin" in t:
1587
+ score += 2.0
1588
+
1589
+ if "official standard" in t:
1590
+ score += 2.0
1591
+
1592
+ # ------------------------
1593
+ # Negative authority
1594
+ # ------------------------
1595
+
1596
+ # Explicit disclaimers (very negative)
1597
+ if "should not be treated as the governing source" in t:
1598
+ score -= 8.0
1599
+
1600
+ if "consult the active governing policy if a conflict exists" in t:
1601
+ score -= 6.0
1602
+
1603
+ if "does not state the current requirement" in t:
1604
+ score -= 7.0
1605
+
1606
+ # Status markers
1607
+ if "superseded" in t and "supersedes" not in t:
1608
+ score -= 6.0
1609
+
1610
+ if status_hint == "archived":
1611
+ score -= 5.0
1612
+
1613
+ if status_hint == "draft":
1614
+ score -= 4.0
1615
+
1616
+ # Document type markers (secondary sources)
1617
+ if "secondary internal summary" in t:
1618
+ score -= 4.0
1619
+
1620
+ if "implementation memo" in t:
1621
+ score -= 3.0
1622
+
1623
+ if "training guide" in t:
1624
+ score -= 2.5
1625
+
1626
+ if "planning brief" in t:
1627
+ score -= 2.5
1628
+
1629
+ if "compliance digest" in t:
1630
+ score -= 2.0
1631
+
1632
+ if "reference card" in t:
1633
+ score -= 2.0
1634
+
1635
+ if "background note" in t:
1636
+ score -= 3.0
1637
+
1638
+ if "faq" in t:
1639
+ score -= 1.5
1640
+
1641
+ # Scope issues
1642
+ if "wrong scope" in t:
1643
+ score -= 5.0
1644
+
1645
+ if "neighboring category" in t:
1646
+ score -= 4.0
1647
+
1648
+ if "not the target category" in t:
1649
+ score -= 4.0
1650
+
1651
+ return score
1652
+
1653
+
1654
+ def extract_claim(question: str, text: str):
1655
+ """Extract numerical claim most related to question"""
1656
+ candidates = []
1657
+
1658
+ for sent in sentences(text):
1659
+ matches = QUANTITY_PATTERN.findall(sent)
1660
+
1661
+ if not matches:
1662
+ continue
1663
+
1664
+ relevance = keyword_overlap(question, sent)
1665
+
1666
+ for value in matches:
1667
+ value = value.strip()
1668
+
1669
+ candidates.append(
1670
+ (
1671
+ relevance,
1672
+ value,
1673
+ sent
1674
+ )
1675
+ )
1676
+
1677
+ if not candidates:
1678
+ return None, None
1679
+
1680
+ candidates.sort(
1681
+ key=lambda x: x[0],
1682
+ reverse=True
1683
+ )
1684
+
1685
+ _, value, sentence = candidates[0]
1686
+
1687
+ return value, sentence
1688
+
1689
+
1690
+ def normalize_claim(claim):
1691
+ """Normalize claim text for comparison"""
1692
+ if not claim:
1693
+ return "NO_CLAIM"
1694
+
1695
+ x = claim.lower().strip()
1696
+
1697
+ x = x.replace(",", "")
1698
+ x = x.replace("kilometers", "km")
1699
+ x = x.replace("kilometer", "km")
1700
+ x = x.replace("degrees celsius", "°c")
1701
+
1702
+ x = re.sub(r"\s+", " ", x)
1703
+
1704
+ return x
1705
+
1706
+
1707
+ def normalize_authority(raw):
1708
+ """Normalize authority score to 0-1 range"""
1709
+ # expected approximate range [-10, +15]
1710
+ raw = max(-10, min(15, raw))
1711
+
1712
+ return (raw + 10) / 25
1713
+
1714
+
1715
+ def group_by_claim(candidates):
1716
+ """Group candidates by normalized claim"""
1717
+ groups = defaultdict(list)
1718
+
1719
+ for candidate in candidates:
1720
+ key = normalize_claim(candidate.claim)
1721
+ groups[key].append(candidate)
1722
+
1723
+ return groups
1724
+
1725
+
1726
+ # ============================================================
1727
+ # RETRIEVAL (adapted for Gemini)
1728
+ # ============================================================
1729
+
1730
+ def semantic_retrieve(question, chunks, embedder, k=INITIAL_RETRIEVAL_K):
1731
+ """Broad semantic retrieval over chunks using Gemini embeddings."""
1732
+
1733
+ # Encode query with RETRIEVAL_QUERY task type
1734
+ q_embedding = embedder.encode([question], task_type="RETRIEVAL_QUERY")[0]
1735
+
1736
+ scored = []
1737
+
1738
+ for chunk in chunks:
1739
+ score = cosine_similarity(q_embedding, chunk.embedding)
1740
+ scored.append((score, chunk))
1741
+
1742
+ scored.sort(key=lambda x: x[0], reverse=True)
1743
+ return scored[:k], q_embedding
1744
+
1745
+
1746
+ _BM25_TOKEN = re.compile(r"\w+")
1747
+
1748
+
1749
+ def hybrid_retrieve(question, chunks, embedder, k=INITIAL_RETRIEVAL_K, rrf_k=60):
1750
+ """Hybrid retrieval control: BM25 and dense rankings fused with reciprocal
1751
+ rank fusion (``1/(rrf_k + rank)``, summed over the two rankers).
1752
+
1753
+ Returns ``(retrieved, q_embedding, fused)`` where ``retrieved`` is the
1754
+ fused top-k as ``(cosine_score, chunk)`` pairs so downstream code sees the
1755
+ same shape as ``semantic_retrieve``, and ``fused`` maps chunk_id to its
1756
+ fusion score for use as the final ranking score.
1757
+ """
1758
+ from rank_bm25 import BM25Okapi
1759
+
1760
+ q_embedding = embedder.encode([question], task_type="RETRIEVAL_QUERY")[0]
1761
+ dense = sorted(
1762
+ ((cosine_similarity(q_embedding, c.embedding), c) for c in chunks),
1763
+ key=lambda x: x[0], reverse=True,
1764
+ )
1765
+ cosine_by_id = {c.chunk_id: score for score, c in dense}
1766
+
1767
+ tokenised = [_BM25_TOKEN.findall(c.text.lower()) for c in chunks]
1768
+ bm25 = BM25Okapi(tokenised)
1769
+ bm25_scores = bm25.get_scores(_BM25_TOKEN.findall(question.lower()))
1770
+ lexical = sorted(zip(bm25_scores, chunks), key=lambda x: x[0], reverse=True)
1771
+
1772
+ fused = {}
1773
+ for ranking in (dense, lexical):
1774
+ for rank, (_, chunk) in enumerate(ranking, start=1):
1775
+ fused[chunk.chunk_id] = fused.get(chunk.chunk_id, 0.0) + 1.0 / (rrf_k + rank)
1776
+
1777
+ by_id = {c.chunk_id: c for c in chunks}
1778
+ top = sorted(fused.items(), key=lambda x: x[1], reverse=True)[:k]
1779
+ retrieved = [(cosine_by_id[cid], by_id[cid]) for cid, _ in top]
1780
+ return retrieved, q_embedding, fused
1781
+
1782
+
1783
+ def first_8_sentence_scope_text(document_text):
1784
+ """Return the scope text used for reranking: first 8 sentences of a chunk."""
1785
+ return " ".join(sentences(document_text)[:8])
1786
+
1787
+
1788
+ def get_scope_score(chunk, q_embedding):
1789
+ """Score scope match using the chunk's persisted scope embedding."""
1790
+ if chunk.scope_embedding is None:
1791
+ return 0.0
1792
+ return cosine_similarity(q_embedding, chunk.scope_embedding)
1793
+
1794
+
1795
+ # ============================================================
1796
+ # CANDIDATE BUILDING (same logic, different embedder)
1797
+ # ============================================================
1798
+
1799
+ def build_candidates(question, retrieved, q_embedding, doc_meta):
1800
+ """Build ranking candidates from retrieved chunks.
1801
+
1802
+ Governance metadata (status/doc_type/authority) is looked up per
1803
+ document_id and reused across every chunk of that document; when a
1804
+ document has no explicit governance signals, doc_meta yields neutral
1805
+ defaults (status=unknown, authority=0.0) so semantic/scope scores
1806
+ dominate ranking naturally rather than being penalized.
1807
+ """
1808
+ candidates = []
1809
+ default_meta = DocumentMeta(status="unknown", doc_type="unknown", authority_raw=0.0)
1810
+ best_semantic = max((semantic for semantic, _ in retrieved), default=0.0)
1811
+
1812
+ for semantic, chunk in retrieved:
1813
+ meta = doc_meta.get(chunk.filename, default_meta)
1814
+ auth = normalize_authority(meta.authority_raw)
1815
+ scope = get_scope_score(chunk, q_embedding)
1816
+ claim, claim_sentence = extract_claim(question, chunk.text)
1817
+ gate = relevance_gate(semantic, best_semantic)
1818
+
1819
+ candidate = Candidate(
1820
+ filename=chunk.filename,
1821
+ text=chunk.text,
1822
+ semantic_score=semantic,
1823
+ authority_score=auth,
1824
+ scope_score=scope,
1825
+ claim=claim,
1826
+ claim_sentence=claim_sentence,
1827
+ status=meta.status,
1828
+ doc_type=meta.doc_type,
1829
+ chunk_index=chunk.chunk_index,
1830
+ document_id=chunk.document_id,
1831
+ chunk_id=chunk.chunk_id,
1832
+ page_start=chunk.page_start,
1833
+ page_end=chunk.page_end,
1834
+ section=chunk.section,
1835
+ relevance_gate=gate,
1836
+ )
1837
+
1838
+ # Authority and scope can only reorder chunks that are comparably
1839
+ # relevant; they cannot lift an off-topic chunk above on-topic ones.
1840
+ candidate.final_score = (
1841
+ W_SEMANTIC * candidate.semantic_score +
1842
+ gate * (
1843
+ W_AUTHORITY * candidate.authority_score +
1844
+ W_SCOPE * candidate.scope_score
1845
+ )
1846
+ )
1847
+
1848
+ candidates.append(candidate)
1849
+
1850
+ return candidates
1851
+
1852
+
1853
+ def diversify_conflicts(candidates, max_per_claim=1, max_no_claim=None):
1854
+ """Reduce duplicate claim passages without collapsing distinct conditions.
1855
+
1856
+ Claim-bearing candidates are grouped by both the extracted number and full
1857
+ normalized passage, so exceptions remain independently reviewable. Chunks
1858
+ without a numeric claim are retained up to their separate context limit.
1859
+ """
1860
+ groups = defaultdict(list)
1861
+ for candidate in candidates:
1862
+ claim_key = normalize_claim(candidate.claim)
1863
+ if claim_key == "NO_CLAIM":
1864
+ groups[claim_key].append(candidate)
1865
+ continue
1866
+ # A repeated number can appear with a materially different condition
1867
+ # or exception; keep those as independent evidence groups.
1868
+ passage_key = " ".join(candidate.text.lower().split())
1869
+ groups[(claim_key, passage_key)].append(candidate)
1870
+ diversified = []
1871
+
1872
+ for claim, docs in groups.items():
1873
+ docs.sort(key=lambda x: x.final_score, reverse=True)
1874
+ if claim == "NO_CLAIM":
1875
+ limit = max_no_claim if max_no_claim is not None else len(docs)
1876
+ else:
1877
+ limit = max_per_claim
1878
+ diversified.extend(docs[:limit])
1879
+
1880
+ diversified.sort(key=lambda x: x.final_score, reverse=True)
1881
+ return diversified
1882
+
1883
+
1884
+ def authority_resolve(candidates):
1885
+ if not candidates:
1886
+ return None
1887
+ return sorted(candidates, key=lambda c: c.final_score, reverse=True)[0]
1888
+
1889
+
1890
+ def print_conflict_table(candidates):
1891
+ """Display candidates in table format."""
1892
+ print("\n" + "=" * 100)
1893
+ print(
1894
+ f"{'FILE':30} {'CLAIM':15} {'STATUS':12} {'TYPE':20} "
1895
+ f"{'SEM':7} {'AUTH':7} {'SCOPE':7} {'FINAL':7}"
1896
+ )
1897
+ print("=" * 100)
1898
+
1899
+ for c in candidates:
1900
+ print(
1901
+ f"{c.filename[:30]:30} "
1902
+ f"{str(c.claim)[:15]:15} "
1903
+ f"{c.status[:12]:12} "
1904
+ f"{c.doc_type[:20]:20} "
1905
+ f"{c.semantic_score:.3f} "
1906
+ f"{c.authority_score:.3f} "
1907
+ f"{c.scope_score:.3f} "
1908
+ f"{c.final_score:.3f}"
1909
+ )
1910
+
1911
+
1912
+ # ============================================================
1913
+ # GOV-RAG with Gemini
1914
+ # ============================================================
1915
+
1916
+ class GovRAGGemini:
1917
+ def __init__(
1918
+ self,
1919
+ doc_dir,
1920
+ project_id=None,
1921
+ region=None,
1922
+ api_key=None,
1923
+ use_llm=True,
1924
+ embedder=None,
1925
+ generator=None,
1926
+ documents=None,
1927
+ ):
1928
+ """Initialize GOV-RAG with Gemini embeddings and optional LLM generation.
1929
+
1930
+ Args:
1931
+ doc_dir: Path to document directory
1932
+ project_id: GCP project ID for Vertex AI
1933
+ region: GCP region (default: us-central1)
1934
+ api_key: API key for AI Studio (fallback)
1935
+ use_llm: If True, use an LLM for final answer generation (default: True)
1936
+ embedder: optional drop-in embedder (e.g. ``providers.LocalEmbedder``);
1937
+ defaults to ``GeminiEmbedder``
1938
+ generator: optional drop-in generator (e.g.
1939
+ ``providers.OpenAICompatGenerator``); defaults to ``GeminiGenerator``
1940
+ """
1941
+
1942
+ print("\nInitializing GOV-RAG...")
1943
+
1944
+ self.use_llm = use_llm
1945
+ self.embedder = embedder or GeminiEmbedder(project_id=project_id, region=region, api_key=api_key)
1946
+
1947
+ # Initialize generator if using LLM
1948
+ if not self.use_llm:
1949
+ self.generator = None
1950
+ elif generator is not None:
1951
+ self.generator = generator
1952
+ else:
1953
+ print("\nInitializing Gemini generator for final resolution...")
1954
+ self.generator = GeminiGenerator(project_id=project_id, region=region, api_key=api_key)
1955
+
1956
+ # Documents may be supplied in memory (``documents=[Document(...)]``),
1957
+ # e.g. for per-question corpora from external benchmarks; otherwise
1958
+ # they are loaded from ``doc_dir``.
1959
+ self.documents = list(documents) if documents is not None else load_documents(doc_dir)
1960
+ self.doc_meta = build_document_meta(self.documents)
1961
+ self.chunks = build_chunks(self.documents)
1962
+
1963
+ # Create embeddings for all chunks (short docs collapse to one chunk
1964
+ # each, so this is equivalent to prior whole-document behavior there).
1965
+ print(f"Creating embeddings for {len(self.chunks)} chunks across {len(self.documents)} documents...")
1966
+ texts = [c.text for c in self.chunks]
1967
+
1968
+ embeddings = self.embedder.encode(texts, task_type="RETRIEVAL_DOCUMENT")
1969
+
1970
+ for chunk, embedding in zip(self.chunks, embeddings):
1971
+ chunk.embedding = embedding
1972
+
1973
+ # Scope embeddings are used during reranking. Persisting them keeps
1974
+ # query-time retrieval to one query embedding plus local vector math.
1975
+ print(f"Creating scope embeddings for {len(self.chunks)} chunks...")
1976
+ scope_texts = [first_8_sentence_scope_text(c.text) for c in self.chunks]
1977
+ non_empty_scope_items = [(idx, text) for idx, text in enumerate(scope_texts) if text]
1978
+ scope_embeddings_by_index = {}
1979
+
1980
+ if non_empty_scope_items:
1981
+ scope_embeddings = self.embedder.encode(
1982
+ [text for _, text in non_empty_scope_items],
1983
+ task_type="RETRIEVAL_DOCUMENT",
1984
+ )
1985
+ scope_embeddings_by_index = {
1986
+ idx: embedding for (idx, _), embedding in zip(non_empty_scope_items, scope_embeddings)
1987
+ }
1988
+
1989
+ for idx, chunk in enumerate(self.chunks):
1990
+ chunk.scope_text = scope_texts[idx]
1991
+ chunk.scope_embedding = scope_embeddings_by_index.get(
1992
+ idx,
1993
+ np.zeros_like(chunk.embedding),
1994
+ )
1995
+
1996
+ print("Ready.")
1997
+
1998
+ def to_persisted_index_rows(self) -> List[Dict]:
1999
+ """Serialize chunk embeddings plus document governance metadata."""
2000
+ rows = []
2001
+ for chunk in self.chunks:
2002
+ meta = self.doc_meta.get(
2003
+ chunk.filename,
2004
+ DocumentMeta(status="unknown", doc_type="unknown", authority_raw=0.0),
2005
+ )
2006
+ embedding = chunk.embedding
2007
+ if hasattr(embedding, "tolist"):
2008
+ embedding = embedding.tolist()
2009
+ scope_embedding = chunk.scope_embedding
2010
+ if hasattr(scope_embedding, "tolist"):
2011
+ scope_embedding = scope_embedding.tolist()
2012
+ scope_text = chunk.scope_text if chunk.scope_text is not None else first_8_sentence_scope_text(chunk.text)
2013
+
2014
+ rows.append({
2015
+ "chunk_id": chunk.chunk_id,
2016
+ "chunk_index": int(chunk.chunk_index),
2017
+ "filename": chunk.filename,
2018
+ "document_id": chunk.document_id,
2019
+ "text": chunk.text,
2020
+ "page_start": chunk.page_start,
2021
+ "page_end": chunk.page_end,
2022
+ "section": chunk.section,
2023
+ "scope_text": scope_text,
2024
+ "status": meta.status,
2025
+ "doc_type": meta.doc_type,
2026
+ "authority_raw": float(meta.authority_raw),
2027
+ "embedding": list(embedding or []),
2028
+ "scope_embedding": list(scope_embedding or []),
2029
+ })
2030
+ return rows
2031
+
2032
+ @classmethod
2033
+ def from_persisted_index(
2034
+ cls,
2035
+ rows: List[Dict],
2036
+ project_id=None,
2037
+ region=None,
2038
+ api_key=None,
2039
+ use_llm=True,
2040
+ embedder=None,
2041
+ generator=None,
2042
+ ):
2043
+ """Create a query-ready GOV-RAG instance from stored chunk embeddings.
2044
+
2045
+ ``embedder`` / ``generator`` are drop-in providers, exactly as in
2046
+ ``__init__``; without them the Gemini classes are used.
2047
+ """
2048
+ print("\nInitializing GOV-RAG from persisted index...")
2049
+
2050
+ obj = cls.__new__(cls)
2051
+ obj.use_llm = use_llm
2052
+ obj.embedder = embedder or GeminiEmbedder(project_id=project_id, region=region, api_key=api_key)
2053
+
2054
+ if not obj.use_llm:
2055
+ obj.generator = None
2056
+ elif generator is not None:
2057
+ obj.generator = generator
2058
+ else:
2059
+ print("\nInitializing Gemini generator for final resolution...")
2060
+ obj.generator = GeminiGenerator(project_id=project_id, region=region, api_key=api_key)
2061
+
2062
+ obj.documents = []
2063
+ obj.doc_meta = {}
2064
+ obj.chunks = []
2065
+
2066
+ for row in rows:
2067
+ embedding = row.get("embedding") or []
2068
+ if hasattr(embedding, "tolist"):
2069
+ embedding = embedding.tolist()
2070
+ scope_embedding = row.get("scope_embedding")
2071
+ if scope_embedding is None:
2072
+ raise ValueError("Persisted index row missing scope_embedding")
2073
+ if hasattr(scope_embedding, "tolist"):
2074
+ scope_embedding = scope_embedding.tolist()
2075
+
2076
+ filename = row["filename"]
2077
+ obj.chunks.append(
2078
+ Chunk(
2079
+ filename=filename,
2080
+ document_id=row.get("document_id") or filename,
2081
+ chunk_index=int(row.get("chunk_index", 0)),
2082
+ chunk_id=row.get("chunk_id") or f"{filename}::chunk-{row.get('chunk_index', 0)}",
2083
+ text=row.get("text") or row.get("scope_text") or "",
2084
+ scope_text=row.get("scope_text"),
2085
+ embedding=np.asarray(embedding, dtype=float),
2086
+ scope_embedding=np.asarray(scope_embedding, dtype=float),
2087
+ page_start=row.get("page_start"),
2088
+ page_end=row.get("page_end"),
2089
+ section=row.get("section"),
2090
+ )
2091
+ )
2092
+ obj.doc_meta[filename] = DocumentMeta(
2093
+ status=row.get("status") or "unknown",
2094
+ doc_type=row.get("doc_type") or "unknown",
2095
+ authority_raw=float(row.get("authority_raw") or 0.0),
2096
+ )
2097
+
2098
+ print(f"Ready from persisted index with {len(obj.chunks)} chunks.")
2099
+ return obj
2100
+
2101
+ def query(self, question, context=None, mode="govrag", retrieval="hybrid", policy="answer_and_flag_final"):
2102
+ """Query the unified GOV-RAG pipeline (chunk retrieval + governance-aware
2103
+ reranking + conflict-aware Gemini reasoning). The same pipeline runs
2104
+ every time; when evidence agrees or has no governance metadata, it
2105
+ naturally reduces to ordinary evidence-grounded semantic RAG.
2106
+
2107
+ ``mode="baseline"`` runs a plain-RAG control for evaluation: the same
2108
+ semantic retrieval, but the top-K chunks are taken by semantic score
2109
+ alone (no authority/scope reranking, no claim diversification) and the
2110
+ generator is given only the passages, with no governance guidance.
2111
+
2112
+ Pipeline:
2113
+ 1. Question
2114
+ 2. Broad semantic retrieval over chunks (top ~30)
2115
+ 3. Claim extraction (auxiliary metadata only, not gating)
2116
+ 4. Governance metadata reuse (per-document, applied to its chunks)
2117
+ 5. Authority + scope scoring
2118
+ 6. Conflict-crowding control (only for genuine claim-bearing chunks)
2119
+ 7. Top evidence chunks
2120
+ 8. GEMINI 2.5 PRO (if use_llm=True)
2121
+ 9. Final answer + supporting/governing source
2122
+ """
2123
+
2124
+ # 1. Broad semantic retrieval over chunks
2125
+ context = {
2126
+ key: value for key, value in (context or {}).items()
2127
+ if value is not None and str(value).strip()
2128
+ }
2129
+ context_text = " ".join(f"{key}: {value}" for key, value in context.items())
2130
+ retrieval_query = f"{question}\nCase context: {context_text}" if context_text else question
2131
+
2132
+ if mode == "closedbook":
2133
+ # Direct few-shot CoT control: no retrieval, no passages.
2134
+ if not (self.use_llm and self.generator and hasattr(self.generator, "closed_book")):
2135
+ failed = generation_failure("Closed-book mode needs a generator with closed_book().")
2136
+ return {**failed, "source": None, "method": "none",
2137
+ "retrieval_mode": "closed_book", "candidates": []}
2138
+ print("\n" + "=" * 80 + "\nFINAL RESOLUTION: closed-book few-shot CoT (no retrieval)\n" + "=" * 80)
2139
+ llm_result = self.generator.closed_book(question, context=context)
2140
+ return {
2141
+ "answer": llm_result.get("answer"),
2142
+ "source": None,
2143
+ "decision": llm_result.get("decision", "insufficient_evidence"),
2144
+ "citations": [],
2145
+ "missing_information": [],
2146
+ "clarification_question": None,
2147
+ "explanation": llm_result.get("explanation", ""),
2148
+ "reason": llm_result.get("reason"),
2149
+ "conflict_detected": False,
2150
+ "confidence": llm_result.get("confidence", "medium"),
2151
+ "short_answers": llm_result.get("short_answers", []),
2152
+ "validation_error": bool(llm_result.get("validation_error", False)),
2153
+ "repair_attempts": int(llm_result.get("repair_attempts", 0)),
2154
+ "dropped_citations": 0,
2155
+ "method": "llm",
2156
+ "retrieval_mode": "closed_book",
2157
+ "candidates": [],
2158
+ }
2159
+
2160
+ timings = {}
2161
+ _t0 = time.perf_counter()
2162
+ fused_scores = None
2163
+ # ``retrieval="hybrid"`` gives GOV-RAG the same BM25+dense RRF first stage
2164
+ # as the hybrid control; governance reranking still runs on top of it.
2165
+ if mode == "hybrid" or (mode == "govrag" and retrieval == "hybrid"):
2166
+ retrieved, q_embedding, fused_scores = hybrid_retrieve(
2167
+ retrieval_query, self.chunks, self.embedder, INITIAL_RETRIEVAL_K
2168
+ )
2169
+ else:
2170
+ retrieved, q_embedding = semantic_retrieve(
2171
+ retrieval_query, self.chunks, self.embedder, INITIAL_RETRIEVAL_K
2172
+ )
2173
+
2174
+ timings["retrieval_s"] = time.perf_counter() - _t0
2175
+ _t0 = time.perf_counter()
2176
+ # 2. Authority + scope extraction
2177
+ candidates = build_candidates(question, retrieved, q_embedding, self.doc_meta)
2178
+
2179
+ baseline = mode in ("baseline", "hybrid")
2180
+ retrieval_mode = {"baseline": "baseline_semantic", "hybrid": "baseline_hybrid_rrf"}.get(mode, "unified_govrag")
2181
+ if mode == "govrag":
2182
+ retrieval_mode = f"unified_govrag_{retrieval}_{policy}"
2183
+ # Change B (answer_and_flag_final only): the retrieved evidence is conflict-free when
2184
+ # its claim-bearing candidates carry at most one distinct normalized claim. Such
2185
+ # questions are ranked by retrieval score exactly as the baseline branch ranks them
2186
+ # (fused score in hybrid mode, cosine otherwise) instead of the authority-weighted
2187
+ # final_score, with no claim diversification.
2188
+ conflict_free = None
2189
+ if mode == "govrag" and policy == "answer_and_flag_final":
2190
+ conflict_free = len(group_by_claim([c for c in candidates if c.claim])) <= 1
2191
+ if baseline or conflict_free:
2192
+ # Plain RAG controls: rank by retrieval score only (cosine, or the
2193
+ # BM25+dense fusion score in hybrid mode), keep top-K.
2194
+ for candidate in candidates:
2195
+ if fused_scores is not None:
2196
+ candidate.final_score = fused_scores.get(candidate.chunk_id, 0.0)
2197
+ else:
2198
+ candidate.final_score = candidate.semantic_score
2199
+ diversified = sorted(candidates, key=lambda c: c.final_score, reverse=True)
2200
+ diversified = diversified[:FINAL_CONTEXT_K]
2201
+ else:
2202
+ # 3. Conflict diversification (claim-bearing chunks capped per claim;
2203
+ # ordinary no-claim evidence is not collapsed to a single chunk).
2204
+ diversified = diversify_conflicts(candidates, max_per_claim=1, max_no_claim=FINAL_CONTEXT_K)
2205
+ diversified = diversified[:FINAL_CONTEXT_K]
2206
+
2207
+ timings["ranking_s"] = time.perf_counter() - _t0 # scoring, claim extraction, diversification
2208
+ print_conflict_table(diversified)
2209
+
2210
+ if not diversified:
2211
+ result = generation_failure("No relevant evidence was retrieved.")
2212
+ return {
2213
+ **result,
2214
+ "source": None,
2215
+ "method": "none",
2216
+ "retrieval_mode": retrieval_mode,
2217
+ "candidates": [],
2218
+ }
2219
+
2220
+ # 4. Final resolution: LLM or rule-based
2221
+ if self.use_llm and self.generator:
2222
+ print("\n" + "="*80)
2223
+ print(f"FINAL RESOLUTION: {'plain RAG baseline' if baseline else 'GOV-RAG'} generation")
2224
+ print("="*80)
2225
+
2226
+ gen_kwargs = {"policy": policy} if (not baseline and policy != "strict") else {}
2227
+ _t0 = time.perf_counter()
2228
+ llm_result = self.generator.generate(
2229
+ question, diversified, context=context, baseline=baseline, **gen_kwargs
2230
+ )
2231
+ timings["generation_s"] = time.perf_counter() - _t0 # model call(s), validation, repair
2232
+
2233
+ return {
2234
+ "answer": llm_result.get("answer"),
2235
+ "source": llm_result.get("selected_source"),
2236
+ "decision": llm_result.get("decision", "insufficient_evidence"),
2237
+ "citations": llm_result.get("citations", []),
2238
+ "missing_information": llm_result.get("missing_information", []),
2239
+ "clarification_question": llm_result.get("clarification_question"),
2240
+ "explanation": llm_result.get("explanation", ""),
2241
+ "reason": llm_result.get("reason"),
2242
+ "conflict_detected": llm_result.get("conflict_detected", False),
2243
+ "confidence": llm_result.get("confidence", "medium"),
2244
+ "short_answers": llm_result.get("short_answers", []),
2245
+ "validation_error": bool(llm_result.get("validation_error", False)),
2246
+ "repair_attempts": int(llm_result.get("repair_attempts", 0)),
2247
+ "dropped_citations": int(llm_result.get("dropped_citations", 0) or 0),
2248
+ "method": "llm",
2249
+ "retrieval_mode": retrieval_mode,
2250
+ "timings": timings,
2251
+ "candidates": [asdict(x) for x in diversified],
2252
+ **({"conflict_free": conflict_free} if conflict_free is not None else {}),
2253
+ **({"answer_rebuilt": bool(llm_result.get("answer_rebuilt", False))}
2254
+ if policy == "answer_and_flag_final" else {}),
2255
+ }
2256
+ else:
2257
+ failed = generation_failure(
2258
+ "Generation is disabled; retrieved evidence is shown without selecting an answer."
2259
+ )
2260
+ return {
2261
+ **failed,
2262
+ "source": None,
2263
+ "method": "generation_disabled",
2264
+ "retrieval_mode": retrieval_mode,
2265
+ "candidates": [asdict(x) for x in diversified]
2266
+ }
2267
+
2268
+
2269
+ # ============================================================
2270
+ # MAIN - Interactive Mode
2271
+ # ============================================================
2272
+
2273
+ def interactive_mode(doc_dir, project_id=None, region=None, api_key=None, use_llm=True):
2274
+ """Run GOV-RAG in interactive mode with Vertex AI or Gemini."""
2275
+ rag = GovRAGGemini(doc_dir, project_id=project_id, region=region, api_key=api_key, use_llm=use_llm)
2276
+
2277
+ while True:
2278
+ question = input("\nQuestion (or 'exit'): ").strip()
2279
+
2280
+ if question.lower() == "exit":
2281
+ break
2282
+
2283
+ result = rag.query(question)
2284
+
2285
+ print("\nGOV-RAG RESULT (Gemini)")
2286
+ print("=" * 60)
2287
+ print(json.dumps(result, indent=2, default=str))
2288
+
2289
+
2290
+ if __name__ == "__main__":
2291
+ import sys
2292
+
2293
+ if len(sys.argv) > 1:
2294
+ doc_dir = sys.argv[1]
2295
+ project_id = sys.argv[2] if len(sys.argv) > 2 else None
2296
+ else:
2297
+ print("Usage: python pipeline/gov_rag_gemini.py <document_directory> [project_id]")
2298
+ print("\nExample with Vertex AI:")
2299
+ print(" export GOOGLE_CLOUD_PROJECT='your-project-id'")
2300
+ print(" gcloud auth application-default login")
2301
+ print(" python pipeline/gov_rag_gemini.py conflictbench_fictional_full/packs/easy")
2302
+ print("\nOr with AI Studio:")
2303
+ print(" export GOOGLE_API_KEY='your-api-key'")
2304
+ print(" python pipeline/gov_rag_gemini.py conflictbench_fictional_full/packs/easy")
2305
+ sys.exit(1)
2306
+
2307
+ interactive_mode(doc_dir, project_id=project_id)