跳到正文
DEV Community· M.T.Ramkrushna·· 6 小時前AI 評分65

如何用 logprobs 將 LLM 分類器的不確定結果送交覆核

Your LLM classifier is guessing and not telling you: use logprobs to route the uncertain cases

AI 導讀

文章示範如何在 OpenAI Chat Completions API 使用 logprobs,按 LLM 分類結果的信心程度決定自動處理或送交人工覆核。方法以首個輸出 token 的 log probability 計算候選標籤機率,並建議用自有標註數據校準覆核門檻。top_logprobs 可設為 0 至 20,但不同模型及 API 對 logprobs 的支援各異。

正文

Monday AI Insight. One practical lesson for anyone using an LLM as a classifier: the label text says nothing about how sure the model was. "Politics" at 100% and "Politics" on a coin flip look identical in message.content. Ask for logprobs, and you can tell them apart.

The problem: every answer looks equally confident

LLMs are now the default classifier for a lot of glue work: ticket routing, intent detection, content tagging, "is this answer supported by the context, true or false?" The usual call returns one word and you act on it.

But some inputs are easy and some are genuinely ambiguous. Without a confidence signal you treat both the same way, so the ambiguous ones get auto-processed right alongside the obvious ones. You only find the errors later.

What logprobs give you

In the OpenAI Chat Completions API you can set:

  • logprobs: true returns the log probability of each output token in message.content.
  • top_logprobs: k (an integer from 0 to 20; requires logprobs: true) also returns the k most likely tokens at each position, each with its log probability. The API reference notes you may get back fewer than you asked for.

A logprob is log(p). It is 0.0 at 100% probability and negative otherwise, so exp(logprob) turns it back into a probability. If a token is outside the top 20, the API uses -9999.0 to signal "very unlikely".

The OpenAI Cookbook's Using logprobs notebook shows exactly why this matters. It classifies news headlines into Technology, Politics, Sports or Art with top_logprobs=2:

  • "Tech Giant Unveils Latest Smartphone Model..." → Technology, logprob 0.0 (100%)
  • "Local Mayor Launches Initiative to Enhance Urban Public Transport." → Politics, ~100%
  • "Tennis Champion Showcases Hidden Talents in Symphony Orchestra Debut" → Art at 97.23%, with Sports as the runner-up at 1.39%

Same one-word output format for all three. Only the logprobs show the third one was a mixed case. The Cookbook's suggestion: auto-classify above a threshold and send less certain ones to manual review.

The pattern: single-token labels, read the first token, route on confidence

import math
from openai import OpenAI

client = OpenAI()
LABELS = ["billing", "bug", "feature", "other"]  # short, distinct labels

PROMPT = """Classify the support ticket into exactly one label:
billing, bug, feature, other.
Reply with the label only, lowercase, nothing else.

Ticket: {ticket}"""

def classify(ticket: str, model: str):
    resp = client.chat.completions.create(
        model=model,                    # must be a model that returns logprobs
        messages=[{"role": "user", "content": PROMPT.format(ticket=ticket)}],
        temperature=0,
        max_completion_tokens=1,        # we only need the label's first token
        logprobs=True,
        top_logprobs=10,                # up to 20
    )
    first = resp.choices[0].logprobs.content[0]

    # Sum probability per label; several tokens can map to one label
    # (e.g. "Bug", "bug", " bug"), and some tokens map to no label at all.
    scores = {label: 0.0 for label in LABELS}
    for alt in first.top_logprobs:
        tok = alt.token.strip().lower()
        for label in LABELS:
            if tok and label.startswith(tok):
                scores[label] += math.exp(alt.logprob)

    label = max(scores, key=scores.get)
    return label, scores[label], scores

def route(ticket: str, model: str, threshold: float = 0.90):
    label, p, _ = classify(ticket, model)
    if p >= threshold:
        return {"label": label, "p": p, "action": "auto"}
    return {"label": label, "p": p, "action": "review"}  # human or a stronger model

A few details matter here:

  1. Make labels short and distinct so the first token decides. If two labels start with the same token ("feature_request" vs "feature_flag"), the first token can't separate them. Pick labels that differ at the start, or use letter options like A/B/C/D.
  2. Map tokens to labels, don't compare strings exactly. The Cookbook's Politics example has "Polit" as the second candidate token. Tokenization splits words in ways you don't control, so sum the probability of every candidate that's a prefix of a label (the startswith check above is deliberately crude; check it against your tokenizer and labels).
  3. Watch the leftover mass. If the label probabilities add up to much less than 1, the model wanted to say something off-list. That is a signal too: route it.
  4. Multi-token labels need the joint probability. The Cookbook notes you can sum the logprobs of a sequence's tokens and exponentiate to get the joint probability. For long labels, that's more work and more ways to get it wrong, which is another reason to keep labels to one token.

Don't trust 0.90 until you've checked it

A probability from the model is not automatically a calibrated probability: "90%" should mean right about 90% of the time, and nothing guarantees that.

  • Guo et al. (2017), On Calibration of Modern Neural Networks, found that modern neural networks, unlike those from a decade earlier, are poorly calibrated. Their practical fix was temperature scaling, a single-parameter variant of Platt scaling, fit on a validation set. It doesn't change which class wins, so accuracy stays the same; only the confidence changes.
  • Kadavath et al. (2022), Language Models (Mostly) Know What They Know (Anthropic), found large language models well calibrated on multiple-choice and true/false questions when the format is right: visible lettered options, the model answering with the letter. They expect this format helps partly because each answer option is a single token. Replacing an option with "none of the above" hurt both accuracy and calibration. RLHF-tuned models looked poorly calibrated, though a single temperature adjustment (T=2.5) largely fixed it on the evaluations they tested.

So the format advice above isn't just tidiness. It's the setting where these probabilities are most likely to mean something. Then check it on your own data:

  1. Label a few hundred real examples.
  2. Run the classifier and save the label plus its probability.
  3. Bucket by confidence (0.5-0.6, ..., 0.9-1.0) and compare accuracy to average confidence in each bucket (a reliability diagram; Guo et al. summarize the gap as Expected Calibration Error).
  4. Pick the threshold from the trade-off you actually want: "auto-handle X% of traffic at Y% accuracy, send the rest to review".
  5. Re-check when you change the prompt or the model. The numbers move.

Caveats before you build on this

  • Not every model or API exposes logprobs. OpenAI's API reference says parameter support differs by model, particularly for newer reasoning models, so check your model before you design around it. Anthropic's Messages API doesn't offer logprobs, and its OpenAI SDK compatibility layer lists logprobs and top_logprobs as ignored (the response field is always empty). Code ported from OpenAI will run fine there and quietly lose the signal.
  • High confidence isn't the same as correct. A model can be confidently wrong, especially on inputs unlike anything in your labeled set. Calibration on your data is what earns the threshold.
  • The Cookbook notebook is archived and says it may reference outdated models or APIs (it still says top_logprobs goes up to 5; the current API reference says 20). Use the API reference for current limits.

Checklist

  1. Use short, distinct labels that differ at the first token.
  2. Request logprobs=True, top_logprobs around 5-20, and max_completion_tokens=1.
  3. Convert with exp(logprob), sum probability per label, and keep the off-list mass.
  4. Auto-act above a threshold; send the rest to a human or a stronger model.
  5. Pick the threshold from labeled data and check calibration per bucket.

Takeaway: a label alone doesn't tell you how sure the model was. Its first token's probability does, if you ask for it and check it against labeled data.

What do you route your low-confidence LLM outputs to today: a human, a bigger model, or nothing?

References

來源:DEV Community · dev.to