Interactions API

Etkileşimler API'si (Beta), Gemini modelleri ve aracılarıyla etkileşim kurmak için kullanılan birleşik bir arayüzdür. generateContent API'ye kıyasla daha iyi bir alternatif olan bu API, durum yönetimini, araç düzenlemeyi ve uzun süren görevleri basitleştirir. API şemasına kapsamlı bir bakış için API Referansı'na bakın. Beta sürümü sırasında özellikler ve şemalar uyumluluğu bozan değişikliklere tabi olabilir. Hızlı bir başlangıç için Etkileşimler API'si hızlı başlangıç not defterini deneyin.

Aşağıdaki örnekte, Etkileşimler API'sinin bir metin istemiyle nasıl çağrılacağı gösterilmektedir.

Python

from google import genai

client = genai.Client()

interaction =  client.interactions.create(
    model="gemini-3-flash-preview",
    input="Tell me a short joke about programming."
)

print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction =  await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a short joke about programming.',
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me a short joke about programming."
}'

Temel etkileşimler

Etkileşimler API'si mevcut SDK'larımız aracılığıyla kullanılabilir. Modelle etkileşime girmenin en basit yolu metin istemi sağlamaktır. input; dize, içerik nesneleri içeren bir liste veya roller ve içerik nesneleri içeren dönüşlerin listesi olabilir.

Python

from google import genai

client = genai.Client()

interaction =  client.interactions.create(
    model="gemini-3-flash-preview",
    input="Tell me a short joke about programming."
)

print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction =  await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a short joke about programming.',
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me a short joke about programming."
}'

Etkileşim

Çok turlu görüşmeleri iki şekilde oluşturabilirsiniz:

  • Önceki bir etkileşime referans vererek durum bilgili
  • Tüm görüşme geçmişini sağlayarak durum bilgisiz olarak

Durumlu görüşme

Bir ileti dizisine devam etmek için önceki etkileşimden alınan id değerini previous_interaction_id parametresine iletin. API, görüşme geçmişini hatırladığından yalnızca yeni girişi göndermeniz gerekir. Hangi alanların devralındığı ve hangilerinin yeniden belirtilmesi gerektiği hakkında ayrıntılı bilgi için Sunucu tarafında durum yönetimi başlıklı makaleye bakın.

Python

from google import genai

client = genai.Client()

# 1. First turn
interaction1 = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")

# 2. Second turn (passing previous_interaction_id)
interaction2 = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is my name?",
    previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.outputs[-1].text}")

JavaScript

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

const client = new GoogleGenAI({});

// 1. First turn
const interaction1 = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Hi, my name is Phil.'
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);

// 2. Second turn (passing previous_interaction_id)
const interaction2 = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'What is my name?',
    previous_interaction_id: interaction1.id
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);

REST

# 1. First turn
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Hi, my name is Phil."
}'

# 2. Second turn (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
#     "model": "gemini-3-flash-preview",
#     "input": "What is my name?",
#     "previous_interaction_id": "INTERACTION_ID"
# }'

Geçmiş durum bilgili etkileşimleri alma

Sohbetin önceki dönüşlerini almak için etkileşimi id kullanma.

Python

previous_interaction = client.interactions.get("<YOUR_INTERACTION_ID>")

print(previous_interaction)

JavaScript

const previous_interaction = await client.interactions.get("<YOUR_INTERACTION_ID>");
console.log(previous_interaction);

REST

curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>" \
-H "x-goog-api-key: $GEMINI_API_KEY"

Orijinal girişi dahil et

interactions.get(), varsayılan olarak yalnızca modelin çıkışlarını döndürür. Yanıtı orijinal normalleştirilmiş girişle birlikte göndermek için include_input seçeneğini true olarak ayarlayın.

Python

interaction = client.interactions.get(
    "<YOUR_INTERACTION_ID>",
    include_input=True
)

print(f"Input: {interaction.input}")
print(f"Output: {interaction.outputs}")

JavaScript

const interaction = await client.interactions.get(
    "<YOUR_INTERACTION_ID>",
    { include_input: true }
);

console.log(`Input: ${JSON.stringify(interaction.input)}`);
console.log(`Output: ${JSON.stringify(interaction.outputs)}`);

REST

curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>?include_input=true" \
-H "x-goog-api-key: $GEMINI_API_KEY"

Durumsuz görüşme

Sohbet geçmişini istemci tarafında manuel olarak yönetebilirsiniz.

Python

from google import genai

client = genai.Client()

conversation_history = [
    {
        "role": "user",
        "content": "What are the three largest cities in Spain?"
    }
]

interaction1 = client.interactions.create(
    model="gemini-3-flash-preview",
    input=conversation_history
)

print(f"Model: {interaction1.outputs[-1].text}")

conversation_history.append({"role": "model", "content": interaction1.outputs})
conversation_history.append({
    "role": "user",
    "content": "What is the most famous landmark in the second one?"
})

interaction2 = client.interactions.create(
    model="gemini-3-flash-preview",
    input=conversation_history
)

print(f"Model: {interaction2.outputs[-1].text}")

JavaScript

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

const client = new GoogleGenAI({});

const conversationHistory = [
    {
        role: 'user',
        content: "What are the three largest cities in Spain?"
    }
];

const interaction1 = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: conversationHistory
});

console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);

conversationHistory.push({ role: 'model', content: interaction1.outputs });
conversationHistory.push({
    role: 'user',
    content: "What is the most famous landmark in the second one?"
});

const interaction2 = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: conversationHistory
});

console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);

REST

 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
 -H "Content-Type: application/json" \
 -H "x-goog-api-key: $GEMINI_API_KEY" \
 -d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {
            "role": "user",
            "content": "What are the three largest cities in Spain?"
        },
        {
            "role": "model",
            "content": "The three largest cities in Spain are Madrid, Barcelona, and Valencia."
        },
        {
            "role": "user",
            "content": "What is the most famous landmark in the second one?"
        }
    ]
}'

Çok formatlı özellikler

Görüntü anlama veya video üretimi gibi çok formatlı kullanım alanları için Interactions API'yi kullanabilirsiniz.

Çok formatlı anlama

Çok formatlı girişi base64 olarak kodlanmış veriler şeklinde satır içi olarak, daha büyük dosyalar için Files API'yi kullanarak veya uri alanına herkese açık bir bağlantı ileterek sağlayabilirsiniz. Aşağıdaki kod örneklerinde herkese açık URL yöntemi gösterilmektedir.

Görüntü anlama

Python

from google import genai
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {"type": "text", "text": "Describe the image."},
        {
            "type": "image",
            "uri": "YOUR_URL",
            "mime_type": "image/png"
        }
    ]
)
print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        {type: 'text', text: 'Describe the image.'},
        {
            type: 'image',
            uri: 'YOUR_URL',
            mime_type: 'image/png'
        }
    ]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
    {
        "type": "text",
        "text": "Describe the image."
    },
    {
        "type": "image",
        "uri": "YOUR_URL",
        "mime_type": "image/png"
    }
    ]
}'

Ses yorumlama

Python

from google import genai
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {"type": "text", "text": "What does this audio say?"},
        {
            "type": "audio",
            "uri": "YOUR_URL",
            "mime_type": "audio/wav"
        }
    ]
)
print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        { type: 'text', text: 'What does this audio say?' },
        {
            type: 'audio',
            uri: 'YOUR_URL',
            mime_type: 'audio/wav'
        }
    ]
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {"type": "text", "text": "What does this audio say?"},
        {
            "type": "audio",
            "uri": "YOUR_URL",
            "mime_type": "audio/wav"
        }
    ]
}'

Video anlama

Python

from google import genai
client = genai.Client()

print("Analyzing video...")
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {"type": "text", "text": "What is happening in this video? Provide a timestamped summary."},
        {
            "type": "video",
            "uri": "YOUR_URL",
            "mime_type": "video/mp4"
        }
    ]
)

print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

console.log('Analyzing video...');
const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        { type: 'text', text: 'What is happening in this video? Provide a timestamped summary.' },
        {
            type: 'video',
            uri: 'YOUR_URL',
            mime_type: 'video/mp4'
        }
    ]
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {"type": "text", "text": "What is happening in this video?"},
        {
            "type": "video",
            "uri": "YOUR_URL",
            "mime_type": "video/mp4"
        }
    ]
}'

Belge (PDF) anlama

Python

from google import genai
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {"type": "text", "text": "What is this document about?"},
        {
            "type": "document",
            "uri": "YOUR_URL",
            "mime_type": "application/pdf"
        }
    ]
)
print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        { type: 'text', text: 'What is this document about?' },
        {
            type: 'document',
            uri: 'YOUR_URL',
            mime_type: 'application/pdf'
        }
    ],
});
console.log(interaction.outputs[0].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {"type": "text", "text": "What is this document about?"},
        {
            "type": "document",
            "uri": "YOUR_URL",
            "mime_type": "application/pdf"
        }
    ]
}'

Çok formatlı üretim

Çok formatlı çıkışlar oluşturmak için Interactions API'yi kullanabilirsiniz.

Görüntü üretme

Python

import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-pro-image-preview",
    input="Generate an image of a futuristic city.",
    response_modalities=["IMAGE"]
)

for output in interaction.outputs:
    if output.type == "image":
        print(f"Generated image with mime_type: {output.mime_type}")
        # Save the image
        with open("generated_city.png", "wb") as f:
            f.write(base64.b64decode(output.data))

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-pro-image-preview',
    input: 'Generate an image of a futuristic city.',
    response_modalities: ['IMAGE']
});

for (const output of interaction.outputs) {
    if (output.type === 'image') {
        console.log(`Generated image with mime_type: ${output.mime_type}`);
        // Save the image
        fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-pro-image-preview",
    "input": "Generate an image of a futuristic city.",
    "response_modalities": ["IMAGE"]
}'
Görüntü çıkışını yapılandırma

En boy oranını ve çözünürlüğü kontrol etmek için generation_config içindeki image_config simgesini kullanarak oluşturulan görüntüleri özelleştirebilirsiniz.

Parametre Seçenekler Açıklama
aspect_ratio 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 Çıkış resminin en-boy oranını kontrol eder.
image_size 1k, 2k, 4k Çıkış görüntüsünün çözünürlüğünü ayarlar.

Python

import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-pro-image-preview",
    input="Generate an image of a futuristic city.",
    generation_config={
        "image_config": {
            "aspect_ratio": "9:16",
            "image_size": "2k"
        }
    }
)

for output in interaction.outputs:
    if output.type == "image":
        print(f"Generated image with mime_type: {output.mime_type}")
        # Save the image
        with open("generated_city.png", "wb") as f:
            f.write(base64.b64decode(output.data))

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-pro-image-preview',
    input: 'Generate an image of a futuristic city.',
    generation_config: {
        image_config: {
            aspect_ratio: '9:16',
            image_size: '2k'
        }
    }
});

for (const output of interaction.outputs) {
    if (output.type === 'image') {
        console.log(`Generated image with mime_type: ${output.mime_type}`);
        // Save the image
        fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-pro-image-preview",
    "input": "Generate an image of a futuristic city.",
    "generation_config": {
        "image_config": {
            "aspect_ratio": "9:16",
            "image_size": "2k"
        }
    }
}'

Konuşma üretme

Metin okuma (TTS) modelini kullanarak metinden doğal sesler üretin. speech_config parametresiyle ses, dil ve hoparlör ayarlarını yapılandırın.

Python

import base64
from google import genai
import wave

# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
    with wave.open(filename, "wb") as wf:
        wf.setnchannels(channels)
        wf.setsampwidth(sample_width)
        wf.setframerate(rate)
        wf.writeframes(pcm)

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-flash-preview-tts",
    input="Say the following: WOOHOO This is so much fun!.",
    response_modalities=["AUDIO"],
    generation_config={
        "speech_config": {
            "language": "en-us",
            "voice": "kore"
        }
    }
)

for output in interaction.outputs:
    if output.type == "audio":
        print(f"Generated audio with mime_type: {output.mime_type}")
        # Save the audio as wave file to the current directory.
        wave_file("generated_audio.wav", base64.b64decode(output.data))

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import wav from 'wav';

async function saveWaveFile(
    filename,
    pcmData,
    channels = 1,
    rate = 24000,
    sampleWidth = 2,
) {
    return new Promise((resolve, reject) => {
        const writer = new wav.FileWriter(filename, {
                channels,
                sampleRate: rate,
                bitDepth: sampleWidth * 8,
        });

        writer.on('finish', resolve);
        writer.on('error', reject);

        writer.write(pcmData);
        writer.end();
    });
}

async function main() {
    const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
    const client = new GoogleGenAI({apiKey: GEMINI_API_KEY});

    const interaction = await client.interactions.create({
        model: 'gemini-2.5-flash-preview-tts',
        input: 'Say the following: WOOHOO This is so much fun!.',
        response_modalities: ['AUDIO'],
        generation_config: {
            speech_config: {
                language: "en-us",
                voice: "kore"
            }
        }
    });

    for (const output of interaction.outputs) {
        if (output.type === 'audio') {
            console.log(`Generated audio with mime_type: ${output.mime_type}`);
            const audioBuffer = Buffer.from(output.data, 'base64');
            // Save the audio as wave file to the current directory
            await saveWaveFile("generated_audio.wav", audioBuffer);
        }
    }
}
await main();

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-2.5-flash-preview-tts",
    "input": "Say the following: WOOHOO This is so much fun!.",
    "response_modalities": ["AUDIO"],
    "generation_config": {
        "speech_config": {
            "language": "en-us",
            "voice": "kore"
        }
    }
}' | jq -r '.outputs[] | select(.type == "audio") | .data' | base64 -d > generated_audio.pcm
# You may need to install ffmpeg.
ffmpeg -f s16le -ar 24000 -ac 1 -i generated_audio.pcm generated_audio.wav
Birden fazla konuşmacının konuşmasını üretme

İstemde konuşmacı adlarını belirterek ve bunları speech_config içinde eşleştirerek birden fazla konuşmacıyla konuşma oluşturun.

İstemde konuşmacı adları yer almalıdır:

TTS the following conversation between Alice and Bob:
Alice: Hi Bob, how are you doing today?
Bob: I'm doing great, thanks for asking! How about you?
Alice: Fantastic! I just learned about the Gemini API.

Ardından speech_config'ı eşleşen hoparlörlerle yapılandırın:

"generation_config": {
    "speech_config": [
        {"voice": "Zephyr", "speaker": "Alice", "language": "en-US"},
        {"voice": "Puck", "speaker": "Bob", "language": "en-US"}
    ]
}

Ajan tabanlı yetenekler

Etkileşimler API'si, ajan oluşturmak ve ajanlarla etkileşim kurmak için tasarlanmıştır. İşlev çağrısı, yerleşik araçlar, yapılandırılmış çıkışlar ve Model Context Protocol (MCP) desteği içerir.

Temsilciler

Karmaşık görevler için deep-research-pro-preview-12-2025 gibi özel aracıları kullanabilirsiniz. Gemini Deep Research Agent hakkında daha fazla bilgi edinmek için Deep Research kılavuzuna bakın.

Python

import time
from google import genai

client = genai.Client()

# 1. Start the Deep Research Agent
initial_interaction = client.interactions.create(
    input="Research the history of the Google TPUs with a focus on 2025 and 2026.",
    agent="deep-research-pro-preview-12-2025",
    background=True
)

print(f"Research started. Interaction ID: {initial_interaction.id}")

# 2. Poll for results
while True:
    interaction = client.interactions.get(initial_interaction.id)
    print(f"Status: {interaction.status}")

    if interaction.status == "completed":
        print("\nFinal Report:\n", interaction.outputs[-1].text)
        break
    elif interaction.status in ["failed", "cancelled"]:
        print(f"Failed with status: {interaction.status}")
        break

    time.sleep(10)

JavaScript

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

const client = new GoogleGenAI({});

// 1. Start the Deep Research Agent
const initialInteraction = await client.interactions.create({
    input: 'Research the history of the Google TPUs with a focus on 2025 and 2026.',
    agent: 'deep-research-pro-preview-12-2025',
    background: true
});

console.log(`Research started. Interaction ID: ${initialInteraction.id}`);

// 2. Poll for results
while (true) {
    const interaction = await client.interactions.get(initialInteraction.id);
    console.log(`Status: ${interaction.status}`);

    if (interaction.status === 'completed') {
        console.log('\nFinal Report:\n', interaction.outputs[interaction.outputs.length - 1].text);
        break;
    } else if (['failed', 'cancelled'].includes(interaction.status)) {
        console.log(`Failed with status: ${interaction.status}`);
        break;
    }

    await new Promise(resolve => setTimeout(resolve, 10000));
}

REST

# 1. Start the Deep Research Agent
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Research the history of the Google TPUs with a focus on 2025 and 2026.",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true
}'

# 2. Poll for results (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"

Araçlar ve işlev çağrısı

Bu bölümde, özel araçları tanımlamak için işlev çağrısının nasıl kullanılacağı ve Google'ın yerleşik araçlarının Interactions API'de nasıl kullanılacağı açıklanmaktadır.

İşlev çağırma

Python

from google import genai

client = genai.Client()

# 1. Define the tool
def get_weather(location: str):
    """Gets the weather for a given location."""
    return f"The weather in {location} is sunny."

weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
        },
        "required": ["location"]
    }
}

# 2. Send the request with tools
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the weather in Paris?",
    tools=[weather_tool]
)

# 3. Handle the tool call
for output in interaction.outputs:
    if output.type == "function_call":
        print(f"Tool Call: {output.name}({output.arguments})")
        # Execute tool
        result = get_weather(**output.arguments)

        # Send result back
        interaction = client.interactions.create(
            model="gemini-3-flash-preview",
            previous_interaction_id=interaction.id,
            input=[{
                "type": "function_result",
                "name": output.name,
                "call_id": output.id,
                "result": result
            }]
        )
        print(f"Response: {interaction.outputs[-1].text}")

JavaScript

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

const client = new GoogleGenAI({});

// 1. Define the tool
const weatherTool = {
    type: 'function',
    name: 'get_weather',
    description: 'Gets the weather for a given location.',
    parameters: {
        type: 'object',
        properties: {
            location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
        },
        required: ['location']
    }
};

// 2. Send the request with tools
let interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'What is the weather in Paris?',
    tools: [weatherTool]
});

// 3. Handle the tool call
for (const output of interaction.outputs) {
    if (output.type === 'function_call') {
        console.log(`Tool Call: ${output.name}(${JSON.stringify(output.arguments)})`);

        // Execute tool (Mocked)
        const result = `The weather in ${output.arguments.location} is sunny.`;

        // Send result back
        interaction = await client.interactions.create({
            model: 'gemini-3-flash-preview',
            previous_interaction_id:interaction.id,
            input: [{
                type: 'function_result',
                name: output.name,
                call_id: output.id,
                result: result
            }]
        });
        console.log(`Response: ${interaction.outputs[interaction.outputs.length - 1].text}`);
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the weather in Paris?",
    "tools": [{
        "type": "function",
        "name": "get_weather",
        "description": "Gets the weather for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
            },
            "required": ["location"]
        }
    }]
}'

# Handle the tool call and send result back (Replace INTERACTION_ID and CALL_ID)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
#     "model": "gemini-3-flash-preview",
#     "previous_interaction_id": "INTERACTION_ID",
#     "input": [{
#         "type": "function_result",
#         "name": "get_weather",
#         "call_id": "FUNCTION_CALL_ID",
#         "result": "The weather in Paris is sunny."
#     }]
# }'
İstemci tarafı durumla işlev çağrısı

Sunucu tarafı durumu kullanmak istemiyorsanız tüm durumu istemci tarafında yönetebilirsiniz.

Python

from google import genai
client = genai.Client()

functions = [
    {
        "type": "function",
        "name": "schedule_meeting",
        "description": "Schedules a meeting with specified attendees at a given time and date.",
        "parameters": {
            "type": "object",
            "properties": {
                "attendees": {"type": "array", "items": {"type": "string"}},
                "date": {"type": "string", "description": "Date of the meeting (e.g., 2024-07-29)"},
                "time": {"type": "string", "description": "Time of the meeting (e.g., 15:00)"},
                "topic": {"type": "string", "description": "The subject of the meeting."},
            },
            "required": ["attendees", "date", "time", "topic"],
        },
    }
]

history = [{"role": "user","content": [{"type": "text", "text": "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API."}]}]

# 1. Model decides to call the function
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=history,
    tools=functions
)

# add model interaction back to history
history.append({"role": "model", "content": interaction.outputs})

for output in interaction.outputs:
    if output.type == "function_call":
        print(f"Function call: {output.name} with arguments {output.arguments}")

        # 2. Execute the function and get a result
        # In a real app, you would call your function here.
        # call_result = schedule_meeting(**json.loads(output.arguments))
        call_result = "Meeting scheduled successfully."

        # 3. Send the result back to the model
        history.append({"role": "user", "content": [{"type": "function_result", "name": output.name, "call_id": output.id, "result": call_result}]})

        interaction2 = client.interactions.create(
            model="gemini-3-flash-preview",
            input=history,
        )
        print(f"Final response: {interaction2.outputs[-1].text}")
    else:
        print(f"Output: {output}")

JavaScript

// 1. Define the tool
const functions = [
    {
        type: 'function',
        name: 'schedule_meeting',
        description: 'Schedules a meeting with specified attendees at a given time and date.',
        parameters: {
            type: 'object',
            properties: {
                attendees: { type: 'array', items: { type: 'string' } },
                date: { type: 'string', description: 'Date of the meeting (e.g., 2024-07-29)' },
                time: { type: 'string', description: 'Time of the meeting (e.g., 15:00)' },
                topic: { type: 'string', description: 'The subject of the meeting.' },
            },
            required: ['attendees', 'date', 'time', 'topic'],
        },
    },
];

const history = [
    { role: 'user', content: [{ type: 'text', text: 'Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API.' }] }
];

// 2. Model decides to call the function
let interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: history,
    tools: functions
});

// add model interaction back to history
history.push({ role: 'model', content: interaction.outputs });

for (const output of interaction.outputs) {
    if (output.type === 'function_call') {
        console.log(`Function call: ${output.name} with arguments ${JSON.stringify(output.arguments)}`);

        // 3. Send the result back to the model
        history.push({ role: 'user', content: [{ type: 'function_result', name: output.name, call_id: output.id, result: 'Meeting scheduled successfully.' }] });

        const interaction2 = await client.interactions.create({
            model: 'gemini-3-flash-preview',
            input: history,
        });
        console.log(`Final response: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
    }
}
Çok modlu işlev sonuçları

function_result içindeki result alanı düz dizeyi veya TextContent ve ImageContent nesnelerinin dizisini kabul eder. Bu işlev, işlev çağrılarınızdaki metinle birlikte ekran görüntüleri veya grafikler gibi resimleri döndürmenize olanak tanır. Böylece model, görsel çıktı üzerinde akıl yürütebilir.

Python

import base64
from google import genai

client = genai.Client()

functions = [
    {
        "type": "function",
        "name": "take_screenshot",
        "description": "Takes a screenshot of a specified website.",
        "parameters": {
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": "The URL to take a screenshot of."},
            },
            "required": ["url"],
        },
    }
]

# 1. Model decides to call the function
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Can you take a screenshot of https://google.com and tell me what you see?",
    tools=functions
)

for output in interaction.outputs:
    if output.type == "function_call":
        print(f"Function call: {output.name}({output.arguments})")

        # 2. Execute the function and load the image
        # Replace with actual function call, pseudo code for reading image from disk
        with open("screenshot.png", "rb") as f:
            base64_image = base64.b64encode(f.read()).decode("utf-8")

        # 3. Return a multimodal result (text + image)
        call_result = [
            {"type": "text", "text": "Screenshot captured successfully."},
            {"type": "image", "mime_type": "image/png", "data": base64_image}
        ]

        response = client.interactions.create(
            model="gemini-3-flash-preview",
            tools=functions,
            previous_interaction_id=interaction.id,
            input=[{
                "type": "function_result",
                "name": output.name,
                "call_id": output.id,
                "result": call_result
            }]
        )
        print(f"Response: {response.outputs[-1].text}")

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';

const client = new GoogleGenAI({});

const functions = [
    {
        type: 'function',
        name: 'take_screenshot',
        description: 'Takes a screenshot of a specified website.',
        parameters: {
            type: 'object',
            properties: {
                url: { type: 'string', description: 'The URL to take a screenshot of.' },
            },
            required: ['url'],
        },
    }
];

// 1. Model decides to call the function
let interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Can you take a screenshot of https://google.com and tell me what you see?',
    tools: functions
});

for (const output of interaction.outputs) {
    if (output.type === 'function_call') {
        console.log(`Function call: ${output.name}(${JSON.stringify(output.arguments)})`);

        // 2. Execute the function and load the image
        // Replace with actual function call, pseudo code for reading image from disk
        const base64Image = fs.readFileSync('screenshot.png').toString('base64');

        // 3. Return a multimodal result (text + image)
        const callResult = [
            { type: 'text', text: 'Screenshot captured successfully.' },
            { type: 'image', mime_type: 'image/png', data: base64Image }
        ];

        const response = await client.interactions.create({
            model: 'gemini-3-flash-preview',
            tools: functions,
            previous_interaction_id: interaction.id,
            input: [{
                type: 'function_result',
                name: output.name,
                call_id: output.id,
                result: callResult
            }]
        });
        console.log(`Response: ${response.outputs[response.outputs.length - 1].text}`);
    }
}

REST

# 1. Send request with tools (will return a function_call)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Can you take a screenshot of https://google.com and tell me what you see?",
    "tools": [{
        "type": "function",
        "name": "take_screenshot",
        "description": "Takes a screenshot of a specified website.",
        "parameters": {
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": "The URL to take a screenshot of."}
            },
            "required": ["url"]
        }
    }]
}'

# 2. Send multimodal result back (Replace INTERACTION_ID, CALL_ID, and BASE64_IMAGE)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
#     "model": "gemini-3-flash-preview",
#     "tools": [{"type": "function", "name": "take_screenshot", "description": "Takes a screenshot of a specified website.", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}],
#     "previous_interaction_id": "INTERACTION_ID",
#     "input": [{
#         "type": "function_result",
#         "name": "take_screenshot",
#         "call_id": "CALL_ID",
#         "result": [
#             {"type": "text", "text": "Screenshot captured successfully."},
#             {"type": "image", "mime_type": "image/png", "data": "BASE64_IMAGE"}
#         ]
#     }]
# }'

Yerleşik araçlar

Gemini'da Google Arama ile temellendirme, Google Görsel Arama ile temellendirme, Google Haritalar ile temellendirme, kod yürütme, URL bağlamı ve bilgisayar kullanımı gibi yerleşik araçlar bulunur.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Who won the last Super Bowl?",
    tools=[{"type": "google_search"}]
)
# Find the text output (not the GoogleSearchResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
    print(text_output.text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Who won the last Super Bowl?',
    tools: [{ type: 'google_search' }]
});
// Find the text output (not the GoogleSearchResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the last Super Bowl?",
    "tools": [{"type": "google_search"}]
}'
Google Görsel Arama ile temellendirme (yalnızca 3.1 Flash Image için)

Google Görsel Arama ile temellendirme, modellerin Google Görsel Arama aracılığıyla alınan web görsellerini görüntü üretme için görsel bağlam olarak kullanmasına olanak tanır. Görsel Arama, mevcut Google Arama ile Temellendirme aracındaki yeni bir arama türüdür ve standart Web Arama ile birlikte çalışır.

google_search aracı için search_types dizisine "image_search" ekleyerek resim sonuçları isteyin.

Python

interaction = client.interactions.create(
    model="gemini-3.1-flash-image-preview",
    input="Search for an image of a vintage gold bitcoin coin.",
    tools=[{
        "type": "google_search",
        "search_types": ["web_search", "image_search"]
    }]
)

JavaScript

const interaction = await client.interactions.create({
    model: 'gemini-3.1-flash-image-preview',
    input: 'Search for an image of a vintage gold bitcoin coin.',
    tools: [{
        type: 'google_search',
        search_types: ['web_search', 'image_search']
    }]
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3.1-flash-image-preview",
    "input": "Search for an image of a vintage gold bitcoin coin.",
    "tools": [{
        "type": "google_search",
        "search_types": ["web_search", "image_search"]
    }]
}'
Zorunlu görüntüleme koşulları

Google Arama Terimleri Hizmet Şartları'na uymak için kullanıcı arayüzünüzde iki farklı ilişkilendirme düzeyi uygulanmalıdır:

  1. Google Arama İlişkilendirmesi

    google_search_result bloğunda sağlanan "Google'da kontrol et" arama önerilerini göstermeniz gerekir.

    • Alan: rendered_content (HTML/CSS)
    • İşlem: Bu çipi, modelin yanıtının yakınında olduğu gibi oluşturun.
  2. Yayıncı İlişkilendirmesi

    Gösterilen her resim için "içeren sayfaya" (açılış sayfası) bir bağlantı sağlamanız gerekir.

    • Alan: url (result dizisinde bulunur)
    • Şart: Resimden, kaynağını içeren web sayfasına doğrudan tek tıklamayla erişilebilen bir yol sağlamanız gerekir. Ara resim görüntüleyicilerin veya çok tıklamalı yolların kullanılmasına izin verilmez.
Temellendirilmiş yanıtı işleme

Aşağıdaki snippet'te, hem ham görüntü verileri hem de zorunlu ilişkilendirme için araya eklenmiş yanıt bloklarının nasıl işleneceği gösterilmektedir.

Python

for output in interaction.outputs:
    # 1. Handle raw multimodal image data
    if output.type == "image":
        print(f"🖼️ Image received: {output.mime_type}")
        # 'data' contains base64-encoded image content
        display_image(output.data, output.mime_type)
    # 2. Handle mandatory Search and Publisher attribution
    elif output.type == "google_search_result":
        # Display Google Search Attribution
        if output.rendered_content:
            render_html_chips(output.rendered_content)

        # Provide Publisher Attribution

        for source in output.result:
            print(f"Source Page: {source['url']}")

JavaScript

for (const output of interaction.outputs) {
  // 1. Handle raw multimodal image data
  if (output.type === 'image') {
    console.log(`🖼️ Image received: ${output.mimeType}`);
    // 'data' contains base64-encoded image content
    displayImage(output.data, output.mimeType);
  }
    // 2. Handle mandatory Search and Publisher attribution
    else if (output.type === 'google_search_result') {
      // Display Google Search Attribution
      if (output.renderedContent) {
        renderHtmlChips(output.renderedContent);
      }

      // Provide Publisher Attribution

    for (const source of output.result) {
      console.log(`Source Page: ${source.url}`);
    }
  }
}
Beklenen çıkış şeması

Görüntü Bloğu (tür: "image"), model tarafından oluşturulan veya alınan ham görsel verileri içerir.

{
  "type": "image",
  "mime_type": "image/png",
  "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB..." // Base64 content
}

Sonuç Bloğu (tür: "google_search_result"), aramayla bağlantılı zorunlu ilişkilendirme meta verilerini içerir.

{
  "type": "google_search_result",
  "call_id": "search_002",
  "rendered_content": "<div class=\"search-suggestions\">...</div>", // Google Search Attribution

  "result": [
    {
      "url": "https://example.com/source-page", // Publisher Attribution
      "title": "Source Page Title"
    }
  ]
}
Google Haritalar ile Temellendirme

Google Haritalar ile temellendirme, modellerin görsel bağlam, harita işaretleri ve konuma dayalı keşif için Google Haritalar verilerini kullanmasına olanak tanır.

Python

from google import genai
client = genai.Client()
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What's the best coffee shop near me?",
    tools=[{"type": "google_maps"}]
)

JavaScript

import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'What\'s the best coffee shop near me?',
    tools: [{ type: 'google_maps' }]
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the best coffee shop near me?",
    "tools": [{"type": "google_maps"}]
}'
Hizmet kullanım şartları

Google Haritalar ile Temellendirme'den elde edilen sonuçları sunarken Google Haritalar Hizmet Şartları'na uymanız gerekir. Kullanıcılarınızı aşağıdakiler hakkında bilgilendirmeniz ve bu görüntüleme koşullarını karşılamanız gerekir:

  • Kullanıcıyı bilgilendirin: Oluşturulan içeriğin hemen ardından ilişkili Google Haritalar kaynaklarını ekleyin. Kaynaklar tek bir kullanıcı etkileşimi içinde görüntülenebilmelidir.
  • Görüntüleme bağlantıları: Her kaynak için bağlantı önizlemesi oluşturun (varsa inceleme snippet'leri dahil).
  • "Google Haritalar"a atıfta bulunun: Metin ilişkilendirme yönergelerine uyun.
  • Kaynak başlığını görüntüleme
  • Sağlanan URL'yi kullanarak kaynağa bağlantı verin.
  • Atıf Kuralları: "Google Haritalar" metnini değiştirmeyin (büyük harf kullanımı, kaydırma). translate="no" kullanarak tarayıcı çevirisini engelleme
Yanıtı ele alma

Aşağıdaki snippet'te, metni ve satır içi alıntıları (yorum snippet'leri dahil) çıkararak yanıta nasıl müdahale edileceği gösterilmektedir. Bu sayede, yanıtta görüntüleme koşulları karşılanmış olur.

Python

for output in interaction.outputs:
    if output.type == "text":
        print(output.text)
        if output.annotations:
            print("\nSources:")
            for annotation in output.annotations:
                if annotation.get("type") == "place_citation":
                    # Display place citation
                    print(f"- {annotation['name']} (Google Maps): {annotation['url']}")
                    # Display review snippets if available
                    if "review_snippets" in annotation:
                        for snippet in annotation["review_snippets"]:
                            print(f"  - Review: {snippet['title']} ({snippet['url']})")
    elif output.type == "google_maps_result":
        # You can also access the raw place data here if needed for map pins
        pass

JavaScript

for (const output of interaction.outputs) {
    if (output.type === 'text') {
        console.log(output.text);
        if (output.annotations) {
            console.log('\nSources:');
            for (const annotation of output.annotations) {
                if (annotation.type === 'place_citation') {
                    console.log(`- ${annotation.name} (Google Maps): ${annotation.url}`);
                    if (annotation.review_snippets) {
                        for (const snippet of annotation.review_snippets) {
                            console.log(`  - Review: ${snippet.title} (${snippet.url})`);
                        }
                    }
                }
            }
        }
    }
}
Beklenen çıkış şeması

Google Haritalar ile Temellendirme'yi kullanırken aşağıdaki çıkış şemasını bekleyebilirsiniz.

Sonuç Bloğu (tür: "google_maps_result"), yapılandırılmış yer verilerini içerir.

{
  "type": "google_maps_result",
  "call_id": "maps_001",
  "result": {
    "places": [
      {
        "place_id": "ChIJ...",
        "name": "Blue Bottle Coffee", // Google Maps Source
        "url": "https://maps.google.com/?cid=...", // Google Maps Link
        "review_snippets": [
          {
            "title": "Amazing single-origin selections",
            "url": "https://maps.google.com/...",
            "review_id": "def456"
          }
        ]
      }
    ],
    "widget_context_token": "widgetcontent/..."
  },
  "signature": "..."
}

Metin Bloğu (tür: "text"), satır içi ek açıklamalarla oluşturulan içeriği içerir.

{
  "type": "text",
  "text": "Blue Bottle Coffee (4.5★) on Mint Plaza was rated highly online...",
  "annotations": [
    {
      "type": "place_citation",
      "place_id": "ChIJ...",
      "name": "Blue Bottle Coffee", // Google Maps Source
      "url": "https://maps.google.com/?cid=...", // Google Maps Link
      "review_snippets": [
        {
          "title": "Amazing single-origin selections",
          "url": "https://maps.google.com/...",
          "review_id": "def456"
        }
      ],
      "start_index": 0,
      "end_index": 42
    }
  ]
}
Kod yürütme

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Calculate the 50th Fibonacci number.",
    tools=[{"type": "code_execution"}]
)
print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Calculate the 50th Fibonacci number.',
    tools: [{ type: 'code_execution' }]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Calculate the 50th Fibonacci number.",
    "tools": [{"type": "code_execution"}]
}'
URL bağlamı

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Summarize the content of https://www.wikipedia.org/",
    tools=[{"type": "url_context"}]
)
# Find the text output (not the URLContextResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
    print(text_output.text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Summarize the content of https://www.wikipedia.org/',
    tools: [{ type: 'url_context' }]
});
// Find the text output (not the URLContextResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Summarize the content of https://www.wikipedia.org/",
    "tools": [{"type": "url_context"}]
}'
Bilgisayar kullanımı

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-computer-use-preview-10-2025",
    input="Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
    tools=[{
        "type": "computer_use",
        "environment": "browser",
        "excludedPredefinedFunctions": ["drag_and_drop"]
    }]
)

# The response will contain tool calls (actions) for the computer interface
# or text explaining the action
for output in interaction.outputs:
    print(output)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-2.5-computer-use-preview-10-2025',
    input: 'Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.',
    tools: [{
        type: 'computer_use',
        environment: 'browser',
        excludedPredefinedFunctions: ['drag_and_drop']
    }]
});

// The response will contain tool calls (actions) for the computer interface
// or text explaining the action
interaction.outputs.forEach(output => console.log(output));

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-2.5-computer-use-preview-10-2025",
    "input": "Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
    "tools": [{
        "type": "computer_use",
        "environment": "browser",
        "excludedPredefinedFunctions": ["drag_and_drop"]
    }]
}'

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Tell me about the book 'I, Claudius'",
    tools=[{"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]}]
)
# Find the text output
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
    print(text_output.text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "Tell me about the book 'I, Claudius'",
    tools: [{ type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] }]
});
// Find the text output
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me about the book I, Claudius",
    "tools": [{"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]}]
}'

Yerleşik araçları ve işlev çağrısını birleştirme

Aynı istekte yerleşik araçları ve işlev çağrısını birlikte kullanabilirsiniz.

Python

from google import genai
import json

client = genai.Client()

get_weather = {
    "type": "function",
    "name": "getWeather",
    "description": "Gets the weather for a requested city.",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "The city and state, e.g. Utqiaġvik, Alaska",
            },
        },
        "required": ["city"],
    },
}

tools = [
    {"type": "google_search"},  # Built-in tool
    get_weather                 # Custom tool (callable)
]

# Turn 1: Initial request with both tools enabled
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the northernmost city in the United States? What's the weather like there today?",
    tools=tools
)

for output in interaction.outputs:
    if output.type == "function_call":
        print(f"Function call: {output.name} (ID: {output.id})")
        # Execute your custom function locally
        result = {"response": "Very cold. 22 degrees Fahrenheit."}
        # Turn 2: Provide the function result back to the model.
        # Passing `previous_interaction_id` automatically circulates the
        # built-in Google Search context (and thought signatures) from Turn 1
        interaction_2 = client.interactions.create(
            model="gemini-3-flash-preview",
            previous_interaction_id=interaction.id,
            tools=tools,
            input=[{
                "type": "function_result",
                "name": output.name,
                "call_id": output.id,
                "result": json.dumps(result)
            }]
        )

        for output in interaction_2.outputs:
            if output.type == "text":
                print(output.text)

JavaScript

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

const client = new GoogleGenAI({});

const weatherTool = {
    type: 'function',
    name: 'get_weather',
    description: 'Gets the weather for a given location.',
    parameters: {
        type: 'object',
        properties: {
            location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
        },
        required: ['location']
    }
};

const tools = [
    {type: 'google_search'}, // Built-in tool
    weatherTool              // Custom tool
];

// Turn 1: Initial request with both tools enabled
let interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "What is the northernmost city in the United States? What's the weather like there today?",
    tools: tools
});

for (const output of interaction.outputs) {
    if (output.type == "function_call") {
        console.log(`Function call: ${output.name} (ID: ${output.id})`);
        // Execute your custom function locally
        const result = {response: "Very cold. 22 degrees Fahrenheit."};
        // Turn 2: Provide the function result back to the model.
        // Passing `previous_interaction_id` automatically circulates the
        // built-in Google Search context (and thought signatures) from Turn 1
        const interaction_2 = await client.interactions.create({
            model: "gemini-3-flash-preview",
            previous_interaction_id: interaction.id,
            tools: tools,
            input: [{
                type: "function_result",
                name: output.name,
                call_id: output.id,
                result: JSON.stringify(result)
            }]
        });

        for (const output_2 of interaction_2.outputs) {
            if (output_2.type == "text") {
                console.log(output_2.text);
            }
        }
    }
}

REST

# Turn 1: Initial request with both tools enabled
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the northernmost city in the United States? What is the weather like there today?",
    "tools": [
        {"type": "google_search"},
        {
            "type": "function",
            "name": "get_weather",
            "description": "Gets the weather for a given location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
                },
                "required": ["location"]
            }
        }
    ]
}'

# Assuming Turn 1 returns a function_call for get_weather,
# replace INTERACTION_ID and CALL_ID with values from Turn 1 response.
# Turn 2: Provide the function result back to the model.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "previous_interaction_id": "INTERACTION_ID",
    "tools": [
        {"type": "google_search"},
        {
            "type": "function",
            "name": "get_weather",
            "description": "Gets the weather for a given location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
                },
                "required": ["location"]
            }
        }
    ],
    "input": [{
        "type": "function_result",
        "name": "get_weather",
        "call_id": "CALL_ID",
        "result": "{\"response\": \"Very cold. 22 degrees Fahrenheit.\"}"
    }]
}'
Araç bağlamı dolaşımını anlama

Gemini 3 ve daha yeni modeller, sunucu tarafı işlemlerinin güvenilir bir "hafızasını" korumak için araç bağlamı dolaşımını destekler. Yerleşik bir araç (ör. Google Arama) tetiklendiğinde API, belirli toolCall ve toolResponse bölümleri oluşturur. Bu bölümler, modelin bir sonraki dönüşte bu sonuçlar hakkında akıl yürütmek için ihtiyaç duyduğu tam bağlamı içerir.

  • Durumlu (Önerilir): previous_interaction_id kullanıyorsanız API bu dolaşımı sizin için otomatik olarak yönetir.
  • Durum bilgisiz: Geçmişi manuel olarak yönetiyorsanız bu blokları, giriş dizinize API tarafından döndürüldüğü şekilde eklemeniz gerekir.

Uzak Model Context Protocol (MCP)

Uzak MCP entegrasyonu, Gemini API'nin uzak sunucularda barındırılan harici araçları doğrudan çağırmasına olanak tanıyarak aracı geliştirme sürecini basitleştirir.

Python

import datetime
from google import genai

client = genai.Client()

mcp_server = {
    "type": "mcp_server",
    "name": "weather_service",
    "url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}

today = datetime.date.today().strftime("%d %B %Y")

interaction = client.interactions.create(
    model="gemini-2.5-flash",
    input="What is the weather like in New York today?",
    tools=[mcp_server],
    system_instruction=f"Today is {today}."
)

print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const mcpServer = {
    type: 'mcp_server',
    name: 'weather_service',
    url: 'https://gemini-api-demos.uc.r.appspot.com/mcp'
};

const today = new Date().toDateString();

const interaction = await client.interactions.create({
    model: 'gemini-2.5-flash',
    input: 'What is the weather like in New York today?',
    tools: [mcpServer],
    system_instruction: `Today is ${today}.`
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-2.5-flash",
    "input": "What is the weather like in New York today?",
    "tools": [{
        "type": "mcp_server",
        "name": "weather_service",
        "url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
    }],
    "system_instruction": "Today is '"$(date +"%du%Bt%Y")"' YYYY-MM-DD>."
}'

Önemli notlar:

  • Uzak MCP yalnızca yayınlanabilir HTTP sunucularıyla çalışır (SSE sunucuları desteklenmez).
  • Uzak MCP, Gemini 3 modelleriyle çalışmaz (bu özellik yakında kullanıma sunulacaktır)
  • MCP sunucu adları "-" karakterini içermemelidir (bunun yerine snake_case sunucu adları kullanın).

Yapılandırılmış çıkış (JSON şeması)

response_format parametresinde bir JSON şeması sağlayarak belirli bir JSON çıkışını zorunlu kılın. Bu özellik; moderasyon, sınıflandırma veya veri ayıklama gibi görevler için kullanışlıdır.

Python

from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()

class SpamDetails(BaseModel):
    reason: str = Field(description="The reason why the content is considered spam.")
    spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]

class NotSpamDetails(BaseModel):
    summary: str = Field(description="A brief summary of the content.")
    is_safe: bool = Field(description="Whether the content is safe for all audiences.")

class ModerationResult(BaseModel):
    decision: Union[SpamDetails, NotSpamDetails]

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
    response_format=ModerationResult.model_json_schema(),
)

parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)

JavaScript

import { GoogleGenAI } from '@google/genai';
import { z } from 'zod';
const client = new GoogleGenAI({});

const moderationSchema = z.object({
    decision: z.union([
        z.object({
            reason: z.string().describe('The reason why the content is considered spam.'),
            spam_type: z.enum(['phishing', 'scam', 'unsolicited promotion', 'other']).describe('The type of spam.'),
        }).describe('Details for content classified as spam.'),
        z.object({
            summary: z.string().describe('A brief summary of the content.'),
            is_safe: z.boolean().describe('Whether the content is safe for all audiences.'),
        }).describe('Details for content classified as not spam.'),
    ]),
});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
    response_format: z.toJSONSchema(moderationSchema),
});
console.log(interaction.outputs[0].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
    "response_format": {
        "type": "object",
        "properties": {
            "decision": {
                "type": "object",
                "properties": {
                    "reason": {"type": "string", "description": "The reason why the content is considered spam."},
                    "spam_type": {"type": "string", "description": "The type of spam."}
                },
                "required": ["reason", "spam_type"]
            }
        },
        "required": ["decision"]
    }
}'

Araçları birleştirme ve yapılandırılmış çıkış

Bir araç tarafından alınan bilgilere dayalı güvenilir bir JSON nesnesi elde etmek için yerleşik araçları yapılandırılmış çıkışla birleştirin.

Python

from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union

client = genai.Client()

class SpamDetails(BaseModel):
    reason: str = Field(description="The reason why the content is considered spam.")
    spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]

class NotSpamDetails(BaseModel):
    summary: str = Field(description="A brief summary of the content.")
    is_safe: bool = Field(description="Whether the content is safe for all audiences.")

class ModerationResult(BaseModel):
    decision: Union[SpamDetails, NotSpamDetails]

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
    response_format=ModerationResult.model_json_schema(),
    tools=[{"type": "url_context"}]
)

parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)

JavaScript

import { GoogleGenAI } from '@google/genai';
import { z } from 'zod'; // Assuming zod is used for schema generation, or define manually
const client = new GoogleGenAI({});

const obj = z.object({
    winning_team: z.string(),
    score: z.string(),
});
const schema = z.toJSONSchema(obj);

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Who won the last euro?',
    tools: [{ type: 'google_search' }],
    response_format: schema,
});
console.log(interaction.outputs[0].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the last euro?",
    "tools": [{"type": "google_search"}],
    "response_format": {
        "type": "object",
        "properties": {
            "winning_team": {"type": "string"},
            "score": {"type": "string"}
        }
    }
}'

Gelişmiş özellikler

Etkileşimler API'si ile çalışırken daha fazla esneklik sağlayan ek gelişmiş özellikler de vardır.

Canlı Yayın

Yanıtlar oluşturuldukça kademeli olarak alınır.

stream=true olduğunda, son interaction.complete etkinliği outputs alanında oluşturulan içeriği içermiyor. Yalnızca kullanım meta verilerini ve nihai durumu içerir. Tam yanıtı veya araç çağrısı bağımsız değişkenlerini yeniden oluşturmak için content.delta etkinliklerini istemci tarafında toplamanız gerekir.

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Explain quantum entanglement in simple terms.",
    stream=True
)

for chunk in stream:
    if chunk.event_type == "content.delta":
        if chunk.delta.type == "text":
            print(chunk.delta.text, end="", flush=True)
        elif chunk.delta.type == "thought":
            print(chunk.delta.thought, end="", flush=True)
    elif chunk.event_type == "interaction.complete":
        print(f"\n\n--- Stream Finished ---")
        print(f"Total Tokens: {chunk.interaction.usage.total_tokens}")

JavaScript

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

const client = new GoogleGenAI({});

const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Explain quantum entanglement in simple terms.',
    stream: true,
});

for await (const chunk of stream) {
    if (chunk.event_type === 'content.delta') {
        if (chunk.delta.type === 'text' && 'text' in chunk.delta) {
            process.stdout.write(chunk.delta.text);
        } else if (chunk.delta.type === 'thought' && 'thought' in chunk.delta) {
            process.stdout.write(chunk.delta.thought);
        }
    } else if (chunk.event_type === 'interaction.complete') {
        console.log('\n\n--- Stream Finished ---');
        console.log(`Total Tokens: ${chunk.interaction.usage.total_tokens}`);
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Explain quantum entanglement in simple terms.",
    "stream": true
}'

Yayın etkinliği türleri

Akış etkinleştirildiğinde API, sunucu tarafından gönderilen etkinlikleri (SSE) döndürür. Her etkinliğin amacını belirten bir event_type alanı vardır. Etkinlik türlerinin tam listesi API referansında mevcuttur.

Etkinlik Türü Açıklama
interaction.start İlk etkinlik. Etkileşim id ve ilk status (in_progress) öğesini içerir.
interaction.status_update Durum değişikliklerini (ör. in_progress) gösterir.
content.start Yeni bir çıkış bloğunun başlangıcını işaretler. index ve type içeriklerini (ör. text, thought) içerir.
content.delta Artımlı içerik güncellemeleri. delta.type ile anahtarlanmış kısmi verileri içerir.
content.stop index konumundaki bir çıktı bloğunun sonunu işaretler.
interaction.complete Son etkinlik. id, status, usage ve meta verileri içerir. Not: outputs, None'dir. Çıkışları content.* etkinliklerinden yeniden oluşturmanız gerekir.
error Bir hata oluştuğunu gösterir. error.code ve error.message içerir.

Etkileşim nesnesini yayın etkinliklerinden yeniden oluşturma

Akış şeklinde olmayan yanıtların aksine, akış şeklinde yanıtlar dizisi içermez.outputs content.delta etkinliklerinden içerik toplayarak çıkışları yeniden oluşturmanız gerekir.

Python

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Write a haiku about Python programming.",
    stream=True
)

# Accumulate outputs by index
outputs = {}
usage = None

for chunk in stream:
    if chunk.event_type == "content.start":
        outputs[chunk.index] = {"type": chunk.content.type}

    elif chunk.event_type == "content.delta":
        output = outputs[chunk.index]
        if chunk.delta.type == "text":
            output["text"] = output.get("text", "") + chunk.delta.text
        elif chunk.delta.type == "thought_signature":
            output["signature"] = chunk.delta.signature
        elif chunk.delta.type == "thought_summary":
            output["summary"] = output.get("summary", "") + getattr(chunk.delta.content, "text", "")

    elif chunk.event_type == "interaction.complete":
        usage = chunk.interaction.usage

# Final outputs list (sorted by index)
final_outputs = [outputs[i] for i in sorted(outputs.keys())]
print(f"\n\nOutputs: {final_outputs}")

JavaScript

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

const client = new GoogleGenAI({});

const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Write a haiku about Python programming.',
    stream: true,
});

// Accumulate outputs by index
const outputs = new Map();
let usage = null;

for await (const chunk of stream) {
    if (chunk.event_type === 'content.start') {
        outputs.set(chunk.index, { type: chunk.content.type });

    } else if (chunk.event_type === 'content.delta') {
        const output = outputs.get(chunk.index);
        if (chunk.delta.type === 'text') {
            output.text = (output.text || '') + chunk.delta.text;
            process.stdout.write(chunk.delta.text);
        } else if (chunk.delta.type === 'thought_signature') {
            output.signature = chunk.delta.signature;
        } else if (chunk.delta.type === 'thought_summary') {
            output.summary = (output.summary || '') + (chunk.delta.content?.text || '');
        }

    } else if (chunk.event_type === 'interaction.complete') {
        usage = chunk.interaction.usage;
    }
}

// Final outputs list (sorted by index)
const finalOutputs = [...outputs.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(([_, output]) => output);
console.log(`\n\nOutputs:`, finalOutputs);

Akış aracı çağrıları

Model, akışla birlikte araçları kullanırken akışta bir dizi content.delta etkinliği olarak işlev çağrıları oluşturur. Metinden farklı olarak, araç bağımsız değişkenleri tek bir content.delta etkinliği içinde eksiksiz JSON nesneleri olarak sunulur. Yayın sırasında interaction.complete etkinliğinde outputs dizisi boşsa araç çağrılarını aşağıdaki gibi deltalardan yakalamanız gerekir.

Python

from google import genai
import json

client = genai.Client()

weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The city and state"}
        },
        "required": ["location"]
    }
}

stream = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the weather in Paris?",
    tools=[weather_tool],
    stream=True
)

# A map to capture tool calls by their ID as they arrive
function_calls = {}

for chunk in stream:
    if chunk.event_type == "content.delta":
        if chunk.delta.type == "text" and chunk.delta.text:
            print(chunk.delta.text, end="", flush=True)

        elif chunk.delta.type == "function_call":
            print(f"\nExecuting {chunk.delta.name} immediately...")
            # result = my_tools[chunk.delta.name](**chunk.delta.arguments)
            function_calls[chunk.delta.id] = chunk.delta

    elif chunk.event_type == "interaction.complete":
        print("\n\nAll tools executed. Stream finished.")

JavaScript

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

const client = new GoogleGenAI({});

const weatherTool = {
    type: 'function',
    name: 'get_weather',
    description: 'Gets the weather for a given location.',
    parameters: {
        type: 'object',
        properties: {
            location: { type: 'string', description: 'The city and state' }
        },
        required: ['location']
    }
};

const stream = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'What is the weather in Paris?',
    tools: [weatherTool],
    stream: true,
});

const toolCalls = new Map();

for await (const chunk of stream) {
    if (chunk.event_type === 'content.delta') {
        if (chunk.delta.type === 'text' && chunk.delta.text) {
            process.stdout.write(chunk.delta.text);

        } else if (chunk.delta.type === 'function_call') {
            console.log(`\nExecuting ${chunk.delta.name} immediately...`);
            // const result = myTools[chunk.delta.name](chunk.delta.arguments);
            toolCalls.set(chunk.delta.id, chunk.delta);
        }
    } else if (chunk.event_type === 'interaction.complete') {
        console.log('\n\nAll tools executed. Stream finished.');
    }
}

REST

# When streaming via SSE, capture function_call data from content.delta events.
# The 'arguments' field arrives as a complete JSON object once generated.

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the weather in Paris?",
    "tools": [{
        "type": "function",
        "name": "get_weather",
        "description": "Gets the weather for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "The city and state"}
            },
            "required": ["location"]
        }
    }],
    "stream": true
}'

Yapılandırma

generation_config ile modelin davranışını özelleştirin.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Tell me a story about a brave knight.",
    generation_config={
        "temperature": 0.7,
        "max_output_tokens": 500,
        "thinking_level": "low",
    }
)

print(interaction.outputs[-1].text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Tell me a story about a brave knight.',
    generation_config: {
        temperature: 0.7,
        max_output_tokens: 500,
        thinking_level: 'low',
    }
});

console.log(interaction.outputs[interaction.outputs.length - 1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Tell me a story about a brave knight.",
    "generation_config": {
        "temperature": 0.7,
        "max_output_tokens": 500,
        "thinking_level": "low"
    }
}'

Düşünen

Gemini 2.5 ve daha yeni modeller, yanıt oluşturmadan önce "düşünme" adı verilen dahili bir akıl yürütme süreci kullanır. Bu sayede model, matematik, kodlama ve çok adımlı akıl yürütme gibi karmaşık görevler için daha iyi yanıtlar üretebilir.

Düşünme düzeyi

thinking_level parametresi, modelin muhakeme derinliğini kontrol etmenizi sağlar:

Seviye Açıklama Desteklenen Modeller
minimal Çoğu sorgu için "düşünme yok" ayarıyla eşleşir. Bazı durumlarda modeller çok az düşünebilir. Gecikmeyi ve maliyeti en aza indirir. Yalnızca Flash Modelleri
(ör. Gemini 3 Flash)
low Basit talimatları uygulamaya ve sohbet etmeye yönelik gecikme süresine ve maliyet tasarrufuna öncelik veren hafif akıl yürütme. Tüm Düşünce Modelleri
medium Çoğu görev için dengeli düşünme Yalnızca Flash Modelleri
(ör. Gemini 3 Flash)
high (Varsayılan) Muhakeme derinliğini en üst düzeye çıkarır. Modelin ilk jetona ulaşması önemli ölçüde daha uzun sürebilir ancak çıkış daha dikkatli bir şekilde gerekçelendirilir. Tüm Düşünce Modelleri

Düşünme özetleri

Modelin düşünme süreci, yanıt çıkışlarında düşünce blokları (type: "thought") olarak gösterilir. thinking_summaries parametresini kullanarak düşünce sürecinin insan tarafından okunabilir özetlerini alıp almayacağınızı kontrol edebilirsiniz:

Değer Açıklama
auto (Varsayılan) Kullanılabilir olduğunda düşünce özetlerini döndürür.
none Düşünce özetlerini devre dışı bırakır.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Solve this step by step: What is 15% of 240?",
    generation_config={
        "thinking_level": "high",
        "thinking_summaries": "auto"
    }
)

for output in interaction.outputs:
    if output.type == "thought":
        print(f"Thinking: {output.summary}")
    elif output.type == "text":
        print(f"Answer: {output.text}")

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: 'Solve this step by step: What is 15% of 240?',
    generation_config: {
        thinking_level: 'high',
        thinking_summaries: 'auto'
    }
});

for (const output of interaction.outputs) {
    if (output.type === 'thought') {
        console.log(`Thinking: ${output.summary}`);
    } else if (output.type === 'text') {
        console.log(`Answer: ${output.text}`);
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "Solve this step by step: What is 15% of 240?",
    "generation_config": {
        "thinking_level": "high",
        "thinking_summaries": "auto"
    }
}'

Her düşünce bloğu bir signature alanı (dahili akıl yürütme durumunun kriptografik karması) ve isteğe bağlı bir summary alanı (modelin akıl yürütmesinin insan tarafından okunabilir özeti) içerir. signature her zaman bulunur ancak bu durumlarda düşünce bloğu yalnızca imza içerebilir ve özet içermeyebilir:

  • Basit istekler: Model, özet oluşturmak için yeterince gerekçe sunmadı.
  • thinking_summaries: "none": Özetler açıkça devre dışı bırakıldı

Kodunuz, summary öğesinin boş veya eksik olduğu düşünce bloklarını her zaman işlemelidir. Görüşme geçmişini manuel olarak yönetirken (durum bilgisiz mod), orijinalliği doğrulamak için sonraki isteklerde imzalarıyla birlikte düşünce bloklarını eklemeniz gerekir.

Dosyalarla çalışma

Uzak dosyalarla çalışma

API çağrısında doğrudan uzak URL'leri kullanarak dosyalara erişme.

Python

from google import genai
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {
            "type": "image",
            "uri": "https://github.com/<github-path>/cats-and-dogs.jpg",
        },
        {"type": "text", "text": "Describe what you see."}
    ],
)
for output in interaction.outputs:
    if output.type == "text":
        print(output.text)

JavaScript

import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        {
            type: 'image',
            uri: 'https://github.com/<github-path>/cats-and-dogs.jpg',
        },
        { type: 'text', text: 'Describe what you see.' }
    ],
});
for (const output of interaction.outputs) {
    if (output.type === 'text') {
        console.log(output.text);
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {
            "type": "image",
            "uri": "https://github.com/<github-path>/cats-and-dogs.jpg"
        },
        {"type": "text", "text": "Describe what you see."}
    ]
}'

Gemini Files API ile çalışma

Dosyaları kullanmadan önce Gemini Files API'ye yükleyin.

Python

from google import genai
import time
import requests
client = genai.Client()

# 1. Download the file
url = "https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg"
response = requests.get(url)
with open("cats-and-dogs.jpg", "wb") as f:
    f.write(response.content)

# 2. Upload to Gemini Files API
file = client.files.upload(file="cats-and-dogs.jpg")

# 3. Wait for processing
while client.files.get(name=file.name).state != "ACTIVE":
    time.sleep(2)

# 4. Use in Interaction
interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {
            "type": "image",
            "uri": file.uri,
        },
        {"type": "text", "text": "Describe what you see."}
    ],
)
for output in interaction.outputs:
    if output.type == "text":
        print(output.text)

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import fetch from 'node-fetch';
const client = new GoogleGenAI({});

// 1. Download the file
const url = 'https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg';
const filename = 'cats-and-dogs.jpg';
const response = await fetch(url);
const buffer = await response.buffer();
fs.writeFileSync(filename, buffer);

// 2. Upload to Gemini Files API
const myfile = await client.files.upload({ file: filename, config: { mimeType: 'image/jpeg' } });

// 3. Wait for processing
while ((await client.files.get({ name: myfile.name })).state !== 'ACTIVE') {
    await new Promise(resolve => setTimeout(resolve, 2000));
}

// 4. Use in Interaction
const interaction = await client.interactions.create({
    model: 'gemini-3-flash-preview',
    input: [
        { type: 'image', uri: myfile.uri, },
        { type: 'text', text: 'Describe what you see.' }
    ],
});
for (const output of interaction.outputs) {
    if (output.type === 'text') {
        console.log(output.text);
    }
}

REST

# 1. Upload the file (Requires File API setup)
# See https://ai.google.dev/gemini-api/docs/files for details.
# Assume FILE_URI is obtained from the upload step.

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "gemini-3-flash-preview",
    "input": [
        {"type": "image", "uri": "FILE_URI"},
        {"type": "text", "text": "Describe what you see."}
    ]
}'

Veri modeli

Veri modeli hakkında daha fazla bilgiyi API Referansı'nda bulabilirsiniz. Aşağıda, ana bileşenlere ilişkin üst düzey bir genel bakış verilmiştir.

Etkileşim

Mülk Tür Açıklama
id string Etkileşimin benzersiz tanımlayıcısı.
model/agent string Kullanılan model veya aracı. Yalnızca bir tane sağlanabilir.
input Content[] Sağlanan girişler.
outputs Content[] Modelin yanıtları
tools Tool[] Kullanılan araçlar
previous_interaction_id string Bağlam için önceki etkileşimin kimliği.
stream boolean Etkileşimin yayınlanıp yayınlanmadığı
status string Durum: completed, in_progress, requires_action,failed vb.
background boolean Etkileşimin arka plan modunda olup olmadığı.
store boolean Etkileşimin saklanıp saklanmayacağı. Varsayılan: true. Devre dışı bırakmak için false olarak ayarlayın.
usage Kullanım Etkileşim isteğinin jeton kullanımı.

Desteklenen modeller ve temsilciler

Model Adı Tür Model Kimliği
Gemini 3.1 Flash-Lite Önizlemesi Model gemini-3.1-flash-lite-preview
Gemini 3.1 Pro Önizlemesi Model gemini-3.1-pro-preview
Gemini 3 Flash Önizlemesi Model gemini-3-flash-preview
Gemini 2.5 Pro Model gemini-2.5-pro
Gemini 2.5 Flash Model gemini-2.5-flash
Gemini 2.5 Flash-lite Model gemini-2.5-flash-lite
Deep Research Önizlemesi Temsilci deep-research-pro-preview-12-2025

Etkileşimler API'sinin işleyiş şekli

Etkileşimler API'si, merkezi bir kaynak olan Interaction etrafında tasarlanmıştır. Interaction, bir görüşme veya görevdeki tam dönüşü temsil eder. Tüm kullanıcı girişleri, model düşünceleri, araç çağrıları, araç sonuçları ve nihai model çıkışları dahil olmak üzere bir etkileşimin tüm geçmişini içeren bir oturum kaydı olarak işlev görür.

interactions.create adresine çağrı yaptığınızda yeni bir Interaction kaynağı oluşturursunuz.

Sunucu tarafı durum yönetimi

Sohbete devam etmek için previous_interaction_id parametresini kullanarak sonraki bir çağrıda tamamlanmış bir etkileşimin id değerini kullanabilirsiniz. Sunucu, sohbet geçmişini almak için bu kimliği kullanır. Böylece tüm sohbet geçmişini yeniden göndermeniz gerekmez.

previous_interaction_id kullanılarak yalnızca görüşme geçmişi (girişler ve çıkışlar) korunur. Diğer parametreler etkileşim kapsamlıdır ve yalnızca şu anda oluşturduğunuz etkileşim için geçerlidir:

  • tools
  • system_instruction
  • generation_config (thinking_level, temperature vb. dahil)

Bu, geçerli olmasını istediğiniz takdirde bu parametreleri her yeni etkileşimde yeniden belirtmeniz gerektiği anlamına gelir. Bu sunucu tarafı durum yönetimi isteğe bağlıdır. Her istekte tam görüşme geçmişini göndererek durum bilgisiz modda da çalışabilirsiniz.

Veri depolama ve saklama

Varsayılan olarak, sunucu tarafı durum yönetimi özelliklerinin (store=true ile), arka planda yürütmenin (background=true kullanılarak) ve gözlemlenebilirlik amaçlarının kullanımını basitleştirmek için tüm Etkileşim nesneleri depolanır (store=true).previous_interaction_id

  • Ücretli katman: Etkileşimler 55 gün boyunca saklanır.
  • Ücretsiz katman: Etkileşimler 1 gün boyunca saklanır.

Bunu istemiyorsanız isteğinizde store=false ayarlayabilirsiniz. Bu kontrol, durum yönetiminden ayrıdır. Herhangi bir etkileşim için depolamayı devre dışı bırakabilirsiniz. Ancak store=false ile background=true'nin uyumsuz olduğunu ve sonraki dönüşlerde previous_interaction_id'nin kullanılmasını engellediğini unutmayın.

API Referansı'nda bulunan silme yöntemini kullanarak depolanan etkileşimleri istediğiniz zaman silebilirsiniz. Yalnızca etkileşim kimliğini biliyorsanız etkileşimleri silebilirsiniz.

Saklama süresi sona erdikten sonra verileriniz otomatik olarak silinir.

Etkileşim nesneleri, şartlara göre işlenir.

En iyi uygulamalar

  • Önbellek isabet oranı: Konuşmalara devam etmek için previous_interaction_id kullanıldığında sistem, konuşma geçmişi için örtülü önbelleğe almayı daha kolay kullanabilir. Bu da performansı artırır ve maliyetleri düşürür.
  • Etkileşimleri karıştırma: Bir görüşmede Aracı ve Model etkileşimlerini karıştırıp eşleştirebilirsiniz. Örneğin, ilk veri toplama için Deep Research aracısı gibi özel bir aracı kullanabilir, ardından özetleme veya yeniden biçimlendirme gibi takip görevleri için standart bir Gemini modeli kullanabilirsiniz. Bu adımları previous_interaction_id ile bağlayabilirsiniz.

SDK'lar

Etkileşimler API'sine erişmek için Google GenAI SDK'larının en son sürümünü kullanabilirsiniz.

  • Python'da bu, 1.55.0 sürümünden itibaren google-genai paketidir.
  • JavaScript'te bu, 1.33.0 sürümünden itibaren @google/genai paketidir.

SDK'ları nasıl yükleyeceğiniz hakkında daha fazla bilgiyi Kitaplıklar sayfasında bulabilirsiniz.

Sınırlamalar

  • Beta durumu: Etkileşimler API'si beta/önizleme sürümündedir. Özellikler ve şemalar değişebilir.
  • Uzak MCP: Gemini 3, uzak MCP'yi desteklemez. Bu özellik yakında kullanıma sunulacaktır.

Zarar veren değişiklikler

Etkileşimler API'si şu anda erken beta aşamasındadır. API özelliklerini, kaynak şemalarını ve SDK arayüzlerini gerçek hayattaki kullanıma ve geliştirici geri bildirimlerine göre aktif olarak geliştirip iyileştiriyoruz.

Bu nedenle, uyumluluğu bozan değişiklikler olabilir. Güncellemeler şunlarda değişiklikler içerebilir:

  • Giriş ve çıkış şemaları.
  • SDK yöntemi imzaları ve nesne yapıları.
  • Belirli özelliklerin davranışları.

Üretim iş yükleri için standart generateContent API'yi kullanmaya devam etmelisiniz. Kararlı dağıtımlar için önerilen yol olmaya devam eder ve aktif olarak geliştirilip sürdürülür.

Geri bildirim

Geri bildiriminiz, Etkileşimler API'sinin geliştirilmesi açısından büyük önem taşır. Düşüncelerinizi paylaşmak, hataları bildirmek veya özellik isteğinde bulunmak için Google AI Geliştirici Topluluğu Forumu'nu kullanabilirsiniz.

Sırada ne var?