A Python package for extracting confidence scores from LLM models outputs, particularly using log probabilities
Project description
llm-confidence
llm-confidence is a Python package designed to extract and calculate confidence scores from outputs of large language models (LLMs), specifically focusing on log probabilities. The package helps you work with model responses, particularly when working with structured data such as JSON outputs.
Features
- Extract token-level log probabilities.
- Aggregate probabilities to calculate confidence scores for key-value pairs.
- Handle nested keys to compute confidence scores for related fields.
- Simple API for processing log probabilities from OpenAI GPT models.
Installation
You can install the package using pip:
pip install llm-confidence
Usage
Here’s an example of how to use the llm-confidence package to calculate confidence scores based on log probabilities from OpenAI GPT models:
from openai import OpenAI
import os
from llm_confidence.logprobs_handler import LogprobsHandler
# Initialize the LogprobsHandler
logprobs_handler = LogprobsHandler()
def get_completion(
messages: list[dict[str, str]],
model: str = "gpt-4o",
max_tokens=500,
temperature=0,
stop=None,
seed=42,
response_format=None,
logprobs=None,
top_logprobs=None,
):
params = {
"model": model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"stop": stop,
"seed": seed,
"logprobs": logprobs,
"top_logprobs": top_logprobs,
}
if response_format:
params["response_format"] = response_format
completion = client.chat.completions.create(**params)
return completion
# Set up your OpenAI client with your API key
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
# Define a prompt for completion
response_raw = get_completion(
[{'role': 'user', 'content': 'Tell me the name of a city and a few streets in this city, and return the response in JSON format.'}],
logprobs=True,
response_format={'type': 'json_object'}
)
# Print the output
print(response_raw.choices[0].message.content)
# Extract the log probabilities from the response
response_logprobs = response_raw.choices[0].logprobs.content if hasattr(response_raw.choices[0], 'logprobs') else []
# Format the logprobs
logprobs_formatted = logprobs_handler.format_logprobs(response_logprobs)
# Process the log probabilities to get confidence scores
confidence = logprobs_handler.process_logprobs(
logprobs_formatted,
nested_keys_dct={'vat': ['vat_data', 'percent', 'vat_amount', 'exclude_vat_amount']}
)
# Print the confidence scores
print(confidence)
Example Breakdown
- Get Completion: Sends a prompt to the OpenAI GPT model and retrieves the completion, including log probabilities.
- Logprobs Formatting: Formats the raw log probabilities into a structured format that can be processed.
- Confidence Calculation: Aggregates the probabilities and returns confidence scores for key-value pairs in the model's JSON response.
Customization
You can customize the nested_keys_dct parameter to aggregate confidence scores for your specific fields. For example:
nested_keys_dct={'address': ['street', 'city', 'state']}
This will compute a combined confidence score for all fields related to addresses.
License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Contributing
We welcome contributions! Here's how you can help:
- Fork the project.
- Create a branch for your feature or bug fix.
- Open a pull request.
Make sure to include tests for any new features or bug fixes.
Feel free to use the package and improve upon it. If you encounter any issues, please open an issue in the repository.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file llm_confidence-0.2.1.tar.gz.
File metadata
- Download URL: llm_confidence-0.2.1.tar.gz
- Upload date:
- Size: 8.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
00d2bdd7fa0704830094f2a3faae23f2a2725812c5988a2b6cfe8f0784b21786
|
|
| MD5 |
b4f0708776894939d31a3eafa5f3327c
|
|
| BLAKE2b-256 |
13e70353e31da13378c09d8fab006033b15ee67b43da57d9a74fa8b32509e1c0
|
File details
Details for the file llm_confidence-0.2.1-py3-none-any.whl.
File metadata
- Download URL: llm_confidence-0.2.1-py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bb7ae8efcf91ba7195cd472c9992dc315907ed2296168726daf5c146dda5f21a
|
|
| MD5 |
28f08b8fc826ad88a95d20f61c5a5b9b
|
|
| BLAKE2b-256 |
f3d3e9832b67ddcaca906ccee96fd70c00c0e569bffd82f246ebad532589e43a
|