AI Hints
Home›LangChain Tutorial›Shapes, Labels, Extraction
LangChain · Lesson 32 of 120

Classification

Fixed labels.

⏱ 2 min read▶ Video at 34:16🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Riverside Books gets hundreds of emails a day. Each should be labelled as an order question, a return, a book request, or something else. The label must be exactly one of those four, never something new.

Classification
From the video: Classification
  • Hundreds of emails
  • Four labels
  • Exactly one of them

Literal labels

Literal, from Python's typing module, limits a field to fixed values. Our model has a category, which must be one of four words, and an urgency from one to three. We classify three emails in one batch. Run it. Every email gets a valid label, so code can route it safely.

classify.pypython
from typing import Literal
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class Ticket(BaseModel):
    category: Literal["order", "return", "book_request", "other"]
    urgency: int = Field(ge=1, le=3, description="1 low, 3 high")

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
classify = model.with_structured_output(Ticket)

emails = ["My parcel is a week late and it was a gift for tomorrow!",
          "Do you stock the new Murakami novel?",
          "The book arrived torn, I want to send it back."]
for e, t in zip(emails, classify.batch(emails)):
    print(f"{t.category:<13} urgency {t.urgency} | {e[:40]}")
Output
order         urgency 3 | My parcel is a week late and it was a gi
book_request  urgency 1 | Do you stock the new Murakami novel?
return        urgency 2 | The book arrived torn, I want to send it

Why fixed labels matter

Free text labels drift. One call says return, the next says refund request. Literal types stop that. You can then count labels, route by them, and build reports. Field limits, like greater than or equal to one, do the same for numbers.

keyvalue
Free textlabels drift
Literalonly allowed values
ge / lenumber limits
Resultsafe to route

Summary

Use Literal types for fixed labels, and field limits for numbers, so classification results are always valid. Next, pulling facts out of messy text.

Key takeaways
  • Literal[...]
  • Field(ge=1, le=3)
  • Safe routing
Next up: Extraction — fields from text