pcs-annotator 0.2.2__tar.gz → 2.0.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 (50) hide show
  1. pcs_annotator-2.0.0/.gitignore +8 -0
  2. pcs_annotator-2.0.0/CHANGELOG.md +30 -0
  3. {pcs_annotator-0.2.2 → pcs_annotator-2.0.0}/LICENSE +4 -2
  4. pcs_annotator-2.0.0/PKG-INFO +276 -0
  5. pcs_annotator-2.0.0/README.md +247 -0
  6. pcs_annotator-2.0.0/examples/api_examples.py +31 -0
  7. pcs_annotator-2.0.0/examples/offline_demo.py +49 -0
  8. pcs_annotator-2.0.0/pcs_annotator/__init__.py +15 -0
  9. pcs_annotator-2.0.0/pcs_annotator/backends/__init__.py +6 -0
  10. pcs_annotator-2.0.0/pcs_annotator/backends/base.py +115 -0
  11. pcs_annotator-2.0.0/pcs_annotator/backends/cache.py +45 -0
  12. pcs_annotator-2.0.0/pcs_annotator/backends/openai_compat.py +78 -0
  13. pcs_annotator-2.0.0/pcs_annotator/cli.py +102 -0
  14. pcs_annotator-2.0.0/pcs_annotator/core/__init__.py +7 -0
  15. pcs_annotator-2.0.0/pcs_annotator/core/engine.py +109 -0
  16. pcs_annotator-2.0.0/pcs_annotator/core/result.py +21 -0
  17. pcs_annotator-2.0.0/pcs_annotator/core/weights.py +129 -0
  18. pcs_annotator-2.0.0/pcs_annotator/eval/__init__.py +10 -0
  19. pcs_annotator-2.0.0/pcs_annotator/eval/baselines.py +246 -0
  20. pcs_annotator-2.0.0/pcs_annotator/eval/crossval.py +84 -0
  21. pcs_annotator-2.0.0/pcs_annotator/eval/metrics.py +59 -0
  22. pcs_annotator-2.0.0/pcs_annotator/pcs.py +119 -0
  23. pcs_annotator-2.0.0/pcs_annotator/tasks/__init__.py +7 -0
  24. pcs_annotator-2.0.0/pcs_annotator/tasks/base.py +74 -0
  25. pcs_annotator-2.0.0/pcs_annotator/tasks/builtin.py +167 -0
  26. pcs_annotator-2.0.0/pcs_annotator/transforms/__init__.py +7 -0
  27. pcs_annotator-2.0.0/pcs_annotator/transforms/_refactor_c.py +874 -0
  28. pcs_annotator-2.0.0/pcs_annotator/transforms/align.py +75 -0
  29. pcs_annotator-2.0.0/pcs_annotator/transforms/base.py +34 -0
  30. pcs_annotator-2.0.0/pcs_annotator/transforms/code_c.py +83 -0
  31. pcs_annotator-2.0.0/pcs_annotator/transforms/text.py +58 -0
  32. pcs_annotator-2.0.0/pyproject.toml +49 -0
  33. pcs_annotator-2.0.0/tests/test_backends.py +146 -0
  34. pcs_annotator-2.0.0/tests/test_cli.py +48 -0
  35. pcs_annotator-2.0.0/tests/test_core.py +116 -0
  36. pcs_annotator-2.0.0/tests/test_cpp_behavior.py +260 -0
  37. pcs_annotator-2.0.0/tests/test_eval.py +98 -0
  38. pcs_annotator-2.0.0/tests/test_refactor_c.py +322 -0
  39. pcs_annotator-2.0.0/tests/test_tasks_pcs.py +195 -0
  40. pcs_annotator-2.0.0/tests/test_transforms.py +120 -0
  41. pcs_annotator-0.2.2/PKG-INFO +0 -152
  42. pcs_annotator-0.2.2/README.md +0 -131
  43. pcs_annotator-0.2.2/pcs_annotator/Annotator.py +0 -39
  44. pcs_annotator-0.2.2/pcs_annotator/LLM.py +0 -68
  45. pcs_annotator-0.2.2/pcs_annotator/PCS.py +0 -364
  46. pcs_annotator-0.2.2/pcs_annotator/TextMutator.py +0 -53
  47. pcs_annotator-0.2.2/pcs_annotator/Tools.py +0 -43
  48. pcs_annotator-0.2.2/pcs_annotator/__init__.py +0 -3
  49. pcs_annotator-0.2.2/pyproject.toml +0 -33
  50. pcs_annotator-0.2.2/requirements.txt +0 -7
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.sqlite
4
+ .pcs_cache*
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ release_build/
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0
4
+
5
+ A rewrite that extends PCS from text classification to source code.
6
+
7
+ **New**
8
+ - Three built-in tasks: text classification, C/C++ vulnerability classification and C/C++ bug localization.
9
+ - Eight program rewrites for C and C++ (M4-M11), built on tree-sitter and checked for behaviour preservation with
10
+ gcc and g++, and line alignment, so answers that refer to lines of the input can be compared across rewrites.
11
+ - A `Task` interface: a new task needs only its answer space, rewrites, alignment and ground truth.
12
+ - Equal weights by default, so no labelled data is needed. Fitted weights use constrained least squares, which
13
+ replaces the genetic algorithm.
14
+ - Several models with shared version weights and model weights.
15
+ - Any OpenAI-compatible endpoint (OpenRouter, OpenAI, Groq, vLLM, Ollama), with a reply cache, resume and a
16
+ spending cap.
17
+ - `pcs_annotator.eval`: AUROC, ECE, Brier, paired cluster bootstrap, recalibration, and the baselines
18
+ self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2.
19
+ - `pcs-annotator` command line.
20
+
21
+ **Removed**
22
+ - The 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)` and the LangChain dependency.
23
+
24
+ **Fixed (compared with 0.2.3)**
25
+ - "Not vulnerable" is no longer read as "Vulnerable".
26
+ - Custom rewrites are used, not only registered.
27
+
28
+ ## 0.2.3 and earlier
29
+
30
+ Text classification with three LLM-written rewrites (see the GitHub history).
@@ -1,4 +1,6 @@
1
- Copyright (c) 2025 Sina Salimian
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Sina Salimian, Anik Islam, Gias Uddin, Shaina Raza, Henry Leung
2
4
 
3
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
4
6
  of this software and associated documentation files (the "Software"), to deal
@@ -16,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
- SOFTWARE.
21
+ SOFTWARE.
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.5
2
+ Name: pcs-annotator
3
+ Version: 2.0.0
4
+ Summary: Perceived Confidence Scoring (PCS) for black-box LLMs on text classification, C/C++ vulnerability classification and C/C++ bug localization
5
+ Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
6
+ Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
7
+ Project-URL: Changelog, https://github.com/salsina/PCS-Python-Library/blob/main/CHANGELOG.md
8
+ Author: Anik Islam, Sina Salimian, Gias Uddin, Shaina Raza, Henry Leung
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: bug localization,confidence,llm,metamorphic testing,uncertainty,vulnerability detection
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: requests>=2.28
20
+ Requires-Dist: scipy>=1.10
21
+ Provides-Extra: code
22
+ Requires-Dist: tree-sitter-c>=0.23; extra == 'code'
23
+ Requires-Dist: tree-sitter-cpp>=0.23; extra == 'code'
24
+ Requires-Dist: tree-sitter>=0.23; extra == 'code'
25
+ Provides-Extra: eval
26
+ Requires-Dist: pandas>=2.0; extra == 'eval'
27
+ Requires-Dist: scikit-learn>=1.3; extra == 'eval'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # PCS Annotator: A Python Library for Confidence Scoring of LLM Answers on Text and Code
31
+
32
+ PCS (Perceived Confidence Scoring) tells you how much to trust an answer from a black-box LLM. It rewrites the input
33
+ in ways that should not change the correct answer (metamorphic relations), asks the LLM about every version, and
34
+ combines the answers in a weighted vote. Version 2 supports three tasks:
35
+
36
+ | Task | Answer | Rewrites |
37
+ |---|---|---|
38
+ | Text classification | a label (e.g. Fake / Real) | M1–M3: voice change, double negation, synonyms |
39
+ | C/C++ vulnerability classification | Vulnerable / Not vulnerable | M4–M11: eight program transformations |
40
+ | C/C++ bug localization | a line number | M4–M11, with answers mapped back to the original lines |
41
+
42
+ ## How to Install
43
+
44
+ ```bash
45
+ pip install "pcs-annotator[code]"
46
+ ```
47
+
48
+ The `[code]` extra adds the C and C++ parsers (tree-sitter) needed for the code tasks. Use `pcs-annotator[code,eval]` to also
49
+ get the evaluation tools.
50
+
51
+ ## How to Use
52
+
53
+ ```python
54
+ from pcs_annotator import PCS
55
+ from pcs_annotator.backends import OpenAICompatible
56
+ from pcs_annotator.tasks import TextClassification, VulnClassification, BugLocalization
57
+ ```
58
+
59
+ ### Choose a Model
60
+
61
+ Any OpenAI-compatible endpoint works: OpenRouter (default), OpenAI, Groq, Together, or a local vLLM or Ollama server.
62
+
63
+ ```python
64
+ model = OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32)
65
+ ```
66
+
67
+ ### Choose a Task
68
+
69
+ ```python
70
+ task = BugLocalization() # which line of a C/C++ function holds the bug?
71
+ task = VulnClassification() # is a C/C++ function vulnerable?
72
+ task = TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter) # text: see below
73
+ ```
74
+
75
+ ### Annotate
76
+
77
+ ```python
78
+ pcs = PCS(task, model)
79
+ result = pcs.predict(open("func.c").read())
80
+ ```
81
+
82
+ ## 🔧 Customizing Hyperparameters
83
+
84
+ The `PCS` class lets you choose the task, one or more models, the rewrites, and the weights.
85
+
86
+ ### 📌 Example Usage
87
+
88
+ ```python
89
+ from pcs_annotator import PCS
90
+ from pcs_annotator.backends import OpenAICompatible
91
+ from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
92
+
93
+ rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800)
94
+ annotators = [
95
+ OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
96
+ OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
97
+ ]
98
+
99
+ pcs = PCS(
100
+ task=TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter),
101
+ models=annotators,
102
+ )
103
+
104
+ print(pcs.predict("Aliens landed in New York yesterday."))
105
+ ```
106
+
107
+ ### 🖨️ Output
108
+
109
+ `.predict()` returns a `Result`:
110
+
111
+ ```python
112
+ result.prediction # 'Fake': the answer on the original input (several models: their majority)
113
+ result.confidence # 0.25: how much weight agrees with that answer
114
+ result.scores # {'Fake': 0.25, 'Real': 0.75}: score of every answer that got a vote
115
+ result.answers # {'haiku': {'original': 'Fake', 'passive_active': 'Real', ...}, ...}
116
+ ```
117
+
118
+ For bug localization the answers are line numbers of the original function, e.g. `prediction=11, confidence=0.16`.
119
+
120
+ ### 🧪 Try It Without an API Key
121
+
122
+ ```bash
123
+ python examples/offline_demo.py
124
+ ```
125
+
126
+ A toy model answers line 11 on the original C function but finds the real flaw on most rewrites. PCS gives line 11 a
127
+ confidence of 0.33, where self-consistency would give 1.00.
128
+
129
+ # Configuration
130
+
131
+ ## 🔹 Task (`task`)
132
+ Defines what the LLMs are asked and how their answers are compared.
133
+ * **Options**:
134
+ * `TextClassification(labels, prompt, rewriter=...)`: the prompt must contain `{text}` and ask for
135
+ `<label>...</label>`. Ready-made prompts: `NEWS_PROMPT`, `SENTIMENT_PROMPT`.
136
+ * `VulnClassification()`: answers `Vulnerable` or `Not vulnerable`.
137
+ * `BugLocalization()`: answers a line number, counted over the function's non-blank lines from 1.
138
+ * **Customization**:
139
+ * `transforms=[...]` replaces the default rewrites (see below).
140
+ * `lang="auto"` (default) detects C or C++; `lang="c"` or `lang="cpp"` forces one.
141
+ * `braces_first=False` makes M5 (branch swap) swap only, without adding braces first.
142
+ * `assume_builtin_types=True` lets M9 and M10 rewrite C++ expressions too (see Notes).
143
+ * `BugLocalization(lenient=True)` also reads malformed answers such as `<10>N`, which some small local models
144
+ produce.
145
+
146
+ ## 🔹 Annotators (`models`)
147
+ Defines the LLM or list of LLMs used for annotation.
148
+ * **Default Value**: none; pass one model or a list.
149
+ * **Customization**:
150
+ * One model: `PCS(task, model)`.
151
+ * Several models: `PCS(task, [model_a, model_b, model_c])`. The prediction is the majority of their answers on the
152
+ original input, and the confidence combines their scores with model weights.
153
+ * Each model needs a unique `name`.
154
+
155
+ ## 🔹 Model Settings (`OpenAICompatible`)
156
+ Determines how each model is called.
157
+
158
+ | Parameter | Default | Description |
159
+ |-----------|---------|-------------|
160
+ | `model` | – | Provider model id, e.g. `"anthropic/claude-haiku-5.5"` |
161
+ | `base_url` | OpenRouter | Endpoint root, e.g. `"http://localhost:8000/v1"` for a local vLLM server |
162
+ | `api_key_env` | `"OPENROUTER_API_KEY"` | Name of the environment variable that holds the key |
163
+ | `temperature` | `1.0` | Sampling temperature; `None` leaves it out, for models that reject it (e.g. Claude Haiku) |
164
+ | `max_tokens` | `32` | Output limit; raise it for models that explain before answering |
165
+ | `extra` | `{}` | Extra request fields, e.g. `{"reasoning": {"enabled": False}}` on OpenRouter |
166
+ | `cache` | none | `Cache("file.sqlite")`: stores every reply, so a stopped run resumes without paying twice |
167
+ | `budget` | no cap | `Budget(cap=1.00)`: stops before a new call once this many US dollars are spent |
168
+
169
+ ## 🔹 API Keys
170
+ The key is read from an environment variable (or a `.env` file loaded by your own code). It is never stored or cached.
171
+
172
+ | Provider | Set this variable | Then use |
173
+ |----------|-------------------|----------|
174
+ | OpenRouter | `OPENROUTER_API_KEY` | the default `base_url` |
175
+ | OpenAI | `OPENAI_API_KEY` | `base_url="https://api.openai.com/v1", api_key_env="OPENAI_API_KEY"` |
176
+ | Groq | `GROQ_API_KEY` | `base_url="https://api.groq.com/openai/v1", api_key_env="GROQ_API_KEY"` |
177
+ | Local vLLM / Ollama | any value, e.g. `LOCAL_KEY=x` | `base_url="http://localhost:8000/v1", api_key_env="LOCAL_KEY"` |
178
+
179
+ ## 🔹 Text Mutator (`rewriter`)
180
+ Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
181
+ rule-based.
182
+ * **Recommended Model**: `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2, as in the paper.
183
+ * **Customization**:
184
+ * Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
185
+
186
+ ## ⚙️ Weights (`weights` and `calibrate`)
187
+
188
+ PCS combines the versions with one weight each (and, for several models, one weight per model).
189
+
190
+ ### 🔧 Options
191
+
192
+ | Option | Description |
193
+ |--------|-------------|
194
+ | Equal weights | Every version counts the same. **No labelled data needed.** *(default; as good as fitted weights in the paper)* |
195
+ | `pcs.calibrate(inputs, golds)` | **Constrained least squares**: fits the weights on labelled examples. Weights stay non-negative and sum to 1. |
196
+ | `PCS(task, model, weights=Weights.from_json("w.json"))` | Reuse weights saved with `pcs.weights.to_json("w.json")`. |
197
+
198
+ `golds` are labels for classification and the bug line (or a list of bug lines) for localization.
199
+
200
+ ## 🖥️ Command Line
201
+
202
+ ```bash
203
+ pcs-annotator predict --task loc --model anthropic/claude-haiku-5.5 --no-temperature --max-tokens 160 --input func.c
204
+ pcs-annotator calibrate --task vuln --model deepseek/deepseek-v4.1-flash --data cal.jsonl --out weights.json
205
+ pcs-annotator predict --task text --preset news --model deepseek/deepseek-v4.1-flash --data test.jsonl
206
+ ```
207
+
208
+ Data files are JSONL, one `{"input": ..., "gold": ...}` per line. Run `pcs-annotator predict --help` for all options.
209
+
210
+ ## ➕ Adding a Custom Metamorphic Relation (MR)
211
+
212
+ **For text**, give a prompt containing `{text}` that asks for a reply starting with `new text:`:
213
+
214
+ ```python
215
+ from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
216
+ from pcs_annotator.transforms import LLMRewrite, text_transforms
217
+
218
+ custom_negation = LLMRewrite(
219
+ "custom_negation",
220
+ "Transform all affirmative statements in the following text into their negated forms.\n"
221
+ "Start the response with 'new text:' and include only the revised text.\n\nOriginal Text:\n{text}",
222
+ rewriter,
223
+ )
224
+ task = TextClassification(["Fake", "Real"], NEWS_PROMPT,
225
+ transforms=text_transforms(rewriter) + [custom_negation])
226
+ ```
227
+
228
+ **For code**, subclass `Transform` and return the rewritten function. If the rewrite does not apply, return the input
229
+ unchanged:
230
+
231
+ ```python
232
+ from pcs_annotator.tasks import BugLocalization
233
+ from pcs_annotator.transforms import Transform, code_transforms
234
+
235
+ class RenameHelper(Transform):
236
+ name = "rename_helper"
237
+ def apply(self, code):
238
+ return code.replace("helper_0(", "func_a(")
239
+
240
+ task = BugLocalization(transforms=code_transforms() + [RenameHelper()])
241
+ ```
242
+
243
+ ## ➕ Adding a Custom Task
244
+
245
+ Subclass `Task`, or `ClassificationTask` for a fixed label set, and define four methods:
246
+ * `messages(x)`: the prompt;
247
+ * `parse(raw)`: the answer in a reply, or `None`;
248
+ * `candidates(x)`: the possible answers;
249
+ * `truth(gold)`: the set of correct answers.
250
+
251
+ If answers refer to positions in the input, as line numbers do, also define `align(x, x_k, answer, k)` to map an
252
+ answer on version `k` back to the original. Voting, weights, several models and calibration are shared.
253
+
254
+ ## 📊 Evaluation Tools
255
+
256
+ `pcs_annotator.eval` (install with `[eval]`) contains the paper's evaluation:
257
+ * AUROC, ECE and Brier score;
258
+ * paired bootstrap confidence intervals;
259
+ * repeated k-fold PCS and Platt / isotonic recalibration;
260
+ * the baselines self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2, with the paper's prompts.
261
+
262
+ ## 📝 Notes
263
+
264
+ * **Cost:** each input costs K + 1 queries per model: 4 for text, 9 for code. A version that a rewrite leaves
265
+ unchanged is still queried.
266
+ * **Missing answers:** an answer that cannot be read votes for nothing. If the answer on the original input cannot be
267
+ read, the confidence is 0.
268
+ * **Not probabilities:** PCS scores measure agreement. Use `eval.recalibrate` if you need calibrated probabilities.
269
+ * **Weak models:** when a model performs near chance, no consistency signal, including PCS, is informative.
270
+ * **C and C++:** the program rewrites keep behaviour in both languages: the tests compile C programs with gcc and
271
+ C++ programs with g++ before and after every rewrite. In C++, comparison reversal (M9) and explicit conditions
272
+ (M10) are skipped by default, because the operators may be overloaded; set `assume_builtin_types=True` if your
273
+ code compares only built-in types. Code that does not parse, often because of unexpanded macros, is left unchanged.
274
+ * **Upgrading from 0.x:** version 2 replaces the 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)`.
275
+ See `CHANGELOG.md`.
276
+
@@ -0,0 +1,247 @@
1
+ # PCS Annotator: A Python Library for Confidence Scoring of LLM Answers on Text and Code
2
+
3
+ PCS (Perceived Confidence Scoring) tells you how much to trust an answer from a black-box LLM. It rewrites the input
4
+ in ways that should not change the correct answer (metamorphic relations), asks the LLM about every version, and
5
+ combines the answers in a weighted vote. Version 2 supports three tasks:
6
+
7
+ | Task | Answer | Rewrites |
8
+ |---|---|---|
9
+ | Text classification | a label (e.g. Fake / Real) | M1–M3: voice change, double negation, synonyms |
10
+ | C/C++ vulnerability classification | Vulnerable / Not vulnerable | M4–M11: eight program transformations |
11
+ | C/C++ bug localization | a line number | M4–M11, with answers mapped back to the original lines |
12
+
13
+ ## How to Install
14
+
15
+ ```bash
16
+ pip install "pcs-annotator[code]"
17
+ ```
18
+
19
+ The `[code]` extra adds the C and C++ parsers (tree-sitter) needed for the code tasks. Use `pcs-annotator[code,eval]` to also
20
+ get the evaluation tools.
21
+
22
+ ## How to Use
23
+
24
+ ```python
25
+ from pcs_annotator import PCS
26
+ from pcs_annotator.backends import OpenAICompatible
27
+ from pcs_annotator.tasks import TextClassification, VulnClassification, BugLocalization
28
+ ```
29
+
30
+ ### Choose a Model
31
+
32
+ Any OpenAI-compatible endpoint works: OpenRouter (default), OpenAI, Groq, Together, or a local vLLM or Ollama server.
33
+
34
+ ```python
35
+ model = OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32)
36
+ ```
37
+
38
+ ### Choose a Task
39
+
40
+ ```python
41
+ task = BugLocalization() # which line of a C/C++ function holds the bug?
42
+ task = VulnClassification() # is a C/C++ function vulnerable?
43
+ task = TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter) # text: see below
44
+ ```
45
+
46
+ ### Annotate
47
+
48
+ ```python
49
+ pcs = PCS(task, model)
50
+ result = pcs.predict(open("func.c").read())
51
+ ```
52
+
53
+ ## 🔧 Customizing Hyperparameters
54
+
55
+ The `PCS` class lets you choose the task, one or more models, the rewrites, and the weights.
56
+
57
+ ### 📌 Example Usage
58
+
59
+ ```python
60
+ from pcs_annotator import PCS
61
+ from pcs_annotator.backends import OpenAICompatible
62
+ from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
63
+
64
+ rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800)
65
+ annotators = [
66
+ OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
67
+ OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
68
+ ]
69
+
70
+ pcs = PCS(
71
+ task=TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter),
72
+ models=annotators,
73
+ )
74
+
75
+ print(pcs.predict("Aliens landed in New York yesterday."))
76
+ ```
77
+
78
+ ### 🖨️ Output
79
+
80
+ `.predict()` returns a `Result`:
81
+
82
+ ```python
83
+ result.prediction # 'Fake': the answer on the original input (several models: their majority)
84
+ result.confidence # 0.25: how much weight agrees with that answer
85
+ result.scores # {'Fake': 0.25, 'Real': 0.75}: score of every answer that got a vote
86
+ result.answers # {'haiku': {'original': 'Fake', 'passive_active': 'Real', ...}, ...}
87
+ ```
88
+
89
+ For bug localization the answers are line numbers of the original function, e.g. `prediction=11, confidence=0.16`.
90
+
91
+ ### 🧪 Try It Without an API Key
92
+
93
+ ```bash
94
+ python examples/offline_demo.py
95
+ ```
96
+
97
+ A toy model answers line 11 on the original C function but finds the real flaw on most rewrites. PCS gives line 11 a
98
+ confidence of 0.33, where self-consistency would give 1.00.
99
+
100
+ # Configuration
101
+
102
+ ## 🔹 Task (`task`)
103
+ Defines what the LLMs are asked and how their answers are compared.
104
+ * **Options**:
105
+ * `TextClassification(labels, prompt, rewriter=...)`: the prompt must contain `{text}` and ask for
106
+ `<label>...</label>`. Ready-made prompts: `NEWS_PROMPT`, `SENTIMENT_PROMPT`.
107
+ * `VulnClassification()`: answers `Vulnerable` or `Not vulnerable`.
108
+ * `BugLocalization()`: answers a line number, counted over the function's non-blank lines from 1.
109
+ * **Customization**:
110
+ * `transforms=[...]` replaces the default rewrites (see below).
111
+ * `lang="auto"` (default) detects C or C++; `lang="c"` or `lang="cpp"` forces one.
112
+ * `braces_first=False` makes M5 (branch swap) swap only, without adding braces first.
113
+ * `assume_builtin_types=True` lets M9 and M10 rewrite C++ expressions too (see Notes).
114
+ * `BugLocalization(lenient=True)` also reads malformed answers such as `<10>N`, which some small local models
115
+ produce.
116
+
117
+ ## 🔹 Annotators (`models`)
118
+ Defines the LLM or list of LLMs used for annotation.
119
+ * **Default Value**: none; pass one model or a list.
120
+ * **Customization**:
121
+ * One model: `PCS(task, model)`.
122
+ * Several models: `PCS(task, [model_a, model_b, model_c])`. The prediction is the majority of their answers on the
123
+ original input, and the confidence combines their scores with model weights.
124
+ * Each model needs a unique `name`.
125
+
126
+ ## 🔹 Model Settings (`OpenAICompatible`)
127
+ Determines how each model is called.
128
+
129
+ | Parameter | Default | Description |
130
+ |-----------|---------|-------------|
131
+ | `model` | – | Provider model id, e.g. `"anthropic/claude-haiku-5.5"` |
132
+ | `base_url` | OpenRouter | Endpoint root, e.g. `"http://localhost:8000/v1"` for a local vLLM server |
133
+ | `api_key_env` | `"OPENROUTER_API_KEY"` | Name of the environment variable that holds the key |
134
+ | `temperature` | `1.0` | Sampling temperature; `None` leaves it out, for models that reject it (e.g. Claude Haiku) |
135
+ | `max_tokens` | `32` | Output limit; raise it for models that explain before answering |
136
+ | `extra` | `{}` | Extra request fields, e.g. `{"reasoning": {"enabled": False}}` on OpenRouter |
137
+ | `cache` | none | `Cache("file.sqlite")`: stores every reply, so a stopped run resumes without paying twice |
138
+ | `budget` | no cap | `Budget(cap=1.00)`: stops before a new call once this many US dollars are spent |
139
+
140
+ ## 🔹 API Keys
141
+ The key is read from an environment variable (or a `.env` file loaded by your own code). It is never stored or cached.
142
+
143
+ | Provider | Set this variable | Then use |
144
+ |----------|-------------------|----------|
145
+ | OpenRouter | `OPENROUTER_API_KEY` | the default `base_url` |
146
+ | OpenAI | `OPENAI_API_KEY` | `base_url="https://api.openai.com/v1", api_key_env="OPENAI_API_KEY"` |
147
+ | Groq | `GROQ_API_KEY` | `base_url="https://api.groq.com/openai/v1", api_key_env="GROQ_API_KEY"` |
148
+ | Local vLLM / Ollama | any value, e.g. `LOCAL_KEY=x` | `base_url="http://localhost:8000/v1", api_key_env="LOCAL_KEY"` |
149
+
150
+ ## 🔹 Text Mutator (`rewriter`)
151
+ Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
152
+ rule-based.
153
+ * **Recommended Model**: `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2, as in the paper.
154
+ * **Customization**:
155
+ * Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
156
+
157
+ ## ⚙️ Weights (`weights` and `calibrate`)
158
+
159
+ PCS combines the versions with one weight each (and, for several models, one weight per model).
160
+
161
+ ### 🔧 Options
162
+
163
+ | Option | Description |
164
+ |--------|-------------|
165
+ | Equal weights | Every version counts the same. **No labelled data needed.** *(default; as good as fitted weights in the paper)* |
166
+ | `pcs.calibrate(inputs, golds)` | **Constrained least squares**: fits the weights on labelled examples. Weights stay non-negative and sum to 1. |
167
+ | `PCS(task, model, weights=Weights.from_json("w.json"))` | Reuse weights saved with `pcs.weights.to_json("w.json")`. |
168
+
169
+ `golds` are labels for classification and the bug line (or a list of bug lines) for localization.
170
+
171
+ ## 🖥️ Command Line
172
+
173
+ ```bash
174
+ pcs-annotator predict --task loc --model anthropic/claude-haiku-5.5 --no-temperature --max-tokens 160 --input func.c
175
+ pcs-annotator calibrate --task vuln --model deepseek/deepseek-v4.1-flash --data cal.jsonl --out weights.json
176
+ pcs-annotator predict --task text --preset news --model deepseek/deepseek-v4.1-flash --data test.jsonl
177
+ ```
178
+
179
+ Data files are JSONL, one `{"input": ..., "gold": ...}` per line. Run `pcs-annotator predict --help` for all options.
180
+
181
+ ## ➕ Adding a Custom Metamorphic Relation (MR)
182
+
183
+ **For text**, give a prompt containing `{text}` that asks for a reply starting with `new text:`:
184
+
185
+ ```python
186
+ from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
187
+ from pcs_annotator.transforms import LLMRewrite, text_transforms
188
+
189
+ custom_negation = LLMRewrite(
190
+ "custom_negation",
191
+ "Transform all affirmative statements in the following text into their negated forms.\n"
192
+ "Start the response with 'new text:' and include only the revised text.\n\nOriginal Text:\n{text}",
193
+ rewriter,
194
+ )
195
+ task = TextClassification(["Fake", "Real"], NEWS_PROMPT,
196
+ transforms=text_transforms(rewriter) + [custom_negation])
197
+ ```
198
+
199
+ **For code**, subclass `Transform` and return the rewritten function. If the rewrite does not apply, return the input
200
+ unchanged:
201
+
202
+ ```python
203
+ from pcs_annotator.tasks import BugLocalization
204
+ from pcs_annotator.transforms import Transform, code_transforms
205
+
206
+ class RenameHelper(Transform):
207
+ name = "rename_helper"
208
+ def apply(self, code):
209
+ return code.replace("helper_0(", "func_a(")
210
+
211
+ task = BugLocalization(transforms=code_transforms() + [RenameHelper()])
212
+ ```
213
+
214
+ ## ➕ Adding a Custom Task
215
+
216
+ Subclass `Task`, or `ClassificationTask` for a fixed label set, and define four methods:
217
+ * `messages(x)`: the prompt;
218
+ * `parse(raw)`: the answer in a reply, or `None`;
219
+ * `candidates(x)`: the possible answers;
220
+ * `truth(gold)`: the set of correct answers.
221
+
222
+ If answers refer to positions in the input, as line numbers do, also define `align(x, x_k, answer, k)` to map an
223
+ answer on version `k` back to the original. Voting, weights, several models and calibration are shared.
224
+
225
+ ## 📊 Evaluation Tools
226
+
227
+ `pcs_annotator.eval` (install with `[eval]`) contains the paper's evaluation:
228
+ * AUROC, ECE and Brier score;
229
+ * paired bootstrap confidence intervals;
230
+ * repeated k-fold PCS and Platt / isotonic recalibration;
231
+ * the baselines self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2, with the paper's prompts.
232
+
233
+ ## 📝 Notes
234
+
235
+ * **Cost:** each input costs K + 1 queries per model: 4 for text, 9 for code. A version that a rewrite leaves
236
+ unchanged is still queried.
237
+ * **Missing answers:** an answer that cannot be read votes for nothing. If the answer on the original input cannot be
238
+ read, the confidence is 0.
239
+ * **Not probabilities:** PCS scores measure agreement. Use `eval.recalibrate` if you need calibrated probabilities.
240
+ * **Weak models:** when a model performs near chance, no consistency signal, including PCS, is informative.
241
+ * **C and C++:** the program rewrites keep behaviour in both languages: the tests compile C programs with gcc and
242
+ C++ programs with g++ before and after every rewrite. In C++, comparison reversal (M9) and explicit conditions
243
+ (M10) are skipped by default, because the operators may be overloaded; set `assume_builtin_types=True` if your
244
+ code compares only built-in types. Code that does not parse, often because of unexpanded macros, is left unchanged.
245
+ * **Upgrading from 0.x:** version 2 replaces the 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)`.
246
+ See `CHANGELOG.md`.
247
+
@@ -0,0 +1,31 @@
1
+ """The three tasks with real models through OpenRouter (costs money; set OPENROUTER_API_KEY first).
2
+
3
+ Settings as in the paper: temperature 1, reasoning off, one answer per version; Claude Haiku rejects a temperature
4
+ parameter (it runs at its default of 1.0) and needs a longer output limit because it often explains before the tag.
5
+ """
6
+ from pcs_annotator import PCS
7
+ from pcs_annotator.backends import Budget, Cache, OpenAICompatible
8
+ from pcs_annotator.tasks import NEWS_PROMPT, BugLocalization, TextClassification, VulnClassification
9
+
10
+ cache, budget = Cache(".pcs_cache.sqlite"), Budget(cap=0.50) # replies are cached; stop before $0.50
11
+ off = {"reasoning": {"enabled": False}}
12
+ haiku = OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, extra=off, cache=cache,
13
+ budget=budget, name="haiku")
14
+ deepseek = OpenAICompatible("deepseek/deepseek-v4.1-flash", max_tokens=32, extra=off, cache=cache, budget=budget,
15
+ name="deepseek")
16
+
17
+ # 1. Text classification: M1-M3 written by LLaMA-3.1-8B at temperature 0.2
18
+ rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800, cache=cache,
19
+ budget=budget, name="rewriter")
20
+ news = PCS(TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter), haiku)
21
+ print(news.predict("Aliens landed in New York yesterday, officials confirmed."))
22
+
23
+ # 2. Vulnerability classification of a C function
24
+ vuln = PCS(VulnClassification(), deepseek)
25
+ print(vuln.predict(open("func.c").read()))
26
+
27
+ # 3. Bug localization, two models combined (equal weights; call .calibrate(xs, golds) to fit weights)
28
+ loc = PCS(BugLocalization(), [haiku, deepseek])
29
+ r = loc.predict(open("func.c").read())
30
+ print(r.prediction, r.confidence)
31
+ print(f"spent ${budget.spent:.4f}")
@@ -0,0 +1,49 @@
1
+ """Runs without an API key: a toy "model" stands in for an LLM, so you can see what PCS does.
2
+
3
+ python examples/offline_demo.py
4
+
5
+ The toy model answers line 11 (the sign check) whenever it sees the function exactly as written, but finds the real
6
+ flaw (the multiplication) on every rewritten version -- the paper's motivating example in miniature. Self-consistency would report
7
+ full confidence in line 11; PCS does not.
8
+ """
9
+ from pcs_annotator import PCS
10
+ from pcs_annotator.backends import FunctionBackend
11
+ from pcs_annotator.tasks import BugLocalization
12
+ from pcs_annotator.transforms import numbered
13
+
14
+ FUNC = """void helper_0()
15
+ {
16
+ int64_t data;
17
+ data = 0LL;
18
+ if(globalReturnsTrue())
19
+ {
20
+ fscanf (stdin, "%" SCNd64, &data);
21
+ }
22
+ if(globalReturnsTrue())
23
+ {
24
+ if(data < 0)
25
+ {
26
+ int64_t result = data * 2;
27
+ printLongLongLine(result);
28
+ }
29
+ }
30
+ }"""
31
+
32
+
33
+ def toy_model(messages):
34
+ prompt = messages[-1]["content"]
35
+ target = "data < 0" if numbered(FUNC) in prompt else "* 2" # fooled only by the exact original text
36
+ for line in prompt.splitlines():
37
+ if "|" in line and target in line:
38
+ return f"<line>{line.split('|')[0].strip()}</line>"
39
+ return "I am not sure."
40
+
41
+
42
+ pcs = PCS(BugLocalization(), FunctionBackend(toy_model, name="toy"))
43
+ r = pcs.predict(FUNC)
44
+ print(f"prediction: line {r.prediction} confidence: {r.confidence:.2f} (self-consistency would say 1.00)")
45
+ print("answer per version (mapped to the original lines):")
46
+ for version, line in r.answers["toy"].items():
47
+ print(f" {version:22s} {line}")
48
+ print("scores of all voted lines:", {k: round(v, 2) for k, v in r.scores.items()})
49
+ print("(versions that a relation leaves unchanged repeat the original's answer, as in the paper's Figure 1)")
@@ -0,0 +1,15 @@
1
+ """pcs-annotator 2: Perceived Confidence Scoring for black-box LLMs (text and C code).
2
+
3
+ from pcs_annotator import PCS
4
+ from pcs_annotator.tasks import BugLocalization
5
+ from pcs_annotator.backends import OpenAICompatible
6
+
7
+ pcs = PCS(BugLocalization(), OpenAICompatible("anthropic/claude-haiku-5.5", max_tokens=160, temperature=None))
8
+ r = pcs.predict(c_function) # r.prediction (line), r.confidence
9
+ """
10
+ from .core import Result, Weights, fit_joint, fit_single, majority, multi_predict, multi_scores, predict, scores
11
+ from .pcs import PCS, Collected
12
+
13
+ __version__ = "2.0.0"
14
+ __all__ = ["PCS", "Collected", "Result", "Weights", "fit_joint", "fit_single", "majority", "multi_predict",
15
+ "multi_scores", "predict", "scores", "__version__"]