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.0.tar.gz (30.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.0-py3-none-any.whl (26.2 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.0.tar.gz
Algorithm Hash digest
SHA256 cf42e794690a083b9c224e9e7eb7f5c97709bd6140701ecf82d1d678fc5b644b
MD5 068f00879889e734d54e7e2f55fc54d3
BLAKE2b-256 398c0018e55d5dad2590f800e3c5189d169e3be8b836dc4825079c2db1deff3f

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for llm_structured_confidence-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dc2603daa070393e047a815ff9e31ca0f32623260ee352f5a058ced15981109f
MD5 4a8b5ea303273e3162ceab2c028e0e27
BLAKE2b-256 86b4e77f6945358762bb4e2324b407afb07be89cbd3a74f4b98aa11fdb7cb4dd

See more details on using hashes here.

Provenance

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