Classifying With Enums
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 14 of 22.
Classifying text means picking one label from a fixed list: the topic of a support message, the mood of a review, whether an email is spam. A free-text answer can be Shipping., delivery or a whole sentence, and code cannot count those reliably.
An enum in the schema lists the allowed values, so the model must answer with exactly one of them:
schema = {
"type": "object",
"properties": {"mood": {"type": "string", "enum": ["positive", "negative", "neutral"]}},
"required": ["mood"],
"additionalProperties": False,
}
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=100,
messages=[{"role": "user", "content": "The soup was cold and the waiter was rude."}],
output_config={"format": {"type": "json_schema", "schema": schema}},
)
print(json.loads(response.content[0].text)["mood"])This prints negative. Because the label is always one of the listed strings, you can use it as a dict key to count labels or to route a message to the right team. Add a catch-all value such as other for text that fits none of the labels.
Challenge
MediumSort support messages by topic. The starter reads how many messages there are, then the messages, and defines TOPICS and a SCHEMA with a topic enum.
- Send each message on its own, with
model="claude-opus-5-5",max_tokens=100andSCHEMAas the JSON schema format. - Read the topic from the parsed JSON and print
<topic>: <message>. - After the last message, print
Counts:and every topic with its count, in the order ofTOPICS, joined by a comma and a space.
For example, for the input 3, I was charged twice this month., My parcel has not arrived yet. and I forgot my password. the program prints:
billing: I was charged twice this month.
shipping: My parcel has not arrived yet.
account: I forgot my password.
Counts: billing 1, shipping 1, account 1, other 0Try it yourself
import coddy_ai as anthropic # in production: import anthropic
import json
client = anthropic.Anthropic()
TOPICS = ["billing", "shipping", "account", "other"]
SCHEMA = {
"type": "object",
"properties": {"topic": {"type": "string", "enum": TOPICS}},
"required": ["topic"],
"additionalProperties": False,
}
count = int(input())
messages = [input() for _ in range(count)]
# Label every message with a topic, print "<topic>: <message>" for each,
# then print the counts for every topic in the order of TOPICS
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
3Tokens and Structure
Counting Tokens and CostHandling API ErrorsJSON Schema OutputClassifying With EnumsRecap: Review SorterPractice on your own: Online Python compiler