Gemini AI ile Fonksiyon Çağrısı: Hava Durumu Entegrasyonu

Google Gemini AI API kullanarak özel fonksiyonlar ile hava durumu verisi alma

Mikail Karadeniz tarafından yazılmıştır

Kurulum

Gereksinimler

Bu kodu çalıştırmak için aşağıdaki gereksinimlere ihtiyacınız vardır:

  • Python 3.7 veya üzeri
  • Google AI API anahtarı
  • Gerekli Python paketleri

Paket Kurulumu

Aşağıdaki komutu kullanarak gerekli paketleri yükleyin:

pip install google-generativeai python-dotenv requests

API Anahtarı Ayarları

Google AI API anahtarınızı bir env dosyasında saklayın:

# .env dosyası
GOOGLE_AI_API_KEY=your_api_key_here

Kullanılan Kütüphaneler

google-generativeai

Google'ın Gemini AI modellerine erişim sağlayan resmi Python kütüphanesi.

python-dotenv

Ortam değişkenlerini .env dosyasından yüklemek için kullanılır.

requests

HTTP istekleri yapmak için kullanılır, bu örnekte Open-Meteo API'sine istek göndermek için.

os

Python'un standart kütüphanesi, ortam değişkenlerine erişim için kullanılır.

Adım Adım Kullanım

1

Hava Durumu Fonksiyonunu Tanımlama

get_weather fonksiyonu, Open-Meteo API'sini kullanarak belirtilen koordinatlar için bugünün hava durumu verilerini alır.

def get_weather(latitude: float, longitude: float) -> dict:
    """Retrieves today's temperature data from the Open-Meteo API for the specified coordinates."""
    url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "Europe/Istanbul",
        "forecast_days": 1
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        date = data.get("daily", {}).get("time", [])[0]
        temp_max = data.get("daily", {}).get("temperature_2m_max", [])[0]
        temp_min = data.get("daily", {}).get("temperature_2m_min", [])[0]
        result = {
            "date": date,
            "max_temperature": temp_max,
            "min_temperature": temp_min
        }
        return result
    else:
        print("API request failed with status code:", response.status_code)
        return None
2

Fonksiyon Deklarasyonunu Oluşturma

weather_function_declaration, Gemini AI'nin get_weather fonksiyonunu tanıması için bir fonksiyon deklarasyonu oluşturur.

weather_function_declaration = types.FunctionDeclaration(
    name="get_weather",
    description="Retrieves today's temperature data for the specified coordinates",
    parameters={
        "type": "object",
        "properties": {
            "latitude": {"type": "number", "description": "The latitude of the location"},
            "longitude": {"type": "number", "description": "The longitude of the location"}
        },
        "required": ["latitude", "longitude"]
    }
)
3

API Anahtarını Yükleme ve İstemci Oluşturma

Ortam değişkenlerinden API anahtarını yükler ve Google AI API istemcisini oluşturur.

load_dotenv()
api_key = os.getenv("GOOGLE_AI_API_KEY")
client = genai.Client(api_key=api_key)
4

İlk Prompt ile Gemini AI'ye İstek Gönderme

"What is the weather in Konya?" promptu ile Gemini AI'ye istek gönderir.

first_prompt = "What is the weather in Konya?"
model_id = "gemini-2.0-flash"
response = client.models.generate_content(
    contents=[first_prompt],
    model=model_id,
    config=types.GenerateContentConfig(
        tools=[types.Tool(function_declarations=[weather_function_declaration])],
        tool_config=types.ToolConfig(
            function_calling_config=types.FunctionCallingConfig(mode="any", allowed_function_names=["get_weather"])
        ),
        automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=False)
    )
)
                    
5

Yanıtı İşleme ve Fonksiyon Çağrısını Kontrol Etme

Yanıtın bir fonksiyon çağrısı içerip içermediğini kontrol eder.

if hasattr(response.candidates[0].content.parts[0], 'function_call'):
    function_call = response.candidates[0].content.parts[0].function_call
    function_name = function_call.name
    function_args = function_call.args
    print(f"Function called: {function_name}")
    print(f"Arguments: {function_args}")
6

Fonksiyonu Çağırma ve Veriyi Alma

get_weather fonksiyonunu, Gemini AI'den alınan koordinatlarla çağırır.

if function_name == "get_weather":
    latitude = function_args.get("latitude")
    longitude = function_args.get("longitude")
    weather_data = get_weather(latitude, longitude)
    print(f"Weather data: {weather_data}")
7

Fonksiyon Yanıtını Gemini AI'ye Geri Gönderme

Alınan hava durumu verisini Gemini AI'ye geri gönderir ve son yanıtı alır.

follow_up = client.models.generate_content(
    model=model_id,
    contents=[
        types.Content(parts=[types.Part(text=first_prompt)], role="user"),
        types.Content(parts=[types.Part(function_call=function_call)], role="model"),
        types.Content(
            parts=[
                types.Part(
                    function_response=types.FunctionResponse(
                        name=function_name, 
                        response=weather_data
                    )
                )
            ], 
            role="function"
        )
    ]
)
print(f"Final response: {follow_up.text}")

Kod Akışı

  1. Kullanıcı, "What is the weather in Konya?" gibi bir soru sorar.
  2. Gemini AI, bu soruyu analiz eder ve get_weather fonksiyonunu çağırmaya karar verir.
  3. AI, fonksiyon için gerekli parametreleri (latitude, longitude) belirler.
  4. Script, get_weather fonksiyonunu bu parametrelerle çağırır ve hava durumu verisini alır.
  5. Alınan veriyi Gemini AI'ye geri gönderir.
  6. Gemini AI, bu veriyi kullanarak kullanıcıya bir yanıt üretir ve bunu ekrana yazdırır.

Özet

Bu kod, Google Gemini AI API'sini kullanarak özel bir fonksiyonun (get_weather) nasıl entegre edilebileceğini ve AI'nin bu fonksiyonu çağırarak dinamik verilerle nasıl etkileşime girebileceğini gösterir. Örnekte, Konya'nın hava durumu sorulduğunda, AI önce koordinatları belirler, ardından get_weather fonksiyonunu çağırarak gerçek zamanlı hava durumu verisini alır ve bu veriyi kullanarak kullanıcıya bir yanıt sunar.

Bu yaklaşım, AI modellerinin harici API'ler veya özel fonksiyonlarla entegre edilerek daha zengin ve dinamik yanıtlar üretmesini sağlar.

Tam Kod

from google import genai
from google.genai import types
import os
from dotenv import load_dotenv
import requests

# Load environment variables from .env file
load_dotenv()

# Get API key from environment variable
api_key = os.getenv("GOOGLE_AI_API_KEY")
client = genai.Client(api_key=api_key)

def get_weather(latitude: float, longitude: float) -> dict:
    """Retrieves today's temperature data from the Open-Meteo API for the specified coordinates."""
    url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "daily": "temperature_2m_max,temperature_2m_min",
        "timezone": "Europe/Istanbul",
        "forecast_days": 1
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        date = data.get("daily", {}).get("time", [])[0]
        temp_max = data.get("daily", {}).get("temperature_2m_max", [])[0]
        temp_min = data.get("daily", {}).get("temperature_2m_min", [])[0]
        result = {
            "date": date,
            "max_temperature": temp_max,
            "min_temperature": temp_min
        }
        return result
    else:
        print("API request failed with status code:", response.status_code)
        return None

weather_function_declaration = types.FunctionDeclaration(
    name="get_weather",
    description="Retrieves today's temperature data for the specified coordinates",
    parameters={
        "type": "object",
        "properties": {
            "latitude": {"type": "number", "description": "The latitude of the location"},
            "longitude": {"type": "number", "description": "The longitude of the location"}
        },
        "required": ["latitude", "longitude"]
    }
)

first_prompt = "What is the weather in Konya?"
model_id = "gemini-2.0-flash"
response = client.models.generate_content(
    contents=[first_prompt],
    model=model_id,
    config=types.GenerateContentConfig(
        tools=[types.Tool(function_declarations=[weather_function_declaration])],
        tool_config=types.ToolConfig(
            function_calling_config=types.FunctionCallingConfig(mode="any", allowed_function_names=["get_weather"])
        ),
        automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=False)
    )
)

if hasattr(response.candidates[0].content.parts[0], 'function_call'):
    function_call = response.candidates[0].content.parts[0].function_call
    function_name = function_call.name
    function_args = function_call.args
    print(f"Function called: {function_name}")
    print(f"Arguments: {function_args}")
    if function_name == "get_weather":
        latitude = function_args.get("latitude")
        longitude = function_args.get("longitude")
        weather_data = get_weather(latitude, longitude)
        print(f"Weather data: {weather_data}")
        follow_up = client.models.generate_content(
            model=model_id,
            contents=[
                types.Content(parts=[types.Part(text=first_prompt)], role="user"),
                types.Content(parts=[types.Part(function_call=function_call)], role="model"),
                types.Content(
                    parts=[
                        types.Part(
                            function_response=types.FunctionResponse(
                                name=function_name, 
                                response=weather_data
                            )
                        )
                    ], 
                    role="function"
                )
            ]
        )
        print(f"Final response: {follow_up.text}")
else:
    print(f"Text response: {response.text}")