How to Build an LLM Text Classifier

An LLM text classifier is a single function: send the text with a system prompt that restricts the model to one of N labels, then read the label back. No fine-tuning, no training data - just a well-written prompt and an HTTP call.

AI Engineerpythonllmclassification

The pattern

A classifier asks the LLM to pick a category and return only that word. The system prompt does two things: lists the valid labels, and forbids any explanation. Set "temperature": 0 so the output is deterministic.

import requests, sys

LLM_URL = "http://your-llm-service/v1/chat/completions"

SYSTEM = (
    "You are a customer support classifier. "
    "Classify the message into exactly one of these categories: "
    "billing, technical, general. "
    "Reply with only the single category word, nothing else."
)

def classify(message: str) -> str:
    resp = requests.post(LLM_URL, json={
        "model": "your-model",
        "messages": [
            {"role": "system", "content": SYSTEM},
            {"role": "user",   "content": message},
        ],
        "temperature": 0,
        "max_tokens": 10,
    }, timeout=30)
    resp.raise_for_status()
    return resp.json()["choices"][0]["message"]["content"].strip().lower()

if __name__ == "__main__":
    print(classify(" ".join(sys.argv[1:])))

Run it from the CLI:

python3 classify.py "I was charged twice this month"
# billing
python3 classify.py "The app crashes on login"
# technical
python3 classify.py "How do I change my username?"
# general

Why the prompt is the hard part

The reliability of a one-shot classifier lives almost entirely in the system prompt. Three things matter:

Validate the output

Even with a tight prompt, add a guard:

VALID = {"billing", "technical", "general"}

def classify(message: str) -> str:
    label = _call_llm(message).strip().lower()
    if label not in VALID:
        raise ValueError(f"Unexpected label: {label!r}")
    return label

A ValueError is much easier to debug than silently routing a message to the wrong queue.

When to use this shape

Single-call classifiers, extractors, and formatters make up a large share of production LLM workloads - far more than chat loops. This pattern works for sentiment analysis, intent detection, priority scoring, and any case where the output is one of a small, known set of values. Once the function is solid, you can pipe it into bash, call it from a service, or schedule it as a cron job.

Want to try it hands-on? HeyDevJob gives you this exact setup in a live cloud workspace in your browser - edit it, run it, and see it work. Free, nothing to install.

Try it in a workspace →

What you'll practice

FAQ

How do I build an LLM text classifier without fine-tuning?

Write a system prompt that names the valid categories and instructs the model to return only one category word. Send the text as the user message, set temperature to 0 for determinism, and read the label from choices[0].message.content. No training data needed.

How do I stop an LLM from adding explanation to its classification output?

Put the constraint directly in the system prompt - 'Reply with only the single category word, nothing else.' Also set max_tokens to a small value (10 is enough for a one-word label) so even a verbose model can't fit much extra text.

How do I handle unexpected labels from an LLM classifier?

Validate the returned string against your known label set and raise an error if it doesn't match. This surfaces prompt or model issues immediately instead of silently misrouting data.

Are LLMs good for text classification?

Yes, especially zero- or few-shot when you lack labeled data - constrain the model to one of N labels and set temperature 0 for stable output. For high-volume, fixed-label tasks, a fine-tuned smaller model can be cheaper and faster.

Keep learning

Restore a Broken LLM API IntegrationAI/ML projectHarden an LLM Pipeline Against API FailuresAI/ML projectParse JSON From an LLM (Strip Markdown Fences)AI/ML projectAI/ML roadmapStep by step to hiredAI/ML interview questionsSTAR answersAll AI/ML projectsProjects hub

Learn it by doing. Open this in a live cloud workspace, make the change yourself, and keep a record of the work you can share.

Open the workspace →