Skip to content

Connecting to Google Gemini Model Using Python

πŸš€ 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.


πŸ”Ή Prerequisites

1️⃣ Check If You Have a Google AI API Key

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.

2️⃣ Generate a New API Key

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

1️⃣ Install Required Python Packages

Ensure you have the google-generativeai package installed:

Terminal window
pip install google-generativeai python-dotenv

2️⃣ Setting Up the API Key

You can store the API key in two different ways:

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

Option 2: Use a .env File

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

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

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)

4️⃣ Run the Script

Execute the Python script:

Terminal window
python gemini_chat.py

βœ… Expected Output:

Gemini AI Response: The capital of France is Paris.

πŸ”Ή Understanding the temperature Parameter

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


πŸš€ Conclusion

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! πŸš€


References: