docresolve 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gaurav Najpande and Vivek Gupta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.4
2
+ Name: docresolve
3
+ Version: 0.1.0
4
+ Summary: Conflict-aware question answering over documents that disagree: commits to an answer, flags the dissent, cites verbatim.
5
+ Author: Gaurav Najpande, Vivek Gupta
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/fridayyy3000/DocResolve
8
+ Project-URL: Repository, https://github.com/fridayyy3000/DocResolve
9
+ Project-URL: Documentation, https://fridayyy3000.github.io/DocResolve/
10
+ Project-URL: Issues, https://github.com/fridayyy3000/DocResolve/issues
11
+ Keywords: rag,retrieval-augmented-generation,knowledge-conflicts,question-answering,citations,llm
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Text Processing :: Indexing
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy<2,>=1.26
25
+ Requires-Dist: sentence-transformers>=3.0
26
+ Requires-Dist: openai>=1.40
27
+ Requires-Dist: rank-bm25>=0.2.2
28
+ Requires-Dist: pypdf>=5.0
29
+ Requires-Dist: python-docx>=1.1
30
+ Provides-Extra: server
31
+ Requires-Dist: fastapi>=0.115; extra == "server"
32
+ Requires-Dist: uvicorn[standard]>=0.30; extra == "server"
33
+ Requires-Dist: python-multipart>=0.0.9; extra == "server"
34
+ Requires-Dist: pydantic>=2.9; extra == "server"
35
+ Requires-Dist: mammoth>=1.8; extra == "server"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=8; extra == "dev"
38
+ Requires-Dist: build>=1.2; extra == "dev"
39
+ Requires-Dist: twine>=5; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # DocResolve
43
+
44
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
46
+ [![Project page](https://img.shields.io/badge/project-page-245c49.svg)](https://fridayyy3000.github.io/DocResolve/)
47
+
48
+ Conflict-aware question answering over documents that disagree. DocResolve retrieves,
49
+ notices when the sources give different values, **commits to one answer under a stated
50
+ resolution order, flags the dissent**, and cites every claim as a verbatim quote you can
51
+ open at the sentence in the original PDF, Word or text file.
52
+
53
+ By Gaurav Najpande and Vivek Gupta.
54
+
55
+ ![DocResolve demo: load twelve disagreeing documents, get a committed answer with the dissent flagged, mark the governing bulletin superseded, and watch the answer re-evaluate](assets/demo.gif)
56
+
57
+ Plain RAG follows the most repeated value, which is how superseded and copied documents
58
+ beat the one authoritative source. Refuse-on-conflict systems abstain on exactly the
59
+ questions people ask. DocResolve does neither. Governance signals come first (status,
60
+ authority, scope), then corroboration counted in distinct documents, then consistency.
61
+ Factual disagreements are always resolved, the rejected value is named as rejected, and a
62
+ reviewer can override a document's status and watch the answer re-evaluate.
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install git+https://github.com/fridayyy3000/DocResolve
68
+ ```
69
+
70
+ Python 3.10 or newer. Embeddings run locally (`BAAI/bge-small-en-v1.5`, downloaded on
71
+ first use, about 130 MB). Generation goes to any OpenAI-compatible chat endpoint, so you
72
+ bring either **your own API key** or **a locally hosted model**. Nothing is bundled.
73
+
74
+ ## Bring your own key, or your own model
75
+
76
+ **Option A, a hosted endpoint with your key.** The default endpoint is the NVIDIA API
77
+ catalogue; any OpenAI-compatible provider works.
78
+
79
+ ```bash
80
+ export NVIDIA_API_KEY=... # NVIDIA API catalogue (default endpoint)
81
+ # or
82
+ export OPENAI_API_KEY=... DOCRESOLVE_BASE_URL=https://api.openai.com/v1 NEMOTRON_MODEL=gpt-4o-mini
83
+ ```
84
+
85
+ **Option B, a model running on your machine.** No key is needed. Point the base URL at
86
+ the server and name the model it serves.
87
+
88
+ ```bash
89
+ # vLLM
90
+ export DOCRESOLVE_BASE_URL=http://localhost:8001/v1 NEMOTRON_MODEL=Qwen/Qwen3-32B
91
+ # Ollama
92
+ export DOCRESOLVE_BASE_URL=http://localhost:11434/v1 NEMOTRON_MODEL=qwen3:32b
93
+ # llama.cpp server
94
+ export DOCRESOLVE_BASE_URL=http://localhost:8080/v1 NEMOTRON_MODEL=default
95
+ ```
96
+
97
+ `NEMOTRON_THINKING=0` asks the server to turn the model's reasoning mode off (sent as
98
+ `chat_template_kwargs`, which vLLM honours and other servers ignore). The same
99
+ variables can live in a file: copy [`.env.example`](.env.example) to `demo/.env` for the
100
+ browser demo, or pass `--env-file path/to/.env` to the CLI. `.env` files are gitignored.
101
+
102
+ | Variable | Default | What it does |
103
+ |---|---|---|
104
+ | `NVIDIA_API_KEY` or `OPENAI_API_KEY` | none | key for a hosted endpoint (not needed for a local server) |
105
+ | `DOCRESOLVE_BASE_URL` | `https://integrate.api.nvidia.com/v1` | OpenAI-compatible chat endpoint |
106
+ | `NEMOTRON_MODEL` | `nvidia/nemotron-3.5-super-vl-120b-a12b` | chat model name at that endpoint |
107
+ | `NEMOTRON_THINKING` | `1` | `0` asks the server to turn the model's reasoning mode off |
108
+ | `NEMOTRON_TIMEOUT_S` | `300` | per-request timeout |
109
+ | `GOVRAG_EMBED_MODEL` | `BAAI/bge-small-en-v1.5` | local sentence-transformers embedder |
110
+ | `GOVRAG_RETRIEVAL` | `hybrid` | `hybrid` (BM25 + dense, RRF) or `dense` |
111
+ | `GOVRAG_POLICY` | `answer_and_flag_final` | `answer_and_flag_final`, `answer_and_flag` (first prompt), `strict` (refuse on conflict) |
112
+
113
+ ## Ask a question over a folder
114
+
115
+ ```bash
116
+ docresolve ask --docs ./my_policies "Which defect-rate limit applies to Q4-certified suppliers?"
117
+ ```
118
+
119
+ ```
120
+ Decision : answered (conflict flagged)
121
+ Answer : 0.72%, per the active and authoritative Policy Bulletin ...
122
+ Short : 0.72%
123
+ Citations:
124
+ [governing ] Policy Bulletin.md: "For Q4-certified suppliers, the current requirement is 0.72%."
125
+ [conflicting] FAQ.md: "It answers that Q4-certified suppliers uses 1.00%"
126
+ ```
127
+
128
+ `--docs` is searched recursively for `.md`, `.txt`, `.pdf` and `.docx`. `--json` prints the
129
+ full result (decision, answer, citations with chunk ids and treatments, competing values,
130
+ explanation). `--model`, `--base-url`, `--embed-model`, `--retrieval` and `--policy`
131
+ override the environment for one call.
132
+
133
+ From Python:
134
+
135
+ ```python
136
+ from docresolve import load_folder, build_pipeline
137
+
138
+ pipe = build_pipeline(load_folder("./my_policies")) # key / base URL from the environment
139
+ # pipe = build_pipeline(docs, base_url="http://localhost:11434/v1", model="qwen3:32b")
140
+ result = pipe.query("Which defect-rate limit applies to Q4-certified suppliers?")
141
+ result["decision"], result["answer"], result["citations"]
142
+ ```
143
+
144
+ Ablations are arguments: `policy="answer_and_flag"` (first prompt), `policy="strict"`
145
+ (refuse on conflict), `retrieval="dense"`.
146
+
147
+ ## The browser demo
148
+
149
+ The evidence-review interface (result card, corroboration strip, reader with sentence
150
+ highlights in the original file, governance overrides, audit record) is a FastAPI server
151
+ in [`demo/`](demo/).
152
+
153
+ ```bash
154
+ git clone https://github.com/fridayyy3000/DocResolve && cd DocResolve
155
+ pip install -e ".[server]" -r demo/requirements.txt
156
+ cp .env.example demo/.env # then fill in a key, or a local base URL
157
+ python -m uvicorn main:app --app-dir demo --port 8000
158
+ ```
159
+
160
+ Open http://localhost:8000/app. Create a workspace, drop in files or a whole folder, ask.
161
+ The server ships with the paper's governed policy pack ([`policy_pack/`](policy_pack/),
162
+ 30 questions over 360 documents) and can load any question of the RAMDocs and CONFLICTS
163
+ benchmarks once they are downloaded from their original hosts:
164
+
165
+ ```bash
166
+ python demo/fetch_benchmarks.py # RAMDocs (MIT) and CONFLICTS (Apache-2.0) into data/external/
167
+ ```
168
+
169
+ | Result card | Reader with the cited sentence highlighted |
170
+ |---|---|
171
+ | ![Result card](docs/images/fig_result_card.png) | ![Reader](docs/images/fig_reader.png) |
172
+
173
+ The server-side folder connector (index a folder path typed in the UI) is off by default.
174
+ Enable it with `DOCRESOLVE_ALLOWED_ROOTS=/path/that/may/be/indexed`. Offline tests:
175
+
176
+ ```bash
177
+ python -m pytest -q demo/test_inspectable_evidence.py
178
+ ```
179
+
180
+ A Dockerfile is included: `docker build -f demo/Dockerfile -t docresolve-demo .` then
181
+ `docker run -p 8000:8000 -e NVIDIA_API_KEY=... docresolve-demo`.
182
+
183
+ ## How it works
184
+
185
+ | Stage | Setting |
186
+ |---|---|
187
+ | First-stage retrieval | BM25 + dense (`bge-small`), reciprocal-rank fusion, top 30 chunks |
188
+ | Reranking | 0.30 semantic + gate × (0.50 authority + 0.20 scope); status, authority and scope read from the documents |
189
+ | Conflict diversification | claim values extracted per chunk; duplicates collapsed so every competing value survives; 8 chunks kept |
190
+ | Resolution policy | answer-and-flag: governance first, then corroboration counted in distinct documents, then consistency; factual disagreements always resolved; the rejected value named as rejected |
191
+ | Validation | every citation must be a retrieved chunk and a verbatim quote, and the answer must not carry a rejected value; one repair, then salvage |
192
+
193
+ The package in [`docresolve/`](docresolve/) is the pipeline exactly as evaluated:
194
+ `core.py` (ranking, diversification, prompts, validation), `providers.py` (local embedder,
195
+ OpenAI-compatible generator), `chunker.py`, `document_parser.py`, `cli.py`.
196
+
197
+ ## Results
198
+
199
+ Fully correct (FC, higher is better) and incorrect (Inc, lower is better) answer rates
200
+ judged by an LLM judge, mean over three generators on two public conflict benchmarks
201
+ (RAMDocs test set, CONFLICTS). Same retriever and generator for every row except the
202
+ frameworks.
203
+
204
+ | System | FC ↑ | Inc ↓ |
205
+ |---|---|---|
206
+ | **DocResolve** (hybrid, answer-and-flag) | **59.2** | **23.8** |
207
+ | Hybrid RAG (no policy) | 53.9 | 25.0 |
208
+ | Vanilla RAG (dense retrieval) | 51.3 | 27.0 |
209
+ | Direct CoT (no retrieval) | 27.3 | 60.0 |
210
+ | LlamaIndex, k=8 | 53.8 | 25.9 |
211
+ | LlamaIndex, k=2 | 38.2 | 36.9 |
212
+ | Rankify | 53.4 | 27.2 |
213
+
214
+ On the governed policy pack (30 questions, each with one authoritative document against
215
+ superseded, draft, out-of-scope and copied ones), DocResolve answers 100% correctly against
216
+ 56.7% for Hybrid RAG and 70.0% for Vanilla RAG; with the governance signals removed it
217
+ falls to 76.7%, which is what the signals are worth. Full tables, per-cell significance
218
+ tests and the judge-agreement study are in the paper.
219
+
220
+ ## Repository layout
221
+
222
+ ```
223
+ docresolve/ the pip package: the pipeline as evaluated (CLI: docresolve ask)
224
+ demo/ FastAPI server and browser UI
225
+ main.py routes, workspaces, overrides, audit record
226
+ demo_benchmarks.py RAMDocs / CONFLICTS loaders for the picker
227
+ fetch_benchmarks.py downloads the two benchmarks from their original hosts
228
+ pipeline/ the harness copy of the pipeline plus corpus store and evidence locator
229
+ static/ the UI (plain HTML, CSS, JS)
230
+ policy_pack/ the governed policy pack: 30 questions, 360 documents, manifest
231
+ docs/ project website (GitHub Pages)
232
+ .env.example every variable the CLI and the demo read
233
+ ```
234
+
235
+ ## Data and licences
236
+
237
+ Code is MIT. The policy pack is synthetic (fictional companies and policies) and released
238
+ under the same licence. RAMDocs (MIT) and CONFLICTS (Apache-2.0) are downloaded from their
239
+ original hosts by `demo/fetch_benchmarks.py` and keep their own licences; they are not
240
+ redistributed here.
@@ -0,0 +1,199 @@
1
+ # DocResolve
2
+
3
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](pyproject.toml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
5
+ [![Project page](https://img.shields.io/badge/project-page-245c49.svg)](https://fridayyy3000.github.io/DocResolve/)
6
+
7
+ Conflict-aware question answering over documents that disagree. DocResolve retrieves,
8
+ notices when the sources give different values, **commits to one answer under a stated
9
+ resolution order, flags the dissent**, and cites every claim as a verbatim quote you can
10
+ open at the sentence in the original PDF, Word or text file.
11
+
12
+ By Gaurav Najpande and Vivek Gupta.
13
+
14
+ ![DocResolve demo: load twelve disagreeing documents, get a committed answer with the dissent flagged, mark the governing bulletin superseded, and watch the answer re-evaluate](assets/demo.gif)
15
+
16
+ Plain RAG follows the most repeated value, which is how superseded and copied documents
17
+ beat the one authoritative source. Refuse-on-conflict systems abstain on exactly the
18
+ questions people ask. DocResolve does neither. Governance signals come first (status,
19
+ authority, scope), then corroboration counted in distinct documents, then consistency.
20
+ Factual disagreements are always resolved, the rejected value is named as rejected, and a
21
+ reviewer can override a document's status and watch the answer re-evaluate.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install git+https://github.com/fridayyy3000/DocResolve
27
+ ```
28
+
29
+ Python 3.10 or newer. Embeddings run locally (`BAAI/bge-small-en-v1.5`, downloaded on
30
+ first use, about 130 MB). Generation goes to any OpenAI-compatible chat endpoint, so you
31
+ bring either **your own API key** or **a locally hosted model**. Nothing is bundled.
32
+
33
+ ## Bring your own key, or your own model
34
+
35
+ **Option A, a hosted endpoint with your key.** The default endpoint is the NVIDIA API
36
+ catalogue; any OpenAI-compatible provider works.
37
+
38
+ ```bash
39
+ export NVIDIA_API_KEY=... # NVIDIA API catalogue (default endpoint)
40
+ # or
41
+ export OPENAI_API_KEY=... DOCRESOLVE_BASE_URL=https://api.openai.com/v1 NEMOTRON_MODEL=gpt-4o-mini
42
+ ```
43
+
44
+ **Option B, a model running on your machine.** No key is needed. Point the base URL at
45
+ the server and name the model it serves.
46
+
47
+ ```bash
48
+ # vLLM
49
+ export DOCRESOLVE_BASE_URL=http://localhost:8001/v1 NEMOTRON_MODEL=Qwen/Qwen3-32B
50
+ # Ollama
51
+ export DOCRESOLVE_BASE_URL=http://localhost:11434/v1 NEMOTRON_MODEL=qwen3:32b
52
+ # llama.cpp server
53
+ export DOCRESOLVE_BASE_URL=http://localhost:8080/v1 NEMOTRON_MODEL=default
54
+ ```
55
+
56
+ `NEMOTRON_THINKING=0` asks the server to turn the model's reasoning mode off (sent as
57
+ `chat_template_kwargs`, which vLLM honours and other servers ignore). The same
58
+ variables can live in a file: copy [`.env.example`](.env.example) to `demo/.env` for the
59
+ browser demo, or pass `--env-file path/to/.env` to the CLI. `.env` files are gitignored.
60
+
61
+ | Variable | Default | What it does |
62
+ |---|---|---|
63
+ | `NVIDIA_API_KEY` or `OPENAI_API_KEY` | none | key for a hosted endpoint (not needed for a local server) |
64
+ | `DOCRESOLVE_BASE_URL` | `https://integrate.api.nvidia.com/v1` | OpenAI-compatible chat endpoint |
65
+ | `NEMOTRON_MODEL` | `nvidia/nemotron-3.5-super-vl-120b-a12b` | chat model name at that endpoint |
66
+ | `NEMOTRON_THINKING` | `1` | `0` asks the server to turn the model's reasoning mode off |
67
+ | `NEMOTRON_TIMEOUT_S` | `300` | per-request timeout |
68
+ | `GOVRAG_EMBED_MODEL` | `BAAI/bge-small-en-v1.5` | local sentence-transformers embedder |
69
+ | `GOVRAG_RETRIEVAL` | `hybrid` | `hybrid` (BM25 + dense, RRF) or `dense` |
70
+ | `GOVRAG_POLICY` | `answer_and_flag_final` | `answer_and_flag_final`, `answer_and_flag` (first prompt), `strict` (refuse on conflict) |
71
+
72
+ ## Ask a question over a folder
73
+
74
+ ```bash
75
+ docresolve ask --docs ./my_policies "Which defect-rate limit applies to Q4-certified suppliers?"
76
+ ```
77
+
78
+ ```
79
+ Decision : answered (conflict flagged)
80
+ Answer : 0.72%, per the active and authoritative Policy Bulletin ...
81
+ Short : 0.72%
82
+ Citations:
83
+ [governing ] Policy Bulletin.md: "For Q4-certified suppliers, the current requirement is 0.72%."
84
+ [conflicting] FAQ.md: "It answers that Q4-certified suppliers uses 1.00%"
85
+ ```
86
+
87
+ `--docs` is searched recursively for `.md`, `.txt`, `.pdf` and `.docx`. `--json` prints the
88
+ full result (decision, answer, citations with chunk ids and treatments, competing values,
89
+ explanation). `--model`, `--base-url`, `--embed-model`, `--retrieval` and `--policy`
90
+ override the environment for one call.
91
+
92
+ From Python:
93
+
94
+ ```python
95
+ from docresolve import load_folder, build_pipeline
96
+
97
+ pipe = build_pipeline(load_folder("./my_policies")) # key / base URL from the environment
98
+ # pipe = build_pipeline(docs, base_url="http://localhost:11434/v1", model="qwen3:32b")
99
+ result = pipe.query("Which defect-rate limit applies to Q4-certified suppliers?")
100
+ result["decision"], result["answer"], result["citations"]
101
+ ```
102
+
103
+ Ablations are arguments: `policy="answer_and_flag"` (first prompt), `policy="strict"`
104
+ (refuse on conflict), `retrieval="dense"`.
105
+
106
+ ## The browser demo
107
+
108
+ The evidence-review interface (result card, corroboration strip, reader with sentence
109
+ highlights in the original file, governance overrides, audit record) is a FastAPI server
110
+ in [`demo/`](demo/).
111
+
112
+ ```bash
113
+ git clone https://github.com/fridayyy3000/DocResolve && cd DocResolve
114
+ pip install -e ".[server]" -r demo/requirements.txt
115
+ cp .env.example demo/.env # then fill in a key, or a local base URL
116
+ python -m uvicorn main:app --app-dir demo --port 8000
117
+ ```
118
+
119
+ Open http://localhost:8000/app. Create a workspace, drop in files or a whole folder, ask.
120
+ The server ships with the paper's governed policy pack ([`policy_pack/`](policy_pack/),
121
+ 30 questions over 360 documents) and can load any question of the RAMDocs and CONFLICTS
122
+ benchmarks once they are downloaded from their original hosts:
123
+
124
+ ```bash
125
+ python demo/fetch_benchmarks.py # RAMDocs (MIT) and CONFLICTS (Apache-2.0) into data/external/
126
+ ```
127
+
128
+ | Result card | Reader with the cited sentence highlighted |
129
+ |---|---|
130
+ | ![Result card](docs/images/fig_result_card.png) | ![Reader](docs/images/fig_reader.png) |
131
+
132
+ The server-side folder connector (index a folder path typed in the UI) is off by default.
133
+ Enable it with `DOCRESOLVE_ALLOWED_ROOTS=/path/that/may/be/indexed`. Offline tests:
134
+
135
+ ```bash
136
+ python -m pytest -q demo/test_inspectable_evidence.py
137
+ ```
138
+
139
+ A Dockerfile is included: `docker build -f demo/Dockerfile -t docresolve-demo .` then
140
+ `docker run -p 8000:8000 -e NVIDIA_API_KEY=... docresolve-demo`.
141
+
142
+ ## How it works
143
+
144
+ | Stage | Setting |
145
+ |---|---|
146
+ | First-stage retrieval | BM25 + dense (`bge-small`), reciprocal-rank fusion, top 30 chunks |
147
+ | Reranking | 0.30 semantic + gate × (0.50 authority + 0.20 scope); status, authority and scope read from the documents |
148
+ | Conflict diversification | claim values extracted per chunk; duplicates collapsed so every competing value survives; 8 chunks kept |
149
+ | Resolution policy | answer-and-flag: governance first, then corroboration counted in distinct documents, then consistency; factual disagreements always resolved; the rejected value named as rejected |
150
+ | Validation | every citation must be a retrieved chunk and a verbatim quote, and the answer must not carry a rejected value; one repair, then salvage |
151
+
152
+ The package in [`docresolve/`](docresolve/) is the pipeline exactly as evaluated:
153
+ `core.py` (ranking, diversification, prompts, validation), `providers.py` (local embedder,
154
+ OpenAI-compatible generator), `chunker.py`, `document_parser.py`, `cli.py`.
155
+
156
+ ## Results
157
+
158
+ Fully correct (FC, higher is better) and incorrect (Inc, lower is better) answer rates
159
+ judged by an LLM judge, mean over three generators on two public conflict benchmarks
160
+ (RAMDocs test set, CONFLICTS). Same retriever and generator for every row except the
161
+ frameworks.
162
+
163
+ | System | FC ↑ | Inc ↓ |
164
+ |---|---|---|
165
+ | **DocResolve** (hybrid, answer-and-flag) | **59.2** | **23.8** |
166
+ | Hybrid RAG (no policy) | 53.9 | 25.0 |
167
+ | Vanilla RAG (dense retrieval) | 51.3 | 27.0 |
168
+ | Direct CoT (no retrieval) | 27.3 | 60.0 |
169
+ | LlamaIndex, k=8 | 53.8 | 25.9 |
170
+ | LlamaIndex, k=2 | 38.2 | 36.9 |
171
+ | Rankify | 53.4 | 27.2 |
172
+
173
+ On the governed policy pack (30 questions, each with one authoritative document against
174
+ superseded, draft, out-of-scope and copied ones), DocResolve answers 100% correctly against
175
+ 56.7% for Hybrid RAG and 70.0% for Vanilla RAG; with the governance signals removed it
176
+ falls to 76.7%, which is what the signals are worth. Full tables, per-cell significance
177
+ tests and the judge-agreement study are in the paper.
178
+
179
+ ## Repository layout
180
+
181
+ ```
182
+ docresolve/ the pip package: the pipeline as evaluated (CLI: docresolve ask)
183
+ demo/ FastAPI server and browser UI
184
+ main.py routes, workspaces, overrides, audit record
185
+ demo_benchmarks.py RAMDocs / CONFLICTS loaders for the picker
186
+ fetch_benchmarks.py downloads the two benchmarks from their original hosts
187
+ pipeline/ the harness copy of the pipeline plus corpus store and evidence locator
188
+ static/ the UI (plain HTML, CSS, JS)
189
+ policy_pack/ the governed policy pack: 30 questions, 360 documents, manifest
190
+ docs/ project website (GitHub Pages)
191
+ .env.example every variable the CLI and the demo read
192
+ ```
193
+
194
+ ## Data and licences
195
+
196
+ Code is MIT. The policy pack is synthetic (fictional companies and policies) and released
197
+ under the same licence. RAMDocs (MIT) and CONFLICTS (Apache-2.0) are downloaded from their
198
+ original hosts by `demo/fetch_benchmarks.py` and keep their own licences; they are not
199
+ redistributed here.
@@ -0,0 +1,80 @@
1
+ """DocResolve: conflict-aware retrieval-augmented answering over documents that disagree.
2
+
3
+ This package is the system configuration reported in the paper:
4
+
5
+ * first-stage retrieval: BM25 + dense fusion (``retrieval="hybrid"``)
6
+ * governance-aware reranking and conflict diversification
7
+ * resolution policy: answer-and-flag, final prompt (``policy="answer_and_flag_final"``):
8
+ governance -> corroboration by distinct documents -> consistency; factual
9
+ disagreements are always resolved and the answer states the committed value only.
10
+
11
+ Ablations stay available as arguments: ``policy="answer_and_flag"`` (the first prompt,
12
+ "without commitment"), ``policy="strict"`` (refuse on conflict), ``retrieval="dense"``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from pathlib import Path
19
+ from typing import List, Optional
20
+
21
+ from .core import Document, GovRAGGemini
22
+ from .document_parser import SUPPORTED_EXTENSIONS, parse_document_bytes
23
+ from .providers import LocalEmbedder, OpenAICompatGenerator
24
+
25
+ __all__ = [
26
+ "__version__",
27
+ "Document",
28
+ "GovRAGGemini",
29
+ "LocalEmbedder",
30
+ "OpenAICompatGenerator",
31
+ "DEFAULT_RETRIEVAL",
32
+ "DEFAULT_POLICY",
33
+ "load_folder",
34
+ "build_pipeline",
35
+ ]
36
+
37
+ __version__ = "0.1.0"
38
+ DEFAULT_RETRIEVAL = "hybrid"
39
+ DEFAULT_POLICY = "answer_and_flag_final"
40
+
41
+
42
+ def load_folder(folder: str) -> List[Document]:
43
+ """Load every supported file (.md, .txt, .pdf, .docx) under ``folder``.
44
+
45
+ The document name is the path relative to ``folder`` so a folder tree keeps
46
+ its structure in citations.
47
+ """
48
+ base = Path(folder)
49
+ if not base.is_dir():
50
+ raise FileNotFoundError(f"Not a directory: {folder}")
51
+ docs: List[Document] = []
52
+ for path in sorted(p for p in base.rglob("*") if p.is_file()):
53
+ ext = path.suffix.lower()
54
+ if ext not in SUPPORTED_EXTENSIONS:
55
+ continue
56
+ text = parse_document_bytes(path.read_bytes(), ext)
57
+ if text and text.strip():
58
+ docs.append(Document(filename=str(path.relative_to(base)), text=text))
59
+ if not docs:
60
+ raise ValueError(f"No supported documents ({', '.join(sorted(SUPPORTED_EXTENSIONS))}) found under {folder}")
61
+ return docs
62
+
63
+
64
+ def build_pipeline(
65
+ documents: List[Document],
66
+ model: Optional[str] = None,
67
+ base_url: Optional[str] = None,
68
+ api_key: Optional[str] = None,
69
+ embed_model: Optional[str] = None,
70
+ use_llm: bool = True,
71
+ ) -> GovRAGGemini:
72
+ """Index ``documents`` and return a ready pipeline.
73
+
74
+ ``model`` and ``base_url`` select any OpenAI-compatible chat endpoint
75
+ (defaults: ``NEMOTRON_MODEL`` / ``DOCRESOLVE_BASE_URL`` env vars, then the
76
+ NVIDIA hosted endpoint). The embedder runs locally.
77
+ """
78
+ embedder = LocalEmbedder(model_name=embed_model) if embed_model else LocalEmbedder()
79
+ generator = OpenAICompatGenerator(model=model, base_url=base_url, api_key=api_key) if use_llm else None
80
+ return GovRAGGemini(None, embedder=embedder, generator=generator, use_llm=use_llm, documents=documents)
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,125 @@
1
+ """Split long documents into overlapping chunks for retrieval.
2
+
3
+ Short documents (the common case for ConflictBench-style single-page bulletins)
4
+ are returned as a single chunk, so existing whole-document behavior is
5
+ unchanged when a document already fits within the target size.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import List, NamedTuple, Optional
12
+
13
+ # Word count is used as a cheap proxy for token count (~0.75 words/token is
14
+ # typical for English, so this comfortably targets the requested 800-1200
15
+ # token / 100-200 token overlap range without adding a tokenizer dependency).
16
+ TARGET_CHUNK_WORDS = 900
17
+ OVERLAP_WORDS = 150
18
+ MIN_CHUNK_WORDS = 50
19
+
20
+
21
+ class ChunkSegment(NamedTuple):
22
+ text: str
23
+ page_start: Optional[int] = None
24
+ page_end: Optional[int] = None
25
+ section: Optional[str] = None
26
+
27
+
28
+ def _split_paragraphs(text: str) -> List[str]:
29
+ paragraphs = re.split(r"\n\s*\n", text.strip())
30
+ return [p.strip() for p in paragraphs if p.strip()]
31
+
32
+
33
+ def _split_sentences(text: str) -> List[str]:
34
+ return [s.strip() for s in re.split(r"(?<=[.!?])\s+|\n+", text) if s.strip()]
35
+
36
+
37
+ def _word_count(text: str) -> int:
38
+ return len(text.split())
39
+
40
+
41
+ def chunk_text(
42
+ text: str,
43
+ target_words: int = TARGET_CHUNK_WORDS,
44
+ overlap_words: int = OVERLAP_WORDS,
45
+ ) -> List[str]:
46
+ """Split text into overlapping chunks on paragraph/sentence boundaries."""
47
+ text = text.strip()
48
+ if not text:
49
+ return []
50
+
51
+ if _word_count(text) <= target_words:
52
+ return [text]
53
+
54
+ # Paragraphs are the preferred unit; any paragraph bigger than the target
55
+ # on its own is further split into sentences so nothing gets skipped.
56
+ units: List[str] = []
57
+ for para in _split_paragraphs(text):
58
+ if _word_count(para) <= target_words:
59
+ units.append(para)
60
+ else:
61
+ units.extend(_split_sentences(para))
62
+
63
+ chunks: List[str] = []
64
+ buffer_units: List[str] = []
65
+ buffer_words = 0
66
+
67
+ def flush() -> None:
68
+ nonlocal buffer_units, buffer_words
69
+ if buffer_units:
70
+ chunks.append(" ".join(buffer_units).strip())
71
+ buffer_units = []
72
+ buffer_words = 0
73
+
74
+ for unit in units:
75
+ unit_words = _word_count(unit)
76
+
77
+ if buffer_words + unit_words > target_words and buffer_units:
78
+ flush()
79
+ # Carry trailing overlap words forward from the chunk just finished.
80
+ if chunks:
81
+ tail_words = chunks[-1].split()[-overlap_words:]
82
+ if tail_words:
83
+ buffer_units = [" ".join(tail_words)]
84
+ buffer_words = len(tail_words)
85
+
86
+ buffer_units.append(unit)
87
+ buffer_words += unit_words
88
+
89
+ flush()
90
+
91
+ # Merge a too-small trailing chunk into the previous one.
92
+ if len(chunks) > 1 and _word_count(chunks[-1]) < MIN_CHUNK_WORDS:
93
+ chunks[-2] = chunks[-2] + " " + chunks[-1]
94
+ chunks.pop()
95
+
96
+ return chunks
97
+
98
+
99
+ def chunk_text_with_locations(text: str) -> List[ChunkSegment]:
100
+ """Chunk normalized text and attach only locations explicitly available."""
101
+ if "\f" in text:
102
+ segments = []
103
+ for page_number, page_text in enumerate(text.split("\f"), start=1):
104
+ page_chunks = chunk_text(page_text)
105
+ for page_chunk in page_chunks:
106
+ segments.append(ChunkSegment(
107
+ text=page_chunk,
108
+ page_start=page_number,
109
+ page_end=page_number,
110
+ section=_section_for_text(page_chunk),
111
+ ))
112
+ return segments
113
+
114
+ return [
115
+ ChunkSegment(text=chunk, section=_section_for_text(chunk))
116
+ for chunk in chunk_text(text)
117
+ ]
118
+
119
+
120
+ def _section_for_text(text: str) -> Optional[str]:
121
+ for line in text.splitlines():
122
+ match = re.match(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$", line)
123
+ if match:
124
+ return match.group(1).strip()
125
+ return None