OutputFixingParser
Self-healing chains. What to do when the JSON is broken.
1. The Problem: "Unexpected ',' at line 5"
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.
2. The Solution: Ask the Model to Fix It
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.
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!3. The Trade-off
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.
4. Summary
Use OutputFixingParser as a safety net for critical structured data tasks where a crash is unacceptable.
Key Intuition: "Resilience beats perfection."