Day 3, 30 minutes · beginner
Why it matters
A chat answer is written for a person. Your code cannot do much with a friendly paragraph, but it can do a lot with a field called visitors that holds the number 12. Structured output makes Gemini return JSON that follows a shape you define, so the next line of your program does not have to guess.
Today Wilmot's helper learns to read visitor emails. Each email goes in, and a small record comes out: the topic, how many people, the date, whether a human should answer, and a one-line summary. You finish with five test emails checked by code instead of by eye.
Structured output in one picture
You describe the shape you want as a JSON Schema. Gemini then writes JSON that fits it. In Python you do not have to write the schema by hand: you write a Pydantic class (Pydantic is a popular Python package for data shapes), and Google's docs show how to turn it into a schema and back.
In the Interactions API, the request has a response_format setting with three parts:
typeistext.mime_typeisapplication/json.schemais the JSON Schema, hereEnquiry.model_json_schema().
The answer comes back as a JSON string in interaction.output_text. You turn it into an object with model_validate_json. If the text does not fit the class, Pydantic raises an error, which is exactly what you want in a program.
Design the fields well
- Use a fixed list for categories.
Literal["tour", "group_booking", ...]becomes an enum, so the model cannot invent a topic called "tours?". - Allow null for missing facts. An email that does not give a date should give null, not a guess. Say so in the system instruction ("Do not guess") and in each field description.
- Describe every field. Descriptions steer the model, and they cost no extra structure.
- Add a way out. The
needs_humanfield gives the model a place to put a complaint or a medical question, so it does not try to answer them.
What structured output does not do
Google's docs are clear that the JSON is valid in shape, not necessarily right in content. A visitor count can fit the schema and still be wrong. Always check values in your own code.
Some schema rules are not enforced. Length limits such as minLength and maxLength, and some array and object limits, are stripped or ignored. minItems and maxItems are enforced. If you need the others, check them with Pydantic after the call. Very large or deeply nested schemas can be refused with a 400 INVALID_ARGUMENT error: keep them small, and move extra rules into field descriptions.
Also check interaction.status. If the model hits an output limit before it finishes, the status is incomplete and the JSON may be cut off or empty. The script treats anything other than completed as an error.
Structured output or function calling
The docs sum it up like this. Use structured output when you want the final answer in a set format. Use function calling (next lesson) when the model needs your code to do something before it can answer. They can also be combined.
About the sample emails
All five emails are invented. In real work, do not paste real customer emails into a free-tier prompt (see lesson 1). Remove names and contact details first, or use a paid project.
The steps
- Install Pydantic.
- Write
enquiry.pywith the schema and the function that reads one email. - Write
read_emails.pywith five test emails. - Run it and compare each result with its email.
- Add one email of your own that is tricky, and save the results.
Pick your tool below and follow the steps.
Common mistakes
- Asking for JSON in the prompt only. Use
response_formatso the shape is enforced. - Letting every field be required, so the model invents values. Allow null.
- Trusting a valid result without checking it.
- Making the schema huge. Start with five fields.
Today's actions
Ticks are not saved without an accountDo it in Gemini API
Gemini API
- In your project folder, with the virtual environment on, install Pydantic:
pip install pydantic. - Create
enquiry.py. It defines the shape of one enquiry and a function that sends an email to Gemini with that shape as theresponse_format.from typing import Literal, Optional from pydantic import BaseModel, Field from config import MODEL, client class Enquiry(BaseModel): topic: Literal["tour", "group_booking", "accessibility", "lost_property", "other"] visitors: Optional[int] = Field(description="Number of people, or null if the email does not say.") date: Optional[str] = Field(description="Requested date as YYYY-MM-DD, or null if the email has no date.") needs_human: bool = Field(description="True for a complaint, a medical question or anything unclear.") summary: str = Field(description="One sentence that summarises the email.") def read_enquiry(email: str) -> Enquiry: interaction = client.interactions.create( model=MODEL, system_instruction="Fill in the fields from the visitor email. Use null when the email does not say. Do not guess.", input=email, response_format={ "type": "text", "mime_type": "application/json", "schema": Enquiry.model_json_schema(), }, generation_config={"thinking_level": "low"}, ) if interaction.status != "completed": raise RuntimeError(f"Interaction ended with status {interaction.status}") return Enquiry.model_validate_json(interaction.output_text) - Create
read_emails.pywith five invented visitor emails. It prints each result as JSON.from enquiry import read_enquiry EMAILS = [ "Hello, we are 12 people from a walking club and would like the 11:00 tour on 2026-12-12.", "Hi, can my dad get up the tower? He uses a wheelchair. Thanks, Ruth", "I think I left a blue scarf on the stairs last Sunday.", "Hello, two adults and one child, we come on Saturday if you have room.", "Your guide was rude to my daughter and I want to speak to someone.", ] for email in EMAILS: result = read_enquiry(email) print(result.model_dump_json()) - Run
python read_emails.py. Each line should be one JSON record. If you get an error about status, the answer was cut off: run it again. - Check each result against its email. Does the count of 12 show up? Is the date null in the email that has none? Which email was flagged
needs_human? Write down anything wrong. - Add a sixth email of your own to
EMAILSthat mixes two topics, run again and decide whether the result is acceptable. - Run
python read_emails.py > enquiry-results.txtto save all the results in one file.
Note: The JSON always fits the shape but can still be wrong in content, so keep checking values in code. Length limits like minLength are ignored by the server. Very large schemas can be refused with a 400 INVALID_ARGUMENT error.
Create a free account to save your progress
Free, and no payment details. Your ticks and finished lessons are kept, on every device.
Create a free account I already have an accountCreate a free account to save your progress. Sign in or sign up