Learn/LangChain Mastery/Part 3 · 2. LCEL & Prompt Architecture
Lesson 19 of 68
SyllabusLangChain Mastery · Part 3

OutputFixingParser

Self-healing chains. What to do when the JSON is broken.

Course outline & contents
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains

Even with prompt instructions, models fail. They forget a closing bracket }. They use single quotes ' instead of double quotes ".

When a Pydantic Parser sees this, it throws an exception. CRASH.

If a human miswrites code, you say: "Hey, you missed a comma." They say: "Oh, oops," and fix it. OutputFixingParser does exactly this automatically.

It wraps your main parser. If the main parser fails, it sends the bad output and the error message back to the LLM and asks for a correction.

fixing_parser.py
from langchain.output_parsers import OutputFixingParser

## Wrap the strict parser
fixing_parser = OutputFixingParser.from_llm(
  parser=pydantic_parser,
  llm=model
)

## If this bad string comes in:
bad_json = "{ 'setup': 'Why did the chicken...' " # Missing closing brace

## The fixing parser fixes it using the LLM
result = fixing_parser.parse(bad_json)
print(result.setup) # It works!

Pros: Your app is much more resilient. Cons: It costs double. (1 call for the error, 1 call for the fix). Also, it adds latency.

Use OutputFixingParser as a safety net for critical structured data tasks where a crash is unacceptable.

Key Intuition: "Resilience beats perfection."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonPydanticOutputParserNext lesson →Streaming Tokens & Async Chains