How do you extract logprobs from chat completion responses to compute token level confidence scores? | A1Lab@HamzaM to AI & LLMEnglish • 5 days ago

How do you extract logprobs from chat completion responses to compute token level confidence scores?

message-square
0

How Logprobs Convert to Token-Level Confidence Scores

When you enable logprobs in a Chat Completions request, the API returns the natural logarithm ($\ln$) of each output token’s predicted probability. Because probabilities sit between $0$ and $1$, logprobs are always $0$ or negative:

  • logprob = 0.0: $\exp(0.0) = 1.0$ (100% probability)
  • logprob = -0.693: $\exp(-0.693) \approx 0.50$ (50% probability)
  • logprob = -2.30: $\exp(-2.30) \approx 0.10$ (10% probability)

To turn a logprob back into a linear confidence score between 0 and 1, apply the exponential function:

$$\text{confidence} = e^{\text{logprob}} = \text{Math.exp}(\text{logprob})$$

You can also inspect top_logprobs (up to the top 20 candidate tokens at each position) to compare the chosen token against runner-up alternatives or compute sequence-level confidence (such as mean token confidence or perplexity).

Steps to Extract Logprobs and Compute Confidence

  1. Enable logprobs: true (and optional top_logprobs): Pass logprobs: true and top_logprobs: 3 (or up to 20) in chat.completions.create().
  2. Read choices[0].logprobs.content: Each entry in content corresponds to one generated token and contains token, logprob, and top_logprobs.
  3. Convert each token’s logprob with Math.exp(): Map each token to a percentage or 0.0–1.0 probability score.
  4. Aggregate carefully across multi-token answers: For multi-token spans or full answers, compute either the average token probability or the geometric mean ($\exp(\text{mean}(\text{logprobs}))$) so longer outputs are not unfairly penalized compared to multiplying raw probabilities.

Node.js Example Using OpenAI Chat Completions

import OpenAI from "openai";

const openai = new OpenAI();

async function classifyWithTokenConfidence(prompt) {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    temperature: 0,
    logprobs: true,
    top_logprobs: 3,
    messages: [
      {
        role: "system",
        content: "Classify the ticket priority as Low, Medium, or High. Reply with one word.",
      },
      { role: "user", content: prompt },
    ],
  });

  const choice = response.choices[0];
  const tokenEntries = choice.logprobs?.content ?? [];

  const tokens = tokenEntries.map((entry) => {
    const probability = Math.exp(entry.logprob);
    const alternatives = (entry.top_logprobs ?? []).map((alt) => ({
      token: alt.token,
      logprob: alt.logprob,
      probability: Number(Math.exp(alt.logprob).toFixed(4)),
    }));

    return {
      token: entry.token,
      logprob: entry.logprob,
      confidence: Number(probability.toFixed(4)),
      alternatives,
    };
  });

  // Geometric mean probability across all generated tokens (length-normalized)
  const avgLogprob =
    tokenEntries.length > 0
      ? tokenEntries.reduce((sum, t) => sum + t.logprob, 0) / tokenEntries.length
      : -Infinity;

  const overallConfidence = Number.isFinite(avgLogprob)
    ? Number(Math.exp(avgLogprob).toFixed(4))
    : 0;

  return {
    answer: choice.message.content ?? "",
    overallConfidence,
    tokens,
  };
}

const result = await classifyWithTokenConfidence(
  "Production checkout API is returning 500 errors for all users."
);
console.log(JSON.stringify(result, null, 2));

Helpful Tips for Confidence Scoring

  • Combine case/whitespace variants in top_logprobs: Models split tokens like "High", " High", and "high" into separate token IDs—summing linear probabilities (Math.exp(logprob)) across equivalent variants gives a cleaner label probability.
  • Do not confuse token probability with factual truth: A high logprob means the model is certain about which token comes next given the context, not that the statement is factually verified.
  • Reasoning models skew final-answer logprobs: On reasoning/thinking models, chain-of-thought reasoning happens before the final answer token, which often pushes the final token’s logprob near 0.0 (100%) even when the question is ambiguous.