AI Engineer Portal
Your personal operating system for career transition.
Exercise
Validate LLM structured output with Pydantic
Validate LLM Structured Output with Pydantic
LLMs frequently return structured data that does not perfectly match what you asked for. A model asked to extract entities might wrap its JSON in a markdown code fence. It might omit required fields. It might return a string where you expect a list. Your application code should never let these failures propagate silently.
What to build
Implement a parse_llm_output function that robustly parses and validates LLM-generated structured data:
- Strip markdown code fences — handle responses wrapped in
```jsonor```blocks. - Extract the JSON object or array — find the outermost
{...}or[...]even when surrounded by prose. - Validate against a Pydantic model — use
model_class.model_validate()to check the parsed JSON. - Return a typed result — return a
ParseResultdataclass with:success: bool,data: BaseModel | None,error: str | None,raw: str.
Also implement ExtractedFacts, a Pydantic model for the test case:
subject: str— required, minimum length 1claims: list[str]— required, minimum 1 itemconfidence: float— required, between 0.0 and 1.0
Why this matters
LLM structured outputs fail in the same small set of predictable ways. Building one robust parser you can reuse across many prompt tasks is far better than adding ad-hoc cleanup logic everywhere. Explicit ParseResult return types give callers the information they need to decide how to handle failures — log and skip, retry, or escalate to a human reviewer.
Constraints
- Do not use
eval()orast.literal_eval()to parse JSON — usejson.loads(). - Handle the case where JSON extraction succeeds but Pydantic validation fails.
- All fields of
ParseResultshould be populated even on failure.
Python Refresh / medium / Step 9 of 16
Core runtime habits
Normalize the boundary first, keep return shapes stable, and make the middle of the function boring on purpose.
- - Returns one stable shape across branches
- - Makes failure handling obvious
- - Keeps the core logic readable in under a minute
- - Did I make the input and output shapes explicit?
- - Would a teammate know where validation happens?
- - Did I avoid silent mutation or vague branching?
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.