AI Engineer Portal
Your personal operating system for career transition.
Exercise
Parse structured LLM output with fallback
Parse Structured LLM Output with Fallback
LLMs are not databases. Even when you ask for JSON, you sometimes get JSON wrapped in markdown fences, JSON with trailing commas, JSON preceded by "Sure! Here is the output:", or valid JSON that does not match the schema you specified. Production-grade parsing must handle all of these cases gracefully.
What you are building
Build a parse_llm_output function that:
- Accepts raw model output text and a Pydantic model class
- Tries to parse the text as direct JSON
- Falls back to extracting JSON from markdown code fences
- Falls back to extracting the first JSON object found in the text
- Validates the extracted dict against the Pydantic model
- If all parsing attempts fail, calls a
fallback_factorycallable to produce a safe default - Returns a
ParseResultwith the parsed value, the strategy that worked, and whether it fell back
Why this matters
A structured output parser with explicit fallback behavior is one of the most reused components in an LLM application codebase. Every feature that writes to a database, triggers an action, or renders structured UI needs one. Building it once, correctly, is a force multiplier.
Constraints
- Do not use
eval()for JSON parsing - Import only the standard library plus
pydantic - The
fallback_factoryshould be called with no arguments and return a value that passes Pydantic validation - Log a warning (using the
loggingmodule) when a non-primary parse strategy is used
Llm Foundations / medium / Step 2 of 6
General drill
Keep the solution explicit and reviewable.
Make the solution explicit, debuggable, and easy to explain.
Review where the boundary is, what gets validated, and what would be hard to debug later.
Practice
Generate a variation
Generate a new exercise variation to deepen understanding or practice a related concept.
Attempt history
Recent submissions
Before you submit, decide what a strong answer should make obvious to the reviewer.
No attempts yet.