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 osfrom enum import Enumfrom dotenv import load_dotenvfrom pydantic import BaseModelfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.output_parsers import PydanticOutputParserfrom langchain_core.prompts import PromptTemplateload_dotenv()api_key = os.getenv("GEMINI_API_KEY")llm =ChatGoogleGenerativeAI(model="gemini-2.5-flash",api_key=api_key)# Step 1: Define enumclassColorEnum(str,Enum):RED="red"GREEN="green"BLUE="blue"# Step 2: Define Pydantic model using enumclassFavoriteColor(BaseModel): color: ColorEnum# Step 3: Create parserparser =PydanticOutputParser(pydantic_object=FavoriteColor)# Step 4: Prepare promptprompt =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 outputresponse = 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
Define an Enum with allowed values.
Create a Pydantic model that uses the Enum.
Prepare the prompt instructing the LLM to respond in JSON format.
Parse the LLM output with PydanticOutputParser.
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.