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.1.tar.gz (31.9 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.1-py3-none-any.whl (26.7 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.1.tar.gz
Algorithm Hash digest
SHA256 f9624d2f01e05f8dddc82a9794c61266209f8957b0202a6b784ad138a4c45f9c
MD5 f51447f0282779f2005d19e7ce9fee74
BLAKE2b-256 e4e7f676cb37c97728eca4337747a52dbe6c9345dccaeeec3f80440966ee7938

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_structured_confidence-0.4.1.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.1-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3e5038345172d44729761d8fa2872fce5a36bb73c2cfdc7c0119f372bb3f8992
MD5 06e22100c25bc28a99983d14a31fc61a
BLAKE2b-256 1e3315fd537b876e1595757fdcf8faec9230e1a965d4c170cfe243578ce5d891

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_structured_confidence-0.4.1-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