1.2 Classification
Classification is the most practically applicable case. The task is simple: given a text, determine which category it belongs to. It can be classifying complaints by type (delivery, returns, technical question), determining the sentiment of a review, or determining the topic of an email. But there are nuances here too.
The basic approach to classification with a model: define the categories, describe them, give the model several examples, and it classifies a new text on that basis. The process breaks down into several steps. First, define the categories and write their descriptions. Not a single word like "delivery", but a full description: what falls into this category and which specific questions or complaints belong here. The model must understand the boundaries between categories. Second, give several examples. This is called few-shot prompting. You do not need hundreds of examples; usually five to ten examples per category already help noticeably. The examples show the model how you interpret the boundaries between categories. Third, formulate the task clearly. Tell the model that you need the result in a specific format.
Here is a concrete example. Suppose there are customer requests that need to be classified. The categories are DELIVERY (a question about delivery), RETURN (a product return), TECHNICAL (a technical question), QUALITY (a product quality problem), and OTHER (everything else).
from openai import OpenAI
client = OpenAI()
def classify_support_ticket(ticket_text):
"""
Classifies a customer request by category.
Args:
ticket_text: Text of the customer's request
Returns:
The request category
"""
# System prompt: define the task and the categories
system_prompt = """You are a system for classifying customer support requests.
Categories:
- DELIVERY: questions and problems with delivery, timing, delivery location
- RETURN: requests to return a product, refunds, sending the product back
- TECHNICAL: technical problems with the website, app, or checkout
- QUALITY: product quality problems, defects, damage, mismatch with the description
- OTHER: everything else that does not fit the other categories
Answer only with the category name, without explanations."""
# Few-shot examples: show the model how to classify
messages = [
{"role": "system", "content": system_prompt},
# Examples of correct classification
{
"role": "user",
"content": "When will my order arrive? I ordered it 3 days ago"
},
{
"role": "assistant",
"content": "DELIVERY"
},
{
"role": "user",
"content": "I want to return the item, it does not fit"
},
{
"role": "assistant",
"content": "RETURN"
},
{
"role": "user",
"content": "I get a 500 error when placing an order on the website"
},
{
"role": "assistant",
"content": "TECHNICAL"
},
{
"role": "user",
"content": "The package arrived with a crack in the packaging. I want to return it and get a new one"
},
{
"role": "assistant",
"content": "RETURN"
},
# Now the text to classify
{
"role": "user",
"content": ticket_text
}
]
response = client.responses.create(
model="gpt-5-mini",
input=messages,
temperature=0
)
return response.output_text
# Usage
ticket = "The item arrived damaged. The packaging is deformed and the product does not open"
category = classify_support_ticket(ticket)
print(f"Category: {category}")
Let us look at the details. The system prompt contains not just a list of categories but a description of each one with examples of what belongs to it. This helps the model understand the boundaries. Then come examples of correct classification (this is the few-shot part). The model sees that when a customer asks about delivery, it is DELIVERY, and when they ask for a return, it is RETURN.
Notice that in the fourth example, a request about a damaged product is classified as RETURN, although it could also be QUALITY. This demonstrates priority: if the customer wants to return the product, the category is RETURN, even if the reason is quality. The model sees this priority from the example.
Enforcing the Response Format
Models tend to give full, elaborate answers. If you ask it to classify a text, it may reply: "This seems to be a question about delivery, because the customer asks about timing." That is not what we need. We need just the category.
def extract_category(response_text, valid_categories):
"""
Extracts the category from the model's response.
Robust to the model adding explanations.
Args:
response_text: Text of the model's response
valid_categories: List of allowed categories
Returns:
The category, or "UNKNOWN" if no category is found
"""
response_upper = response_text.strip().upper()
# Look for category names in the response
for category in valid_categories:
if category in response_upper:
return category
# If nothing was found, return UNKNOWN
return "UNKNOWN"
# Usage
valid_categories = ["DELIVERY", "RETURN", "TECHNICAL", "QUALITY", "OTHER"]
raw_response = response.output_text
category = extract_category(raw_response, valid_categories)
This function searches the response for category names, ignoring case and extra words. If the model answered "This request belongs to the DELIVERY category, because the customer asks about delivery", the function finds DELIVERY and returns it. This is a simple way to deal with unwanted verbosity from the model.
Adding a Confidence Score
Sometimes it is useful to know how confident the model is in its classification. Some requests obviously belong to one category, while others are ambiguous and could be assigned to several. If the model's confidence is low, such a request is better sent for manual review.
system_prompt = """You are a system for classifying customer support requests.
Categories:
- DELIVERY: questions about delivery
- RETURN: requests to return a product
- TECHNICAL: technical problems
- QUALITY: quality problems
- OTHER: everything else
Answer in the format: CATEGORY|CONFIDENCE
Where CONFIDENCE is a number from 0 to 100 reflecting your confidence in the classification.
Example answers:
- DELIVERY|95
- OTHER|45
- TECHNICAL|88"""
# With this formatting the model returns something like "DELIVERY|87"
# which we can parse easily
def parse_classification_with_confidence(response_text):
"""Parses a response in the CATEGORY|CONFIDENCE format"""
parts = response_text.strip().split('|')
if len(parts) == 2:
category = parts[0].strip()
try:
confidence = int(parts[1].strip())
return category, confidence
except ValueError:
pass
return None, None
# Usage
response_text = "DELIVERY|87"
category, confidence = parse_classification_with_confidence(response_text)
if confidence and confidence < 50:
print(f"Low confidence ({confidence}%), sending for manual review")
else:
print(f"Classified: {category} (confidence: {confidence}%)")
An important limitation: this "confidence" is the model's subjective estimate. The model can be 95% sure and still be wrong. The signal correlates with the real difficulty of the case and is useful for prioritization: requests with low confidence should be checked first.
Adapting to Different Tasks
The principles above apply to any classification, but the details depend on the task.
Sentiment classification requires clear boundaries between categories. If you use a five-level scale (very negative, negative, neutral, positive, very positive), it gives more information than a three-level one. But it also makes the task harder for the model. The choice depends on how the results will be used. If the results are only for statistics ("how many positive reviews"), three classes are enough. If you need fine-grained gradation for recommendations or prioritization, you need five classes.
system_prompt = """Determine the sentiment of a product review.
Categories:
- VERY_NEGATIVE: strongly negative, clear dissatisfaction, demands a refund, "I'm throwing this in the trash"
- NEGATIVE: moderately negative, points out flaws without emotion, "didn't like it, but it's fine"
- NEUTRAL: informational review without a clear rating, just a description of the product
- POSITIVE: positive, points out strengths, "good product"
- VERY_POSITIVE: enthusiastic, recommends it to others, "the best product I have ever seen"
Answer only with the category name."""
The descriptions help the model tell the categories apart. "Strongly negative" differs from "moderately negative" in intensity and often in the presence of a demand for action (return it, exchange it).
News topic classification usually requires a more elaborate taxonomy. A direct approach (assigning the topic to one of 20–30 categories) is hard for the model. It is better to use hierarchical classification: first determine the high-level topic (politics, economics, sports, technology), then refine the subtopic. This splits a complex task into several simple ones.
Detecting user intent in dialogue systems is similar to classifying support requests, but with an emphasis on action. The categories relate to what the user wants to do: get information, perform an action, complain, or get help. This helps the system understand how to interact with the user next.
How to Monitor Classifier Quality?
A classifier must be monitored continuously, because its quality can degrade for various reasons, for example changes in the input data or model updates.
There are several ways to catch problems.
Random sampling for manual review. Once a day (or a week, depending on the load), run a random sample of 50–100 classified requests through real feedback from a human reviewer. This lets you track quality drift and spot new patterns the model handles incorrectly. If accuracy is usually 95% and the latest sample shows 85%, something has broken.
Anomalies in the distribution. Track how many requests land in each category. If the share of TECHNICAL has stayed at 20% and suddenly jumps to 40% one day, it may reflect a real change in the types of requests, but it may also mean a classification error. It is worth checking.
Feedback loop from operators. If operators reassign the category after the model has classified a request, this information should be stored. It helps you understand which types of requests the model handles incorrectly. You can analyze these errors periodically and improve the prompt.
Test set. Create a fixed set of 100–200 requests with verified categories. After every prompt change or model update, run the classifier on this set. If accuracy has dropped, roll back the changes. This guarantees that improvements in some cases do not cause regressions in others.
def evaluate_classifier(classifier_func, test_cases, true_labels):
"""
Evaluates classifier quality on a test set.
Args:
classifier_func: The classification function
test_cases: List of texts to classify
true_labels: The true categories
Returns:
Accuracy
"""
correct = 0
for text, true_label in zip(test_cases, true_labels):
predicted = classifier_func(text)
if predicted == true_label:
correct += 1
accuracy = correct / len(test_cases)
return accuracy
# Usage
test_texts = ["When will the order arrive?", "I want to return the item", ...]
test_labels = ["DELIVERY", "RETURN", ...]
accuracy = evaluate_classifier(classify_support_ticket, test_texts, test_labels)
print(f"Accuracy: {accuracy * 100:.1f}%")
In reality you need more metrics than plain accuracy: precision and recall for each category, and a confusion matrix (to see which categories the model mixes up). But even simple accuracy on a fixed set gives at least some control.