npNick Paolini

NOTE No.22 · ■ AI · · 6 min read

Classifying Free Text with an LLM: A Pipeline You Can Defend

LLMs make it easy to tag thousands of survey comments or support notes. Making the result trustworthy takes a fixed label set, a hand-labelled sample, and an agreement check before anyone builds a chart on it.

Every organization sits on piles of free text it never analyzes: survey comments, support notes, cancellation reasons, the "Other (please specify)" box. Before LLMs, getting that into a chart meant keyword rules that broke constantly, or a person reading a few hundred rows and extrapolating.

Now you can send every comment to a model with "categorize this" and have a chart by lunch. That's genuinely useful, and it's also how you end up presenting "34% of complaints are about billing" without knowing whether the model's idea of "billing" matches yours.

The work isn't the API call. It's everything around it that lets you answer the follow-up question: how do you know?

Fix the labels before you touch the model

The most common mistake is letting the model invent categories. You get "Billing issue", "Billing problem", and "Invoice confusion" as three separate buckets, and a different set next week.

Write the label set yourself, with a one-line definition each, and include a way out:

LABELS = {
    "billing": "Charges, invoices, payments, refunds, or price changes.",
    "network": "Coverage, speed, outages, or dropped connections.",
    "device": "Problems with hardware: phones, modems, routers.",
    "support": "The experience of contacting support: wait times, agent conduct, unresolved tickets.",
    "account": "Plan changes, moves, cancellations, login or profile problems.",
    "other": "Clearly about something not listed above.",
    "unclear": "Too short, off-topic, or ambiguous to classify.",
}

Two things make this work. The definitions settle edge cases before the model sees them: is a refund delay "billing" or "support"? Decide now, write it down. And the other and unclear buckets give the model somewhere honest to put things, so it isn't forced to jam every comment into a real category.

Hand-label a sample first

Before running anything at scale, pull a random sample of a couple of hundred comments and label them yourself, ideally with a colleague labelling the same rows separately.

This feels slow. It's the most valuable hour in the whole project, for three reasons:

  1. You find out whether the labels work. If you and your colleague disagree often, the definitions are ambiguous, and no model will fix that.
  2. You get a test set. This is what you'll measure the model against.
  3. You learn what's actually in the data, which tends to change the label set.

Constrain the output

Ask for structured output (JSON mode or tool calling, depending on your provider) and validate it anyway. Here complete() stands in for whatever client you use:

import json
 
SYSTEM = (
    "You classify customer comments. Choose exactly one label.\n\n"
    + "\n".join(f"- {name}: {desc}" for name, desc in LABELS.items())
    + '\n\nRespond with JSON only: {"label": "<label>", "reason": "<under 15 words>"}'
)
 
 
def classify(comment: str, complete) -> dict:
    """complete(system, user) -> str. Returns {"label": ..., "reason": ...}."""
    for _ in range(2):  # one retry on malformed output
        try:
            result = json.loads(complete(SYSTEM, comment))
        except json.JSONDecodeError:
            continue
        if result.get("label") in LABELS:
            return result
    return {"label": "needs_review", "reason": "No valid label returned"}

The short reason field costs a few tokens and pays for itself the first time someone asks why a comment landed where it did. The needs_review fallback makes failures visible as their own bucket instead of quietly turning into a guess.

Measure agreement, per label

Run the classifier on your hand-labelled sample and compare. Overall accuracy is the number people ask for, but it hides the problem you care about, so look per label:

from sklearn.metrics import classification_report, cohen_kappa_score
 
human = [row["label"] for row in sample]
model = [classify(row["comment"], complete)["label"] for row in sample]
 
print(classification_report(human, model, zero_division=0))
print("Cohen's kappa:", round(cohen_kappa_score(human, model), 2))

The per-label report is where the useful findings are. The model might be excellent on network and poor on support versus account, and that tells you which definition to sharpen. Kappa corrects for agreement you'd get by chance, which matters when one label dominates.

Also compute the same kappa between you and your colleague. That's your ceiling. If two people only agree moderately, a model that matches that level is doing about as well as anyone can, and the honest move is to report the numbers with that caveat attached.

Iterate on the definitions and the prompt against this sample until the results are good enough for the decision the numbers will feed. Just don't tune against the whole sample and then report your score on it. Keep part of it aside for the final check.

Record how every label was made

When you run the full dataset, store more than the label:

ColumnWhy
label, reasonThe output, and a reason someone can read
modelModel upgrades change results
prompt_versionSo does editing the definitions
classified_atTo tell old runs from new

Without the model and prompt version, a shift in your monthly chart could be customers changing or your pipeline changing, and you can't tell which. With them, you can re-run last quarter with the new setup and compare like with like.

Keep checking after launch

Data drifts. New products launch, new complaints appear, and the label set slowly stops fitting. Two cheap habits help:

  • Watch the other and unclear rates. A rising trend is your early warning that the categories need updating.
  • Hand-label a small fresh sample every so often and re-run the agreement check. If agreement drops, something changed, either in the data or in the model behind the API.

Is it worth it?

For most teams, yes, by a lot. The alternative usually isn't perfect human labelling. It's nobody reading the comments at all. A classifier that agrees with careful humans most of the time, with its error rate measured and written down, is a big step up from a word cloud.

What makes it defensible isn't the model. It's that when someone asks "how do you know 34% are about billing?", you can show them the definitions, the agreement numbers, and the sample you checked it against.