Course contentsShow
← AI Engineering
Lesson 769 of 1,88619. Structured Output and ValidationFree lesson

Enums and Literal Types

Constrain LLM outputs to specific allowed values using enums and literals for classification and categorical data.

Enums and Literal Types

What You'll Learn

You'll learn how to constrain LLM outputs to specific allowed values, ensuring your model only returns valid categories or classification labels.

The Problem with Free-Form Text

When you ask an LLM to classify something—like sentiment, priority level, or product category—it might return variations you don't expect: "positive", "Positive", "good", "happy", or even misspellings. This creates chaos when you need reliable, predictable values for downstream processing.

Enums: Your Allowed Values List

Enums (enumerations) and literal types let you define an exact set of acceptable values. Think of it like a multiple-choice question instead of an essay prompt—the model must pick from your predefined options, nothing else.

In Pydantic, you combine these with your schema definitions:

from pydantic import BaseModel
from enum import Enum
from typing import Literal

class Priority(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"

class Sentiment(BaseModel):
    category: Literal["positive", "negative", "neutral"]

class Task(BaseModel):
    priority: Priority
    sentiment: Sentiment

When the LLM generates output, it must choose from these exact values. No typos, no variations, no creative interpretations. You get "low", "medium", "high", or "critical"—guaranteed.

When to Use Each

  • Enum: Better for reusable categories across multiple models
  • Literal: Quick inline constraints for one-off fields

Both accomplish the same goal: turning unreliable text generation into reliable categorical data you can trust in your application logic.

Key Takeaway: Enums and literal types transform fuzzy LLM outputs into strict, validated categorical values by forcing the model to choose only from your predefined allowed options.