Structured output¶
This example shows how to generate structured data using a pydantic model to represent Cats with name, colour, and special ability.
Import the Gemini API and pydantic
Define a Pydantic model for a Cat
Initialize the Gemini client with your API key
Define the prompt. Note: It asks for 3 cats
Call the API to generate content, specifying the response schema. Note that it expects a list
and not a typing.List
object. For some reason Gemini models are finicky about that.
response = client.models.generate_content(
model="gemini-2.0-flash-lite",
contents=prompt,
config={
"response_mime_type": "application/json",
"response_schema": list[Cat],
},
)
Parse the json response to a list of Cat objects
Print the generated cat data
for cat in my_cats:
print(
f"Name: {cat.name}, Colour: {cat.colour}, Special Ability: {cat.special_ability}"
)
Running the Example¶
First, install the Google Generative AI library and pydantic
Then run the program with Python
$ python structured_cats.py
Name: Aria, Colour: tortoiseshell, Special Ability: Can teleport short distances
Name: Blupus, Colour: ginger, Special Ability: Understands human speech
Name: Moonshine, Colour: black and white, Special Ability: Invisible at night