方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

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:

  1. Accepts raw model output text and a Pydantic model class
  2. Tries to parse the text as direct JSON
  3. Falls back to extracting JSON from markdown code fences
  4. Falls back to extracting the first JSON object found in the text
  5. Validates the extracted dict against the Pydantic model
  6. If all parsing attempts fail, calls a fallback_factory callable to produce a safe default
  7. Returns a ParseResult with 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_factory should be called with no arguments and return a value that passes Pydantic validation
  • Log a warning (using the logging module) when a non-primary parse strategy is used

Llm Foundations / medium / Step 2 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

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.