MCPcopy Index your code
hub / github.com/googleapis/python-genai

github.com/googleapis/python-genai @v2.10.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.10.0 ↗ · + Follow
4,925 symbols 17,145 edges 487 files 1,794 documented · 36% updated 4d agov2.10.0 · 2026-06-24★ 3,835190 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Google Gen AI SDK

PyPI version Python support PyPI - Downloads


Documentation: https://googleapis.github.io/python-genai/

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] Upcoming Breaking Change to Automatic Function Calling (AFC): We will introduce a breaking change to the Automatic Function Calling (AFC) feature in the next major version. Specifically, users will not be able to invoke AFC from direct calls to Models.generate_content or its stream and async variants. Instead, users should invoke AFC from chats modules.

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 Agent 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 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 types from the types module:

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents=types.Part.from_text(text='Why is the sky blue?'),
    config=types.GenerateContentConfig(
        temperature=0,
        top_p=0.95,
        top_k=20,
    ),
)

Alternatively, you can accomplish the same request using dictionaries instead of types:

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents={'text': 'Why is the sky blue?'},
    config={
        'temperature': 0,
        'top_p': 0.95,
        'top_k': 20,
    },
)

(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 Vertex AI.

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:

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 beta API endpoints provided by Google to support preview features in the APIs. The stable API endpoints can be selected by setting the API version to v1.

To set the API version use http_options. For example, to set the API version to v1 for Vertex AI:

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')
)

Faster async client option: Aiohttp

By default we use httpx 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 httpx. 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 httpx 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, httpx supports socks5 proxy if you pass it via args to httpx.Client(). You may install httpx[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-3-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.

Expected request url will be: https://test-api-gateway-proxy.com/publishers/google/models/gemini-3-pro-preview

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-3.5-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-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 uploaded file (Gemini Developer API only)

Download the file in console.

!wget -q https://storage.googleapis.com/generativeai-downloads/data/a11.txt

python code.

file = client.files.upload(file='a11.txt')
response = client.models.generate_content(
    model='gemini-3.5-flash',
    contents=['Could you summarize this file?', file]
)
print(response.text)

How to structure contents argument for generate_content

The SDK always converts the inputs to the contents argument into list[types.Content]. The following shows some common ways to provide your inputs.

Provide a list[types.Content]

This is the canonical way to provide contents, SDK will not do any conversion.

Provide a types.Content instance
from google.genai import types

contents = types.Content(
    role='user',
    parts=[types.Part.from_text(text='Why is the sky blue?')]
)

SDK converts this to

[
    types.Content(
        role='user',
        parts=[types.Part.from_text(text='Why is the sky blue?')]
    )
]
Provide a string
contents='Why is the sky blue?'

The SDK will assume this is a text part, and it converts this into the following:

[
    types.UserContent(
        parts=[
            types.Part.from_text(text='Why is the sky blue?')
        ]
    )
]

Where a types.UserContent is a subclass of types.Content, it sets the role field to be user.

Provide a list of strings
contents=['Why is the sky blue?', 'Why is the cloud white?']

The SDK assumes these are 2 text parts, it converts this into a single content, like the following:

[
    types.UserContent(
        parts=[
            types.Part.from_text(text='Why is the sky blue?'),
            types.Part.from_text(text='Why is the cloud white?'),
        ]
    )
]

Where a types.UserContent is a subclass of types.Content, the role field in types.UserContent is fixed to be user.

Provide a function call part
from google.genai import types

contents = types.Part.from_function_call(
    name='get_weather_by_location',
    args={'location': 'Boston'}
)

The SDK converts a function call part to a content with a model role:

[
    types.ModelContent(
        parts=[
            types.Part.from_function_call(
                name='get_weather_by_location',
                args={'location': 'Boston'}
            )
        ]
    )
]

Where a types.ModelContent is a subclass of types.Content, the role field in types.ModelContent is fixed to be model.

Provide a list of function call parts
from google.genai import types

contents = [
    types.Part.from_function_call(
        name='get_weather_by_location',
        args={'location': 'Boston'}
    ),
    types.Part.from_function_call(
        name='get_weather_by_location',
        args={'location': 'New York'}
    ),
]

The SDK converts a list of function call parts to a content with a model role:

```python [ types.ModelContent( parts=[ types.Part.from_function_call( name='get_weather_by_location', args={'location': 'Boston'} ), types.Part.from_function_call( name='get_weather_by_location', args={'location': 'New York'} )

Core symbols most depended-on inside this repo

get
called by 423
google/genai/_gaos/agents.py
generate_content
called by 184
google/genai/models.py
get
called by 165
google/genai/files.py
get
called by 130
google/genai/models.py
from_callable
called by 112
google/genai/types.py
_from_response
called by 102
google/genai/_common.py
_verify_response
called by 100
google/genai/_api_client.py
model_dump
called by 92
google/genai/_gaos/types/basemodel.py

Shape

Function 2,169
Class 1,620
Method 1,043
Route 93

Languages

Python99%
TypeScript1%

Modules by API surface

google/genai/types.py1,038 symbols
google/genai/models.py178 symbols
google/genai/tests/models/test_generate_content_tools.py132 symbols
google/genai/tests/types/test_types.py123 symbols
google/genai/tests/models/test_generate_content.py111 symbols
google/genai/tests/client/test_client_initialization.py96 symbols
google/genai/tests/live/test_live.py84 symbols
google/genai/tunings.py78 symbols
google/genai/_gaos/google_genai.py76 symbols
google/genai/_gaos/utils/response_helpers.py75 symbols
google/genai/_api_client.py74 symbols
google/genai/batches.py72 symbols

Dependencies from manifests, versioned

absl-py2.1.0 · 1×
annotated-types0.7.0 · 1×
anyio4.8.0 · 1×
cachetools5.5.0 · 1×
certifi2024.8.30 · 1×
charset-normalizer3.4.0 · 1×
coverage7.6.9 · 1×
distro1.9.0 · 1×
google-auth2.47.0 · 1×
httpx0.28.1 · 1×
idna3.10 · 1×
iniconfig2.0.0 · 1×

For agents

$ claude mcp add python-genai \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact