Skip to content

Connecting to Google Gemini Model Using Python

This guide explains how to connect to Googleโ€™s Gemini Model using Python, authenticate with an API key, and send requests to generate responses. We will cover API setup, authentication methods, and sample code for interacting with Gemini.


Before making API requests, check if you already have a Google AI API Key:

  1. Go to Google AI Studio.
  2. Navigate to API Keys in the left menu.
  3. If you have an existing key, copy it.
  4. If no key exists, proceed to the next step.

If you donโ€™t have an API key:

  1. Log in to Google AI Studio.
  2. Click โ€œGenerate API Keyโ€.
  3. Copy the generated key (it wonโ€™t be visible again).
  4. Store it securely in a .env file, environment variable, or directly in your Python script (if necessary).

๐Ÿ”น Step-by-Step: Connecting to Google Gemini Model

Section titled โ€œ๐Ÿ”น Step-by-Step: Connecting to Google Gemini Modelโ€

Ensure you have the google-generativeai package installed:

Terminal window
pip install google-generativeai python-dotenv

You can store the API key in two different ways:

Section titled โ€œOption 1: Use Environment Variables (Recommended for Security)โ€

Set your API key in your terminal:

Terminal window
export GEMINI_API_KEY="your-api-key-here" # Linux/macOS
set GEMINI_API_KEY="your-api-key-here" # Windows (CMD)
$env:GEMINI_API_KEY="your-api-key-here" # Windows (PowerShell)

Then, retrieve it in Python:

import os
api_key = os.getenv("GEMINI_API_KEY")

Create a .env file in your project folder and add:

GEMINI_API_KEY=your-api-key-here

Then load it in Python:

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("GEMINI_API_KEY")
Section titled โ€œOption 3: Set API Key Directly in Python File (Not Recommended for Production)โ€

If you donโ€™t want to use environment variables or a .env file, you can hardcode the API key in your script:

api_key = "your-api-key-here" # Hardcoded API Key (Avoid for security reasons)

โš  Warning: Hardcoding API keys in scripts is insecure and should be avoided in production.


3๏ธโƒฃ Write Python Code to Connect to Google Gemini Model

Section titled โ€œ3๏ธโƒฃ Write Python Code to Connect to Google Gemini Modelโ€

Create a Python file (gemini_chat.py) and add the following:

import google.generativeai as genai
import os
from dotenv import load_dotenv
# Load API Key
load_dotenv()
api_key = "Your GOOGLE_API_KEY" # Hardcoded API Key or use os.getenv("GOOGLE_API_KEY")
# Configure Google Gemini AI
genai.configure(api_key=api_key)
# Use `gemini-2.0-flash` model for faster responses
model_name = "gemini-2.0-flash"
# Function to interact with Gemini
def chat_with_gemini(user_question, temperature=0.7):
model = genai.GenerativeModel(model_name)
response = model.generate_content(user_question, generation_config={"temperature": temperature})
return response.text
# Example Usage
user_question = "Wahat is the capital of India?"
response = chat_with_gemini(user_question, temperature=0.7)
print("Gemini AI Response:", response)

Execute the Python script:

Terminal window
python gemini_chat.py

โœ… Expected Output:

Gemini AI Response: The capital of France is Paris.

The temperature parameter controls the randomness of the AIโ€™s responses:

  • Lower values (e.g., temperature=0.1) โ†’ More deterministic and factual responses.
  • Higher values (e.g., temperature=0.9) โ†’ More creative and diverse responses.

Example:

response = chat_with_gemini("Tell me a joke.", temperature=0.9)
print(response) # AI will generate a more creative joke

Use temperature values based on your needs: โœ… 0.1 - 0.3 โ†’ Best for factual and precise answers (e.g., finance, coding).
โœ… 0.4 - 0.7 โ†’ Balanced (general Q&A, business logic).
โœ… 0.8 - 1.0 โ†’ Best for creativity (storytelling, poetry, brainstorming).


You have successfully: โœ” Verified and generated a Google AI API key
โœ” Installed necessary dependencies
โœ” Written Python code to connect to Googleโ€™s Gemini Model
โœ” Sent user questions and received responses
โœ” Learned different ways to manage API keys (Environment Variable, .env file, Hardcoded - last one not recommended)
โœ” Understood how to use temperature to control response creativity

Now, you can build chatbots, AI-powered apps, and more using Googleโ€™s Gemini Model! ๐Ÿš€