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.
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 Literalfrom pydantic import BaseModel, Fieldfrom langchain.chat_models import init_chat_modelclass 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
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.