truthbench 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.
Files changed (32) hide show
  1. truthbench-0.1.0/PKG-INFO +374 -0
  2. truthbench-0.1.0/README.md +344 -0
  3. truthbench-0.1.0/pyproject.toml +52 -0
  4. truthbench-0.1.0/src/truthbench/__init__.py +4 -0
  5. truthbench-0.1.0/src/truthbench/cli.py +46 -0
  6. truthbench-0.1.0/src/truthbench/llms/__init__.py +0 -0
  7. truthbench-0.1.0/src/truthbench/llms/__pycache__/__init__.cpython-311.pyc +0 -0
  8. truthbench-0.1.0/src/truthbench/llms/__pycache__/openai.cpython-311.pyc +0 -0
  9. truthbench-0.1.0/src/truthbench/llms/openai.py +16 -0
  10. truthbench-0.1.0/src/truthbench/models.py +51 -0
  11. truthbench-0.1.0/src/truthbench/pipeline.py +174 -0
  12. truthbench-0.1.0/src/truthbench/readers/__init__.py +0 -0
  13. truthbench-0.1.0/src/truthbench/readers/__pycache__/__init__.cpython-311.pyc +0 -0
  14. truthbench-0.1.0/src/truthbench/readers/__pycache__/json_reader.cpython-311.pyc +0 -0
  15. truthbench-0.1.0/src/truthbench/readers/json_reader.py +52 -0
  16. truthbench-0.1.0/src/truthbench/steps/__init__.py +0 -0
  17. truthbench-0.1.0/src/truthbench/steps/__pycache__/__init__.cpython-311.pyc +0 -0
  18. truthbench-0.1.0/src/truthbench/steps/__pycache__/blacklist.cpython-311.pyc +0 -0
  19. truthbench-0.1.0/src/truthbench/steps/__pycache__/counter.cpython-311.pyc +0 -0
  20. truthbench-0.1.0/src/truthbench/steps/__pycache__/factual.cpython-311.pyc +0 -0
  21. truthbench-0.1.0/src/truthbench/steps/__pycache__/filter.cpython-311.pyc +0 -0
  22. truthbench-0.1.0/src/truthbench/steps/__pycache__/noise.cpython-311.pyc +0 -0
  23. truthbench-0.1.0/src/truthbench/steps/__pycache__/paraphrase.cpython-311.pyc +0 -0
  24. truthbench-0.1.0/src/truthbench/steps/__pycache__/rank.cpython-311.pyc +0 -0
  25. truthbench-0.1.0/src/truthbench/steps/blacklist.py +60 -0
  26. truthbench-0.1.0/src/truthbench/steps/counter.py +46 -0
  27. truthbench-0.1.0/src/truthbench/steps/factual.py +228 -0
  28. truthbench-0.1.0/src/truthbench/steps/filter.py +61 -0
  29. truthbench-0.1.0/src/truthbench/steps/noise.py +198 -0
  30. truthbench-0.1.0/src/truthbench/steps/paraphrase.py +72 -0
  31. truthbench-0.1.0/src/truthbench/steps/rank.py +129 -0
  32. truthbench-0.1.0/src/truthbench/truth_pipeline.py +54 -0
@@ -0,0 +1,374 @@
1
+ Metadata-Version: 2.1
2
+ Name: truthbench
3
+ Version: 0.1.0
4
+ Summary: A pipeline-based framework to evaluate factual consistency metrics.
5
+ License: MIT
6
+ Keywords: nlp,factuality,evaluation,llm,spacy,hallucination,truthfulness,benchmark
7
+ Author: Giovanni Gatti Pinheiro
8
+ Author-email: giovanni.gatti.pinheiro@gmail.com
9
+ Requires-Python: >=3.10,<3.14
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
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: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: Text Processing :: Linguistic
25
+ Provides-Extra: openai
26
+ Requires-Dist: openai (>=1.82.0,<2.0.0) ; extra == "openai"
27
+ Requires-Dist: spacy (>=3.8.7,<4.0.0)
28
+ Description-Content-Type: text/markdown
29
+
30
+ # TruthBench
31
+
32
+ `truthbench` is a modular pipeline designed to generate controlled factual perturbations of ground-truth answers. These
33
+ perturbations enable fine-grained meta-evaluation of factuality metrics used to assess large language model (LLM)
34
+ outputs.
35
+
36
+ While many tools exist to judge whether LLM-generated answers are "factual," their own sensitivity, reliability, and
37
+ robustness remain underexplored. `truthbench` provides a way to systematically test these tools using corrupted versions
38
+ of correct answers, ranging from semantically faithful paraphrases to subtly or severely inaccurate alternatives.
39
+
40
+ # Key Features
41
+
42
+ * 🧠 LLM-based Paraphrasing and Corruption: Produces answer variants (A0–A4) that span a factuality spectrum.
43
+ * 🏗️ Step-by-Step Pipeline Architecture: Modular components for paraphrasing, information extraction, perturbation, and
44
+ grouping.
45
+ * 🎯 Controlled Evaluation Levels: Supports reproducible degradation of factual content while preserving fluency and
46
+ answer
47
+ structure.
48
+ * 🔍 Built for Evaluating Evaluators: Enables validation of popular factuality metrics like RAGAS, FactScore, and
49
+ LLM-as-judge models.
50
+
51
+ # Use Cases
52
+
53
+ * Meta-evaluating factuality metrics in open-ended QA settings.
54
+ * Building datasets with graded factual errors.
55
+ * Benchmarking the sensitivity of evaluation tools to fine-grained truth degradation.
56
+
57
+ # How It Works
58
+
59
+ The pipeline takes a question and ground-truth answer, and produces 5 graded answers:
60
+
61
+ | Answer | Description |
62
+ |--------|-------------------------------------------|
63
+ | `A0` | Faithful paraphrase of the ground truth |
64
+ | `A1` | Mild factual perturbation |
65
+ | `A2` | Moderate factual error |
66
+ | `A3` | High factual degradation |
67
+ | `A4` | Severely incorrect or misleading response |
68
+
69
+ Internally, the pipeline follows these stages:
70
+
71
+ 1. Paraphrase Ground Truth (A0)
72
+ 2. Extract Key Factual Components
73
+ 3. Filter Overlap with Question
74
+ 4. Rank Factual Importance
75
+ 5. Group by Perturbation Level
76
+ 6. Generate Perturbed Answers (A1–A4)
77
+
78
+ Each step is implemented as a modular Step class, enabling customization and extension.
79
+
80
+ # Example
81
+
82
+ <details>
83
+ <summary><strong>Example</strong>: <em>Who did the United States win its independence from?</em></summary>
84
+
85
+ **A0 (Reference)**
86
+ Independence Day, commonly known as the Fourth of July or July Fourth, is **a federal holiday** in the United States
87
+ celebrating **the adoption of the Declaration of Independence** **on July 4, 1776**. **On this day**, the Continental
88
+ Congress announced that the thirteen American colonies considered themselves a new nation, called **the United States of
89
+ America**, and were no longer under **British rule**. Interestingly, the Congress had voted to declare independence *
90
+ *two days** earlier, **on July 2**.
91
+
92
+ **A1 (Low perturbation)**
93
+ ... celebrating **the adoption of the Declaration of Independence** ~~on July 4, 1776~~ **on August 5, 1776** ...
94
+
95
+ **A2 (Medium perturbation)**
96
+ ... celebrating the Declaration of Independence **on August 5, 1781**. ~~On this day~~ **On that moment**, ...
97
+
98
+ **A3 (High perturbation)**
99
+ ... is **an unofficial event** ... celebrating **a proposal of the Declaration of Independence** **on August 5, 1781
100
+ ** ...
101
+
102
+ **A4 (Extreme perturbation)**
103
+ ... celebrating **a proposal of the drafting of Independence** **on August 5, 1781** ... called **the United States of
104
+ the Colonies**, and were no longer under **Spanish rule**.
105
+
106
+ </details>
107
+
108
+ # Using the perturbation pipeline
109
+
110
+ ## CLI Usage
111
+
112
+ You can run the TruthBench pipeline directly from the command line.
113
+
114
+ ### Installation
115
+
116
+ Install the package with optional OpenAI dependencies:
117
+
118
+ ```bash
119
+ pip install truthbench[openai]
120
+ ```
121
+
122
+ ### Download required spaCy model
123
+
124
+ TruthBench relies on the spaCy English model. Download it once with:
125
+
126
+ ```bash
127
+ python -m spacy download en_core_web_sm
128
+ ```
129
+
130
+ ### Set your OpenAI API key
131
+
132
+ Export your OpenAI API key as an environment variable:
133
+
134
+ ```bash
135
+ export OPENAI_API_KEY="your_openai_api_key_here"
136
+ ```
137
+
138
+ ### Run the pipeline
139
+
140
+ ```bash
141
+ truthbench --input-file path/to/input.json --output-dir path/to/output_dir
142
+ ```
143
+
144
+ This will create `report.json` and `dataset.json` inside `output_dir`.
145
+
146
+ ### Output File Formats
147
+
148
+ After running the pipeline, two main output files are generated in the output directory:
149
+
150
+ #### 1. `dataset.json`
151
+
152
+ This file contains the input questions along with multiple generated answer variants.
153
+
154
+ - **Structure:**
155
+
156
+ ```jsonc
157
+ {
158
+ "questions": [
159
+ {
160
+ "id": 0, // Unique identifier for the question
161
+ "question": "why is the sky blue?", // The original question text.
162
+ "ground_truth": "The sky appears to be blue because...", // The correct answer text.
163
+ "answers": { // A dictionary of answer variants with increased perturbation levels
164
+ "A0": "The sky looks blue because...",
165
+ "A1": "...",
166
+ "A2": "...",
167
+ "A3": "...",
168
+ "A4": "..."
169
+ }
170
+ },
171
+ // ...
172
+ ]
173
+ }
174
+ ```
175
+
176
+ #### 2. `report.json`
177
+
178
+ This file contains all the processing details.
179
+
180
+ ```jsonc
181
+ {
182
+ "report": { // Summary metrics about the evaluation (counts of samples, errors, etc.)
183
+ "input_samples": 100,
184
+ "find_factual_data_error": 0,
185
+ "json_parse_ranking_error": 3,
186
+ "index_ranking_error": 52,
187
+ "ranking_factual_data_error": 2,
188
+ "output_samples": 100
189
+ },
190
+ "questions": [ // The complete processing trace for every dataset sample
191
+ {
192
+ "question": "what do the 3 dots mean in math?",
193
+ "ground_truth": "In logical argument...",
194
+ "raw_factual_data": [
195
+ "logical reasoning",
196
+ "...",
197
+ ],
198
+ "with_brackets": {
199
+ "A0": "In [logical reasoning] and [mathematics] ..."
200
+ // ...
201
+ },
202
+ // ...
203
+ },
204
+ // ...
205
+ ]
206
+ }
207
+ ```
208
+
209
+ ## Creating a Custom Reader, Step, and Using an Open-Source LLM in the Pipeline
210
+
211
+ You can customize the pipeline to your needs. You may combine your custom implementations with available code or
212
+ override any blocks.
213
+
214
+ The `Pipeline` runs on three abstractions:
215
+
216
+ * `Reader`: fetches data;
217
+ * `Step`: provides the processing logic;
218
+ * `Pipeline`: holds a sequence of steps and execute them.
219
+
220
+ You can declare a pipeline by chaining a sequence of `Step`s and run it like this...
221
+
222
+ ```python
223
+ from truthbench import Pipeline
224
+ from truthbench.steps.counter import CounterStep
225
+ from truthbench.steps.paraphrase import ParaphraseStep
226
+
227
+ llm = ...
228
+ reader = ...
229
+
230
+ p = (
231
+ Pipeline()
232
+ .with_step(ParaphraseStep(llm))
233
+ .with_step(CounterStep(expected_levels=5))
234
+ )
235
+
236
+ samples, tracker = p.run(reader)
237
+ ```
238
+
239
+ The `samples` contain the list with the processing traces for each sample, while `tracker` has general stats about the
240
+ processing.
241
+
242
+ Adding a custom step requires you to implement a `Step` abstract class.
243
+
244
+ ```python
245
+ from typing import Dict, Any
246
+ from truthbench import Step
247
+
248
+
249
+ class WordCountStep(Step):
250
+ def __init__(self):
251
+ super().__init__(required_fields={"paraphrased_question"}, counters=frozenset({"word_counted"}))
252
+
253
+ def step(self, sample: Dict[str, Any], tracker: Dict[str, int]) -> None:
254
+ question = sample["paraphrased_question"]
255
+ sample["word_count"] = len(question.split())
256
+ tracker["word_counted"] += 1
257
+ ```
258
+
259
+ Each step may have a dependency on previous processing. In the above example, it requires that a previous step has
260
+ computed `paraphrased_question`. If that's not the case, you likely have a dependency issue or a bug worth
261
+ investigating. A step can also declare a set of `counters` it needs to keep track of stats. In the above example, it
262
+ declares it may increment `word_counted`.
263
+
264
+ The following steps are available:
265
+
266
+ | **Step Name** | **Description** | **Updated Counters** | **Required Fields** |
267
+ |-----------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|--------------------------------------------|
268
+ | [`ParaphraseStep`](truthbench/src/truthbench/steps/paraphrase.py) | Generates a faithful paraphrase of the ground-truth answer using the LLM. | *(none)* | `ground_truth` |
269
+ | [`FactualDataStep`](truthbench/src/truthbench/steps/factual.py) | Identifies factual spans in a sentence using spaCy and brackets them. | `find_factual_data_error` | `answers` |
270
+ | [`BlacklistItemsFromQuestionStep`](truthbench/src/truthbench/steps/blacklist.py)) | Removes factual items from `raw_factual_data` if they appear in the question (minus stopwords). | *(none)* | `question`, `raw_factual_data` |
271
+ | [`RankFactualDataStep`](truthbench/src/truthbench/steps/rank.py) | Uses an LLM to assign an importance ranking to factual terms based on a bracketed sentence. | `ranked_factual_data`, `index_ranking_error`, `ranking_factual_data_error`, `json_parse_ranking_error` | `with_brackets`, `raw_factual_data` |
272
+ | [`FilterFactualDataStep`](truthbench/src/truthbench/steps/filter.py) | Keeps top-ranked factual items and removes those blacklisted (present in the question). | *(none)* | `ranked_factual_data`, `blacklisted` |
273
+ | [`CreateNoiseExamplesStep`](truthbench/src/truthbench/steps/noise.py) | Generates noisy paraphrases with varying levels of factual degradation using factual spans. | *(none)* | `factual_data`, `with_brackets`, `answers` |
274
+ | [`CounterStep`](truthbench/src/truthbench/steps/counter.py) | Verifies if the expected number of answer levels are present and increments a counter. | `output_samples` | `answers` |
275
+
276
+ A pipeline also needs a datasource to fetch data. You can declare your own data fetching mechanism by subclassing
277
+ a `Reader`.
278
+
279
+ ```python
280
+ from typing import List, Dict, Any
281
+ from truthbench import Reader
282
+
283
+
284
+ class StaticReader(Reader):
285
+ def samples(self) -> List[Dict[str, Any]]:
286
+ return [
287
+ {
288
+ "question": "why is the sky blue?",
289
+ "ground_truth": "The sky appears blue because of Rayleigh scattering..."
290
+ }
291
+ ]
292
+ ```
293
+
294
+ Generally, Readers expect to output at least two fields: `question` and `ground_truth`.
295
+
296
+ Right now, we made available a [`JsonReader`](truthbench/src/truthbench/readers/json_reader.py) that expects a `json`
297
+ file with the following structure:
298
+
299
+ ```jsonc
300
+ [
301
+ {
302
+ "question": "who is playing the halftime show at super bowl 2016?",
303
+ "ground_truth": "The Super Bowl 50 Halftime Show took place on..."
304
+ },
305
+ // ...
306
+ ]
307
+ ```
308
+
309
+ Lastly, some steps may need access to a running large language model (LLM). We provide support to OpenAI's ChatGPT with
310
+ `[GPT](truthbench/src/truthbench/llms/openai.py)` (it requires installing `pip install truthbench[openai]`), but you can
311
+ implement your own LLM access by subclassing:
312
+
313
+ ```python
314
+ from typing import List, Dict
315
+ from truthbench import LLM
316
+
317
+
318
+ class OpenSourceLLM(LLM):
319
+ def __init__(self, model):
320
+ self.model = model # e.g., from HuggingFace or llama-cpp
321
+
322
+ def query(self, messages: List[Dict[str, str]]) -> str:
323
+ prompt = ... # Convert messages if needed
324
+ response = self.model.generate(prompt) # Use the appropriate method
325
+ return response
326
+ ```
327
+
328
+ # Pipeline validation
329
+
330
+ To ensure the quality of the factual perturbations, we conducted a human evaluation comparing outputs from the
331
+ truthbench pipeline with those created by experts.
332
+
333
+ Two evaluators were shown factual Q&A pairs with five answer variants (A0–A4) and asked to blindly choose which
334
+ version (AI- or expert-generated) better fit the intended level of factuality — or indicate a tie.
335
+
336
+ Key results:
337
+
338
+ * 🟰 82.5% of evaluations resulted in ties, indicating that AI and human answers were often perceptually
339
+ indistinguishable.
340
+ * ✅ The AI pipeline was statistically non-inferior to human performance.
341
+ * ❗ Only 2.5% of examples showed conflicting preferences between evaluators.
342
+
343
+ # Known limitations
344
+
345
+ Our perturbation pipeline systematically applies linguistic and semantic modifications using dependency parsers and
346
+ predefined operators. However, the effectiveness of these perturbations can vary depending on the properties of the
347
+ target text:
348
+
349
+ * 🧩 **Variation in sensitivity:** Verbose or highly detailed answers (e.g., those generated by large language models)
350
+ may
351
+ require more targeted or intensive perturbations to induce meaningful semantic changes. In contrast, shorter, more
352
+ concise answers tend to be more sensitive to even minor modifications. Consequently, the uniformity of perturbation
353
+ strength across different questions and answers is not guaranteed.
354
+
355
+ * 🛡️ **Core content preservation:** Some perturbations might alter surface-level phrasing without affecting the core
356
+ factual content. For example, for the question “Who breaks a tie in the US Senate?,” `truthbench` will fail to modify
357
+ “the Vice President” in “The Vice President serves as the ex officio President of the Senate but is only permitted to
358
+ vote to resolve a tie.” Although we currently lack quantitative evidence on how widespread these cases are, this
359
+ limitation is especially relevant for verbose answers where the main fact constitutes only a small fraction of the
360
+ text. Our evaluators were not specifically instructed on handling these borderline cases, indicating a need for
361
+ further analysis and possibly alternative perturbation strategies.
362
+
363
+ * ⚠️ **Semantic inconsistencies:** Certain perturbations may introduce contradictions or inconsistencies. For instance,
364
+ for the question “Who wrote the text for Jeanie with the Light Brown Hair?,” `truthbench` can produce “Jeanie with
365
+ the Light Brown Hair is a folk song created by Henry Bishop \[...]. **Foster** composed the song thinking of \[...].
366
+ Such examples fail our semantic guidelines and should be marked as rejected — either accepting a valid human
367
+ alternative or rejecting both answers.
368
+
369
+ * 🌐 **Language dependency:** Although the approach is designed to be language-agnostic in principle, it relies heavily
370
+ on
371
+ the availability and quality of dependency parsers and language models for the target language. Languages with complex
372
+ morphology or syntax, or those that are low-resource, may experience reduced perturbation accuracy and coverage.
373
+
374
+