Using Structured Output and Multi-turn Conversations with Google Gemini
This note covers how to use the Google Gemini API for structured output and multi-turn conversations in Python. It demonstrates defining response schemas with Pydantic, configuring the client, and managing conversational context. The examples use the google.genai library and the Gemini 3.5 Flash model.
Structured Output with Pydantic
Structured output allows you to receive model responses in a well-defined format, making it easier to parse and use the results in your application. This is achieved by defining a response schema using Pydantic's BaseModel.
from google.genai import types
from google import genai
from pydantic import BaseModel
class PythonInfo(BaseModel):
topic: str
summary: str
difficulty: str
use_cases: list[str]
client = genai.Client(
vertexai=True,
project="name",
)
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Tell me about Python",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=PythonInfo
)
)
print("Gemini response:", response.text)
Pydantic Model:
PythonInfodefines the expected structure of the model's response.GenerateContentConfig: Specifies the MIME type (
application/json) and the schema for the response.Client Setup: The
genai.Clientis initialized with a project name and Vertex AI enabled.
Note: The code for setting up credentials (
default()) is commented out. You may need to configure authentication depending on your environment.
Multi-turn Conversations
Multi-turn conversations allow you to maintain context across multiple exchanges with the model. This is useful for chatbots or assistants that need to remember previous messages.
from google import genai
client = genai.Client(
vertexai=True,
project="name"
)
chat = client.chats.create(
model="gemini-3.5-flash"
)
response = chat.send_message("My name is Chandan")
print("Gemini response:", response.text)
response = chat.send_message("I am an AI Engineer")
print("Gemini response:", response.text)
response = chat.send_message("What is my name?")
print("Gemini response:", response.text)
response = chat.send_message("What is my profession?")
print("Gemini response:", response.text)
Chat Object: Created with
client.chats.create, specifying the model.Maintaining Context: Each
send_messagecall builds on the previous conversation, allowing the model to remember information like your name and profession.
Key Takeaways
Structured output with Pydantic schemas makes parsing model responses reliable and type-safe.
The Gemini API supports multi-turn conversations, enabling contextual chat experiences.
Proper client setup (including authentication and project configuration) is essential for successful API calls.
When using structured output, ensure the response schema matches the expected content from the model.