Output Fixing Parser

What it is An Output Fixing Parser takes the AI’s raw output, detects format or structure errors, and tries to automatically correct them so they match the expected schema. It is often used with Pydantic or JSON parsers to make LLM responses more robust.

Why it exists Even when you instruct an LLM to return JSON or a structured format, it sometimes produces minor mistakes: missing quotes, extra text, wrong capitalization, or slight syntax errors. Output Fixing Parser automatically corrects these issues so your code can safely parse the output.

Real-world analogy It’s like a spellchecker and grammar fixer: you write something quickly, and the tool corrects small errors so the text meets the expected rules.

Minimal beginner example

import os
from dotenv import load_dotenv
from pydantic import BaseModel
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.output_parsers import PydanticOutputParser, OutputFixingParser
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 structured output model
class PersonInfo(BaseModel):
    name: str
    age: int

# Step 2: Base parser
pydantic_parser = PydanticOutputParser(pydantic_object=PersonInfo)

# Step 3: Wrap with OutputFixingParser
fixing_parser = OutputFixingParser.from_llm(
    parser=pydantic_parser,
    llm=llm
)

# Step 4: Prompt
prompt = PromptTemplate(
    template="Provide Elon Musk's name and age in JSON format like {{'name':'Elon Musk','age':51}}.",
    input_variables=[]
)

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

print(parsed_output)
print(parsed_output.name, parsed_output.age)

Small LangChain workflow

  1. Define a structured parser (Pydantic, JSON, etc.).

  2. Wrap it with OutputFixingParser and provide the LLM.

  3. Prepare a prompt instructing LLM to output the structure.

  4. Run LLM → raw output → parser automatically corrects errors → structured object.

  5. Use the cleaned output in chains, APIs, or databases.

Common beginner mistakes

  • Assuming OutputFixingParser will fix all types of errors—it mainly fixes minor format/structure mistakes.

  • Not specifying correct parser → fixing may fail.

  • Using it on unstructured free-form text; it works best when a schema exists.

When to use this vs alternatives

  • Use OutputFixingParser when LLM outputs slightly invalid JSON or structured text.

  • Use PydanticOutputParser alone if you are confident the LLM output is perfectly formatted.

  • Use it with Enum, DateTime, or other structured parsers to make your workflows more robust.

Last updated