Gemini API Python SDK Tutorial: Build AI Apps in 2025 | Google AI Guide

Why Gemini API?

Google's Gemini API provides cutting-edge AI capabilities for developers. This tutorial covers:

  • Setting up API credentials
  • Text generation fundamentals
  • Error handling best practices
  • Real-world use cases

1. Installation & Configuration

Prerequisites

# Install official SDK
pip install google-generativeai

API Key Setup

import google.generativeai as genai

# Configure with your API key
genai.configure(api_key='YOUR_API_KEY')

2. Text Generation Basics

Initialize Model

model = genai.GenerativeModel('gemini-pro')

Simple Generation

response = model.generate_content(
    "Explain Newton's third law to a 5 year old"
)
print(response.text)

Streaming Responses

response = model.generate_content(
    "Write a 500-word story about aliens",
    stream=True
)

for chunk in response:
    print(chunk.text, end='')

3. Advanced Implementations

Chat Conversations

chat = model.start_chat(history=[])

response = chat.send_message("Hi! I'm learning Python")
print(response.text)

response = chat.send_message("What's the best way to start?")
print(response.text)

Safety Settings

response = model.generate_content(
    "Controversial topic question...",
    safety_settings={
        'HARM_CATEGORY_HARASSMENT': 'BLOCK_ONLY_HIGH',
        'HARM_CATEGORY_DANGEROUS': 'BLOCK_MEDIUM_AND_ABOVE'
    }
)

4. Production-Ready Code

Error Handling

try:
    response = model.generate_content("Invalid prompt")
    print(response.text)
except genai.types.StopCandidateException as e:
    print(f"Safety violation: {e}")
except genai.GoogleAPIError as e:
    print(f"API error: {e}")

Rate Limiting

import time

def safe_generate(prompt):
    try:
        return model.generate_content(prompt)
    except genai.RateLimitError:
        time.sleep(60)
        return safe_generate(prompt)

5. Professional Tips

  • Use environment variables for API keys
  • Set temperature (0-1) for creativity control
  • Monitor usage in Google Cloud Console
  • Enable content safety filters in production

Next Steps

Explore advanced features:

  • Multimodal inputs (text + images)
  • Model fine-tuning
  • Batch processing

Official documentation: Google AI Developers


Category: Gemini

Trending
Latest Articles