Enum Output Parser

What it is An Enum Output Parser ensures that the LLM’s output matches one of a predefined set of allowed values (an enumeration). It converts free-form text into a fixed set of choices that your code can safely use.

Why it exists LLMs can generate slightly different text than expected. Enum parsers enforce that outputs are limited to a specific set of valid options, reducing downstream errors in programs, workflows, or logic checks.

Real-world analogy Think of a multiple-choice test: even if someone writes a longer answer, you only accept A, B, C, or D. This prevents invalid responses.

Minimal beginner example using Pydantic Enum

import os
from enum import Enum
from dotenv import load_dotenv
from pydantic import BaseModel
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import PromptTemplate

load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")

llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", api_key=api_key)

# Step 1: Define enum
class ColorEnum(str, Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

# Step 2: Define Pydantic model using enum
class FavoriteColor(BaseModel):
    color: ColorEnum

# Step 3: Create parser
parser = PydanticOutputParser(pydantic_object=FavoriteColor)

# Step 4: Prepare prompt
prompt = PromptTemplate(
    template="Pick the favorite color from red, green, or blue and respond in JSON format like {{'color':'red'}}.",
    input_variables=[]
)

# Step 5: Run LLM and parse output
response = llm.invoke(prompt.format())
parsed_output = parser.parse(response.content)

print(parsed_output)
print(parsed_output.color)  # guaranteed to be one of ColorEnum values

Small LangChain workflow

  1. Define an Enum with allowed values.

  2. Create a Pydantic model that uses the Enum.

  3. Prepare the prompt instructing the LLM to respond in JSON format.

  4. Parse the LLM output with PydanticOutputParser.

  5. Use the validated enum value in downstream code.

Common beginner mistakes

  • LLM output does not exactly match Enum values → parsing fails.

  • Forgetting to instruct the LLM to respond in the exact JSON format.

  • Using Enum parser for free-text answers instead of controlled choices.

When to use this vs alternatives

  • Use Enum parser when you need strict controlled outputs.

  • Use JSON or Pydantic parsers for structured outputs with multiple fields.

  • Use Comma-Separated parser for lists of free-form items.

Last updated