Müşteri Hizmetleri Veri Çekme Dokümantasyonu

Google AI API ile Müşteri Hizmetleri Verisinin Çekilmesi Örneği

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ı (.env dosyası)
  • Gerekli Python paketleri: google-generativeai ve python-dotenv

Paket Kurulumu

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

pip install google-generativeai python-dotenv

Kullanılan Kütüphaneler

google-generativeai

Google AI API ile iletişim kurarak AI modellerine istek göndermenizi sağlar.

python-dotenv

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

json

JSON formatındaki verilerin okunması ve işlenmesi için kullanılan standart kütüphanedir.

os

Dosya ve yol işlemleri için Python'un yerleşik kütüphanesidir.

google.genai.types

API istek ve fonksiyon çağrısı yapılandırmaları için kullanılan veri tiplerini sağlar.

Adım Adım Kullanım

1

Ortam Değişkenlerini Yükleme & İstemci Oluşturma

load_dotenv() ile .env dosyasındaki API anahtarını yükleyin ve genai.Client ile API istemcisini oluşturun.

from google import genai
import os
from dotenv import load_dotenv

# Ortam değişkenlerini yükle
load_dotenv()
api_key = os.getenv("GOOGLE_AI_API_KEY")
client = genai.Client(api_key=api_key)
2

Müşteri Hizmetleri Verisini Çekme Fonksiyonu

take_a_look_at_the_customer_service_data() fonksiyonu, aynı dizindeki data.json dosyasından verileri okur.

import os
import json

def take_a_look_at_the_customer_service_data() -> dict:
    """
    Müşteri hizmetleri verisini data.json dosyasından okur.
    Returns:
        dict: Müşteri hizmetleri verileri.
    """
    script_dir = os.path.dirname(os.path.abspath(__file__))
    data_file_path = os.path.join(script_dir, "data.json")
    
    with open(data_file_path, "r") as file:
        data = json.load(file)
    return data
3

Fonksiyon Deklarasyonu ve API İsteği

types.FunctionDeclaration ile fonksiyonunuzu tanımlayın ve model isteğinizi yapılandırın.

from google.genai import types

customer_service_function_declaration = types.FunctionDeclaration(
    name="take_a_look_at_the_customer_service_data",
    description="Retrieves customer service data"
)

first_prompt = "Ürünümü iade etmek istiyorum. Nasıl yaparım?"
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=[customer_service_function_declaration]
        )],
        tool_config=types.ToolConfig(
            function_calling_config=types.FunctionCallingConfig(
                mode="any",
                allowed_function_names=["take_a_look_at_the_customer_service_data"]
            )
        ),
        automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=False)
    )
)
4

Fonksiyon Çağrısını İşleme ve Yanıt Oluşturma

API yanıtı içerisinde fonksiyon çağrısı var mı kontrol edin, varsa ilgili fonksiyonu çalıştırarak müşteri hizmetleri verisini alın ve final yanıtı oluşturun.

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

    if function_name == "take_a_look_at_the_customer_service_data":
        customer_service_data = take_a_look_at_the_customer_service_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=customer_service_data
                    ))],
                    role="function"
                )
            ]
        )
        print(f"Final response: {follow_up.text}")
else:
    print(f"Final response: {response.text}")

Kod Akışı

  1. Ortam Ayarları: .env dosyasından API anahtarı yüklenir ve API istemcisi oluşturulur.
  2. Veri Okuma: take_a_look_at_the_customer_service_data fonksiyonu, data.json dosyasından müşteri hizmetleri verisini okur.
  3. Fonksiyon Deklarasyonu: API isteğinde kullanılacak fonksiyon tanımlanır.
  4. API İsteği: Model, kullanıcı isteğini alır ve fonksiyon çağrısı yapılandırması ile isteği gönderir.
  5. Fonksiyon Çağrısı İşleme: Yanıttaki fonksiyon çağrısı tespit edilirse, ilgili fonksiyon çalıştırılır ve final yanıt oluşturulur.

Özet

Bu örnek, Google AI API kullanılarak müşteri hizmetleri verisinin nasıl çekileceğini gösterir. Kod, öncelikle API anahtarını yükleyip istemci oluşturur, ardından data.json dosyasından verileri okuyarak fonksiyon çağrısı yapılandırması ile modeli bilgilendirir. Eğer API yanıtı içerisinde fonksiyon çağrısı varsa, ilgili fonksiyon çalıştırılarak veriler elde edilir ve final yanıt oluşturulur.

Bu dokümantasyon, kodun her adımını açıklayarak daha iyi anlaşılmasını ve hızlı onboarding sürecini desteklemektedir.

Tam Kod

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

# 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 take_a_look_at_the_customer_service_data() -> dict:
    """
    Retrieves customer service data from the data.json file.
    
    Parameters:
        None
    
    Returns:
        dict: A dictionary with customer service data.
    """
    # Get the directory of the current script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # Create the absolute path to data.json
    data_file_path = os.path.join(script_dir, "data.json")
    
    with open(data_file_path, "r") as file:
        data = json.load(file)
    return data

customer_service_function_declaration = types.FunctionDeclaration(
    name="take_a_look_at_the_customer_service_data",
    description="Retrieves customer service data"
)

first_prompt = "Ürünümü iade etmek istiyorum. Nasıl yaparım?"
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=[customer_service_function_declaration]
        )],
        tool_config=types.ToolConfig(
            function_calling_config=types.FunctionCallingConfig(
                mode="any",
                allowed_function_names=["take_a_look_at_the_customer_service_data"]
            )
        ),
        automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=False)
    )
)

# Process the response and handle function calls
print("Response received from Gemini API")

# Check if there are function calls in the response
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 == "take_a_look_at_the_customer_service_data":
        customer_service_data = take_a_look_at_the_customer_service_data()
        print(f"Customer service data: {customer_service_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=customer_service_data
                    ))],
                    role="function"
                )
            ]
        )
        print(f"Final response: {follow_up.text}")
else:
    print(f"Final response: {response.text}")