Call an LLM and parse a structured JSON response with validation, error handling and retries. The bedrock of every generative AI application.
The retry loop inside call_structured()
1 / 4Call the model
Step 1 of 4
Call the model
Send the query and context with the Answer schema attached, so the model is asked for output that fits the shape.
Step 2 of 4
Parse output
Read the parsed result. When the model refuses, there is no parsed object, and that has to be handled rather than assumed away.
Step 3 of 4
Validate
Pydantic checks the fields, including a rule that confidence sits between 0 and 1. A value outside that range counts as a failure.
Step 4 of 4
Retry or raise
On failure, log the attempt and go round again, up to 3 tries. After the last failure, raise so callers know the call did not succeed.
A structured call is only reliable when parsing, validation and retries are part of it.
Scenario
Build the function that every downstream feature will use: a reliable, validated, retried structured LLM call.
Objective
Implement call_structured() that returns a validated Pydantic model from an LLM, with retry on validation failure.
Starter code
Implement the TODOs to complete the lab.
llm.py
~165 tokens
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI()
# Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.
MODEL = "<small-model>"
class Answer(BaseModel):
summary: str
confidence: float
def call_structured(query: str, context: str) -> Answer:
"""Call the LLM and return a validated Answer.
- Use Structured Outputs: client.responses.parse(..., text_format=Answer)
- Handle a missing parse (a refusal) and retry up to 3 times
- Raise on persistent failure
"""
# TODO: implement
pass
Solution hints
1Pass text_format=Answer to client.responses.parse (Structured Outputs; the older json_object mode only guarantees valid JSON, not your schema)
2Read response.output_parsed; it is None when the model refuses
3Retry up to 3x, logging each failed attempt
4Add a confidence range check (0 to 1) with a Pydantic validator
Validation steps
Your implementation should pass these checks.
Returns valid Answer for a normal query
Retries when no parsed output comes back (test by mocking a refusal)
Raises after 3 failures
Confidence is between 0 and 1
Run validation
This is a simulated validation environment. In production, this would run your code against the validation steps.