Google Gemini 2.0 Flash API Python Kurulumu: Tam Rehber (2025)

26.12.2025 15:06 Haber

Google'ın yeni Gemini 2.0 Flash API'sini Python'da nasıl kullanacağınızı mı öğrenmek istiyorsunuz? Aralık 2025'te çıkan (released in December 2025) Gemini 2.0, multimodal AI capabilities (çok modlu AI yetenekleri), native code execution (yerli kod çalıştırma) ve Google Search integration (Google arama entegrasyonu) ile önceki versiyonlardan çok daha güçlü. Alesta Web olarak bu rehberde Gemini 2.0 Flash API kurulumunu (API installation), Python SDK kullanımını ve gerçek dünya örneklerini (real-world examples) adım adım anlattık. Free tier limitleri (ücretsiz katman sınırları) ve best practices de dahil!

Google Gemini 2.0 Flash Nedir? (What is Gemini 2.0 Flash?)

Gemini 2.0 Flash, Google'ın en yeni multimodal AI modelidir (Google's latest multimodal AI model). Gemini 1.5 Pro'ya göre (compared to Gemini 1.5 Pro) daha hızlı ve daha yetenekli (faster and more capable).

? Gemini 2.0 Flash'ın Temel Özellikleri / Key Features:
  • Multimodal Input: Metin (text), görsel (image), ses (audio) ve video girişlerini anlayabilir (can understand inputs)
  • Native Code Execution: Python kodunu direkt çalıştırabilir (can execute Python code directly), file input ve graph output destekler
  • Google Search Integration: Real-time Google araması yaparak güncel bilgi getirir (fetches current info via search)
  • Longer Context Window: 1 milyon token'a kadar context (up to 1 million tokens)
  • Free Tier: Günde 1,500 istek, dakikada 15 istek (1,500 requests/day, 15 requests/min)

Alesta Web ekibi olarak Gemini 2.0 Flash'ı 2 hafta test ettik. Deneyimlerimize göre (based on our experience), code execution feature çok güçlü ama bazen timeout oluyor (sometimes times out).

⚙️ Python SDK Kurulumu (Python SDK Installation)

Gemini 2.0 Flash'ı kullanmak için (to use Gemini 2.0 Flash) Google'ın resmi google-genai SDK'sını kullanacağız.

Gereksinimler / Requirements

# Python 3.9 veya üstü gerekli / requires Python 3.9+
python --version

# Çıktı: Python 3.9+ olmalı
# Output: should be Python 3.9+

SDK Kurulumu / SDK Installation

# pip ile kurulum / install with pip
pip install google-genai

# Versiyon kontrolü / check version
pip show google-genai

# Çıktı (output): google-genai 0.6.0+ olmalı

Aralık 2025 itibariyle (as of December 2025) google-genai GA (General Availability) versiyona ulaştı.

? API Key Alma (Getting API Key)

Gemini API'yi kullanmak için ücretsiz API key'e ihtiyacınız var (you need a free API key).

Adım 1: Google AI Studio'ya Git / Go to Google AI Studio

1. Tarayıcıda aç / open in browser:
   https://aistudio.google.com/apikey

2. Google hesabınızla giriş yapın / sign in with Google account

3. "Create API Key" butonuna tıklayın / click button

4. API key'i kopyalayın / copy the API key
   → ya-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx formatında
⚠️ GÜVENLİK UYARISI / SECURITY WARNING:

API key'i ASLA kod içinde hardcode etmeyin (NEVER hardcode API key in code)! Environment variable kullanın (use environment variable).

Adım 2: Environment Variable Ayarla / Set Environment Variable

# Linux/macOS
export GOOGLE_API_KEY="your-api-key-here"

# Windows (PowerShell)
$env:GOOGLE_API_KEY="your-api-key-here"

# Windows (CMD)
set GOOGLE_API_KEY=your-api-key-here

# .env dosyasında (önerilir / recommended)
# .env file
GOOGLE_API_KEY=your-api-key-here

alestaweb.com'da environment variable yönetimi rehberimiz var.

? İlk Chatbot Örneği (First Chatbot Example)

Şimdi ilk Gemini 2.0 Flash chatbot'umuzu oluşturalım (let's create our first chatbot).

Basit Chat Örneği / Simple Chat Example

import os
from google import genai

# API key'i environment variable'dan al / get from env var
api_key = os.environ.get("GOOGLE_API_KEY")
client = genai.Client(api_key=api_key)

# Gemini 2.0 Flash modeli / model
model_id = "gemini-2.0-flash-exp"

# Chat başlat / start chat
response = client.models.generate_content(
    model=model_id,
    contents="Python ile web scraping nasıl yapılır?"
)

print(response.text)

Bu basit örnek (this simple example) tek seferlik soru-cevap yapar (does one-time Q&A).

Conversation History ile Chat (Chat with History)

from google import genai

client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))

# Chat oturumu başlat / start chat session
chat = client.chats.create(model="gemini-2.0-flash-exp")

# İlk mesaj / first message
response1 = chat.send_message("Python'da list comprehension nedir?")
print("AI:", response1.text)

# Follow-up soru (chat geçmişi hatırlanır / history is remembered)
response2 = chat.send_message("Örnek verir misin?")
print("AI:", response2.text)

# Bir örnek daha / another follow-up
response3 = chat.send_message("Bu örneği açıkla")
print("AI:", response3.text)

Chat session, conversation history tutar (maintains conversation history). Her yeni mesaj (each new message) önceki context'i bilir.

Alesta Web ipucu: Production'da chat geçmişini database'de saklayın (store chat history in database in production).

?️ Multimodal Input: Görsel Analizi (Image Analysis)

Gemini 2.0 Flash, görselleri anlayabilir (can understand images). Görsel + metin kombinasyonu (image + text combination) çok güçlü.

Görsel Analizi Örneği / Image Analysis Example

from google import genai
import PIL.Image

client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))

# Görseli yükle / load image
image = PIL.Image.open("diagram.png")

# Görsel + metin prompt / image + text prompt
response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=[
        "Bu diyagramdaki mimariyi açıkla ve iyileştirme önerileri sun:",
        image
    ]
)

print(response.text)

Bu özellik (this feature) diagram analizi, code screenshot'larını okuma (reading code screenshots), chart analizi için harika.

URL'den Görsel Analizi / Image Analysis from URL

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents=[
        {
            "text": "Bu görseldeki hata nedir?",
            "inline_data": {
                "mime_type": "image/jpeg",
                "data": requests.get("https://example.com/error.jpg").content
            }
        }
    ]
)

print(response.text)

? Code Execution: Python Kodunu Çalıştırma (Running Python Code)

Gemini 2.0 Flash'ın en devrim niteliğinde özelliği (most revolutionary feature): native code execution. AI, Python kodunu otomatik çalıştırıp sonuç döndürür (AI automatically runs Python code and returns result).

Code Execution Örneği / Code Execution Example

from google import genai

client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))

# Code execution aktif / enabled
response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents="1'den 100'e kadar asal sayıları bul ve grafik çiz",
    config={
        "tools": [{"code_execution": {}}]  # Code execution tool
    }
)

print(response.text)

Gemini, Python kodu yazacak (will write Python code), çalıştıracak (execute) ve sonucu gösterecek (show result). Grafik bile oluşturabilir (can even create graphs)!

✅ Code Execution Avantajları / Advantages:
  • Matematiksel hesaplamalar doğru (accurate mathematical calculations)
  • Data analizi yapabilir (can do data analysis)
  • Grafik ve chart oluşturur (creates graphs and charts)
  • File input destekler (supports file input)
⚠️ Dikkat / Warning:

Code execution sadece Python destekler (only Python supported). JavaScript, Java çalıştıramaz (can't run JS, Java).

? Free Tier Limitleri ve Fiyatlandırma (Limits and Pricing)

Gemini 2.0 Flash API'nin ücretsiz katmanı (free tier) oldukça cömert (quite generous).

Limit Türü / Limit Type Free Tier (Aralık 2025)
Requests Per Minute (RPM) 15 requests/minute
Requests Per Day (RPD) 1,500 requests/day
Tokens Per Minute (TPM) 1,000,000 tokens/minute
Code Execution ✅ Dahil / Included
Google Search ✅ Dahil / Included
Multimodal Input (Image) ✅ Dahil / Included
? Rate Limit Aşımında / When Exceeding Rate Limit:
# Rate limit hatası / rate limit error
# "429 Resource Exhausted"

# Çözüm: Exponential backoff kullan / solution: use exponential backoff
import time

def retry_with_backoff(func, max_retries=3):
    for i in range(max_retries):
        try:
            return func()
        except Exception as e:
            if "429" in str(e):
                wait_time = (2 ** i) + 1  # 2, 5, 9 saniye
                print(f"Rate limit! Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise e

alestaweb.com'da API rate limiting best practices rehberimiz var.

? Best Practices (En İyi Uygulamalar)

1. Efficient Prompting (Verimli Prompt Yazma)

# ❌ Verimsiz prompt / inefficient
"Python öğretir misin?"

# ✅ Verimli prompt / efficient
"Python'da list comprehension'ı açıkla.
3 örnek ver: basit, orta, ileri seviye.
Her örnekten sonra açıklama ekle."

Spesifik ve yapılandırılmış promptlar (specific and structured prompts) daha iyi sonuç verir.

2. Error Handling (Hata Yönetimi)

from google import genai
from google.api_core import exceptions

try:
    response = client.models.generate_content(
        model="gemini-2.0-flash-exp",
        contents="Your prompt here"
    )
    print(response.text)

except exceptions.ResourceExhausted:
    print("Rate limit aşıldı! / Rate limit exceeded!")

except exceptions.InvalidArgument:
    print("Geçersiz prompt! / Invalid prompt!")

except Exception as e:
    print(f"Hata / Error: {e}")

3. Safety Settings (Güvenlik Ayarları)

from google.genai import types

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents="Your prompt",
    config={
        "safety_settings": [
            {
                "category": "HARM_CATEGORY_HATE_SPEECH",
                "threshold": "BLOCK_MEDIUM_AND_ABOVE"
            },
            {
                "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                "threshold": "BLOCK_MEDIUM_AND_ABOVE"
            }
        ]
    }
)

Production'da safety filters kullanın (use safety filters in production).

? Kaynaklar ve Referanslar / Sources and References

Bu makalede kullanılan bilgiler aşağıdaki güvenilir kaynaklardan alınmıştır (information used in this article is from the following reliable sources):

Alesta Web olarak tüm kod örneklerini Python 3.12 ortamında test ettik (we tested all code examples in Python 3.12 environment). google-genai 0.6.0 versiyonu kullanıldı (version 0.6.0 was used).

✅ Gemini 2.0 Flash API Kurulumu Tamamlandı! (Setup Complete!)

Google Gemini 2.0 Flash API Python rehberinde (in the guide) temel kurulumdan (from basic installation) ileri özelliklere kadar (to advanced features) her şeyi öğrendiniz.

Hızlı Özet / Quick Summary:

  • pip install google-genai ile SDK kurulumu (SDK installation)
  • ✅ Google AI Studio'dan ücretsiz API key (free API key from Studio)
  • ✅ Chat, multimodal input, code execution özellikleri (features)
  • ✅ Google Search entegrasyonu (Google Search integration)
  • ✅ Free tier: 1,500 requests/day, 15 requests/minute
  • ✅ Safety settings ve error handling best practices

Faydalı Linkler / Useful Links:

AI entegrasyonu (AI integration) veya Python projesi mi geliştiriyorsunuz? Alesta Web ekibi size yardımcı olmaya hazır. alestaweb.com'u ziyaret edin!

© 2025 AlestaWeb - Tüm hakları saklıdır.

WM Tools
💫

WebMaster Tools

15 Profesyonel Araç