proprioceptive-confidence 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.
- proprioceptive_confidence-0.1.0/LICENSE +21 -0
- proprioceptive_confidence-0.1.0/PKG-INFO +127 -0
- proprioceptive_confidence-0.1.0/README.md +100 -0
- proprioceptive_confidence-0.1.0/pyproject.toml +40 -0
- proprioceptive_confidence-0.1.0/setup.cfg +4 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/__init__.py +39 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/cli.py +71 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/client.py +218 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/core.py +200 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/integrations/__init__.py +5 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/integrations/_common.py +55 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/integrations/langchain.py +57 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/integrations/litellm.py +56 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence/testing.py +114 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/PKG-INFO +127 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/SOURCES.txt +20 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/dependency_links.txt +1 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/entry_points.txt +2 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/requires.txt +6 -0
- proprioceptive_confidence-0.1.0/src/proprioceptive_confidence.egg-info/top_level.txt +1 -0
- proprioceptive_confidence-0.1.0/tests/test_core.py +113 -0
- proprioceptive_confidence-0.1.0/tests/test_integrations.py +84 -0
|
@@ -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,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: proprioceptive-confidence
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: See how sure a language model was about every word: confidence reports from token probabilities for Ollama, OpenAI-compatible servers, LangChain and LiteLLM.
|
|
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: llm,confidence,logprobs,token-probabilities,hallucination,ollama,langchain,litellm,uncertainty
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: langchain
|
|
23
|
+
Requires-Dist: langchain-core>=0.3; extra == "langchain"
|
|
24
|
+
Provides-Extra: litellm
|
|
25
|
+
Requires-Dist: litellm>=1.40; extra == "litellm"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# proprioceptive-confidence
|
|
29
|
+
|
|
30
|
+
**See how sure a language model was about every word.**
|
|
31
|
+
|
|
32
|
+
Models sound equally sure whether they're right or guessing. Their own token probabilities tell the difference.
|
|
33
|
+
`proprioceptive-confidence` turns those probabilities into a plain report: which words were shaky, how shaky,
|
|
34
|
+
and whether a short answer still holds when the model is asked again in full.
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
$ pip install proprioceptive-confidence
|
|
38
|
+
$ proprioconf "In what year was Albert Einstein born? Answer with just the year." --double-check
|
|
39
|
+
|
|
40
|
+
1904
|
|
41
|
+
|
|
42
|
+
shaky: 1 word(s) below 80%: "190" at 66%
|
|
43
|
+
double-check: 'Albert Einstein was born in 1879.' (answers disagree)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
*(Output from a small local model; your numbers will vary by model.)*
|
|
47
|
+
|
|
48
|
+
- **No dependencies.** Standard library only.
|
|
49
|
+
- **Works with what you already run:** Ollama 0.12+ (native API), and any OpenAI-compatible server that returns
|
|
50
|
+
`logprobs` (OpenAI, vLLM, llama.cpp, LM Studio, Ollama's `/v1`).
|
|
51
|
+
- **Plugs into frameworks:** a LangChain callback and a LiteLLM logger.
|
|
52
|
+
- **Nothing leaves your machine** when you point it at a local model.
|
|
53
|
+
|
|
54
|
+
## Python
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from proprioceptive_confidence import ConfidenceClient
|
|
58
|
+
|
|
59
|
+
client = ConfidenceClient(model="llama3.2", threshold=0.8) # Ollama at 127.0.0.1:11434
|
|
60
|
+
ans = client.ask("What is the capital of Australia?", double_check=True)
|
|
61
|
+
|
|
62
|
+
print(ans.text) # the answer
|
|
63
|
+
print(ans.report.summary()) # 'confident: ...' or 'shaky: ... "Sydney" at 41%'
|
|
64
|
+
print(ans.report.is_confident) # False if any word was below the threshold
|
|
65
|
+
print(ans.report.to_dict()) # min / mean probability, shaky tokens, alternatives
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Already have a response? Analyse it directly:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from proprioceptive_confidence import analyze
|
|
72
|
+
|
|
73
|
+
report = analyze(openai_response) # OpenAI-style dict or object requested with logprobs=True
|
|
74
|
+
report = analyze(ollama_response) # Ollama /api/chat response requested with "logprobs": true
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
OpenAI-compatible servers:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
client = ConfidenceClient(api="openai", base_url="http://127.0.0.1:8000/v1", model="my-model")
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## LangChain
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from langchain_openai import ChatOpenAI
|
|
87
|
+
from proprioceptive_confidence.integrations.langchain import ConfidenceCallbackHandler
|
|
88
|
+
|
|
89
|
+
conf = ConfidenceCallbackHandler(threshold=0.8)
|
|
90
|
+
llm = ChatOpenAI(model="gpt-4o-mini", logprobs=True, callbacks=[conf])
|
|
91
|
+
llm.invoke("In what year was Albert Einstein born?")
|
|
92
|
+
print(conf.last_report.summary())
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`pip install "proprioceptive-confidence[langchain]"`. Pass `raise_on_low=True` to stop a chain when an answer is shaky.
|
|
96
|
+
|
|
97
|
+
## LiteLLM
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
import litellm
|
|
101
|
+
from proprioceptive_confidence.integrations.litellm import ConfidenceLogger
|
|
102
|
+
|
|
103
|
+
conf = ConfidenceLogger(threshold=0.8, on_report=lambda r: print(r.summary()))
|
|
104
|
+
litellm.callbacks = [conf]
|
|
105
|
+
litellm.completion(model="ollama_chat/llama3.2", messages=[{"role": "user", "content": "..."}], logprobs=True)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`pip install "proprioceptive-confidence[litellm]"`. LiteLLM runs loggers after the call returns, so use
|
|
109
|
+
`on_report` (or read `conf.reports`) rather than relying on an exception.
|
|
110
|
+
|
|
111
|
+
## Testing without a model
|
|
112
|
+
|
|
113
|
+
`proprioceptive_confidence.testing.FakeModelServer` speaks Ollama's and OpenAI's chat APIs with scripted token
|
|
114
|
+
probabilities, so you can test confidence handling in CI without a GPU.
|
|
115
|
+
|
|
116
|
+
## What it can't do
|
|
117
|
+
|
|
118
|
+
A model can be wrong and certain. Token probabilities catch *shaky* answers, not confident mistakes.
|
|
119
|
+
|
|
120
|
+
## Related
|
|
121
|
+
|
|
122
|
+
- **pytest-llm-confidence**: fail a test when the model wasn't sure of its answer.
|
|
123
|
+
- **proprioceptive-mcp**: let Claude Code, Cursor and other agents ask your local model and see how sure it was.
|
|
124
|
+
- **Proprioceptive Lens**: the full local app, with live confidence colouring, double-check, private memory and
|
|
125
|
+
internal-state behaviour readings: `pip install proprioceptive-lens`.
|
|
126
|
+
|
|
127
|
+
MIT licensed. From [Proprioceptive AI](https://proprioceptiveai.com).
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# proprioceptive-confidence
|
|
2
|
+
|
|
3
|
+
**See how sure a language model was about every word.**
|
|
4
|
+
|
|
5
|
+
Models sound equally sure whether they're right or guessing. Their own token probabilities tell the difference.
|
|
6
|
+
`proprioceptive-confidence` turns those probabilities into a plain report: which words were shaky, how shaky,
|
|
7
|
+
and whether a short answer still holds when the model is asked again in full.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
$ pip install proprioceptive-confidence
|
|
11
|
+
$ proprioconf "In what year was Albert Einstein born? Answer with just the year." --double-check
|
|
12
|
+
|
|
13
|
+
1904
|
|
14
|
+
|
|
15
|
+
shaky: 1 word(s) below 80%: "190" at 66%
|
|
16
|
+
double-check: 'Albert Einstein was born in 1879.' (answers disagree)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
*(Output from a small local model; your numbers will vary by model.)*
|
|
20
|
+
|
|
21
|
+
- **No dependencies.** Standard library only.
|
|
22
|
+
- **Works with what you already run:** Ollama 0.12+ (native API), and any OpenAI-compatible server that returns
|
|
23
|
+
`logprobs` (OpenAI, vLLM, llama.cpp, LM Studio, Ollama's `/v1`).
|
|
24
|
+
- **Plugs into frameworks:** a LangChain callback and a LiteLLM logger.
|
|
25
|
+
- **Nothing leaves your machine** when you point it at a local model.
|
|
26
|
+
|
|
27
|
+
## Python
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from proprioceptive_confidence import ConfidenceClient
|
|
31
|
+
|
|
32
|
+
client = ConfidenceClient(model="llama3.2", threshold=0.8) # Ollama at 127.0.0.1:11434
|
|
33
|
+
ans = client.ask("What is the capital of Australia?", double_check=True)
|
|
34
|
+
|
|
35
|
+
print(ans.text) # the answer
|
|
36
|
+
print(ans.report.summary()) # 'confident: ...' or 'shaky: ... "Sydney" at 41%'
|
|
37
|
+
print(ans.report.is_confident) # False if any word was below the threshold
|
|
38
|
+
print(ans.report.to_dict()) # min / mean probability, shaky tokens, alternatives
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Already have a response? Analyse it directly:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from proprioceptive_confidence import analyze
|
|
45
|
+
|
|
46
|
+
report = analyze(openai_response) # OpenAI-style dict or object requested with logprobs=True
|
|
47
|
+
report = analyze(ollama_response) # Ollama /api/chat response requested with "logprobs": true
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
OpenAI-compatible servers:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
client = ConfidenceClient(api="openai", base_url="http://127.0.0.1:8000/v1", model="my-model")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## LangChain
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from langchain_openai import ChatOpenAI
|
|
60
|
+
from proprioceptive_confidence.integrations.langchain import ConfidenceCallbackHandler
|
|
61
|
+
|
|
62
|
+
conf = ConfidenceCallbackHandler(threshold=0.8)
|
|
63
|
+
llm = ChatOpenAI(model="gpt-4o-mini", logprobs=True, callbacks=[conf])
|
|
64
|
+
llm.invoke("In what year was Albert Einstein born?")
|
|
65
|
+
print(conf.last_report.summary())
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`pip install "proprioceptive-confidence[langchain]"`. Pass `raise_on_low=True` to stop a chain when an answer is shaky.
|
|
69
|
+
|
|
70
|
+
## LiteLLM
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import litellm
|
|
74
|
+
from proprioceptive_confidence.integrations.litellm import ConfidenceLogger
|
|
75
|
+
|
|
76
|
+
conf = ConfidenceLogger(threshold=0.8, on_report=lambda r: print(r.summary()))
|
|
77
|
+
litellm.callbacks = [conf]
|
|
78
|
+
litellm.completion(model="ollama_chat/llama3.2", messages=[{"role": "user", "content": "..."}], logprobs=True)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`pip install "proprioceptive-confidence[litellm]"`. LiteLLM runs loggers after the call returns, so use
|
|
82
|
+
`on_report` (or read `conf.reports`) rather than relying on an exception.
|
|
83
|
+
|
|
84
|
+
## Testing without a model
|
|
85
|
+
|
|
86
|
+
`proprioceptive_confidence.testing.FakeModelServer` speaks Ollama's and OpenAI's chat APIs with scripted token
|
|
87
|
+
probabilities, so you can test confidence handling in CI without a GPU.
|
|
88
|
+
|
|
89
|
+
## What it can't do
|
|
90
|
+
|
|
91
|
+
A model can be wrong and certain. Token probabilities catch *shaky* answers, not confident mistakes.
|
|
92
|
+
|
|
93
|
+
## Related
|
|
94
|
+
|
|
95
|
+
- **pytest-llm-confidence**: fail a test when the model wasn't sure of its answer.
|
|
96
|
+
- **proprioceptive-mcp**: let Claude Code, Cursor and other agents ask your local model and see how sure it was.
|
|
97
|
+
- **Proprioceptive Lens**: the full local app, with live confidence colouring, double-check, private memory and
|
|
98
|
+
internal-state behaviour readings: `pip install proprioceptive-lens`.
|
|
99
|
+
|
|
100
|
+
MIT licensed. From [Proprioceptive AI](https://proprioceptiveai.com).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "proprioceptive-confidence"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "See how sure a language model was about every word: confidence reports from token probabilities for Ollama, OpenAI-compatible servers, LangChain and LiteLLM."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
authors = [{ name = "Proprioceptive AI", email = "logan@proprioceptiveai.com" }]
|
|
15
|
+
keywords = ["llm", "confidence", "logprobs", "token-probabilities", "hallucination", "ollama", "langchain", "litellm", "uncertainty"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Intended Audience :: Science/Research",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
23
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
langchain = ["langchain-core>=0.3"]
|
|
28
|
+
litellm = ["litellm>=1.40"]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://proprioceptiveai.com/products.html"
|
|
32
|
+
Repository = "https://github.com/Loganwins/proprioceptive-confidence"
|
|
33
|
+
Issues = "https://github.com/Loganwins/proprioceptive-confidence/issues"
|
|
34
|
+
"Proprioceptive Lens" = "https://pypi.org/project/proprioceptive-lens/"
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
proprioconf = "proprioceptive_confidence.cli:main"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""proprioceptive-confidence: see how sure a language model was about every word.
|
|
2
|
+
|
|
3
|
+
from proprioceptive_confidence import ask
|
|
4
|
+
ans = ask("In what year was Albert Einstein born? Answer with just the year.", model="llama3.2")
|
|
5
|
+
print(ans.text, ans.report.summary())
|
|
6
|
+
|
|
7
|
+
From Proprioceptive AI (https://proprioceptiveai.com). For a full local app with live
|
|
8
|
+
confidence colouring, memory and internal-state readings: pip install proprioceptive-lens
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
from .core import ( # noqa: E402
|
|
14
|
+
DEFAULT_THRESHOLD,
|
|
15
|
+
ConfidenceReport,
|
|
16
|
+
Token,
|
|
17
|
+
analyze,
|
|
18
|
+
from_logprobs,
|
|
19
|
+
from_ollama,
|
|
20
|
+
from_openai,
|
|
21
|
+
)
|
|
22
|
+
from .client import Answer, ConfidenceClient, ConfidenceError, DoubleCheck, answers_agree, ask # noqa: E402
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"__version__",
|
|
26
|
+
"DEFAULT_THRESHOLD",
|
|
27
|
+
"Answer",
|
|
28
|
+
"ConfidenceClient",
|
|
29
|
+
"ConfidenceError",
|
|
30
|
+
"ConfidenceReport",
|
|
31
|
+
"DoubleCheck",
|
|
32
|
+
"Token",
|
|
33
|
+
"analyze",
|
|
34
|
+
"answers_agree",
|
|
35
|
+
"ask",
|
|
36
|
+
"from_logprobs",
|
|
37
|
+
"from_ollama",
|
|
38
|
+
"from_openai",
|
|
39
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Command line: ask a local model and see how sure it was about every word.
|
|
2
|
+
|
|
3
|
+
proprioconf "In what year was Albert Einstein born? Answer with just the year."
|
|
4
|
+
proprioconf --api openai --base-url http://127.0.0.1:8000/v1 --model my-model "..."
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .client import ConfidenceClient, ConfidenceError
|
|
16
|
+
from .core import DEFAULT_THRESHOLD, pct
|
|
17
|
+
|
|
18
|
+
LENS_LINE = "See this live in a full app, with memory and internal-state readings: pip install proprioceptive-lens"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _color(prob: float, threshold: float) -> str:
|
|
22
|
+
if prob >= max(threshold, 0.9):
|
|
23
|
+
return "\033[38;5;121m" # green
|
|
24
|
+
if prob >= threshold:
|
|
25
|
+
return "\033[38;5;229m" # yellow
|
|
26
|
+
return "\033[38;5;215m\033[4m" # orange, underlined
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def render(report, threshold: float, use_color: bool) -> str:
|
|
30
|
+
if not use_color:
|
|
31
|
+
return report.text
|
|
32
|
+
reset = "\033[0m"
|
|
33
|
+
return "".join(_color(t.prob, threshold) + t.text + reset for t in report.tokens)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv=None) -> int:
|
|
37
|
+
ap = argparse.ArgumentParser(prog="proprioconf", description="Ask a model and see how sure it was about every word.")
|
|
38
|
+
ap.add_argument("prompt", nargs="+", help="the question to ask")
|
|
39
|
+
ap.add_argument("--model", "-m", default=None, help="model name (default: $PCONF_MODEL or llama3.2)")
|
|
40
|
+
ap.add_argument("--api", choices=["ollama", "openai"], default=None, help="server type (default: ollama)")
|
|
41
|
+
ap.add_argument("--base-url", default=None, help="server address (default: $OLLAMA_HOST or http://127.0.0.1:11434)")
|
|
42
|
+
ap.add_argument("--threshold", "-t", type=float, default=DEFAULT_THRESHOLD, help="probability below which a word counts as shaky (default 0.8)")
|
|
43
|
+
ap.add_argument("--double-check", "-d", action="store_true", help="re-ask shaky short answers in full")
|
|
44
|
+
ap.add_argument("--json", action="store_true", help="print JSON instead of coloured text")
|
|
45
|
+
ap.add_argument("--version", action="version", version=f"proprioconf {__version__}")
|
|
46
|
+
args = ap.parse_args(argv)
|
|
47
|
+
|
|
48
|
+
client = ConfidenceClient(model=args.model, base_url=args.base_url, api=args.api, threshold=args.threshold)
|
|
49
|
+
try:
|
|
50
|
+
ans = client.ask(" ".join(args.prompt), double_check=args.double_check)
|
|
51
|
+
except ConfidenceError as exc:
|
|
52
|
+
print(f"proprioconf: {exc}", file=sys.stderr)
|
|
53
|
+
return 2
|
|
54
|
+
if args.json:
|
|
55
|
+
print(json.dumps(ans.to_dict(), indent=2))
|
|
56
|
+
return 0
|
|
57
|
+
use_color = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
|
|
58
|
+
print(render(ans.report, args.threshold, use_color))
|
|
59
|
+
print()
|
|
60
|
+
print(ans.report.summary())
|
|
61
|
+
if ans.double_check is not None:
|
|
62
|
+
dc = ans.double_check
|
|
63
|
+
verdict = "answers agree" if dc.agrees else "answers disagree"
|
|
64
|
+
print(f"double-check: {dc.second_answer!r} ({verdict})")
|
|
65
|
+
print()
|
|
66
|
+
print(LENS_LINE)
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
if __name__ == "__main__": # pragma: no cover
|
|
71
|
+
sys.exit(main())
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Ask a model a question and get its answer with a confidence report.
|
|
2
|
+
|
|
3
|
+
Uses only the standard library. Talks to Ollama's native API or to any
|
|
4
|
+
OpenAI-compatible /v1/chat/completions endpoint that returns logprobs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from .core import DEFAULT_THRESHOLD, ConfidenceReport, from_ollama, from_openai
|
|
18
|
+
|
|
19
|
+
DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434"
|
|
20
|
+
SHORT_ANSWER_WORDS = 8
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConfidenceError(RuntimeError):
|
|
24
|
+
"""Raised when the model server can't be reached or returns no usable answer."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class DoubleCheck:
|
|
29
|
+
question: str
|
|
30
|
+
first_answer: str
|
|
31
|
+
second_answer: str
|
|
32
|
+
agrees: bool
|
|
33
|
+
report: ConfidenceReport
|
|
34
|
+
|
|
35
|
+
def to_dict(self) -> dict:
|
|
36
|
+
return {
|
|
37
|
+
"second_answer": self.second_answer,
|
|
38
|
+
"agrees": self.agrees,
|
|
39
|
+
"second_report": self.report.to_dict(),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Answer:
|
|
45
|
+
text: str
|
|
46
|
+
report: ConfidenceReport
|
|
47
|
+
model: str
|
|
48
|
+
raw: Any = None
|
|
49
|
+
double_check: Optional[DoubleCheck] = None
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def is_confident(self) -> bool:
|
|
53
|
+
return self.report.is_confident
|
|
54
|
+
|
|
55
|
+
def to_dict(self) -> dict:
|
|
56
|
+
out = {"text": self.text, "model": self.model, "confidence": self.report.to_dict()}
|
|
57
|
+
if self.double_check is not None:
|
|
58
|
+
out["double_check"] = self.double_check.to_dict()
|
|
59
|
+
return out
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _post(url: str, payload: dict, api_key: Optional[str], timeout: float) -> dict:
|
|
63
|
+
body = json.dumps(payload).encode("utf-8")
|
|
64
|
+
headers = {"Content-Type": "application/json"}
|
|
65
|
+
if api_key:
|
|
66
|
+
headers["Authorization"] = "Bearer " + api_key
|
|
67
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
68
|
+
try:
|
|
69
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
70
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
71
|
+
except urllib.error.HTTPError as exc:
|
|
72
|
+
detail = exc.read().decode("utf-8", "replace")[:300]
|
|
73
|
+
raise ConfidenceError(f"{url} returned HTTP {exc.code}: {detail}") from exc
|
|
74
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
75
|
+
raise ConfidenceError(f"could not reach {url}: {exc}") from exc
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _get(url: str, timeout: float) -> dict:
|
|
79
|
+
try:
|
|
80
|
+
with urllib.request.urlopen(url, timeout=timeout) as resp:
|
|
81
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
82
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
83
|
+
raise ConfidenceError(f"could not reach {url}: {exc}") from exc
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ConfidenceClient:
|
|
87
|
+
"""A small client for local or hosted models that return token probabilities.
|
|
88
|
+
|
|
89
|
+
api="ollama" uses Ollama's native /api/chat (Ollama 0.12 or later).
|
|
90
|
+
api="openai" uses /v1/chat/completions on any OpenAI-compatible server.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
model: Optional[str] = None,
|
|
96
|
+
base_url: Optional[str] = None,
|
|
97
|
+
api: Optional[str] = None,
|
|
98
|
+
threshold: float = DEFAULT_THRESHOLD,
|
|
99
|
+
api_key: Optional[str] = None,
|
|
100
|
+
timeout: float = 120.0,
|
|
101
|
+
top_logprobs: int = 3,
|
|
102
|
+
temperature: float = 0.0,
|
|
103
|
+
think: Optional[bool] = None,
|
|
104
|
+
) -> None:
|
|
105
|
+
self.api = (api or os.environ.get("PCONF_API") or "ollama").lower()
|
|
106
|
+
if self.api not in ("ollama", "openai"):
|
|
107
|
+
raise ValueError('api must be "ollama" or "openai"')
|
|
108
|
+
default_url = os.environ.get("OLLAMA_HOST", DEFAULT_OLLAMA_URL) if self.api == "ollama" else "http://127.0.0.1:8000"
|
|
109
|
+
self.base_url = (base_url or os.environ.get("PCONF_BASE_URL") or default_url).rstrip("/")
|
|
110
|
+
if self.api == "ollama" and not self.base_url.startswith("http"):
|
|
111
|
+
self.base_url = "http://" + self.base_url
|
|
112
|
+
self.model = model or os.environ.get("PCONF_MODEL") or "llama3.2"
|
|
113
|
+
self.threshold = threshold
|
|
114
|
+
self.api_key = api_key if api_key is not None else os.environ.get("PCONF_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
|
115
|
+
self.timeout = timeout
|
|
116
|
+
self.top_logprobs = top_logprobs
|
|
117
|
+
self.temperature = temperature
|
|
118
|
+
self.think = think
|
|
119
|
+
|
|
120
|
+
# -- requests -----------------------------------------------------------
|
|
121
|
+
def _chat(self, messages: List[Dict[str, str]], model: str) -> tuple:
|
|
122
|
+
if self.api == "ollama":
|
|
123
|
+
payload = {
|
|
124
|
+
"model": model,
|
|
125
|
+
"messages": messages,
|
|
126
|
+
"stream": False,
|
|
127
|
+
"logprobs": True,
|
|
128
|
+
"top_logprobs": self.top_logprobs,
|
|
129
|
+
"options": {"temperature": self.temperature},
|
|
130
|
+
}
|
|
131
|
+
if self.think is not None:
|
|
132
|
+
payload["think"] = self.think
|
|
133
|
+
data = _post(self.base_url + "/api/chat", payload, None, self.timeout)
|
|
134
|
+
text = ((data.get("message") or {}).get("content") or "").strip()
|
|
135
|
+
return text, from_ollama(data, threshold=self.threshold), data
|
|
136
|
+
url = self.base_url + ("/chat/completions" if self.base_url.endswith("/v1") else "/v1/chat/completions")
|
|
137
|
+
payload = {
|
|
138
|
+
"model": model,
|
|
139
|
+
"messages": messages,
|
|
140
|
+
"logprobs": True,
|
|
141
|
+
"top_logprobs": self.top_logprobs,
|
|
142
|
+
"temperature": self.temperature,
|
|
143
|
+
}
|
|
144
|
+
data = _post(url, payload, self.api_key, self.timeout)
|
|
145
|
+
choices = data.get("choices") or []
|
|
146
|
+
if not choices:
|
|
147
|
+
raise ConfidenceError("the server returned no choices")
|
|
148
|
+
text = (((choices[0] or {}).get("message") or {}).get("content") or "").strip()
|
|
149
|
+
return text, from_openai(data, threshold=self.threshold), data
|
|
150
|
+
|
|
151
|
+
def ask(
|
|
152
|
+
self,
|
|
153
|
+
prompt: str,
|
|
154
|
+
model: Optional[str] = None,
|
|
155
|
+
system: Optional[str] = None,
|
|
156
|
+
double_check: bool = False,
|
|
157
|
+
) -> Answer:
|
|
158
|
+
"""Ask a question; optionally re-ask shaky short answers in full."""
|
|
159
|
+
model = model or self.model
|
|
160
|
+
messages = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": prompt}]
|
|
161
|
+
text, report, raw = self._chat(messages, model)
|
|
162
|
+
if not report.tokens:
|
|
163
|
+
raise ConfidenceError(
|
|
164
|
+
"the server returned no token probabilities; for Ollama use version 0.12 or later, "
|
|
165
|
+
"for other servers make sure logprobs are supported"
|
|
166
|
+
)
|
|
167
|
+
answer = Answer(text=text, report=report, model=model, raw=raw)
|
|
168
|
+
if double_check and not report.is_confident and len(text.split()) <= SHORT_ANSWER_WORDS:
|
|
169
|
+
answer.double_check = self.recheck(prompt, text, model=model)
|
|
170
|
+
return answer
|
|
171
|
+
|
|
172
|
+
def recheck(self, question: str, first_answer: str, model: Optional[str] = None) -> DoubleCheck:
|
|
173
|
+
"""Re-ask the question asking for a full sentence, and see if the answer still holds."""
|
|
174
|
+
model = model or self.model
|
|
175
|
+
prompt = (
|
|
176
|
+
"Answer the following question in one complete sentence, stating the answer explicitly.\n\n"
|
|
177
|
+
f"Question: {question}"
|
|
178
|
+
)
|
|
179
|
+
text, report, _ = self._chat([{"role": "user", "content": prompt}], model)
|
|
180
|
+
return DoubleCheck(
|
|
181
|
+
question=question,
|
|
182
|
+
first_answer=first_answer,
|
|
183
|
+
second_answer=text,
|
|
184
|
+
agrees=answers_agree(first_answer, text),
|
|
185
|
+
report=report,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def list_models(self) -> List[str]:
|
|
189
|
+
if self.api == "ollama":
|
|
190
|
+
data = _get(self.base_url + "/api/tags", self.timeout)
|
|
191
|
+
return [m.get("name") or m.get("model") for m in data.get("models", []) if m.get("name") or m.get("model")]
|
|
192
|
+
url = self.base_url + ("/models" if self.base_url.endswith("/v1") else "/v1/models")
|
|
193
|
+
data = _get(url, self.timeout)
|
|
194
|
+
return [m.get("id") for m in data.get("data", []) if m.get("id")]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _norm(text: str) -> str:
|
|
198
|
+
text = text.lower()
|
|
199
|
+
text = re.sub(r"<think>.*?</think>", " ", text, flags=re.S)
|
|
200
|
+
return re.sub(r"[^\w]+", " ", text).strip()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def answers_agree(short: str, full: str) -> bool:
|
|
204
|
+
"""True when the short answer's words all appear in the full answer."""
|
|
205
|
+
s, f = _norm(short), _norm(full)
|
|
206
|
+
if not s:
|
|
207
|
+
return False
|
|
208
|
+
if s in f:
|
|
209
|
+
return True
|
|
210
|
+
words = [w for w in s.split() if len(w) > 1 or w.isdigit()]
|
|
211
|
+
fwords = set(f.split())
|
|
212
|
+
return bool(words) and all(w in fwords for w in words)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def ask(prompt: str, model: Optional[str] = None, **kwargs: Any) -> Answer:
|
|
216
|
+
"""One-call helper: ConfidenceClient(**kwargs).ask(prompt, model)."""
|
|
217
|
+
double_check = kwargs.pop("double_check", False)
|
|
218
|
+
return ConfidenceClient(model=model, **kwargs).ask(prompt, double_check=double_check)
|