Metadata-Version: 2.4
Name: proprioceptive-confidence
Version: 0.3.0
Summary: See how sure a language model was about every word: confidence reports from token probabilities for Ollama, OpenAI-compatible servers, LangChain, LiteLLM and Inspect.
Author-email: Proprioceptive AI <logan@proprioceptiveai.com>
License-Expression: MIT
Project-URL: Homepage, https://proprioceptiveai.com/products.html
Project-URL: Repository, https://github.com/Loganwins/proprioceptive-confidence
Project-URL: Issues, https://github.com/Loganwins/proprioceptive-confidence/issues
Project-URL: Proprioceptive Lens, https://pypi.org/project/proprioceptive-lens/
Keywords: llm,confidence,logprobs,token-probabilities,hallucination,ollama,langchain,litellm,inspect-ai,llm-evaluation,calibration,uncertainty
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.3; extra == "langchain"
Provides-Extra: litellm
Requires-Dist: litellm>=1.40; extra == "litellm"
Provides-Extra: inspect
Requires-Dist: inspect-ai>=0.3.200; extra == "inspect"
Dynamic: license-file

# proprioceptive-confidence

**See how sure a language model was about every word.**

Models sound equally sure whether they're right or guessing. Their own token probabilities tell the difference.
`proprioceptive-confidence` turns those probabilities into a plain report: which words were shaky, how shaky,
and whether a short answer still holds when the model is asked again in full.

```
$ pip install proprioceptive-confidence
$ proprioconf "In what year was Albert Einstein born? Answer with just the year." --double-check

1904

shaky: 1 word(s) below 80%: "190" at 66%
double-check: 'Albert Einstein was born in 1879.' (answers disagree)
```

*(Output from a small local model; your numbers will vary by model.)*

- **No dependencies.** Standard library only.
- **Works with what you already run:** Ollama 0.12+ (native API), and any OpenAI-compatible server that returns
  `logprobs` (OpenAI, vLLM, llama.cpp, LM Studio, Ollama's `/v1`).
- **Plugs into frameworks:** a LangChain callback, a LiteLLM logger and an Inspect scorer.
- **Nothing leaves your machine** when you point it at a local model.

## Python

```python
from proprioceptive_confidence import ConfidenceClient

client = ConfidenceClient(model="llama3.2", threshold=0.8)           # Ollama at 127.0.0.1:11434
ans = client.ask("What is the capital of Australia?", double_check=True)

print(ans.text)                      # the answer
print(ans.report.summary())          # 'confident: ...' or 'shaky: ... "Sydney" at 41%'
print(ans.report.is_confident)       # False if any word was below the threshold
print(ans.report.to_dict())          # min / mean probability, shaky tokens, alternatives
```

Already have a response? Analyse it directly:

```python
from proprioceptive_confidence import analyze

report = analyze(openai_response)    # OpenAI-style dict or object requested with logprobs=True
report = analyze(ollama_response)    # Ollama /api/chat response requested with "logprobs": true
```

OpenAI-compatible servers:

```python
client = ConfidenceClient(api="openai", base_url="http://127.0.0.1:8000/v1", model="my-model")
```

## Which threshold should I use? `proprioconf calibrate`

Every model is sure in its own way, so 80% is only a starting point. `calibrate` asks your model a set of questions
with known answers and shows how well its confidence separates right answers from wrong ones, then recommends a
threshold:

```
$ proprioconf calibrate --sample --model llama3.2:1b      # 60 built-in general-knowledge questions
$ proprioconf calibrate my_questions.jsonl --json result.json
```

Questions file: one JSON object per line, `{"question": "...", "answer": "..."}` (several acceptable answers:
`"answers": [...]`), or a CSV with `question,answer` columns. An answer counts as right when it contains an acceptable
answer as whole words, ignoring case, accents and punctuation.

A real run on GitHub's CPU runners ([see it](https://github.com/Loganwins/proprioceptive-confidence/actions/runs/47259536552)):

```
Model llama3.2:1b: 47 of 60 right (78%).
Confidence separates right from wrong answers with AUROC 0.89 (1.00 = perfectly, 0.50 = no better than chance).
Median lowest-word probability: right answers 92%, wrong answers 35%.

Threshold   flags   wrong caught   right flagged   accuracy of the rest
      50%     18%     7 of 13          4 of 47          88%
      70%     35%    10 of 13         11 of 47          92%
      80%     47%    13 of 13         15 of 47         100%  <- recommended
      90%     55%    13 of 13         20 of 47         100%
```

The same 60 questions on `qwen2.5:0.5b`: 34 right, AUROC 0.87, and the recommended threshold is 70% (it catches 25
of 26 wrong answers). Different models, different thresholds: that's why it's worth measuring yours.

You get the accuracy, the AUROC (how well confidence separates right from wrong answers: 1.00 perfectly, 0.50 not at
all), accuracy per confidence band, and for each threshold how many wrong answers it catches and how many right ones
it flags. `--target-accuracy 0.95` picks the lowest threshold that keeps the unflagged answers 95% accurate. From
Python: `proprioceptive_confidence.calibration.calibrate(items, client)`.

## LangChain

```python
from langchain_openai import ChatOpenAI
from proprioceptive_confidence.integrations.langchain import ConfidenceCallbackHandler

conf = ConfidenceCallbackHandler(threshold=0.8)
llm = ChatOpenAI(model="gpt-4o-mini", logprobs=True, callbacks=[conf])
llm.invoke("In what year was Albert Einstein born?")
print(conf.last_report.summary())
```

`pip install "proprioceptive-confidence[langchain]"`. Pass `raise_on_low=True` to stop a chain when an answer is shaky.

## LiteLLM

```python
import litellm
from proprioceptive_confidence.integrations.litellm import ConfidenceLogger

conf = ConfidenceLogger(threshold=0.8, on_report=lambda r: print(r.summary()))
litellm.callbacks = [conf]
litellm.completion(model="ollama_chat/llama3.2", messages=[{"role": "user", "content": "..."}], logprobs=True)
```

`pip install "proprioceptive-confidence[litellm]"`. LiteLLM runs loggers after the call returns, so use
`on_report` (or read `conf.reports`) rather than relying on an exception.

## Inspect

Score every sample of an [Inspect](https://inspect.aisi.org.uk/) eval by whether the model was sure of its answer:

```python
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.model import GenerateConfig
from inspect_ai.scorer import match
from inspect_ai.solver import generate
from proprioceptive_confidence.integrations.inspect import confidence

@task
def capitals():
    return Task(
        dataset=[Sample(input="Capital of France? One word.", target="Paris")],
        solver=generate(),
        scorer=[match(), confidence(threshold=0.8)],
        config=GenerateConfig(logprobs=True, top_logprobs=3),
    )
```

`pip install "proprioceptive-confidence[inspect]"`. Each sample scores C (every word at or above the threshold),
I (a shaky word) or N (no logprobs returned); metadata has `min_prob`, `mean_prob` and the shaky words with their
alternatives. Pairing it with `match()` shows which wrong answers the model was unsure of.

## Testing without a model

`proprioceptive_confidence.testing.FakeModelServer` speaks Ollama's and OpenAI's chat APIs with scripted token
probabilities, so you can test confidence handling in CI without a GPU.

## What it can't do

A model can be wrong and certain. Token probabilities catch *shaky* answers, not confident mistakes.

## Related

- **pytest-llm-confidence**: fail a test when the model wasn't sure of its answer, or got less sure than its saved
  baseline.
- **proprioceptive-mcp**: let Claude Code, Cursor and other agents ask your local model and see how sure it was.
- **Proprioceptive Lens**: the full local app, with live confidence colouring, double-check, private memory and
  internal-state behaviour readings: `pip install proprioceptive-lens`.

MIT licensed. From [Proprioceptive AI](https://proprioceptiveai.com).
