pytest-llm-confidence 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.
@@ -0,0 +1,14 @@
1
+ """pytest-llm-confidence: fail a test when the model wasn't sure of its answer.
2
+
3
+ def test_capital(llm_confidence):
4
+ ans = llm_confidence.ask("What is the capital of Australia? One word.")
5
+ llm_confidence.assert_confident(ans)
6
+
7
+ From Proprioceptive AI (https://proprioceptiveai.com).
8
+ """
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .plugin import LLMConfidence, ShakyAnswerError, assert_confident # noqa: E402
13
+
14
+ __all__ = ["__version__", "LLMConfidence", "ShakyAnswerError", "assert_confident"]
@@ -0,0 +1,213 @@
1
+ """pytest-llm-confidence: fail a test when the model wasn't sure of its answer.
2
+
3
+ Reads the model's own token probabilities, so there is no judge model, no extra API
4
+ cost, and the same response always gives the same verdict.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass
11
+ from typing import Any, List, Optional
12
+
13
+ import pytest
14
+
15
+ from proprioceptive_confidence import (
16
+ DEFAULT_THRESHOLD,
17
+ Answer,
18
+ ConfidenceClient,
19
+ ConfidenceError,
20
+ ConfidenceReport,
21
+ analyze,
22
+ )
23
+ from proprioceptive_confidence.core import pct, quote
24
+
25
+ LENS_LINE = "See every word's confidence live: pip install proprioceptive-lens (proprioceptiveai.com)"
26
+ _RECORDS_KEY = pytest.StashKey["List[Record]"]() if hasattr(pytest, "StashKey") else None
27
+
28
+
29
+ @dataclass
30
+ class Record:
31
+ nodeid: str
32
+ report: ConfidenceReport
33
+ passed: bool
34
+
35
+
36
+ class ShakyAnswerError(AssertionError):
37
+ """The model wasn't sure enough of its answer."""
38
+
39
+
40
+ def _to_report(obj: Any, threshold: float) -> ConfidenceReport:
41
+ if isinstance(obj, Answer):
42
+ rep = obj.report
43
+ rep.threshold = threshold
44
+ return rep
45
+ return analyze(obj, threshold=threshold)
46
+
47
+
48
+ def _failure_message(report: ConfidenceReport, label: Optional[str]) -> str:
49
+ head = f"{label}: " if label else ""
50
+ lines = [f"{head}model wasn't sure of its answer ({report.summary()})", f"answer: {report.text!r}"]
51
+ for t in sorted(report.shaky, key=lambda t: t.prob)[:8]:
52
+ alts = ", ".join(f"{quote(a)} {pct(p)}" for a, p in t.alternatives if a != t.text)[:120]
53
+ lines.append(f" {quote(t.text)} at {pct(t.prob)}" + (f" (alternatives: {alts})" if alts else ""))
54
+ return "\n".join(lines)
55
+
56
+
57
+ def assert_confident(response: Any, threshold: float = DEFAULT_THRESHOLD, msg: Optional[str] = None) -> ConfidenceReport:
58
+ """Assert every word of a response was at or above `threshold` probability.
59
+
60
+ `response` can be an Answer, a ConfidenceReport, an OpenAI-style response
61
+ (requested with logprobs=True), an Ollama response (requested with
62
+ "logprobs": true), or a list of (token, logprob) pairs.
63
+ """
64
+ report = _to_report(response, threshold)
65
+ if not report.tokens:
66
+ raise ShakyAnswerError(
67
+ "no token probabilities in the response: request it with logprobs=True "
68
+ "(OpenAI-compatible) or \"logprobs\": true (Ollama 0.12+)"
69
+ )
70
+ if not report.is_confident:
71
+ raise ShakyAnswerError(_failure_message(report, msg))
72
+ return report
73
+
74
+
75
+ class LLMConfidence:
76
+ """The `llm_confidence` fixture: ask a model, check responses, record results."""
77
+
78
+ def __init__(self, request: pytest.FixtureRequest) -> None:
79
+ self._request = request
80
+ cfg = request.config
81
+ marker = request.node.get_closest_marker("llm_confidence")
82
+ threshold = _opt(cfg, "threshold")
83
+ double_check = bool(_opt(cfg, "double_check"))
84
+ if marker is not None:
85
+ if marker.args:
86
+ threshold = float(marker.args[0])
87
+ threshold = float(marker.kwargs.get("threshold", threshold))
88
+ double_check = bool(marker.kwargs.get("double_check", double_check))
89
+ self.threshold = float(threshold)
90
+ self.double_check = double_check
91
+ self.strict = bool(_opt(cfg, "strict"))
92
+ self.client = ConfidenceClient(
93
+ model=_opt(cfg, "model") or None,
94
+ base_url=_opt(cfg, "base_url") or None,
95
+ api=_opt(cfg, "api") or None,
96
+ threshold=self.threshold,
97
+ )
98
+
99
+ def _record(self, report: ConfidenceReport) -> None:
100
+ _records(self._request.config).append(Record(self._request.node.nodeid, report, report.is_confident))
101
+
102
+ def ask(self, prompt: str, model: Optional[str] = None, system: Optional[str] = None, double_check: Optional[bool] = None) -> Answer:
103
+ """Ask the configured model. Skips the test if the model server isn't reachable
104
+ (use --llm-confidence-strict to fail instead)."""
105
+ dc = self.double_check if double_check is None else double_check
106
+ try:
107
+ ans = self.client.ask(prompt, model=model, system=system, double_check=dc)
108
+ except ConfidenceError as exc:
109
+ if self.strict:
110
+ pytest.fail(f"llm-confidence: {exc}")
111
+ pytest.skip(f"llm-confidence: {exc}")
112
+ self._record(ans.report)
113
+ return ans
114
+
115
+ def check(self, response: Any) -> ConfidenceReport:
116
+ """Build and record a report for a response you already have."""
117
+ report = _to_report(response, self.threshold)
118
+ if report.tokens:
119
+ self._record(report)
120
+ return report
121
+
122
+ def assert_confident(self, response: Any, threshold: Optional[float] = None, msg: Optional[str] = None) -> ConfidenceReport:
123
+ th = self.threshold if threshold is None else threshold
124
+ report = _to_report(response, th)
125
+ if report.tokens and not any(r.report is report for r in _records(self._request.config)):
126
+ self._record(report)
127
+ return assert_confident(report, threshold=th, msg=msg)
128
+
129
+
130
+ # -- plugin hooks -------------------------------------------------------------
131
+
132
+ _DEFAULTS = {"threshold": DEFAULT_THRESHOLD, "model": "", "api": "", "base_url": "", "strict": False, "double_check": False, "report": ""}
133
+
134
+
135
+ def _opt(config: pytest.Config, name: str) -> Any:
136
+ val = config.getoption(f"llm_confidence_{name}", default=None)
137
+ if val not in (None, ""):
138
+ return val
139
+ ini = config.getini(f"llm_confidence_{name}")
140
+ if ini not in (None, "", []):
141
+ if name == "threshold":
142
+ return float(ini)
143
+ if name in ("strict", "double_check"):
144
+ return str(ini).lower() in ("1", "true", "yes", "on")
145
+ return ini
146
+ return _DEFAULTS[name]
147
+
148
+
149
+ def _records(config: pytest.Config) -> List[Record]:
150
+ if _RECORDS_KEY is not None:
151
+ return config.stash.setdefault(_RECORDS_KEY, [])
152
+ if not hasattr(config, "_llm_confidence_records"): # pragma: no cover - old pytest
153
+ config._llm_confidence_records = []
154
+ return config._llm_confidence_records # pragma: no cover
155
+
156
+
157
+ def pytest_addoption(parser: pytest.Parser) -> None:
158
+ g = parser.getgroup("llm-confidence", "fail tests when a language model wasn't sure of its answer")
159
+ g.addoption("--llm-confidence-threshold", dest="llm_confidence_threshold", type=float, default=None,
160
+ help="probability below which a word counts as shaky (default 0.8)")
161
+ g.addoption("--llm-confidence-model", dest="llm_confidence_model", default=None, help="model for llm_confidence.ask (default llama3.2)")
162
+ g.addoption("--llm-confidence-api", dest="llm_confidence_api", choices=["ollama", "openai"], default=None,
163
+ help="server type for llm_confidence.ask (default ollama)")
164
+ g.addoption("--llm-confidence-base-url", dest="llm_confidence_base_url", default=None,
165
+ help="model server address (default $OLLAMA_HOST or http://127.0.0.1:11434)")
166
+ g.addoption("--llm-confidence-strict", dest="llm_confidence_strict", action="store_true", default=None,
167
+ help="fail instead of skip when the model server can't be reached")
168
+ g.addoption("--llm-confidence-double-check", dest="llm_confidence_double_check", action="store_true", default=None,
169
+ help="re-ask shaky short answers in full")
170
+ g.addoption("--llm-confidence-report", dest="llm_confidence_report", default=None,
171
+ help="write a JSON report of every confidence check to this path")
172
+ for name, help_ in [
173
+ ("threshold", "default confidence threshold"), ("model", "default model"), ("api", "ollama or openai"),
174
+ ("base_url", "model server address"), ("strict", "fail when the server can't be reached"),
175
+ ("double_check", "re-ask shaky short answers"), ("report", "JSON report path"),
176
+ ]:
177
+ parser.addini(f"llm_confidence_{name}", help_, default="")
178
+
179
+
180
+ def pytest_configure(config: pytest.Config) -> None:
181
+ config.addinivalue_line(
182
+ "markers",
183
+ "llm_confidence(threshold=0.8, double_check=False): confidence settings for this test's llm_confidence checks",
184
+ )
185
+
186
+
187
+ @pytest.fixture
188
+ def llm_confidence(request: pytest.FixtureRequest) -> LLMConfidence:
189
+ """Ask a model and assert it was sure of its answer."""
190
+ return LLMConfidence(request)
191
+
192
+
193
+ def pytest_terminal_summary(terminalreporter, exitstatus, config) -> None:
194
+ records = _records(config)
195
+ if not records:
196
+ return
197
+ tr = terminalreporter
198
+ tr.write_sep("=", "LLM confidence")
199
+ shaky = 0
200
+ for r in records:
201
+ mark = "ok " if r.passed else "SHAKY"
202
+ shaky += 0 if r.passed else 1
203
+ weak = r.report.weakest
204
+ detail = f"lowest {quote(weak.text)} at {pct(weak.prob)}" if weak else "no tokens"
205
+ tr.write_line(f"{mark} {r.nodeid} {detail}")
206
+ tr.write_line(f"{len(records)} check(s), {shaky} shaky, threshold set per test (default {pct(_opt(config, 'threshold'))})")
207
+ tr.write_line(LENS_LINE)
208
+ path = _opt(config, "report")
209
+ if path:
210
+ out = [{"test": r.nodeid, "passed": r.passed, **r.report.to_dict()} for r in records]
211
+ with open(path, "w", encoding="utf-8") as fh:
212
+ json.dump({"checks": out}, fh, indent=2)
213
+ tr.write_line(f"wrote {path}")
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-llm-confidence
3
+ Version: 0.1.0
4
+ Summary: pytest plugin that fails a test when a language model wasn't sure of its answer. Reads token probabilities: no judge model, no extra API cost, deterministic.
5
+ Author-email: Proprioceptive AI <logan@proprioceptiveai.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://proprioceptiveai.com/products.html
8
+ Project-URL: Repository, https://github.com/Loganwins/proprioceptive-confidence
9
+ Project-URL: Issues, https://github.com/Loganwins/proprioceptive-confidence/issues
10
+ Project-URL: Proprioceptive Lens, https://pypi.org/project/proprioceptive-lens/
11
+ Keywords: pytest,llm,testing,evals,confidence,logprobs,hallucination,ollama,ci
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Pytest
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Software Development :: Testing
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: pytest>=7
23
+ Requires-Dist: proprioceptive-confidence>=0.1.0
24
+ Dynamic: license-file
25
+
26
+ # pytest-llm-confidence
27
+
28
+ **Fail a test when the model wasn't sure of its answer.**
29
+
30
+ Most LLM test tools ask a second model to judge the first, which costs money, adds latency and changes from run to
31
+ run. `pytest-llm-confidence` reads the model's own token probabilities instead: no judge model, no extra API cost,
32
+ and the same response always gets the same verdict.
33
+
34
+ ```
35
+ $ pip install pytest-llm-confidence
36
+ ```
37
+
38
+ ```python
39
+ # test_answers.py
40
+ def test_capital(llm_confidence):
41
+ ans = llm_confidence.ask("What is the capital of Australia? Answer with one word.")
42
+ assert ans.text == "Canberra"
43
+ llm_confidence.assert_confident(ans) # fails if any word was below 80%
44
+ ```
45
+
46
+ ```
47
+ $ pytest
48
+ ...
49
+ FAILED test_answers.py::test_capital - ShakyAnswerError: model wasn't sure of its answer
50
+ (shaky: 1 word(s) below 80%: "Syd" at 41%)
51
+ answer: 'Sydney'
52
+ "Syd" at 41% (alternatives: "Can" 38%)
53
+
54
+ ============================ LLM confidence ============================
55
+ SHAKY test_answers.py::test_capital lowest "Syd" at 41%
56
+ 1 check(s), 1 shaky
57
+ ```
58
+
59
+ *(Illustrative output; real numbers depend on your model.)*
60
+
61
+ ## Works with your model
62
+
63
+ - **Ollama 0.12+** (default): `llm_confidence.ask` talks to `http://127.0.0.1:11434`.
64
+ - **Any OpenAI-compatible server that returns logprobs**: OpenAI, vLLM, llama.cpp, LM Studio:
65
+ `pytest --llm-confidence-api openai --llm-confidence-base-url http://127.0.0.1:8000/v1 --llm-confidence-model my-model`
66
+ - **Responses you already have:** `assert_confident(response)` accepts OpenAI-style responses requested with
67
+ `logprobs=True`, Ollama responses requested with `"logprobs": true`, or `(token, logprob)` pairs.
68
+
69
+ ```python
70
+ from pytest_llm_confidence import assert_confident
71
+
72
+ def test_my_pipeline():
73
+ response = my_app.call_model("...", logprobs=True)
74
+ assert_confident(response, threshold=0.9)
75
+ ```
76
+
77
+ ## Settings
78
+
79
+ | Option | ini key | Default |
80
+ |---|---|---|
81
+ | `--llm-confidence-threshold` | `llm_confidence_threshold` | `0.8` |
82
+ | `--llm-confidence-model` | `llm_confidence_model` | `llama3.2` |
83
+ | `--llm-confidence-api` | `llm_confidence_api` | `ollama` |
84
+ | `--llm-confidence-base-url` | `llm_confidence_base_url` | `$OLLAMA_HOST` or `http://127.0.0.1:11434` |
85
+ | `--llm-confidence-double-check` | `llm_confidence_double_check` | off |
86
+ | `--llm-confidence-strict` | `llm_confidence_strict` | off (skip when the server is down) |
87
+ | `--llm-confidence-report PATH` | `llm_confidence_report` | none (writes JSON for CI artifacts) |
88
+
89
+ Per test: `@pytest.mark.llm_confidence(threshold=0.95, double_check=True)`.
90
+
91
+ **CI-safe by default:** if the model server can't be reached, `llm_confidence.ask` skips the test instead of failing
92
+ it. Pass `--llm-confidence-strict` to make that a failure.
93
+
94
+ **Double-check:** with `double_check=True`, a shaky short answer is re-asked in full and `ans.double_check.agrees`
95
+ tells you whether the answer held up.
96
+
97
+ ## Testing without a model
98
+
99
+ `proprioceptive_confidence.testing.FakeModelServer` serves scripted token probabilities over Ollama's and OpenAI's
100
+ APIs, so you can test your confidence handling in CI without a GPU.
101
+
102
+ ## What it can't do
103
+
104
+ A model can be wrong and certain. This plugin catches *shaky* answers, not confident mistakes, so keep your
105
+ correctness assertions too.
106
+
107
+ ## Related
108
+
109
+ - **proprioceptive-confidence**: the library this plugin uses, with LangChain and LiteLLM adapters.
110
+ - **proprioceptive-mcp**: let Claude Code, Cursor and other agents ask your local model and see how sure it was.
111
+ - **Proprioceptive Lens**: see every word's confidence live in a local app: `pip install proprioceptive-lens`.
112
+
113
+ MIT licensed. From [Proprioceptive AI](https://proprioceptiveai.com).
@@ -0,0 +1,8 @@
1
+ pytest_llm_confidence/__init__.py,sha256=mli_s1K4jt7zacdEGgbjNdzUcMnVhOhi0CGkV1oh2xI,496
2
+ pytest_llm_confidence/plugin.py,sha256=USnoXOB0nGOv0WAfs5f48onFKyOg6_RXrvpOeGogUVQ,9262
3
+ pytest_llm_confidence-0.1.0.dist-info/licenses/LICENSE,sha256=WIQNMpYC8SC4ItT2-e2Mipa1I8Jm_GnZSFpA8gzFTF4,1080
4
+ pytest_llm_confidence-0.1.0.dist-info/METADATA,sha256=d2mymAGUNueyH1njMUoaMFbXMOrd95v547TBwmOPL10,4881
5
+ pytest_llm_confidence-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ pytest_llm_confidence-0.1.0.dist-info/entry_points.txt,sha256=GL3dAkTnHaqFfpcXXWtQTOhVFN55-jXhwqmCmTEgdkc,57
7
+ pytest_llm_confidence-0.1.0.dist-info/top_level.txt,sha256=5MtvdaBDMOUYkkW0BLP5h1EG9_gFMpApPKnFbnjOjQU,22
8
+ pytest_llm_confidence-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ llm_confidence = pytest_llm_confidence.plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Proprioceptive AI, Inc.
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 @@
1
+ pytest_llm_confidence