Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 16.6 — Structured Output: JSON, Schemas and Pydantic
Python · Example 3 of 3

The JSON Schema Pydantic generates

Programs need data, not prose, so you ask a model for JSON and then treat its answer as untrusted input: parse it, validate it against a schema with Pydantic, and if it is invalid send the error back and retry a limited number of times.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write safe_parse(text) that removes code fences, parses JSON and returns a dict, or None if parsing fails or the value is not a dict.

02

Write a Pydantic model Review with rating (an integer from 1 to 5) and sentiment (positive, neutral or negative). Validate one good and one bad reply.

03

Without Pydantic, write validate_ticket(data) that returns a list of problem strings (empty means valid).

Explain it without notes

01

Why must you validate a model's JSON even if you asked for a specific schema?

02

Describe a retry-on-invalid loop and its safety limits.

03

How does Pydantic help with both prompting and validating?

04

Your service must extract an invoice into a typed object from a model. Walk through the design from the request to a trusted object, including what you do when it keeps failing.

The JSON Schema Pydantic generates
Sign in to run this example in your browser.

Expected output

{
  "properties": {
    "title": {
      "description": "Short summary",
      "minLength": 3,
      "title": "Title",
      "type": "string"
    },
    "priority": {
      "enum": [
        "low",
        "medium",
        "high"
      ],
      "title": "Priority",
      "type": "string"
    },
    "estimate_hours": {
      "exclusiveMinimum": 0,
      "maximum": 40,
      "title": "Estimate Hours",
      "type": "number"
    }
  },
  "required": [
    "title",
    "priority",
    "estimate_hours"
  ],
  "title": "Ticket",
  "type": "object"
}