Dev.to AI 🤖 Ai 👁 2 📖 2 min read

Structured output with JSON, validated with Pydantic - Chat Orders

Day Topic Example Status 1 Talking to an LLM from code Classifying emails by category and urgency ✅ Code 2 Roles, examples and delimiters in prompts Translating technical language into plain language ✅ Code 3 S

Structured output with JSON, validated with Pydantic - Chat Orders
Day Topic Example Status
1 Talking to an LLM from code Classifying emails by category and urgency ✅ Code
2 Roles, examples and delimiters in prompts Translating technical language into plain language ✅ Code
3 Structured output with JSON, validated with Pydantic Turning a chat order into a table 📍 You're here
4 Images with vision models Scanning a receipt and returning a JSON with the products and the total ⏳ Coming soon
5 Embeddings: meaning as numbers Grouping 20 news articles by topic ⏳ Coming soon

Day 3: Structured output with JSON, validated with Pydantic

The goal: take a list of chat orders, where each order can have several products, and turn them into an orders.csv file with one product per row.

Why Pydantic? It does two jobs:

  1. It defines the shape of the answer. I pass the schema to the model, so it knows exactly which fields to return.
  2. It validates the answer. The model returns JSON as plain text, and Pydantic checks that every field exists and has the right type.

Pydantic can also be flexible: depending on the data type, it converts "5" into 5 or "yes" into True.

The image below shows the whole flow: the model receives an order as plain text, extracts the data following my schema, and Pydantic decides if the result can be used.

Flow from text to a validated Pydantic object

This is the schema. Product describes a single product, which becomes one row in the CSV. Orders describes the whole order and contains a list of products:

class Product(BaseModel):
    product: str | None = Field(
        default=None,
        description="Name of the products not the name of the person who is doing the order",
    )
    amount: int | None


class Orders(BaseModel):
    address: str | None = Field(default=None, description="null if not mentioned")
    payment_method: Literal["Cash", "Card", "Credit Card", "Debit Card", "Bank Transfer"] | None = (
        Field(default=None, description="Method of payment")
    )
    order: bool
    products: list[Product]

A few details that make this schema work:

  • description is an instruction for the model. "Not the name of the person" stops the model from confusing the customer with the product.
  • | None allows a field to be empty when the message doesn't mention it, instead of forcing the model to make something up.
  • Literal limits the possible values. If the model returns a payment method that isn't on the list, Pydantic rejects it.
  • order: bool if it is an actual order

Results

What I learned

  • Pydantic is a gatekeeper. It checks the data the model returns, and only lets it into my code if it meets the requirements.
  • Temperature 0 for extraction. I want consistent results: the same input should always return the same data.
  • Writing the CSV is plain Python. To create the file, I used with open().
  • Nesting models makes the data easy to flatten. Each order has a list of Product objects, so I can loop through them and write one product per row.

👉 Full code: day3_chat-orders.py

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.