Google Gen AI Python SDK provides an interface for developers to integrate
Google's generative models into their Python applications. It supports
the Gemini Developer API and
Gemini Enterprise Agent Platform
APIs.
[!WARNING]
Major version 3 changes:
Default Gemini Developer API version is now v1 (was v1beta).
Enterprise (Vertex AI) clients are unaffected and still default to
v1beta1.
The gemini-flash-latest, gemini-flash-lite-latest and
gemini-pro-latest aliases exist only on v1beta. Use a specific
model version, or switch back to v1beta.
To restore the previous default, set GOOGLE_GENAI_API_VERSION=beta
(or an explicit version such as v1beta), or pass
types.HttpOptions(api_version='v1beta'), which takes precedence.
Default HTTP client is now httpx2 (was httpx), and httpx is no
longer installed by default.
To restore httpx as the default, do both: install
google-genai[httpx] and set GOOGLE_GENAI_HTTP_CLIENT=httpx.
Alternatively, pass httpx_client / httpx_async_client in
HttpOptions.
To migrate to httpx2, import httpx2 as httpx is sufficient in most
cases.
httpx2 verifies SSL certificates against the OS trust store instead
of certifi when SSL_CERT_FILE and are not set.
SSL_CERT_DIR
Objects passed in HttpOptions(client_args=..., async_client_args=...)
(such as Timeout, Limits, transports, Auth subclasses) and
transport exceptions you catch (TimeoutException, ConnectError,
HTTPError) must come from the active HTTP client package.
interactions:CodeExecutionResultStep.result changes from string
to the CodeExecutionResultStepResult union. Check which variant is
present and read the string from it. The JSON for text-only results is
unchanged.
To avoid unexpected updates, pin the SDK version to < 3.0.0.
Agent Skills
Large Language Models (LLMs) and generative AI coding assistants are often trained on static datasets. As a result, they may be unaware of recent updates and suggest outdated or legacy libraries.
To ensure your AI coding helper (such as Antigravity, Claude Code, Cursor, or other IDE extensions) generates up-to-date code using the correct SDK syntax and best practices, we recommend equipping your assistant with Gemini API Skills. Loading these skills injects the correct patterns and guidelines directly into your AI assistant's context.
Depending on your target platform, use the corresponding Agent Skill repository:
from google import genai
# Only run this block for Gemini Developer API
client = genai.Client(api_key='GEMINI_API_KEY')
from google import genai
# Only run this block for Agent Platform
client = genai.Client(
enterprise=True, project='your-project-id', location='global'
)
Using types
All API methods support Pydantic types and dictionaries, which you can access
from google.genai.types. You can import the types module with the following:
from google.genai import types
Below is an example generate_content() call using Part from the types module:
response = client.models.generate_content(
model='gemini-3.8-flash',
contents=types.Part.from_text(text='Why is the sky blue?')
)
Alternatively, you can accomplish the same request using dictionaries instead of
types:
response = client.models.generate_content(
model='gemini-3.8-flash',
contents={'text': 'Why is the sky blue?'}
)
(Optional) Using environment variables:
You can create a client by configuring the necessary environment variables.
Configuration setup instructions depends on whether you're using the Gemini
Developer API or the Gemini API in the Gemini Enterprise Agent Platform.
Gemini Developer API: Set the GEMINI_API_KEY or GOOGLE_API_KEY.
It will automatically be picked up by the client. It's recommended that you
set only one of those variables, but if both are set, GOOGLE_API_KEY takes
precedence.
export GEMINI_API_KEY='your-api-key'
Gemini API on Agent Platform: Set GOOGLE_GENAI_USE_ENTERPRISE,
GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION, as shown below:
Explicitly close the sync client to ensure that resources, such as the
underlying HTTP connections, are properly cleaned up and closed.
from google.genai import Client
client = Client()
response_1 = client.models.generate_content(
model=MODEL_ID,
contents='Hello',
)
response_2 = client.models.generate_content(
model=MODEL_ID,
contents='Ask a question',
)
# Close the sync client to release resources.
client.close()
To explicitly close the async client:
from google.genai import Client
aclient = Client(
enterprise=True, project='my-project-id', location='global'
).aio
response_1 = await aclient.models.generate_content(
model=MODEL_ID,
contents='Hello',
)
response_2 = await aclient.models.generate_content(
model=MODEL_ID,
contents='Ask a question',
)
# Close the async client to release resources.
await aclient.aclose()
Client context managers
By using the sync client context manager, it will close the underlying
sync client when exiting the with block and avoid httpx "client has been closed" error like issues#1763.
from google.genai import Client
with Client() as client:
response_1 = client.models.generate_content(
model=MODEL_ID,
contents='Hello',
)
response_2 = client.models.generate_content(
model=MODEL_ID,
contents='Ask a question',
)
By using the async client context manager, it will close the underlying
async client when exiting the with block.
from google.genai import Client
async with Client().aio as aclient:
response_1 = await aclient.models.generate_content(
model=MODEL_ID,
contents='Hello',
)
response_2 = await aclient.models.generate_content(
model=MODEL_ID,
contents='Ask a question',
)
API Selection
By default, the SDK uses:
the stable v1 API endpoints for the Gemini Developer API.
and the beta v1beta1 API endpoints for Gemini Enterprise Agent Platform.
A different API version (for example v1beta or v1alpha) can be selected
with http_options or with the GOOGLE_GENAI_API_VERSION environment
variable. An explicitly configured version in http_options takes precedence
over the environment variable. Setting GOOGLE_GENAI_API_VERSION=beta selects
the beta version of whichever backend is in use: v1beta for the Gemini
Developer API and v1beta1 for Gemini Enterprise Agent Platform.
To set the API version use http_options. For example, to set the API version
to v1 for Gemini Enterprise Agent Platform:
from google import genai
from google.genai import types
client = genai.Client(
enterprise=True,
project='your-project-id',
location='global',
http_options=types.HttpOptions(api_version='v1')
)
To set the API version to v1alpha for the Gemini Developer API:
from google import genai
from google.genai import types
client = genai.Client(
api_key='GEMINI_API_KEY',
http_options=types.HttpOptions(api_version='v1alpha')
)
HTTP client option: httpx
By default, the SDK uses httpx2 for its HTTP transport. You can opt in to
legacy httpx by installing google-genai[httpx]
and setting the GOOGLE_GENAI_HTTP_CLIENT environment variable:
export GOOGLE_GENAI_HTTP_CLIENT=httpx
Alternatively, you can directly inject an httpx.Client or httpx.AsyncClient
via HttpOptions:
import httpx
from google import genai
from google.genai import types
client = genai.Client(
http_options=types.HttpOptions(
httpx_client=httpx.Client(),
httpx_async_client=httpx.AsyncClient(),
)
)
Faster async client option: Aiohttp
By default we use httpx2 for both sync and async client implementations. In order
to have faster performance, you may install google-genai[aiohttp]. In Gen AI
SDK we configure trust_env=True to match with the default behavior of httpx2.
Additional args of aiohttp.ClientSession.request() (see _RequestOptions args) can be passed
through the following way:
Both httpx2 and aiohttp libraries use urllib.request.getproxies from
environment variables. Before client initialization, you may set proxy (and
optional SSL_CERT_FILE) by setting the environment variables:
If you need socks5 proxy, httpx2 supportssocks5 proxy if you pass it via
args to httpx2.Client(). You may install httpx2[socks] to use it.
Then, you can pass it through the following way:
In some cases you might need a custom base url (for example, API gateway proxy
server) and bypass some authentication checks for project, location, or API key.
You may pass the custom base url like this:
client = Client(
enterprise=True,
http_options=types.HttpOptionsDict(
base_url='https://test-api-gateway-proxy.com',
base_url_resource_scope=types.ResourceScope.COLLECTION,
),
)
response = client.models.generate_content(
model='gemini-3.1-pro-preview', contents='Why is the sky blue?'
)
If base_url_resource_scope=types.ResourceScope.COLLECTION, the resource name
will not include api version, project, or location.
Parameter types can be specified as either dictionaries(TypedDict) or
Pydantic Models.
Pydantic model types are available in the types module.
Models
The client.models module exposes model inferencing and model getters.
See the 'Create a client' section above to initialize a client.
Generate Content
with text content input (text output)
response = client.models.generate_content(
model='gemini-3.8-flash', contents='Why is the sky blue?'
)
print(response.text)
with text content input (image output)
from google.genai import types
response = client.models.generate_content(
model='gemini-3.1-flash-lite-image',
contents='A cartoon infographic for flying sneakers',
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio="9:16",
),
),
)
for part in response.parts:
if part.inline_data:
generated_image = part.as_image()
generated_image.show()
with text content input (audio / speech output)
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash-tts',
contents='Give me a cheerful greeting.',
config=types.GenerateContentConfig(
response_modalities=['AUDIO'],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name='Aoede'
)
)
),
),
)
for part in response.parts:
if part.inline_data:
with open('greeting.wav', 'wb') as f:
f.write(part.inline_data.data)
from google.genai import types
contents = [
types.Part.from_text('What is this image about?'),
types.Part.from_uri(
file_uri: 'gs://generativeai-downloads/images/scones.jpg',
mime_type: 'image/jpeg',
)
]
The SDK will convert the list of parts into a content with a user role
[
types.UserContent(
parts=[
types.Part.from_text('What is this image about?'),
types.Part.from_uri(
file_uri: 'gs://generativeai-downloads/images/scones.jpg',
mime_type: 'image/jpeg',
)
]
)
]
Mix types in contents
You can also provide a list of types.ContentUnion. The SDK leaves items of
types.Content as is, it groups consecutive non function call parts into a
single types.UserContent, and it groups consecutive function call parts into
a single types.ModelContent.
If you put a list within a list, the inner list can only contain
types.PartUnion items. The SDK will convert the inner list into a single
types.UserContent.
System Instructions and Other Configs
The output of the model can be influenced by several optional settings
available in generate_content's config parameter. For example, increasing
max_output_tokens is essential for longer model responses. Capabilities and parameter defaults
for each model is shown in the
Gemini Enterprise Agent Platform docs
and Gemini API docs
respectively. Note that all API methods support Pydantic types and
dictionaries, which you can access from google.genai.types. In this example,
we use GenerateContentConfig to specify the desired behavior from the model.
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='high',
config=types.GenerateContentConfig(
system_instruction='I say high, you say low',
max_output_tokens=3,
),
)
print(response.text)
Automatic Continuation
Automatic continuation is enabled by default. When a response stops with
finish_reason set to CONTINUATION and returns a continuation_token, the
SDK automatically sends follow-up requests with the token until generation
completes and returns the merged response. To disable automatic continuation,
set automatic_continuation=False in GenerateContentConfig.
Streaming (generate_content_stream), async
(client.aio.models.generate_content and
client.aio.models.generate_content_stream), and chats (chat.send_message
and chat.send_message_stream) work very similarly.
from google import genai
from google.genai import types
client = genai.Client(
enterprise=True, project='your-project-id', location='global'
)
# Automatic continuation is enabled by default.
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Write a comprehensive multi-chapter guide on compiler design.',
)
print(response.text)
# Set automatic_continuation=False to disable automatic continuation.
single_hop_response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Write a comprehensive multi-chapter guide on compiler design.',
config=types.GenerateContentConfig(
automatic_continuation=False,
),
)
print(single_hop_response.text)
You can pass a Python function directly and it will be automatically
called and responded by default.
from google.genai import types
def get_current_weather(location: str) -> str:
"""Returns the current weather.
Args:
location: The city and state, e.g. San Francisco, CA
"""
return 'sunny'
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='What is the weather like in Boston?',
config=types.GenerateContentConfig(tools=[get_current_weather]),
)
print(response.text)
Disabling automatic function calling
If you pass in a python function as a tool directly, and do not want
automatic function calling, you can disable automatic function calling
as follows:
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='What is the weather like in Boston?',
config=types.GenerateContentConfig(
tools=[get_current_weather],
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
),
)
With automatic function calling disabled, you will get a list of function call
parts in the response:
Manually declare and invoke a function for function calling
If you don't want to use the automatic function support, you can manually
declare the function and invoke it.
The following example shows how to declare a function and pass it as a tool.
Then you will receive a function call part in the response.
from google.genai import types
function = types.FunctionDeclaration(
name='get_current_weather',
description='Get the current weather in a given location',
parameters_json_schema={
'type': 'object',
'properties': {
'location': {
'type': 'string',
'description': 'The city and state, e.g. San Francisco, CA',
}
},
'required': ['location'],
},
)
tool = types.Tool(function_declarations=[function])
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='What is the weather like in Boston?',
config=types.GenerateContentConfig(tools=[tool]),
)
print(response.function_calls[0])
After you receive the function call part from the model, you can invoke the function
and get the function response. And then you can pass the function response to
the model.
The following example shows how to do it for a simple function invocation.
from google.genai import types
user_prompt_content = types.Content(
role='user',
parts=[types.Part.from_text(text='What is the weather like in Boston?')],
)
function_call_part = response.function_calls[0]
function_call_content = response.candidates[0].content
try:
function_result = get_current_weather(
**function_call_part.function_call.args
)
function_response = {'result': function_result}
except (
Exception
) as e: # instead of raising the exception, you can let the model handle it
function_response = {'error': str(e)}
function_response_part = types.Part.from_function_response(
name=function_call_part.name,
response=function_response,
)
function_response_content = types.Content(
role='tool', parts=[function_response_part]
)
response = client.models.generate_content(
model='gemini-3.8-flash',
contents=[
user_prompt_content,
function_call_content,
function_response_content,
],
config=types.GenerateContentConfig(
tools=[tool],
),
)
print(response.text)
Function calling with ANY tools config mode
If you configure function calling mode to be ANY, then the model will always
return function call parts. If you also pass a python function as a tool, by
default the SDK will perform automatic function calling until the remote calls exceed the
maximum remote call for automatic function calling (default to 10 times).
If you'd like to disable automatic function calling in ANY mode:
from google.genai import types
def get_current_weather(location: str) -> str:
"""Returns the current weather.
Args:
location: The city and state, e.g. San Francisco, CA
"""
return "sunny"
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="What is the weather like in Boston?",
config=types.GenerateContentConfig(
tools=[get_current_weather],
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
),
)
If you'd like to set x number of automatic function call turns, you can
configure the maximum remote calls to be x + 1.
Assuming you prefer 1 turn for automatic function calling.
from google.genai import types
def get_current_weather(location: str) -> str:
"""Returns the current weather.
Args:
location: The city and state, e.g. San Francisco, CA
"""
return "sunny"
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="What is the weather like in Boston?",
config=types.GenerateContentConfig(
tools=[get_current_weather],
automatic_function_calling=types.AutomaticFunctionCallingConfig(
maximum_remote_calls=2
),
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
),
)
Model Context Protocol (MCP) support (experimental)
See below for examples of how to use MCP for the Gemini Developer API and Gemini Enterprise Agent Platform.
MCP for Gemini Developer API
Built-in MCP support is an
experimental feature. You can pass a local MCP server as a tool directly.
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai
client = genai.Client()
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=["-y", "@philschmid/weather-mcp"], # MCP Server
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Prompt to get the weather for the current day in London.
prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection between client and server
await session.initialize()
# Send request to the model with MCP function declarations
response = await client.aio.models.generate_content(
model="gemini-3.8-flash",
contents=prompt,
config=genai.types.GenerateContentConfig(
tools=[session], # uses the session, will automatically call the tool using automatic function calling
),
)
print(response.text)
# Start the asyncio event loop and run the main function
asyncio.run(run())
MCP for Gemini Enterprise Agent Platform
To use MCP with Agent Platform, provide the MCP tool you want to use to
Tool.mcp_servers in your generate_content request. See
here
for a list of available MCP tools.
The mcp package is required to use Agent Platform MCP servers.
You can install it with pip install mcp.
import asyncio
from google import genai
from google.genai import types
PROJECT_ID="your-gcp-project"
LOCATION="your-location"
client = genai.Client(enterprise=True, project=PROJECT_ID, location=LOCATION)
async def agent_platform_mcp():
response = await client.aio.models.generate_content(
model="gemini-3.8-flash",
contents=f"List my endpoints in {LOCATION} for my {PROJECT_ID} project.",
config = types.GenerateContentConfig(
tools=[
types.Tool(
mcp_servers=[
types.McpServer(name='endpoints')
]
)
]
)
)
# Print the model response
if response.text:
print(response.text)
# Optionally, print the full conversation between the model and MCP server
if response.automatic_function_calling_history:
for turn in response.automatic_function_calling_history:
print(f"Role: {turn.role}")
for part in turn.parts:
if part.function_call:
print(f" Tool Called: {part.function_call.name}")
print(f" Arguments: {part.function_call.args}")
elif part.function_response:
print(f" Tool Response: {part.function_response.response}")
print("-" * 40)
asyncio.run(agent_platform_mcp())
JSON Response Schema
However you define your schema, don't duplicate it in your input prompt,
including by giving examples of expected JSON output. If you do, the generated
output might be lower in quality.
from pydantic import BaseModel
from google.genai import types
class CountryInfo(BaseModel):
name: str
population: int
capital: str
continent: str
gdp: int
official_language: str
total_area_sq_mi: int
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Give me information for the United States.',
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_json_schema=CountryInfo.model_json_schema(),
),
)
print(response.text)
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Give me information for the United States.',
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_json_schema={
'required': [
'name',
'population',
'capital',
'continent',
'gdp',
'official_language',
'total_area_sq_mi',
],
'properties': {
'name': {'type': 'STRING'},
'population': {'type': 'INTEGER'},
'capital': {'type': 'STRING'},
'continent': {'type': 'STRING'},
'gdp': {'type': 'INTEGER'},
'official_language': {'type': 'STRING'},
'total_area_sq_mi': {'type': 'INTEGER'},
},
'type': 'OBJECT',
},
),
)
print(response.text)
Generate Content (Synchronous Streaming)
Generate content in a streaming format so that the model outputs streams back
to you, rather than being returned as one chunk.
Streaming for text content
for chunk in client.models.generate_content_stream(
model='gemini-3.8-flash', contents='Tell me a story in 300 words.'
):
print(chunk.text, end='')
Streaming for image content
If your image is stored in Google Cloud Storage,
you can use the from_uri class method to create a Part object.
from google.genai import types
for chunk in client.models.generate_content_stream(
model='gemini-3.8-flash',
contents=[
'What is this image about?',
types.Part.from_uri(
file_uri='gs://generativeai-downloads/images/scones.jpg',
mime_type='image/jpeg',
),
],
):
print(chunk.text, end='')
If your image is stored in your local file system, you can read it in as bytes
data and use the from_bytes class method to create a Part object.
from google.genai import types
YOUR_IMAGE_PATH = 'your_image_path'
YOUR_IMAGE_MIME_TYPE = 'your_image_mime_type'
with open(YOUR_IMAGE_PATH, 'rb') as f:
image_bytes = f.read()
for chunk in client.models.generate_content_stream(
model='gemini-3.8-flash',
contents=[
'What is this image about?',
types.Part.from_bytes(data=image_bytes, mime_type=YOUR_IMAGE_MIME_TYPE),
],
):
print(chunk.text, end='')
Generate Content (Asynchronous Non Streaming)
client.aio exposes all the analogous async methods
that are available on client. Note that it applies to all the modules.
For example, client.aio.models.generate_content is the async version
of client.models.generate_content
response = await client.aio.models.generate_content(
model='gemini-3.8-flash', contents='Tell me a story in 300 words.'
)
print(response.text)
Generate Content (Asynchronous Streaming)
async for chunk in await client.aio.models.generate_content_stream(
model='gemini-3.8-flash', contents='Tell me a story in 300 words.'
):
print(chunk.text, end='')
Count Tokens and Compute Tokens
response = client.models.count_tokens(
model='gemini-3.8-flash',
contents='why is the sky blue?',
)
print(response)
Compute Tokens
Compute tokens is only supported in Gemini Enterprise Agent Platform.
response = client.models.compute_tokens(
model='gemini-3.8-flash',
contents='why is the sky blue?',
)
print(response)
Async
response = await client.aio.models.count_tokens(
model='gemini-3.8-flash',
contents='why is the sky blue?',
)
print(response)
Local Count Tokens
The local tokenizer needs an extra. SentencePiece models such as
gemini-2.5-flash need only the light one. Models that use the Gemma 4
tokenizer, such as gemini-3.5-flash, also need Transformers and PyTorch.
Install one of the two extras:
# SentencePiece models only.
pip install "google-genai[local-tokenizer]"
# Also models that use the Gemma 4 tokenizer (adds Transformers and PyTorch).
pip install "google-genai[local-tokenizer-transformers]"
from google.genai import local_tokenizer
tokenizer = local_tokenizer.LocalTokenizer(model_name='gemini-3.8-flash')
result = tokenizer.count_tokens("What is your name?")
Local Compute Tokens
from google.genai import local_tokenizer
tokenizer = local_tokenizer.LocalTokenizer(model_name='gemini-3.8-flash')
result = tokenizer.compute_tokens("What is your name?")
Embed Content
response = client.models.embed_content(
model='gemini-embedding-001',
contents='why is the sky blue?',
)
print(response)
from google.genai import types
response = client.models.embed_content(
model='gemini-embedding-001',
contents=['why is the sky blue?', 'What is your age?'],
config=types.EmbedContentConfig(output_dimensionality=10),
)
print(response)
Imagen
Generate Images
from google.genai import types
response1 = client.models.generate_images(
model='imagen-4.0-generate-001',
prompt='An umbrella in the foreground, and a rainy night sky in the background',
config=types.GenerateImagesConfig(
number_of_images=1,
include_rai_reason=True,
output_mime_type='image/jpeg',
),
)
response1.generated_images[0].image.show()
Upscale Image
Upscale image is only supported in Gemini Enterprise Agent Platform.
Edit image uses a separate model from generate and upscale.
Edit image is only supported in Gemini Enterprise Agent Platform.
# Edit the generated image from above
from google.genai import types
from google.genai.types import RawReferenceImage, MaskReferenceImage
raw_ref_image = RawReferenceImage(
reference_id=1,
reference_image=response1.generated_images[0].image,
)
# Model computes a mask of the background
mask_ref_image = MaskReferenceImage(
reference_id=2,
config=types.MaskReferenceConfig(
mask_mode='MASK_MODE_BACKGROUND',
mask_dilation=0,
),
)
response3 = client.models.edit_image(
model='imagen-3.0-capability-001',
prompt='Sunlight and clear sky',
reference_images=[raw_ref_image, mask_ref_image],
config=types.EditImageConfig(
edit_mode='EDIT_MODE_INPAINT_INSERTION',
number_of_images=1,
include_rai_reason=True,
output_mime_type='image/jpeg',
),
)
response3.generated_images[0].image.show()
Veo
Currently, only Gemini Enterprise Agent Platform supports video generation.
Generate Videos (Text to Video)
from google import genai
from google.genai import types
client = genai.Client(vertexai=True)
# Create operation
operation = client.models.generate_videos(
model='veo-3.1-generate-001',
source=types.GenerateVideosSource(
prompt='A neon hologram of a cat driving at top speed',
),
config=types.GenerateVideosConfig(
number_of_videos=1,
duration_seconds=5,
enhance_prompt=True,
),
)
# Poll operation
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
video = operation.response.generated_videos[0].video
video.show()
Generate Videos (Image to Video)
from google import genai
from google.genai import types
client = genai.Client(vertexai=True)
# Read local image (uses mimetypes.guess_type to infer mime type)
image = types.Image.from_file(location="local/path/file.png")
# Create operation
operation = client.models.generate_videos(
model='veo-3.1-generate-001',
source=types.GenerateVideosSource(
# Prompt is optional if image is provided
prompt='Night sky',
image=image,
),
config=types.GenerateVideosConfig(
number_of_videos=1,
duration_seconds=5,
enhance_prompt=True,
# Can also pass an Image into last_frame for frame interpolation
),
)
# Poll operation
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
video = operation.response.generated_videos[0].video
video.show()
Generate Videos (Video to Video)
Currently, only Gemini Enterprise Agent Platform supports Video to Video generation (Video extension).
from google import genai
from google.genai import types
client = genai.Client(vertexai=True)
# Read local video (uses mimetypes.guess_type to infer mime type)
video = types.Video.from_file("local/path/video.mp4")
# Create operation
operation = client.models.generate_videos(
model='veo-3.1-generate-001',
source=types.GenerateVideosSource(
# Prompt is optional if Video is provided
prompt='Night sky',
# Input video must be in GCS for Gemini Enterprise Agent Platform or a URI for Gemini
video=types.Video(
uri="gs://bucket-name/inputs/videos/cat_driving.mp4",
),
),
config=types.GenerateVideosConfig(
number_of_videos=1,
duration_seconds=5,
enhance_prompt=True,
),
)
# Poll operation
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
video = operation.response.generated_videos[0].video
video.show()
Chats
Create a chat session to start a multi-turn conversations with the model. Then,
use chat.send_message function multiple times within the same chat session so
that it can reflect on its previous responses (i.e., engage in an ongoing
conversation). See the 'Create a client' section above to initialize a client.
Send Message (Synchronous Non-Streaming)
chat = client.chats.create(model='gemini-3.8-flash')
response = chat.send_message('tell me a story')
print(response.text)
response = chat.send_message('summarize the story you told me in 1 sentence')
print(response.text)
Send Message (Synchronous Streaming)
chat = client.chats.create(model='gemini-3.8-flash')
for chunk in chat.send_message_stream('tell me a story'):
print(chunk.text)
Send Message (Asynchronous Non-Streaming)
chat = client.aio.chats.create(model='gemini-3.8-flash')
response = await chat.send_message('tell me a story')
print(response.text)
Send Message (Asynchronous Streaming)
chat = client.aio.chats.create(model='gemini-3.8-flash')
async for chunk in await chat.send_message_stream('tell me a story'):
print(chunk.text)
Files
Files are only supported in Gemini Developer API. See the 'Create a client'
section above to initialize a client.
from google.genai import types
response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Summarize the pdfs',
config=types.GenerateContentConfig(
cached_content=cached_content.name,
),
)
print(response.text)
Interactions
The Interactions API is a unified interface for interacting with Gemini models and agents. It simplifies state management, tool orchestration, and long-running tasks.
interaction = client.interactions.create(
model='gemini-3.8-flash',
input='Tell me a short joke about programming.'
)
print(interaction.output_text)
Stateful Conversation
The Interactions API supports server-side state management. You can continue a conversation by referencing the previous_interaction_id.
# 1. First turn
interaction1 = client.interactions.create(
model='gemini-3.8-flash',
input='Hi, my name is Amir.'
)
print(f"Model: {interaction1.output_text}")
# 2. Second turn (passing previous_interaction_id)
interaction2 = client.interactions.create(
model='gemini-3.8-flash',
input='What is my name?',
previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.output_text}")
Agents (Deep Research)
You can use specialized agents like deep-research-preview-04-2026 for complex tasks.
import time
# 1. Start the Deep Research Agent
initial_interaction = client.interactions.create(
input='Research the history of the Google TPUs with a focus on 2025 and 2026.',
agent='deep-research-preview-04-2026',
background=True
)
print(f"Research started. Interaction ID: {initial_interaction.id}")
# 2. Poll for results
while True:
interaction = client.interactions.get(id=initial_interaction.id)
print(f"Status: {interaction.status}")
if interaction.status == "completed":
print("\nFinal Report:\n", interaction.output_text)
break
elif interaction.status in ["failed", "cancelled"]:
print(f"Failed with status: {interaction.status}")
break
time.sleep(10)
Multimodal Input
You can provide multimodal data (text, images, audio, etc.) in the input list.
import base64
# Assuming you have an image loaded as bytes
# base64_image = ...
interaction = client.interactions.create(
model='gemini-3.8-flash',
input=[
{'type': 'text', 'text': 'Describe the image.'},
{'type': 'image', 'data': base64_image, 'mime_type': 'image/png'}
]
)
print(interaction.output_text)
Function Calling
You can define custom functions for the model to use. The Interactions API handles the tool selection, and you provide the execution result back to the model.
# 1. Define the tool
def get_weather(location: str):
"""Gets the weather for a given location."""
return f"The weather in {location} is sunny."
weather_tool = {
'type': 'function',
'name': 'get_weather',
'description': 'Gets the weather for a given location.',
'parameters': {
'type': 'object',
'properties': {
'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}
},
'required': ['location']
}
}
# 2. Send the request with tools
interaction = client.interactions.create(
model='gemini-3.8-flash',
input='What is the weather in Mountain View, CA?',
tools=[weather_tool]
)
# 3. Handle the tool call
for step in (interaction.steps or []):
if step.type == 'function_call':
print(f"Tool Call: {step.name}({step.arguments})")
# Execute your actual function here
result = get_weather(**step.arguments)
# Send result back to the model
interaction = client.interactions.create(
model='gemini-3.8-flash',
previous_interaction_id=interaction.id,
input=[{
'type': 'function_result',
'name': step.name,
'call_id': step.id,
'result': result
}]
)
print(f"Response: {interaction.output_text}")
Built-in Tools
You can also use Google's built-in tools, such as Google Search or Code Execution.
Grounding with Google Search
interaction = client.interactions.create(
model='gemini-3.8-flash',
input='Who won the last Super Bowl?',
tools=[{'type': 'google_search'}]
)
print(interaction.output_text)
The Interactions API can generate multimodal outputs, such as images or audio. You must specify the response_modalities.
Image Output
import base64
interaction = client.interactions.create(
model='gemini-3.1-flash-lite-image',
input='Generate an image of a futuristic city.',
response_modalities=['IMAGE']
)
if interaction.output_image:
print(f"Generated image with mime_type: {interaction.output_image.mime_type}")
with open("generated_city.png", "wb") as f:
f.write(base64.b64decode(interaction.output_image.data))
Audio Output
import base64
interaction = client.interactions.create(
model='gemini-3.8-flash-tts',
input='Say hello and give a one sentence motivational quote.',
response_modalities=['AUDIO']
)
if interaction.output_audio:
print(f"Generated audio with mime_type: {interaction.output_audio.mime_type}")
with open("greeting.wav", "wb") as f:
f.write(base64.b64decode(interaction.output_audio.data))
Tunings
client.tunings contains tuning job APIs and supports supervised fine
tuning through tune. Only supported in Gemini Enterprise Agent Platform. See the 'Create a client'
section above to initialize a client.
from google.genai import types
model = 'gemini-3.8-flash'
training_dataset = types.TuningDataset(
# or gcs_uri=my_enterprise_multimodal_dataset
gcs_uri='gs://your-gcs-bucket/your-tuning-data.jsonl',
)
Only supported in Gemini Enterprise Agent Platform. See the 'Create a client' section above to
initialize a client.
Create
Gemini Enterprise Agent Platform:
# Specify model and source file only, destination and job display name will be auto-populated
job = client.batches.create(
model='gemini-3.8-flash',
src='bq://my-project.my-dataset.my-table', # or "gs://path/to/input/data"
)
print(job)
In order to create a batch job with file name. Need to upload a json file.
For example myrequests.json:
{"key":"request_1", "request": {"contents": [{"parts": [{"text":
"Explain how AI works in a few words"}]}], "generation_config": {"response_modalities": ["TEXT"]}}}
{"key":"request_2", "request": {"contents": [{"parts": [{"text": "Explain how Crypto works in a few words"}]}]}}
Then upload the file.
# Upload the file
file = client.files.upload(
file='myrequests.json',
config=types.UploadFileConfig(display_name='test-json')
)
# Create a batch job with file name
batch_job = client.batches.create(
model="gemini-3.8-flash",
src="files/test-json",
)
# Get a job by name
job = client.batches.get(name=job.name)
job.state
completed_states = set(
[
'JOB_STATE_SUCCEEDED',
'JOB_STATE_FAILED',
'JOB_STATE_CANCELLED',
'JOB_STATE_PAUSED',
]
)
while job.state not in completed_states:
print(job.state)
job = client.batches.get(name=job.name)
time.sleep(30)
job
List
for job in client.batches.list(config=types.ListBatchJobsConfig(page_size=10)):
print(job)
# Delete the job resource
delete_job = client.batches.delete(name=job.name)
delete_job
Error Handling
To handle errors raised by the model service, the SDK provides this APIError class.
from google.genai import errors
try:
client.models.generate_content(
model="invalid-model-name",
contents="What is your name?",
)
except errors.APIError as e:
print(e.code) # 404
print(e.message)
Extra Request Body
The extra_body field in HttpOptions accepts a dictionary of additional JSON
properties to include in the request body. This can be used to access new or
experimental backend features that are not yet formally supported in the SDK.
The structure of the dictionary must match the backend API's request structure.
response = client.models.generate_content(
model="gemini-3.8-flash",
contents="What is the weather in Boston? and how about Sunnyvale?",
config=types.GenerateContentConfig(
tools=[get_current_weather],
http_options=types.HttpOptions(extra_body={'tool_config': {'function_calling_config': {'mode': 'COMPOSITIONAL'}}}),
),
)
Alternatives
Use instead of google-genai: tools that do the same job, closest first.