Cleanlab Trustworthy Language Model (TLM) Client

1.1.39 · active · verified Fri Apr 17

The `cleanlab-tlm` library provides a Python client for the Cleanlab Trustworthy Language Model, enabling users to augment LLM interactions with trust scores and explanations. It wraps existing LLM APIs (like OpenAI) to provide a layer of trustworthiness analysis. The current version is 1.1.39, and the library is actively developed with frequent minor releases adding new features and improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `TLMChatCompletion` with an OpenAI client, send a chat request, and retrieve trust scores and explanation metadata. It highlights the importance of explicitly enabling `trust_scores` and `explanation_metadata` during client initialization.

import os
from cleanlab_tlm.tlm import TLMChatCompletion
from openai import OpenAI

# Initialize the TLM ChatCompletion client
# Ensure OPENAI_API_KEY environment variable is set
tlm_client = TLMChatCompletion(
    client=OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "")), # Replace '' with your key if not using env var
    trust_scores=True, # enables trust scores
    explanation_metadata=True # enables explanation metadata
)

# Example chat interaction
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"}
]

try:
    response = tlm_client.chat.completions.create(
        model="gpt-4o", # Use an available OpenAI model
        messages=messages
    )

    print(f"LLM Response: {response.choices[0].message.content}")

    # Get the trust score
    trust_scores = response.get_trust_scores()
    print(f"Trust scores: {trust_scores}")

    # Get explanation metadata
    explanation = response.get_explanation()
    print(f"Explanation: {explanation}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your OPENAI_API_KEY is set and valid, and the model exists.")

view raw JSON →