Google Gen AI SDK
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 platform
APIs.
[!WARNING]
Major version 3 changes:
- Default Gemini Developer API version is now
v1 (was v1beta).
Gemini platform (formerly Gemini Enterprise Agent Platform and 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 SSL_CERT_DIR are not set.
- 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:
Installation
pip install google-genai
With uv:
uv pip install google-genai
Imports
from google import genai
from google.genai import types
Create a client
Please run one of the following code blocks to create a client for
different services (Gemini Developer API or Gemini platform).
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 Gemini 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-4-hydrogen',
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-4-hydrogen',
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 Gemini 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 in Gemini platform: Set GOOGLE_GENAI_USE_ENTERPRISE,
GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION, as shown below:
export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='global'
from google import genai
client = genai.Client()
Close a client
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 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 platform.
To set the API version use http_options. For example, to set the API version
to v1 for Gemini 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:
http_options = types.HttpOptions(
async_client_args={'cookies': ..., 'ssl': ...},
)
client=Client(..., http_options=http_options)
Proxy
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:
export HTTPS_PROXY='http://username:password@proxy_uri:port'
export SSL_CERT_FILE='client.pem'
If you need socks5 proxy, httpx2 supports socks5 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:
http_options = types.HttpOptions(
client_args={'proxy': 'socks5://user:pass@host:port'},
async_client_args={'proxy': 'socks5://user:pass@host:port'},
)
client=Client(..., http_options=http_options)
Custom base url
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-4-hydrogen', 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.
Expected request url will be:
https://test-api-gateway-proxy.com/publishers/google/models/gemini-4-hydrogen
Types
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-4-hydrogen', 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-nano-banana-2.1',
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)
with uploaded file (Gemini Developer API only)
Download the file in console.