To install from PyPI, run pip install google-generativeai. Obtain an API key from AI Studio, then configure it here.

Also, your import statement is wrong. You did import google.generative as genai but it should be import google.generativeai as genai. See PyPi.

Answer from Uchenna Adubasim on Stack Overflow
🌐
Google AI
ai.google.dev › gemini api › migrate to the google genai sdk
Migrate to the Google GenAI SDK | Gemini API | Google AI for Developers
April 28, 2026 - import { GoogleGenerativeAI } from "@google/generative-ai"; import { GoogleAIFileManager, GoogleAICacheManager } from "@google/generative-ai/server"; // For files/caching const genAI = new GoogleGenerativeAI("GEMINI_API_KEY"); const fileManager ...
Docs
We recommend using the Interactions API for all new projects. It is optimized for agentic workflows, state management, and the latest models. Learn more in the Interactions API Overview · The fastest path from prompt to production with Gemini, Veo, Nano Banana, and more
All models
Learn about all of Google's most advanced AI models
API keys
Get your Gemini API key and start building in less than 5 minutes using the Interactions API.
Pricing
Warning: Imagen 4 models (`imagen-4.0-generate-001`, `imagen-4.0-ultra-generate-001`, `imagen-4.0-fast-generate-001`) are deprecated and will be shut down on August 17, 2026; migrate to Gemini 2.5 Flash Image to avoid service disruption.
🌐
npm
npmjs.com › package › @google › genai
@google/genai - npm
1 week ago - For quicker, more responsive API interactions use the generateContentStream method which yields chunks as they're generated: import {GoogleGenAI} from '@google/genai'; const GEMINI_API_KEY = process.env.GEMINI_API_KEY; const ai = new ...
      » npm install @google/genai
    
Published   Jun 24, 2026
Version   2.10.0
Discussions

python - ModuleNotFoundError: No module named 'google.generative' - Stack Overflow
Traceback: File "C:\Users\lucifer\AppData\Roaming\Python\Python310\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 535, in _run_script exec(code, module.__dict__)... More on stackoverflow.com
🌐 stackoverflow.com
Import google.generativeai as genai
I am using this library in Python. I want this library to connect to AI through a proxy How should I set it up? I tried this: os.environ[‘HTTP_PROXY’] = ‘socks5://127.0.0.1:7890’ os.environ[‘HTTPS_PROXY’] = ‘socks5://127.0.0.1:7890’ But it didn’t work. More on discuss.ai.google.dev
🌐 discuss.ai.google.dev
2
0
January 22, 2025
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
PSA / Guide: How to Actually Use the $1000 "GenAI App Builder" Credit (It's NOT for the standard Gemini API)
Hope this helps everyone! It took me a while to figure this out. Let me know if you've had a similar experience or found any other workarounds for this credit More on reddit.com
🌐 r/googlecloud
26
122
June 17, 2025
🌐
PyPI
pypi.org › project › google-generativeai
google-generativeai · PyPI
Google Generative AI High level API client library and tools.
      » pip install google-generativeai
    
Published   Dec 16, 2025
Version   0.8.6
🌐
PyPI
pypi.org › project › google-genai
google-genai · PyPI
2 weeks ago - Capabilities and parameter defaults for each model is shown in the Vertex AI 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.5-flash', contents='high', config=types.GenerateContentConfig( system_instruction='I say high, you say low', max_output_tokens=3, temperature=0.3, ), ) print(response.text)
      » pip install google-genai
    
Published   Jun 24, 2026
Version   2.10.0
🌐
GitHub
github.com › mohitejaikumar › generative-ai-js
GitHub - mohitejaikumar/generative-ai-js: The official Node.js / Typescript library for the Google Gemini API · GitHub
... import { GoogleGenerativeAI } from "@google/generative-ai"; const genAI = new GoogleGenerativeAI(process.env.API_KEY); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
Author   mohitejaikumar
🌐
npm
npmjs.com › package › @google › generative-ai › v › 0.8.0
@google/generative-ai - npm
April 22, 2024 - For web, add import { GoogleGenerativeAI } from "https://esm.run/@google/generative-ai". For detailed instructions, you can find quickstarts for the Google AI JavaScript SDK in the Google documentation: Quickstart for Node.js ·
      » npm install @google/generative-ai
    
Published   Apr 29, 2025
Version   0.8.0
Find elsewhere
🌐
Google
docs.cloud.google.com › gemini enterprise agent platform › google gen ai sdk
Google Gen AI SDK | Gemini Enterprise Agent Platform | Google Cloud Documentation
from google import genai from google.genai.types import HttpOptions client = genai.Client(http_options=HttpOptions(api_version="v1")) response = client.models.generate_content( model="gemini-3.5-flash", contents="How does AI work?", ) print(response.text) # Example response: # Okay, let's break down how AI works.
🌐
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 - 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', )
Starred by 3.8K users
Forked by 929 users
Languages   Python
🌐
Google AI
ai.google.dev › gemini api › gemini api libraries
Gemini API libraries | Google AI for Developers
April 28, 2026 - Download and get started with the Gemini API Libraries + SDKs
🌐
Google AI
discuss.ai.google.dev › gemini api
Import google.generativeai as genai - Gemini API - Google AI Developers Forum
January 22, 2025 - I am using this library in Python. I want this library to connect to AI through a proxy How should I set it up? I tried this: os.environ[‘HTTP_PROXY’] = ‘socks5://127.0.0.1:7890’ os.environ[‘HTTPS_PROXY’] = ‘socks5://127.0.0.1:7890’ But it didn’t work.
🌐
GitHub
github.com › google-gemini › generative-ai-python › blob › main › docs › api › google › generativeai.md
deprecated-generative-ai-python/docs/api/google/generativeai.md at main · google-gemini/deprecated-generative-ai-python
Google AI Python SDK · pip install google-generativeai · Use genai.GenerativeModel to access the API: import google.generativeai as genai import os genai.configure(api_key=os.environ['API_KEY']) model = genai.GenerativeModel(model_name='g...
Author   google-gemini
🌐
GitHub
googleapis.github.io › python-genai
Google Gen AI SDK documentation
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() ... from google.genai import Client aclient = Client( vertexai=True, project='my-project-id', location='us-central1' ).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.
🌐
LangChain
python.langchain.com › api_reference › google_genai
langchain_google_genai | LangChain Reference
LangChain integration for Google's Generative AI models, providing access to Gemini models via both the Gemini Developer API and Vertex AI.
🌐
Medium
medium.com › google-cloud › migrating-to-the-new-google-gen-ai-sdk-python-074d583c2350
Migrating to the new Google Gen AI SDK (Python) | by Maciej Strzelczyk | Google Cloud - Community | Medium
July 24, 2025 - In the first generation libraries, almost everything was done through GenerativeModel class objects. Developers had to initiate a Model, providing model ID and a couple of configuration options like temperature, safety settings, tools etc. Those model objects were holding all this configuration and used it when communicating with the API. # Example of the old way... import google.generativeai as genai model = genai.GenerativeModel('gemini-1.5-flash') response = model.generate_content( 'Tell me a story in 300 words' ) print(response.text)
🌐
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!

🌐
DEV Community
dev.to › evanloria4 › nodes-googlegenerativeai-incorporating-ai-technology-in-javascript-5he9
Node's GoogleGenerativeAI: Incorporating AI Technology In javaScript - DEV Community
January 26, 2025 - ... Once you've accessed an API key you'll need to install the package with node. npm install @google/generative-ai Once you've done all this you're ready to start developing with AI!
🌐
Firebase
firebase.google.com › docs › genkit › plugins › google-genai
Google Generative AI plugin | Genkit
Sets the random seed for generation. Doesn’t guarantee determinism but improves consistency. ... Provides up to 3 reference images to guide the video’s content or style. ... Enable or disable the prompt rewriter. Enabled by default. For Veo 3.1/3.0, the prompt enhancer is always on. ... The Google AI plugin provides access to music and audio generation capabilities through the Lyria models.