Gemini API ile işlev çağırma

İşlev çağrısı, modelleri harici araçlara ve API'lere bağlamanıza olanak tanır. Model, metin yanıtları oluşturmak yerine belirli işlevlerin ne zaman çağrılacağını belirler ve gerçek dünyadaki işlemleri gerçekleştirmek için gerekli parametreleri sağlar. Bu sayede model, doğal dil ile gerçek dünyadaki işlemler ve veriler arasında köprü görevi görebilir. İşlev çağrısının 3 temel kullanım alanı vardır:

  • Bilgiyi Artırma: Veritabanları, API'ler ve bilgi tabanları gibi harici kaynaklardaki bilgilere erişin.
  • Özellikleri genişletme: Hesaplamalar yapmak ve modelin sınırlamalarını genişletmek için harici araçlar kullanın (ör. hesap makinesi kullanma veya grafik oluşturma).
  • İşlem Yapma: API'leri kullanarak harici sistemlerle etkileşim kurun. Örneğin, randevu planlayın, fatura oluşturun, e-posta gönderin veya akıllı ev cihazlarını kontrol edin.

İşlev çağrısının işleyiş şekli

işlev çağırmaya genel bakış

İşlev çağrısı, uygulamanız, model ve harici işlevler arasında yapılandırılmış bir etkileşimdir. Süreçle ilgili ayrıntılı bilgileri aşağıda bulabilirsiniz:

  1. İşlev Bildirimini Tanımlayın: İşlev bildirimini uygulama kodunuzda tanımlayın. İşlev Bildirimleri, işlevin adını, parametrelerini ve amacını modele açıklar.
  2. İşlev bildirimleriyle LLM'yi çağırma: Kullanıcı istemini, işlev bildirimiyle birlikte modele gönderin. İsteği analiz eder ve bir işlev çağrısının faydalı olup olmayacağını belirler. Bu durumda, yapılandırılmış bir JSON nesnesiyle yanıt verir.
  3. İşlev Kodunu Yürütme (Sizin Sorumluluğunuz): Model, işlevi yürütmez. Yanıtı işlemek ve işlev çağrısı olup olmadığını kontrol etmek uygulamanızın sorumluluğundadır.
    • Evet: İşlevin adını ve bağımsız değişkenlerini çıkarın ve uygulamanızda ilgili işlevi yürütün.
    • Hayır: Model, isteme doğrudan metin yanıtı vermiş (bu akış, örnekte daha az vurgulanmıştır ancak olası bir sonuçtur).
  4. Kullanıcı dostu yanıt oluşturma: Bir işlev yürütüldüyse sonucu yakalayın ve konuşmanın sonraki dönüşünde modele geri gönderin. Gemini, işlev çağrısından gelen bilgileri içeren son ve kullanıcı dostu bir yanıt oluşturmak için sonucu kullanır.

Bu süreç birden fazla kez tekrarlanabilir ve karmaşık etkileşimlere ve iş akışlarına olanak tanır. Model, tek bir dönüşte (paralel işlev çağrısı) ve sırayla (bileşik işlev çağrısı) birden fazla işlev çağrısını da destekler.

1. adım: Bir işlev bildirimi tanımlayın

Uygulama kodunuzda, kullanıcıların ışık değerlerini ayarlamasına ve API isteğinde bulunmasına olanak tanıyan bir işlev ve işlev bildirimi tanımlayın. Bu işlev, harici hizmetleri veya API'leri çağırabilir.

Python

# Define a function that the model can call to control smart lights
set_light_values_declaration = {
    "name": "set_light_values",
    "description": "Sets the brightness and color temperature of a light.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
    """Set the brightness and color temperature of a room light. (mock API).

    Args:
        brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
        color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.

    Returns:
        A dictionary containing the set brightness and color temperature.
    """
    return {"brightness": brightness, "colorTemperature": color_temp}

JavaScript

import { Type } from '@google/genai';

// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
  name: 'set_light_values',
  description: 'Sets the brightness and color temperature of a light.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
      },
      color_temp: {
        type: Type.STRING,
        enum: ['daylight', 'cool', 'warm'],
        description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
      },
    },
    required: ['brightness', 'color_temp'],
  },
};

/**

*   Set the brightness and color temperature of a room light. (mock API)
*   @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
*   @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
*   @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
  return {
    brightness: brightness,
    colorTemperature: color_temp
  };
}

2. adım: İşlev beyanlarıyla modeli çağırın

İşlev bildirimlerinizi tanımladıktan sonra, modelden bunları kullanmasını isteyebilirsiniz. İstem ve işlev bildirimlerini analiz eder ve doğrudan yanıt vermeye mi yoksa bir işlevi çağırmaya mı karar verir. Bir işlev çağrılırsa yanıt nesnesi, işlev çağrısı önerisi içerir.

Python

from google.genai import types

# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])

# Define user prompt
contents = [
    types.Content(
        role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
    )
]

# Send request with function declarations
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=contents
    config=config,
)

print(response.candidates[0].content.parts[0].function_call)

JavaScript

import { GoogleGenAI } from '@google/genai';

// Generation config with function declaration
const config = {
  tools: [{
    functionDeclarations: [setLightValuesFunctionDeclaration]
  }]
};

// Configure the client
const ai = new GoogleGenAI({});

// Define user prompt
const contents = [
  {
    role: 'user',
    parts: [{ text: 'Turn the lights down to a romantic level' }]
  }
];

// Send request with function declarations
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: contents,
  config: config
});

console.log(response.functionCalls[0]);

Model daha sonra, kullanıcının sorusuna yanıt vermek için bildirilen işlevlerden bir veya daha fazlasının nasıl çağrılacağını belirten, OpenAPI uyumlu bir şemada functionCall nesnesi döndürür.

Python

id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'

JavaScript

{
  name: 'set_light_values',
  args: { brightness: 25, color_temp: 'warm' }
}

3. adım: set_light_values işlev kodunu yürütün

İşlev çağrısı ayrıntılarını modelin yanıtından çıkarın, bağımsız değişkenleri ayrıştırın ve set_light_values işlevini yürütün.

Python

# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call

if tool_call.name == "set_light_values":
    result = set_light_values(**tool_call.args)
    print(f"Function execution result: {result}")

JavaScript

// Extract tool call details
const tool_call = response.functionCalls[0]

let result;
if (tool_call.name === 'set_light_values') {
  result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
  console.log(`Function execution result: ${JSON.stringify(result)}`);
}

4. adım: İşlev sonucuyla kullanıcı dostu bir yanıt oluşturun ve modeli tekrar çağırın

Son olarak, işlev yürütme sonucunu modele geri gönderin. Böylece model, bu bilgiyi kullanıcıya verdiği nihai yanıta dahil edebilir.

Python

# Create a function response part
function_response_part = types.Part.from_function_response(
    name=tool_call.name,
    response={"result": result},
)

# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

final_response = client.models.generate_content(
    model="gemini-2.5-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

JavaScript

// Create a function response part
const function_response_part = {
  name: tool_call.name,
  response: { result }
}

// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });

// Get the final response from the model
const final_response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

Böylece işlev çağrısı akışı tamamlanır. Model, kullanıcının istek işlemini gerçekleştirmek için set_light_values işlevini başarıyla kullandı.

İşlev beyanları

Bir istemde işlev çağrısını uyguladığınızda, bir veya daha fazla function declarations içeren bir tools nesnesi oluşturursunuz. İşlevleri, OpenAPI şema biçiminin alt kümesini seç kullanarak JSON ile tanımlarsınız. Tek bir işlev bildirimi aşağıdaki parametreleri içerebilir:

  • name (dize): İşlev için benzersiz bir ad (get_weather_forecast, send_email). Boşluk veya özel karakter içermeyen açıklayıcı adlar kullanın (alt çizgi veya camelCase kullanın).
  • description (dize): İşlevin amacının ve özelliklerinin net ve ayrıntılı açıklaması. Bu, modelin işlevi ne zaman kullanacağını anlaması için çok önemlidir. Net olun ve gerekirse örnekler verin ("Konuma ve isteğe bağlı olarak şu anda sinemalarda gösterilen film başlığına göre sinemaları bulur.").
  • parameters (nesne): İşlevin beklediği giriş parametrelerini tanımlar.
    • type (dize): Genel veri türünü belirtir (ör. object).
    • properties (nesne): Her biri şu öğeleri içeren ayrı parametreleri listeler:
      • type (dize): Parametrenin veri türü (ör. string, integer, boolean, array).
      • description (dize): Parametrenin amacı ve biçimiyle ilgili açıklama. Örnekler ve kısıtlamalar sağlayın ("Şehir ve eyalet, ör. "San Francisco, CA" veya posta kodu (ör. '95616'.").
      • enum (dizi, isteğe bağlı): Parametre değerleri sabit bir kümeden geliyorsa izin verilen değerleri yalnızca açıklamada belirtmek yerine listelemek için "enum" özelliğini kullanın. Bu, doğruluğu artırır ("enum": ["daylight", "cool", "warm"]).
    • required (dizi): İşlevin çalışması için zorunlu olan parametre adlarını listeleyen bir dizidir.

Düşünerek işlev çağırma

"Düşünme" özelliğini etkinleştirmek, modelin işlev çağrıları önermeden önce isteği değerlendirmesine olanak tanıyarak işlev çağrısı performansını artırabilir.

Ancak Gemini API durum bilgisi içermediğinden bu akıl yürütme bağlamı dönüşler arasında kaybolur. Bu durum, birden fazla dönüş isteği gerektiren işlev çağrılarının kalitesini düşürebilir.

Bu bağlamı korumak için düşünce imzalarını kullanabilirsiniz. Düşünce imzası, modelin dahili düşünce sürecinin şifrelenmiş bir gösterimidir. Bu gösterimi, sonraki dönüşlerde modele geri iletirsiniz.

Düşünce imzalarını kullanmak için:

  1. İmzayı alma: Düşünme özelliği etkinleştirildiğinde API yanıtı, modelin muhakemesinin şifrelenmiş bir gösterimini içeren bir thought_signature alanı içerir.
  2. İmzayı döndürme: İşlevin yürütme sonucunu sunucuya geri gönderdiğinizde aldığınız thought_signature'ı ekleyin.

Bu sayede model, önceki düşünce bağlamını geri yükleyebilir ve daha iyi işlev çağrısı performansı elde edilebilir.

Sunucudan imza alma

İmzalar, modelin düşünme aşamasından sonraki bölümde döndürülür. Bu bölüm genellikle bir metin veya işlev çağrısıdır.

Aşağıda, Get Weather örneği kullanılarak "Tahoe Gölü'nde hava nasıl?" isteğine yanıt olarak her tür bölümden döndürülen düşünce imzalarının nasıl göründüğüne dair bazı örnekler verilmiştir:

Metin bölümü

[{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Here's what the weather in Lake Tahoe is today",
            "thoughtSignature": "ClcBVKhc7ru7KzUI7SrdUoIdAYLm/+i93aHjfIt4xHyAoO/G70tApxnK2ujBhOhC1PrRy1pkQa88fqFvpHNVd1HDjNLO7mkp6/hFwE+SPPEB3fh0hs4oM8MKhgIBVKhc7uIGvrS7i/T4HpfbnYrluFfWNjZ62gewqe4cVdR/Dlh+zbjtYmDD0gPZ+SuBO7vvHQdzsjePRP+2Y5XddX6LEf/cGGgakq8EhVvw/a6IVzUO6XmpHg2Ag1sl8E9+VFH/lC0R0ZuYdFWligtDuYwp5p5q3o59G0TtWeU2MC1y2MJfE9u/KWd313ldka80/X2W/xF2O/4djMp5G2WKcULfve75zeRCy0mc5iS3SB9mTH0cT6x0vtKjeBx50gcg+CQWtJcRuwTVzz54dmvmK9xvnqA8gKGw3DuaM9wfy5hyY7Qg0z3iyyWdP8T/lbjKim8IEQOk7O1vVwP1Ko7oMYH8JgA1CsoBAVSoXO6v4c5RSyd1cn6EIU0pEFQsjW7rYWPuZdOFq/tsGJT9BCfW7KGkPGwlNSq8jTJFvbcJ/DjtndISQYXwiXd2kGa5JfdS2Kh4zOxCxiWtOk+2nCc3+XQk2nonhO+esGJpkDdbbHZSqRgcUtYKq7q28iPFOQvOFyCiZNB7K86Z/6Hnagu2snSlN/BcTMaFGaWpcCClSUo4foRZn3WbNCoM8rcpD7qEJMp4a5baaSxyyeL1ZTGd2HLpFys/oiW6e3oAnhxuIysCwg=="
          }
        ],
        "role": "model"
      },
      "index": 0
    }
  ],
  # Remainder of response...

İşlev çağrısı bölümü

[{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "functionCall": {
              "name": "getWeather",
              "args": {
                "city": "Lake Tahoe"
              }
            },
            "thoughtSignature": "CiwBVKhc7nRyTi3HmggPD9iQiRc261f5jwuMdw3H/itDH0emsb9ZVo3Nwx9p6wpsAVSoXO5i8fDV4jBSBLoaWxB5zUdlGY6aIGp+I0oEnwRRSRQ1LOvrDlojEH8JE8HjiKXALdJrvNPiG+HY3GZEO8pZjEZtc3UoBUh7+SVyjK7Xolu7aRYYeUyzrCapoETWypER1jbrJXnFV23hCosBAVSoXO6oIPNJSmbuEDfGafOhuCSHkpr1yjTp35RXYqmCESzRzWf5+nFXLqncqeFo4ohoxbiYQVpVQbOZF81p8o9zg6xeRE7qMeOv+XN7enXGJ4/s3qNFQpfkSMqRdBITN1VpX7jyfEAjvxBNc7PDfDJZmEPY338ZIY5nFFcmzJSWjVrboFt2sMFv+A=="
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  # Remainder of response...

Aşağıdaki kodu kullanarak imza aldığınızı onaylayabilir ve imzanın nasıl göründüğünü görebilirsiniz:

# Step 2: Call the model with function declarations
# ...Generation config, Configure the client, and Define user prompt (No changes)

# Send request with declarations (using a thinking model)
response = client.models.generate_content(
  model="gemini-2.5-flash", config=config, contents=contents)

# See thought signatures
for part in response.candidates[0].content.parts:
  if part.thought_signature:
    print("Thought signature:")
    print(part.thought_signature)

İmzaları sunucuya geri gönderme

İmzaları geri yüklemek için:

  • İçeren kısımlarıyla birlikte imzaları sunucuya geri göndermeniz gerekir.
  • İmzalı bir bölümü, imza içeren başka bir bölümle birleştirmemelisiniz. İmza dizesi birleştirilemiyor
  • İmzalı bir bölümü imzasız başka bir bölümle birleştirmemelisiniz. Bu, imza ile gösterilen düşüncenin doğru konumunu bozar.

İşlev yürütme sonucuyla birlikte imzaları modele döndürmek için yukarıdaki 4. Adım'ı ayarlamanız gerekir. Böylece model, düşünceleri nihai yanıtına dahil edebilir:

Python

# Step 4: Create user friendly response with function result and call the model again
# ...Create a function response part (No change)

# Append thought signatures, function call and result of the function execution to contents
function_call_content = response.candidates[0].content
# Append the model's function call message, which includes thought signatures
contents.append(function_call_content)
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response

final_response = client.models.generate_content(
    model="gemini-2.5-flash",
    config=config,
    contents=contents,
)

print(final_response.text)

JavaScript

// Step 4: Create user friendly response with function result and call the model again
// ...Create a function response part (No change)

// Append thought signatures, function call and result of the function execution to contents
const function_response_content = response.candidates[0].content;
contents.push(function_response_content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });

const final_response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: contents,
  config: config
});

console.log(final_response.text);

Aşağıda, düşünce imzası döndüren bir isteğin nasıl görünebileceği gösterilmektedir:

[{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "what is the weather in Lake Tahoe?"
        }
      ]
    },
    {
      "parts": [
        {
          "functionCall": {
            "name": "getWeather",
            "args": {
              "city": "Lake Tahoe"
            }
          },
          "thoughtSignature": "CiIBVKhc7oDPpCaXyJKKssjqr4g3JNOSgJ/M2V+1THC1icsWCmwBVKhc7pBABbZ+zR3e9234WnWWS6GFXmf8IVwpnzjd5KYd7vyJbn/4vTorWBGayj/vbd9JPaZQjxdAIXhoE5mX/MDsQ7M9N/b0qJjHm39tYIBvS4sIWkMDHqTJqXGLzhhKtrTkfbV3RbaJEkQKmwEBVKhc7qVUgC3hfTXZLo9R3AJzUUIx50NKvJTb9B+UU+LBqgg7Nck1x5OpjWVS2R+SsveprIuYOruk2Y0H53J2OJF8qsxTdIq2si8DGW2V7WK8xyoJH5kbqd7drIw1jLb44b6lx4SMyB0VaULuTBki4d+Ljjg1tJTwR0IYMKqDLDZt9mheINsi0ZxcNjfpnDydRXdWbcSwzmK/wgqJAQFUqFzuKgNVElxs3cbO+xebr2IwcOro84nKTisi0tTp9bICPC9fTUhn3L+rvQWA+d3J1Za8at2bakrqiRj7BTh+CVO9fWQMAEQAs3ni0Z2hfaYG92tOD26E4IoZwyYEoWbfNudpH1fr5tEkyqnEGtWIh7H+XoZQ2DXeiOa+br7Zk88SrNE+trJMCogBAVSoXO5e9fBLg7hnbkmKsrzNLnQtLsQm1gNzjcjEC7nJYklYPp0KI2uGBE1PkM8XNsfllAfHVn7LzHcHNlbQ9pJ7QZTSIeG42goS971r5wNZwxaXwCTphClQh826eqJWo6A/28TtAVQWLhTx5ekbP7qb4nh1UblESZ1saxDQAEo4OKPbDzx5BgqKAQFUqFzuVyjNm5i0wN8hTDnKjfpDroEpPPTs531iFy9BOX+xDCdGHy8D+osFpaoBq6TFekQQbz4hIoUR1YEcP4zI80/cNimEeb9IcFxZTTxiNrbhbbcv0969DSMWhB+ZEqIz4vuw4GLe/xcUvqhlChQwFdgIbdOQHSHpatn5uDlktnP/bi26nKuXIwo0AVSoXO7US22OUH7d1f4abNPI0IyAvhqkPp12rbtWLx9vkOtojE8IP+xCfYtIFuZIzRNZqA=="
        }
      ],
      "role": "model"
    },
    {
      "role": "user",
      "parts": [
        {
          "functionResponse": {
            "name": "getWeather",
            "response": {
              "response": {
                "stringValue": "Sunny and hot. 90 degrees Fahrenheit"
              }
            }
          }
        }
      ]
    }
  ],
  # Remainder of request...

Düşünce imzalarının sınırlamaları ve kullanımı ile düşünce modelleri hakkında daha fazla bilgi edinmek için Düşünme sayfasını ziyaret edin.

Paralel işlev çağırma

Tek dönüşlü işlev çağrısının yanı sıra birden fazla işlevi aynı anda da çağırabilirsiniz. Paralel işlev çağrısı, birden fazla işlevi aynı anda yürütmenize olanak tanır ve işlevler birbirine bağlı olmadığında kullanılır. Bu özellik, birden fazla bağımsız kaynaktan veri toplama (ör. farklı veritabanlarından müşteri ayrıntılarını alma veya çeşitli depolardaki envanter seviyelerini kontrol etme) ya da dairenizi diskoya dönüştürme gibi birden fazla işlem gerçekleştirme gibi senaryolarda kullanışlıdır.

Python

power_disco_ball = {
    "name": "power_disco_ball",
    "description": "Powers the spinning disco ball.",
    "parameters": {
        "type": "object",
        "properties": {
            "power": {
                "type": "boolean",
                "description": "Whether to turn the disco ball on or off.",
            }
        },
        "required": ["power"],
    },
}

start_music = {
    "name": "start_music",
    "description": "Play some music matching the specified parameters.",
    "parameters": {
        "type": "object",
        "properties": {
            "energetic": {
                "type": "boolean",
                "description": "Whether the music is energetic or not.",
            },
            "loud": {
                "type": "boolean",
                "description": "Whether the music is loud or not.",
            },
        },
        "required": ["energetic", "loud"],
    },
}

dim_lights = {
    "name": "dim_lights",
    "description": "Dim the lights.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "number",
                "description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
            }
        },
        "required": ["brightness"],
    },
}

JavaScript

import { Type } from '@google/genai';

const powerDiscoBall = {
  name: 'power_disco_ball',
  description: 'Powers the spinning disco ball.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      power: {
        type: Type.BOOLEAN,
        description: 'Whether to turn the disco ball on or off.'
      }
    },
    required: ['power']
  }
};

const startMusic = {
  name: 'start_music',
  description: 'Play some music matching the specified parameters.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      energetic: {
        type: Type.BOOLEAN,
        description: 'Whether the music is energetic or not.'
      },
      loud: {
        type: Type.BOOLEAN,
        description: 'Whether the music is loud or not.'
      }
    },
    required: ['energetic', 'loud']
  }
};

const dimLights = {
  name: 'dim_lights',
  description: 'Dim the lights.',
  parameters: {
    type: Type.OBJECT,
    properties: {
      brightness: {
        type: Type.NUMBER,
        description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
      }
    },
    required: ['brightness']
  }
};

Belirtilen tüm araçların kullanılmasına izin vermek için işlev çağırma modunu yapılandırın. Daha fazla bilgi edinmek için işlev çağrısını yapılandırma hakkında bilgi edinebilirsiniz.

Python

from google import genai
from google.genai import types

# Configure the client and tools
client = genai.Client()
house_tools = [
    types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
    tools=house_tools,
    automatic_function_calling=types.AutomaticFunctionCallingConfig(
        disable=True
    ),
    # Force the model to call 'any' function, instead of chatting.
    tool_config=types.ToolConfig(
        function_calling_config=types.FunctionCallingConfig(mode='ANY')
    ),
)

chat = client.chats.create(model="gemini-2.5-flash", config=config)
response = chat.send_message("Turn this place into a party!")

# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
    args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
    print(f"{fn.name}({args})")

JavaScript

import { GoogleGenAI } from '@google/genai';

// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];

const config = {
    tools: [{
        functionDeclarations: houseFns
    }],
    // Force the model to call 'any' function, instead of chatting.
    toolConfig: {
        functionCallingConfig: {
            mode: 'any'
        }
    }
};

// Configure the client
const ai = new GoogleGenAI({});

// Create a chat session
const chat = ai.chats.create({
    model: 'gemini-2.5-flash',
    config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});

// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
    const args = Object.entries(fn.args)
        .map(([key, val]) => `${key}=${val}`)
        .join(', ');
    console.log(`${fn.name}(${args})`);
}

Yazdırılan sonuçların her biri, modelin istediği tek bir işlev çağrısını yansıtır. Sonuçları geri göndermek için yanıtları, istendikleri sırayla ekleyin.

Python SDK, otomatik işlev çağrısını destekler. Bu işlev, Python işlevlerini otomatik olarak bildirimlere dönüştürür, işlev çağrısı yürütme ve yanıt döngüsünü sizin için yönetir. Aşağıda, disko kullanım alanıyla ilgili bir örnek verilmiştir.

Python

from google import genai
from google.genai import types

# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
    """Powers the spinning disco ball.

    Args:
        power: Whether to turn the disco ball on or off.

    Returns:
        A status dictionary indicating the current state.
    """
    return {"status": f"Disco ball powered {'on' if power else 'off'}"}

def start_music_impl(energetic: bool, loud: bool) -> dict:
    """Play some music matching the specified parameters.

    Args:
        energetic: Whether the music is energetic or not.
        loud: Whether the music is loud or not.

    Returns:
        A dictionary containing the music settings.
    """
    music_type = "energetic" if energetic else "chill"
    volume = "loud" if loud else "quiet"
    return {"music_type": music_type, "volume": volume}

def dim_lights_impl(brightness: float) -> dict:
    """Dim the lights.

    Args:
        brightness: The brightness of the lights, 0.0 is off, 1.0 is full.

    Returns:
        A dictionary containing the new brightness setting.
    """
    return {"brightness": brightness}

# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Do everything you need to this place into party!",
    config=config,
)

print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!

Bileşik işlev çağırma

Gemini, kompozisyonel veya sıralı işlev çağrısı sayesinde karmaşık bir isteği yerine getirmek için birden fazla işlev çağrısını birlikte kullanabilir. Örneğin, "Bulunduğum konumdaki sıcaklığı öğren" sorusunu yanıtlamak için Gemini API önce bir get_current_location() işlevini, ardından konumu parametre olarak alan bir get_weather() işlevini çağırabilir.

Aşağıdaki örnekte, Python SDK ve otomatik işlev çağrısı kullanılarak kompozisyon işlevi çağrısının nasıl uygulanacağı gösterilmektedir.

Python

Bu örnekte, google-genai Python SDK'sının otomatik işlev çağrısı özelliği kullanılmaktadır. SDK, Python işlevlerini otomatik olarak gerekli şemaya dönüştürür, işlev çağrılarını model tarafından istendiğinde yürütür ve görevi tamamlamak için sonuçları modele geri gönderir.

import os
from google import genai
from google.genai import types

# Example Functions
def get_weather_forecast(location: str) -> dict:
    """Gets the current weather temperature for a given location."""
    print(f"Tool Call: get_weather_forecast(location={location})")
    # TODO: Make API call
    print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
    return {"temperature": 25, "unit": "celsius"}  # Dummy response

def set_thermostat_temperature(temperature: int) -> dict:
    """Sets the thermostat to a desired temperature."""
    print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
    # TODO: Interact with a thermostat API
    print("Tool Response: {'status': 'success'}")
    return {"status": "success"}

# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[get_weather_forecast, set_thermostat_temperature]
)

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
    config=config,
)

# Print the final, user-facing response
print(response.text)

Beklenen Çıkış

Kodu çalıştırdığınızda SDK'nın işlev çağrılarını düzenlediğini görürsünüz. Model önce get_weather_forecast işlevini çağırır, sıcaklığı alır ve ardından istemdeki mantığa göre doğru değerle set_thermostat_temperature işlevini çağırır.

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.

JavaScript

Bu örnekte, manuel yürütme döngüsü kullanarak bileşik işlev çağrısı yapmak için JavaScript/TypeScript SDK'sının nasıl kullanılacağı gösterilmektedir.

import { GoogleGenAI, Type } from "@google/genai";

// Configure the client
const ai = new GoogleGenAI({});

// Example Functions
function get_weather_forecast({ location }) {
  console.log(`Tool Call: get_weather_forecast(location=${location})`);
  // TODO: Make API call
  console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
  return { temperature: 25, unit: "celsius" };
}

function set_thermostat_temperature({ temperature }) {
  console.log(
    `Tool Call: set_thermostat_temperature(temperature=${temperature})`,
  );
  // TODO: Make API call
  console.log("Tool Response: {'status': 'success'}");
  return { status: "success" };
}

const toolFunctions = {
  get_weather_forecast,
  set_thermostat_temperature,
};

const tools = [
  {
    functionDeclarations: [
      {
        name: "get_weather_forecast",
        description:
          "Gets the current weather temperature for a given location.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            location: {
              type: Type.STRING,
            },
          },
          required: ["location"],
        },
      },
      {
        name: "set_thermostat_temperature",
        description: "Sets the thermostat to a desired temperature.",
        parameters: {
          type: Type.OBJECT,
          properties: {
            temperature: {
              type: Type.NUMBER,
            },
          },
          required: ["temperature"],
        },
      },
    ],
  },
];

// Prompt for the model
let contents = [
  {
    role: "user",
    parts: [
      {
        text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
      },
    ],
  },
];

// Loop until the model has no more function calls to make
while (true) {
  const result = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents,
    config: { tools },
  });

  if (result.functionCalls && result.functionCalls.length > 0) {
    const functionCall = result.functionCalls[0];

    const { name, args } = functionCall;

    if (!toolFunctions[name]) {
      throw new Error(`Unknown function call: ${name}`);
    }

    // Call the function and get the response.
    const toolResponse = toolFunctions[name](args);

    const functionResponsePart = {
      name: functionCall.name,
      response: {
        result: toolResponse,
      },
    };

    // Send the function response back to the model.
    contents.push({
      role: "model",
      parts: [
        {
          functionCall: functionCall,
        },
      ],
    });
    contents.push({
      role: "user",
      parts: [
        {
          functionResponse: functionResponsePart,
        },
      ],
    });
  } else {
    // No more function calls, break the loop.
    console.log(result.text);
    break;
  }
}

Beklenen Çıkış

Kodu çalıştırdığınızda SDK'nın işlev çağrılarını düzenlediğini görürsünüz. Model önce get_weather_forecast işlevini çağırır, sıcaklığı alır ve ardından istemdeki mantığa göre doğru değerle set_thermostat_temperature işlevini çağırır.

Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.

Bileşik işlev çağrısı, yerel bir Live API özelliğidir. Bu, Live API'nin Python SDK'sına benzer şekilde işlev çağrısını işleyebileceği anlamına gelir.

Python

# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}

prompt = """
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
  """

tools = [
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]

await run(prompt, tools=tools, modality="AUDIO")

JavaScript

// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };

const prompt = `
  Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;

const tools = [
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];

await run(prompt, tools=tools, modality="AUDIO")

İşlev çağırma modları

Gemini API, modelin sağlanan araçları (işlev bildirimleri) nasıl kullanacağını kontrol etmenize olanak tanır. Özellikle, modu function_calling_config içinde ayarlayabilirsiniz.

  • AUTO (Default): Model, isteme ve bağlama göre doğal dil yanıtı oluşturmaya veya işlev çağrısı önermeye karar verir. Bu, en esnek moddur ve çoğu senaryo için önerilir.
  • ANY: Model, her zaman bir işlev çağrısı tahmin etmekle sınırlıdır ve işlev şemasına uyulmasını garanti eder. allowed_function_names belirtilmemişse model, sağlanan işlev bildirimlerinden herhangi birini seçebilir. allowed_function_names liste olarak sağlanırsa model yalnızca bu listedeki işlevleri seçebilir. Her isteme bir işlev çağrısı yanıtı verilmesini gerektiren durumlarda bu modu kullanın (geçerliyse).
  • NONE: Modelin işlev çağrısı yapması yasaktır. Bu, işlev bildirimi olmadan istek göndermeye eşdeğerdir. Bu özelliği, araç tanımlarınızı kaldırmadan işlev çağrısını geçici olarak devre dışı bırakmak için kullanın.

Python

from google.genai import types

# Configure function calling mode
tool_config = types.ToolConfig(
    function_calling_config=types.FunctionCallingConfig(
        mode="ANY", allowed_function_names=["get_current_temperature"]
    )
)

# Create the generation config
config = types.GenerateContentConfig(
    tools=[tools],  # not defined here.
    tool_config=tool_config,
)

JavaScript

import { FunctionCallingConfigMode } from '@google/genai';

// Configure function calling mode
const toolConfig = {
  functionCallingConfig: {
    mode: FunctionCallingConfigMode.ANY,
    allowedFunctionNames: ['get_current_temperature']
  }
};

// Create the generation config
const config = {
  tools: tools, // not defined here.
  toolConfig: toolConfig,
};

Otomatik işlev çağırma (yalnızca Python)

Python SDK'sını kullanırken Python işlevlerini doğrudan araç olarak sağlayabilirsiniz. SDK, Python işlevini otomatik olarak bildirimlere dönüştürür, işlev çağrısı yürütmesini ve yanıt döngüsünü sizin için yönetir. Python SDK'sı daha sonra otomatik olarak:

  1. Modelden gelen işlev çağrısı yanıtlarını algılar.
  2. Kodunuzda ilgili Python işlevini çağırın.
  3. İşlev yanıtını modele geri gönderir.
  4. Modelin nihai metin yanıtını döndürür.

Bu işlevi kullanmak için işlevinizi tür ipuçları ve bir docstring ile tanımlayın, ardından işlevin kendisini (JSON bildirimi değil) araç olarak iletin:

Python

from google import genai
from google.genai import types

# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
    """Gets the current temperature for a given location.

    Args:
        location: The city and state, e.g. San Francisco, CA

    Returns:
        A dictionary containing the temperature and unit.
    """
    # ... (implementation) ...
    return {"temperature": 25, "unit": "Celsius"}

# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
    tools=[get_current_temperature]
)  # Pass the function itself

# Make the request
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="What's the temperature in Boston?",
    config=config,
)

print(response.text)  # The SDK handles the function call and returns the final text

Otomatik işlev çağrısını devre dışı bırakmak için:

Python

config = types.GenerateContentConfig(
    tools=[get_current_temperature],
    automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)

Otomatik işlev şeması bildirimi

Python işlevlerinden otomatik şema çıkarma özelliği her durumda çalışmaz. Örneğin, iç içe yerleştirilmiş bir sözlük nesnesinin alanlarını tanımladığınız durumları işlemez. API, aşağıdaki türlerden herhangi birini açıklayabilir:

Python

AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])

Çıkarılan şemanın nasıl göründüğünü görmek için from_callable kullanarak dönüştürebilirsiniz:

Python

def multiply(a: float, b: float):
    """Returns a * b."""
    return a * b

fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)

# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())

Çoklu araç kullanımı: Yerel araçları işlev çağrısıyla birleştirme

Yerel araçları işlev çağrısıyla birleştirerek aynı anda birden fazla aracı etkinleştirebilirsiniz. Aşağıda, Live API kullanılarak yapılan bir istekte iki aracın (Google Arama ile temellendirme ve kod yürütme) etkinleştirildiği bir örnek verilmiştir.

Python

# Multiple tasks example - combining lights, code execution, and search
prompt = """
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
  """

tools = [
    {'google_search': {}},
    {'code_execution': {}},
    {'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]

# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")

JavaScript

// Multiple tasks example - combining lights, code execution, and search
const prompt = `
  Hey, I need you to do three things for me.

    1.  Turn on the lights.
    2.  Then compute the largest prime palindrome under 100000.
    3.  Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.

  Thanks!
`;

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];

// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});

Python geliştiriciler bu özelliği Live API Tool Use notebook'ta deneyebilir.

Model bağlam protokolü (MCP)

Model Context Protocol (MCP), yapay zeka uygulamalarını harici araçlara ve verilere bağlamak için kullanılan açık bir standarttır. MCP, modellerin işlevler (araçlar), veri kaynakları (kaynaklar) veya önceden tanımlanmış istemler gibi bağlama erişmesi için ortak bir protokol sağlar.

Gemini SDK'ları, MCP için yerleşik destek sunar. Bu sayede ortak metin kodu azaltılır ve MCP araçları için otomatik araç çağrısı özelliği sunulur. Model bir MCP aracı çağrısı oluşturduğunda Python ve JavaScript istemci SDK'sı, MCP aracını otomatik olarak yürütebilir ve yanıtı sonraki bir istekte modele geri göndererek bu döngüyü model tarafından başka araç çağrıları yapılmayana kadar devam ettirebilir.

Burada, Gemini ve mcp SDK ile yerel bir MCP sunucusunun nasıl kullanılacağına dair bir örnek bulabilirsiniz.

Python

Seçtiğiniz platformda mcp SDK'sının en son sürümünün yüklü olduğundan emin olun.

pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai

client = genai.Client()

# Create server parameters for stdio connection
server_params = StdioServerParameters(
    command="npx",  # Executable
    args=["-y", "@philschmid/weather-mcp"],  # MCP Server
    env=None,  # Optional environment variables
)

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Prompt to get the weather for the current day in London.
            prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"

            # Initialize the connection between client and server
            await session.initialize()

            # Send request to the model with MCP function declarations
            response = await client.aio.models.generate_content(
                model="gemini-2.5-flash",
                contents=prompt,
                config=genai.types.GenerateContentConfig(
                    temperature=0,
                    tools=[session],  # uses the session, will automatically call the tool
                    # Uncomment if you **don't** want the SDK to automatically call the tool
                    # automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
                    #     disable=True
                    # ),
                ),
            )
            print(response.text)

# Start the asyncio event loop and run the main function
asyncio.run(run())

JavaScript

Seçtiğiniz platformda mcp SDK'nın en son sürümünün yüklü olduğundan emin olun.

npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
  command: "npx", // Executable
  args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});

const client = new Client(
  {
    name: "example-client",
    version: "1.0.0"
  }
);

// Configure the client
const ai = new GoogleGenAI({});

// Initialize the connection between client and server
await client.connect(serverParams);

// Send request to the model with MCP tools
const response = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
  config: {
    tools: [mcpToTool(client)],  // uses the session, will automatically call the tool
    // Uncomment if you **don't** want the sdk to automatically call the tool
    // automaticFunctionCalling: {
    //   disable: true,
    // },
  },
});
console.log(response.text)

// Close the connection
await client.close();

Yerleşik MCP desteğiyle ilgili sınırlamalar

Dahili MCP desteği, SDK'larımızda deneysel bir özelliktir ve aşağıdaki sınırlamalara sahiptir:

  • Yalnızca araçlar desteklenir, kaynaklar veya istemler desteklenmez.
  • Python ve JavaScript/TypeScript SDK'sında kullanılabilir.
  • Gelecekteki sürümlerde zarar veren değişiklikler olabilir.

Bu sınırlamalar, oluşturduğunuz öğeleri etkiliyorsa MCP sunucularını manuel olarak entegre edebilirsiniz.

Desteklenen modeller

Bu bölümde, modeller ve işlev çağrısı özellikleri listelenmektedir. Deneysel modeller dahil değildir. Kapsamlı bir özelliklere genel bakış için modele genel bakış sayfasına gidebilirsiniz.

Model İşlev Çağırma Paralel İşlev Çağırma Bileşik İşlev Çağırma
Gemini 2.5 Pro ✔️ ✔️ ✔️
Gemini 2.5 Flash ✔️ ✔️ ✔️
Gemini 2.5 Flash-Lite ✔️ ✔️ ✔️
Gemini 2.0 Flash ✔️ ✔️ ✔️
Gemini 2.0 Flash-Lite X X X

En iyi uygulamalar

  • İşlev ve Parametre Açıklamaları: Açıklamalarınızda son derece net ve spesifik olun. Model, doğru işlevi seçmek ve uygun bağımsız değişkenler sağlamak için bunlara güvenir.
  • Adlandırma: Tanımlayıcı işlev adları kullanın (boşluk, nokta veya tire içermeyen).
  • Güçlü Türlendirme: Hataları azaltmak için parametrelerde belirli türleri (tam sayı, dize, enum) kullanın. Bir parametrenin geçerli değerleri sınırlıysa enum kullanın.
  • Araç Seçimi: Model, rastgele sayıda araç kullanabilir ancak çok fazla araç sağlamak yanlış veya en uygun olmayan aracın seçilme riskini artırabilir. En iyi sonuçlar için yalnızca bağlam veya görevle alakalı araçları sağlamayı hedefleyin. İdeal olarak, etkin grubu en fazla 10-20 araçla sınırlayın. Toplam araç sayınız çok fazlaysa konuşma bağlamına göre dinamik araç seçimi yapmayı düşünebilirsiniz.
  • İstem Mühendisliği:
    • Bağlam bilgisi verin: Modele rolünü söyleyin (ör. "You are a helpful weather assistant.").
    • Talimat verin: İşlevlerin nasıl ve ne zaman kullanılacağını belirtin (ör. Tarihleri tahmin etmeyin. Tahminler için her zaman gelecekteki bir tarihi kullanın.").
    • Netleştirme isteme: Gerekirse modele netleştirme soruları sorması talimatını verin.
  • Sıcaklık: Düşük sıcaklık kullanın (ör. 0) daha deterministik ve güvenilir işlev çağrıları için.
  • Doğrulama: Bir işlev çağrısının önemli sonuçları varsa (ör. sipariş verme), yürütmeden önce kullanıcıyla birlikte çağrıyı doğrulayın.
  • Hata İşleme: Beklenmedik girişleri veya API hatalarını sorunsuz bir şekilde işlemek için işlevlerinizde güçlü bir hata işleme yöntemi uygulayın. Modelin kullanıcıya faydalı yanıtlar oluşturmak için kullanabileceği bilgilendirici hata mesajları döndürün.
  • Güvenlik: Harici API'leri çağırırken güvenliğe dikkat edin. Uygun kimlik doğrulama ve yetkilendirme mekanizmalarını kullanın. İşlev çağrılarında hassas verileri açığa çıkarmaktan kaçının.
  • Jeton Sınırları: İşlev açıklamaları ve parametreler, giriş jetonu sınırınıza dahil edilir. Token sınırlarına ulaşıyorsanız işlev sayısını veya açıklamaların uzunluğunu sınırlamayı, karmaşık görevleri daha küçük ve daha odaklanmış işlev kümelerine ayırmayı düşünebilirsiniz.

Notlar ve sınırlamalar

  • Yalnızca OpenAPI şemasının bir alt kümesi desteklenir.
  • Python'da desteklenen parametre türleri sınırlıdır.
  • Otomatik işlev çağırma yalnızca Python SDK'sında bulunan bir özelliktir.