Skip to main content

Extract per-field confidence scores from LLM structured JSON outputs using token-level log-probabilities.

Project description

llm-structured-confidence

Extract path-aware confidence scores from LLM structured JSON outputs using token-level log-probabilities.

License Python PyPI

InstallationQuick StartPath SyntaxDocumentationSupported Providers


Designed for structured JSON outputs from OpenAI, Gemini, and compatible providers. The library aligns token logprobs to exact JSON value spans, strips structural tokens, and computes confidence only from the tokens that belong to the value itself.

Installation

pip install llm-structured-confidence

For DataFrame helpers:

pip install "llm-structured-confidence[pandas]"

Quick Start

import litellm
from llm_structured_confidence import extract_logprobs

response = litellm.completion(
    model="gpt-4.1-mini",
    messages=[
        {"role": "system", "content": "Classify this text."},
        {"role": "user", "content": "Morning yoga and meditation session"},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "classification",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "category": {
                        "type": "string",
                        "enum": ["sports", "health and wellness", "technology"],
                    }
                },
                "required": ["category"],
                "additionalProperties": False,
            },
        },
    },
    logprobs=True,
    top_logprobs=5,
)

entries = extract_logprobs(response, field_path="category")
entry = entries[0]

print(entry.path)                                    # category
print(entry.value)                                   # health and wellness
print(entry.field_logprob.mean_nonzero_probability)  # 0.8451

Arrays

# {"categories": ["health and wellness", "sports", "technology"]}
entries = extract_logprobs(response, field_path="categories[]")

for entry in entries:
    print(entry.path, entry.value)

Nested arrays of objects

# {"classifications": [{"id": 0, "name": "Positive", "color": "#00FF00"}]}
entries = extract_logprobs(response, field_path="classifications[].name")

for entry in entries:
    print(entry.path, entry.value, entry.field_logprob.mean_nonzero_probability)

Schema auto-detection

If you pass response_schema=, the library auto-detects enum-valued paths recursively.

entries = extract_logprobs(response, response_schema=ClassificationModel)

That also enables TopAlternative.resolved_value, so token prefixes like "Pos" can resolve back to "Positive" when the match is unique.

Path Syntax

  • category
  • categories[]
  • classification.name
  • classifications[].name
  • groups[].items[].label

Flat/DataFrame Helpers

from llm_structured_confidence import extract_confidence, add_confidence_columns

metrics = extract_confidence(response, field_path="category")

df = add_confidence_columns(
    df,
    response_column="response",
    field_path="classifications[].name",
)

Helpers always return the first matching value and also expose its resolved path.

Documentation

Supported Providers

  • litellm.ModelResponse
  • openai.ChatCompletion
  • google.genai.GenerateContentResponse
  • raw OpenAI batch response dict with choices
  • raw Vertex AI batch response dict with candidates

Lower-level API

Internal modules remain available for custom workflows:

from llm_structured_confidence._parser import parse_json_spans, build_token_char_ranges, tokens_for_span
from llm_structured_confidence._converter import normalize_response

These are underscore-prefixed internals and may change in minor releases.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

llm_structured_confidence-0.4.2.tar.gz (32.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

llm_structured_confidence-0.4.2-py3-none-any.whl (26.7 kB view details)

Uploaded Python 3

File details

Details for the file llm_structured_confidence-0.4.2.tar.gz.

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.2.tar.gz
Algorithm Hash digest
SHA256 9720e5171be74a1c8531feaef909e0df33f2b77fb9b518a87b1c9813d717a7ee
MD5 4f1ec109b3ddfef2db958434fa85d43c
BLAKE2b-256 29b78ba913cd137622ccaa8a310329c60abafd646e7de1c7a4e21eb7018afb5c

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_structured_confidence-0.4.2.tar.gz:

Publisher: release.yml on rodolfonobrega/llm-structured-confidence

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file llm_structured_confidence-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a9352bf6e78e60f584c7e6d184a506677ad2f28caf5043d29f18b160e665fcc1
MD5 9073495a515cb525e54cd29d6d5e2f33
BLAKE2b-256 ec89bd08076ed05666b6c0e5e8200bf93589078569d135801412af4107ffc915

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_structured_confidence-0.4.2-py3-none-any.whl:

Publisher: release.yml on rodolfonobrega/llm-structured-confidence

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page