OutputParserException
langchain.schema.output_parser.OutputParserException
Stack trace
langchain_core.exceptions.OutputParserException: Nested object depth limit exceeded while parsing LLM output: '{"level1": {"level2": {"level3": {"level4": {...}}}}}' Why it happens
LangChain's output parsers have a maximum nested object depth they can parse to prevent excessive recursion and complexity. When the LLM returns a JSON or structured output with nested objects deeper than this limit, the parser raises this exception to avoid crashes or infinite loops.
Detection
Monitor parser exceptions for OutputParserException mentioning nested depth limits, and log the raw LLM output to identify overly deep nested structures before the app crashes.
Causes & fixes
The LLM response contains JSON or structured data nested deeper than the parser's configured maximum depth.
Simplify the expected output schema to reduce nesting or split the output into multiple smaller objects to stay within depth limits.
Prompt instructions do not constrain the LLM to produce shallow nested structures, allowing deep nesting.
Update the prompt to explicitly instruct the LLM to limit nested object depth, e.g., 'Return JSON with no more than 3 levels of nesting.'
Using a parser or schema that enforces a strict nested depth limit incompatible with the LLM's output complexity.
Adjust the parser configuration or use a more flexible output parser that supports deeper nested objects if needed.
Code: broken vs fixed
from langchain.schema.output_parser import JsonOutputParser
parser = JsonOutputParser()
response = '''{"level1": {"level2": {"level3": {"level4": "too deep"}}}}'''
parsed = parser.parse(response) # This line raises OutputParserException due to nested depth limit
print(parsed) from langchain.schema.output_parser import JsonOutputParser
parser = JsonOutputParser()
response = '''{"level1": {"level2": {"level3": "within limit"}}}'''
parsed = parser.parse(response) # Fixed: reduced nesting depth
print(parsed) # Should print parsed dict without error Workaround
Catch OutputParserException and manually parse the raw LLM output with a custom JSON parser that supports deeper nesting or flatten the nested structure before parsing.
Prevention
Use prompt engineering to constrain output complexity and leverage structured output features like OpenAI's response_format to enforce schema validation at the API level, avoiding parser depth issues.