Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.4 — Data Validation with Pydantic
Python · Example 2 of 2

A chat request: nested models, constraints, validator and JSON Schema

This is the shape of a request to an AI chat API: a model name, a list of messages (each with a role and some text) and settings. temperature is a dial for how adventurous the model's wording is (low is steady, high is varied). Try temperature=1.5 and a valid role to see it pass.

Pydantic turns type hints into real checks: you describe the shape of your data as a class, and it converts and validates incoming dictionaries or JSON, collects clear errors, and can produce a JSON Schema. FastAPI, the AI SDKs and agent frameworks are built on it.

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

Create a model Product with name (non-empty text), price (a number above 0) and in_stock (boolean defaulting to True). Show that Product(name="Pen", price="2.5") works.

02

Show the error loc and type when price is -1.

03

Add a validator so name is stored with the first letter capitalised and surrounding spaces removed.

Explain it without notes

01

What does Pydantic do that type hints alone do not?

02

What does a ValidationError contain, and why is that useful?

03

How do you add a rule that built-in constraints cannot express?

04

Why is model_json_schema() important for AI applications?

05

What is the difference between lax and strict mode, and is a Pydantic object always valid?

A chat request: nested models, constraints, validator and JSON Schema
Sign in to run this example in your browser.

Expected output

model='fake-model-1' messages=[Message(role='user', content='Hi')] temperature=1.0 max_tokens=None
{"model": "fake-model-1", "messages": [{"role": "user", "content": "Hi"}], "temperature": 1.0}
('model',) -> Value error, model names cannot contain spaces
('messages', 0, 'role') -> Input should be 'system', 'user' or 'assistant'
('messages', 0, 'content') -> String should have at least 1 character
('temperature',) -> Input should be less than or equal to 2
['max_tokens', 'messages', 'model', 'temperature']
['model', 'messages']
{'default': 1.0, 'maximum': 2, 'minimum': 0, 'title': 'Temperature', 'type': 'number'}