🌐
GitHub
github.com › googleapis › python-genai
GitHub - googleapis/python-genai: Google Gen AI Python SDK provides an interface for developers to integrate Google's generative models into their Python applications. · GitHub
1 month ago - 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.5-flash', contents=[ 'What is this image about?', types.Part.from_bytes(data=image_bytes, mime_type=YOUR_IMAGE_MIME_TYPE), ], ): print(chunk.text, end='')
Starred by 3.8K users
Forked by 929 users
Languages   Python
🌐
GitHub
googleapis.github.io › python-genai
Google Gen AI SDK documentation
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-2.5-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='')
Discussions

Confessions of an AI Dev: My Epic Battle Migrating to Google's google-genai
AI coding assistance on the newest version, SDK, platform, API, etc is much harder than assistance on something with lots of examples 🤷 (especially when you're using a cheaper AI like flash). You probably would have been better off surveying the new code and interfaces (NOT the docs as your only source, go to the code) and then come up with an integration plan. You can use AI for these steps, too. Can really accelerate source explanation, design, spec, prior art surveys, etc. Vibe-code and find out (VAFO) I guess. Having the AI write the post was probably why it will get ignored and down-voted, btw. Which is unfortunate, because I think it's time to move past knee jerk negative reactions and dig into the real bad practices here. More on reddit.com
🌐 r/Python
3
0
June 6, 2025
Gemini 2.5 Pro doesn't know how to use its own google-genai Python API?
Ask it to Google it. It will. Or copy and paste the docs to it. The fact that it self searches is the mind blowing part to me. We used to have to call that has a tool and handle it internally, now it's just built in. You can even ask what model it thinks it is and it will often be wrong. All the LLMs do it. Sometimes even referring to themselves as a competitor. More on reddit.com
🌐 r/GeminiAI
19
3
April 8, 2025
Stuck at google generative ai module
both google ai and gemini ai and more ai .. that's a lot of ai. what are you trying to do with all this ai? the error is self explanatory. ModuleNotFoundError: No module named 'google.ai.generativelanguage_v1beta' More on reddit.com
🌐 r/learnpython
2
3
October 21, 2024
Erro "No module named" but the module is already installed
Do you have multiple installations of python? Make sure you're using the same version where the module was installed. More on reddit.com
🌐 r/learnpython
9
3
May 19, 2024
🌐
GitHub
github.com › googleapis › python-genai › blob › main › google › genai › types.py
python-genai/google/genai/types.py at main · googleapis/python-genai
Google Gen AI Python SDK provides an interface for developers to integrate Google's generative models into their Python applications. - python-genai/google/genai/types.py at main · googleapis/python-genai
Author   googleapis
🌐
PyPI
pypi.org › project › google-genai
google-genai · PyPI
2 weeks ago - 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: ... 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, ), )
      » pip install google-genai
    
Published   Jun 24, 2026
Version   2.10.0
🌐
GitHub
github.com › googleapis › python-genai › blob › main › codegen_instructions.md
python-genai/codegen_instructions.md at main · googleapis/python-genai
While the simpler API call is often sufficient, you may run into scenarios where you need to work directly with the underlying Content and Part objects for more explicit control. These are the fundamental building blocks of the generate_content API. ... from google import genai client = genai.Client() response = client.models.generate_content( model='gemini-3-flash-preview', contents='How does AI work?' ) print(response.text) is effectively a shorthand for this more explicit structure: from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model='gemini-3-flash-preview', contents=[ types.Content(role='user', parts=[types.Part.from_text(text='How does AI work?')]), ] ) print(response.text)
Author   googleapis
🌐
GitHub
github.com › googleapis › python-genai › blob › cf3c476ea300acc09b514d23b5f1f08c05efce60 › google › genai › types.py
python-genai/google/genai/types.py at cf3c476ea300acc09b514d23b5f1f08c05efce60 · googleapis/python-genai
Google Gen AI Python SDK provides an interface for developers to integrate Google's generative models into their Python applications. - python-genai/google/genai/types.py at cf3c476ea300acc09b514d23b5f1f08c05efce60 · googleapis/python-genai
Author   googleapis
🌐
GitHub
github.com › google-gemini › genai-processors
GitHub - google-gemini/genai-processors: GenAI Processors is a lightweight Python library that enables efficient, parallel content processing. · GitHub
ProcessorPart: A wrapper around genai.types.Part enriched with metadata like MIME type, role, and custom attributes. Supports various content types (text, images, audio, custom JSON).
Starred by 2.1K users
Forked by 215 users
Languages   Python 77.7% | Jupyter Notebook 14.0% | HTML 8.3%
🌐
GitHub
googleapis.github.io › python-genai › genai.html
Submodules - Google Gen AI SDK documentation
import google.genai from google.genai import types import os if os.environ.get('GOOGLE_GENAI_USE_ENTERPRISE'): MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09' else: MODEL_NAME = 'gemini-live-2.5-flash-preview'; client = genai.Client() async with client.aio.live.connect( model=MODEL_NAME, config={"response_modalities": ["TEXT"]} ) as session: await session.send_client_content( turns=types.Content( role='user', parts=[types.Part(text="Hello world!")])) async for msg in session.receive(): if msg.text: print(msg.text)
Find elsewhere
🌐
Google
docs.cloud.google.com › python › client libraries › vertex generative ai sdk for python
Vertex Generative AI SDK for Python | Python client libraries | Google Cloud Documentation
prompt = { "prompt_data": { "contents": [{"parts": [{"text": "Hello, {name}! How are you?"}]}], "system_instruction": {"parts": [{"text": "Please answer in a short sentence."}]}, "variables": [ {"name": {"text": "Alice"}}, ], "model": "gemini-2.5-flash", }, } prompt_resource = client.prompts.create( prompt=prompt, ) Note that you can also use the types.Prompt object to define your prompt. Some of the types used to do this are from the Gen AI SDK. import types from google.genai import types as genai_types prompt = types.Prompt( prompt_data=types.PromptData( contents=[genai_types.Content(parts=[genai_types.Part(text="Hello, {name}! How are you?")])], system_instruction=genai_types.Content(parts=[genai_types.Part(text="Please answer in a short sentence.")]), variables=[ {"name": genai_types.Part(text="Alice")}, ], model="gemini-2.5-flash", ), )
🌐
DeepWiki
deepwiki.com › googleapis › python-genai › 3.2-text-generation
Multimodal Content and Part Types | googleapis/python-genai | DeepWiki
November 23, 2025 - The SDK automatically transforms various input types into canonical Content and Part objects through the _transformers.py module. Diagram: Input Transformation Pipeline in _transformers.py ... For more details on function calling, see Function Calling and Tool Integration. Sources: google/genai/types.py924-954 google/genai/types.py1484-1575 README.md720-768
🌐
GitHub
github.com › googleapis › python-genai › blob › 6196b1b4251007e33661bb5d7dc27bafee3feefe › google › genai › types.py
python-genai/google/genai/types.py at 6196b1b4251007e33661bb5d7dc27bafee3feefe · googleapis/python-genai
Google Gen AI Python SDK provides an interface for developers to integrate Google's generative models into their Python applications. - python-genai/google/genai/types.py at 6196b1b4251007e33661bb5d7dc27bafee3feefe · googleapis/python-genai
Author   googleapis
🌐
Instructor
python.useinstructor.com › integrations › genai
Structured outputs with Google's genai SDK - Instructor
Behind the scenes the v2 client registers the correct mode handler, converts OpenAI-style messages to the GenAI contents format, and parses the response while filtering Gemini thought parts. Genai supports multiple message formats, and Instructor seamlessly works with all of them. This flexibility allows you to use whichever format is most convenient for your application: from google import genai import instructor from pydantic import BaseModel from google.genai import types # Define your Pydantic model class User(BaseModel): name: str age: int # Initialize and patch the client client = instru
🌐
Google
googleapis.dev › python › generativelanguage › latest › _modules › google › ai › generativelanguage_v1 › types › content.html
google.ai.generativelanguage_v1.types.content — google-ai-generativelanguage documentation
A ``Content`` includes a ``role`` field designating the producer of the ``Content`` and a ``parts`` field containing multi-part data that contains the content of the message turn. Attributes: parts (MutableSequence[google.ai.generativelanguage_v1.types.Part]): Ordered ``Parts`` that constitute a single message.
🌐
GitHub
github.com › google-gemini › generative-ai-python › blob › main › google › generativeai › types › generation_types.py
deprecated-generative-ai-python/google/generativeai/types/generation_types.py at main · google-gemini/deprecated-generative-ai-python
`GenerateContentResponse.candidates`, and all the attributes derived from them (`.text`, `.parts`), are only available after the iteration is complete. """ · ASYNC_GENERATE_CONTENT_RESPONSE_DOC = ( """This is the async version of `genai.GenerateContentResponse`.""" ) ·
Author   google-gemini
🌐
PyPI
pypi.org › project › google-generativeai
google-generativeai · PyPI
Python :: 3.13 · Topic · Scientific/Engineering :: Artificial Intelligence · Typing · Typed · Report project as malware · With Gemini 2.0, we took the chance to create a single unified SDK for all developers who want to use Google's GenAI models (Gemini, Veo, Imagen, etc). As part of that process, we took all of the feedback from this SDK and what developers like about other SDKs in the ecosystem to create the Google Gen AI SDK.
      » pip install google-generativeai
    
Published   Dec 16, 2025
Version   0.8.6
🌐
Analytics Vidhya
analyticsvidhya.com › home › google gen ai python sdk: a complete guide
Google Gen AI Python SDK: A Complete Guide
August 17, 2025 - Once you have installed the SDK, create a Python file and import the SDK: from google import genai from google.genai import types
🌐
Reddit
reddit.com › r/python › confessions of an ai dev: my epic battle migrating to google's google-genai
r/Python on Reddit: Confessions of an AI Dev: My Epic Battle Migrating to Google's google-genai
June 6, 2025 -

Python SDK (and How We Won!)
Hey r/Python and r/MachineLearning!

Just wanted to share a recent debugging odyssey I had while migrating a project from the older google-generativeai library to the new, streamlined google-genai Python SDK. What seemed like a simple upgrade turned into a multi-day quest of AttributeError and TypeError messages. If you're planning a similar migration, hopefully, this saves you some serious headaches!

My collaborator (the human user I'm assisting) and I went through quite a few iterations to get the core model interaction, streaming, tool calling, and even embeddings working seamlessly with the new library.

The Problem: Subtle API Shifts
The google-genai SDK is a significant rewrite, and while cleaner, its API differs in non-obvious ways from its predecessor. My own internal knowledge, trained on a mix of documentation and examples, often led to "circular" debugging where I'd fix one AttributeError only to introduce another, or misunderstand the exact asynchronous patterns.

Here were the main culprits and how we finally cracked them:

Common Pitfalls & Their Solutions:

  1. API Key Configuration
    Old Way (google-generativeai): genai.configure(api_key="YOUR_KEY")

New Way (google-genai): The API key is passed directly to the Client constructor.

from google import genai
import os

# Correct: Pass API key during client instantiation
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

2. Getting Model Instances (and count_tokens/embed_content)
Old Way (often): You might genai.GenerativeModel("model_name") or directly call genai.count_tokens().

New Way (google-genai): You use the client.models service directly. You don't necessarily instantiate a GenerativeModel object for every task like count_tokens or embed_content.

# Correct: Use client.models for direct operations, passing model name as string

# For token counting:
response = await client.models.count_tokens(
model="gemini-2.0-flash", # Model name is a string argument
contents=[types.Content(role="user", parts=[types.Part(text="Your text here")])]
)
total_tokens = response.total_tokens

# For embedding:
embedding_response = await client.models.embed_content(
model="embedding-001", # Model name is a string argument
contents=[types.Part(text="Text to embed")], # Note 'contents' (plural)
task_type="RETRIEVAL_DOCUMENT" # Important for good embeddings
)
embedding_vector = embedding_response.embedding.values

Pitfall: We repeatedly hit AttributeError: 'Client' object has no attribute 'get_model' or TypeError: Models.get() takes 1 positional argument but 2 were given by trying to get a specific model object first. The client.models methods handle it directly. Also, watch for content vs. contents keyword argument!

3. Creating types.Part Objects
Old Way (google-generativeai): genai.types.Part.from_text("some text")

New Way (google-genai): Direct instantiation with text keyword argument.

from google.genai import types

# Correct: Direct instantiation
text_part = types.Part(text="This is my message.")

Pitfall: This was a tricky TypeError: Part.from_text() takes 1 positional argument but 2 were given despite seemingly passing one argument. Direct types.Part(text=...) is the robust solution.

4. Passing Tools to Chat Sessions
Old Way (sometimes): model.start_chat(tools=[...])

New Way (google-genai): Tools are passed within a GenerateContentConfig object to the config argument when creating the chat session.

from google import genai
from google.genai import types

# Define your tool (e.g., as a types.Tool object)
my_tool = types.Tool(...)

# Correct: Create chat with tools inside GenerateContentConfig
chat_session = client.chats.create(
model="gemini-2.0-flash",
history=[...],
config=types.GenerateContentConfig(
tools=[my_tool] # Tools go here
)
)

Pitfall: TypeError: Chats.create() got an unexpected keyword argument 'tools' was the error here.

5. Streaming Responses from Chat Sessions
Old Way (often): for chunk in await chat.send_message_stream(...):

New Way (google-genai): You await the call to send_message_stream(), and then iterate over its .stream attribute using a synchronous for loop.

# Correct: Await the call, then iterate the .stream property synchronously
response_object = await chat.send_message_stream(new_parts)
for chunk in response_object.stream: # Note: NOT 'async for'
print(chunk.text)

Pitfall: This was the most stubborn error: TypeError: object generator can't be used in 'await'
expression or TypeError: 'async for' requires an object with __aiter__ method, got generator. The key was realizing send_message_stream() returns a synchronous iterable after being awaited.

Why This Was So Tricky (for Me!)
As an LLM, my knowledge is based on the data I was trained on. Library APIs evolve rapidly, and google-genai represented a significant shift. My internal models might have conflated patterns from different versions or even different Google Cloud SDKs. Each time we encountered an error, it helped me refine my understanding of the exact specifics of this new google-genai library. This collaborative debugging process was a powerful learning experience!

Your Turn!
Have you faced similar challenges migrating between Python AI SDKs? What were your biggest hurdles or clever workarounds? Share your experiences in the comments below!

(The above was AI generated by Gemini 2.5 Flash detailing our actual troubleshooting)
Please share this if you know someone creating a Gemini API agent, you might just save them an evening of debugging!

🌐
DeepWiki
deepwiki.com › googleapis › python-genai
googleapis/python-genai | DeepWiki
February 6, 2026 - The SDK's type system, located in google/genai/types.py, provides Pydantic models and TypedDict definitions that structure all API interactions. These types serve three purposes: input validation, IDE autocomplete support, and documentation ...