Introduction
In this tutorial, you'll learn how to interact with Google's Gemini API using Python. This is a practical guide for beginners who want to understand how to access different Gemini models through code, especially considering the upcoming changes where free users will only get access to the smallest model. We'll walk through setting up your environment, authenticating with Google, and making API calls to different Gemini models.
Prerequisites
Before starting this tutorial, you'll need:
- A Google Cloud account with billing enabled
- Python 3.7 or higher installed on your computer
- Basic understanding of Python programming concepts
- Google Cloud project with the Gemini API enabled
Step-by-step Instructions
Step 1: Set Up Your Google Cloud Environment
The first step is to prepare your Google Cloud environment for using the Gemini API. This ensures you have the necessary permissions and access to make API calls.
1.1 Create a Google Cloud Project
If you don't already have a project, create one in the Google Cloud Console. This project will house all your API access and billing information.
1.2 Enable the Gemini API
Navigate to the API Library in the Google Cloud Console and search for "Gemini API". Click on it and enable it for your project. This step is crucial because without enabling the API, you won't be able to make any calls to Gemini.
1.3 Create a Service Account
In the Google Cloud Console, go to IAM & Admin > Service Accounts. Create a new service account and download the JSON key file. This key will be used to authenticate your Python application with Google Cloud.
Step 2: Install Required Python Packages
Now you need to install the Python libraries required to interact with Google's API. The google-generativeai package is the official Python client for Gemini.
pip install google-generativeai
This command installs the package that provides easy access to Google's Gemini models through Python. The package handles authentication and API communication for you.
Step 3: Configure Your Python Environment
Before making any API calls, you need to set up authentication in your Python script. This involves telling Python where to find your service account key file.
3.1 Set Environment Variable
Set the environment variable to point to your service account key file. You can do this in your terminal:
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/service-account-key.json"
This step is important because it tells the Python library where to find your authentication credentials. Without this, your requests will fail with authentication errors.
3.2 Verify Setup
Test your setup by creating a simple Python script:
import google.generativeai as genai
# This will raise an error if authentication fails
print("Gemini API setup successful")
Step 4: Create Your First Gemini API Call
Now you're ready to make your first API call to Gemini. This example will demonstrate how to use different models based on your subscription level.
4.1 Initialize the Model
Start by initializing a Gemini model. You can choose between different models depending on your access level:
import google.generativeai as genai
genai.configure(api_key="your-api-key-here")
# Initialize different models based on access level
flash_model = genai.GenerativeModel("gemini-1.5-flash")
pro_model = genai.GenerativeModel("gemini-1.5-pro")
flash_lite_model = genai.GenerativeModel("gemini-1.5-flash-8b")
Notice how we're initializing different models. The Flash-Lite model is the smallest and fastest, while the Pro model is more powerful but requires a subscription. This reflects the upcoming tier changes mentioned in the article.
4.2 Make a Simple Request
Now make a request to one of your models:
response = flash_model.generate_content("What is the capital of France?")
print(response.text)
This basic call will return the answer to your question. The Flash model will be faster but might provide less detailed responses compared to the Pro model.
Step 5: Handle Different Model Access Levels
Based on the article's news, you'll need to be aware of which models you can access. This section shows how to handle different access levels programmatically.
5.1 Check Model Availability
Before making calls to specific models, you should check if they're available to your account:
def check_model_access(model_name):
try:
model = genai.GenerativeModel(model_name)
# Try a simple test call
response = model.generate_content("Test")
return True
except Exception as e:
print(f"Model {model_name} not accessible: {e}")
return False
# Test different models
flash_available = check_model_access("gemini-1.5-flash")
pro_available = check_model_access("gemini-1.5-pro")
flash_lite_available = check_model_access("gemini-1.5-flash-8b")
This function checks whether you have access to specific models. If you're on a free plan, you might only have access to the Flash-Lite model, as mentioned in the article.
5.2 Use Appropriate Models Based on Access
Based on your access level, choose the appropriate model:
def get_appropriate_model():
if pro_available:
return genai.GenerativeModel("gemini-1.5-pro")
elif flash_available:
return genai.GenerativeModel("gemini-1.5-flash")
else:
return genai.GenerativeModel("gemini-1.5-flash-8b")
# Use the appropriate model
model = get_appropriate_model()
response = model.generate_content("Explain quantum computing in simple terms")
print(response.text)
This approach ensures your code works regardless of which models are available to you, reflecting the tiered access changes.
Step 6: Test Your Implementation
Finally, test your complete implementation with a practical example:
import google.generativeai as genai
class GeminiClient:
def __init__(self):
genai.configure(api_key="your-api-key-here")
self.models = {
'pro': genai.GenerativeModel('gemini-1.5-pro'),
'flash': genai.GenerativeModel('gemini-1.5-flash'),
'flash_lite': genai.GenerativeModel('gemini-1.5-flash-8b')
}
def query(self, prompt, model_type='flash_lite'):
try:
model = self.models[model_type]
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"Error: {e}"
# Test the client
client = GeminiClient()
print(client.query("What is machine learning?", 'flash_lite'))
This creates a reusable client class that can work with different models, making it easy to adapt your code as access levels change.
Summary
In this tutorial, you've learned how to set up and use Google's Gemini API with Python. You've seen how to configure authentication, make API calls to different models, and handle access level differences. As mentioned in the article, free users will soon only have access to the smallest model (Flash-Lite), while Pro features will be reserved for paying customers. This tutorial gives you the foundation to work with these different access levels in your code, ensuring your applications can adapt to these changes. Remember to keep your service account keys secure and to monitor your Google Cloud billing to avoid unexpected charges.