Interactions API (בטא) הוא ממשק מאוחד לאינטראקציה עם מודלים וסוכנים של Gemini. הוא מהווה חלופה משופרת ל-API generateContent, ומפשט את ניהול המצב, את תזמור הכלים ואת המשימות ארוכות הטווח. לסקירה מקיפה של סכימת ה-API, ראו הפניית API. במהלך תקופת הבטא, התכונות והסכימות כפופות לשינויים שעלולים לשבור את התאימות לאחור.
כדי להתחיל במהירות, כדאי לנסות את המדריך למתחילים בנושא Interactions API.
בדוגמה הבאה אפשר לראות איך שולחים קריאה ל-API של אינטראקציות עם הנחיה טקסטואלית.
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."
}'
אינטראקציות בסיסיות
Interactions API זמין דרך ערכות ה-SDK הקיימות שלנו. הדרך הכי פשוטה ליצור אינטראקציה עם המודל היא באמצעות הנחיה טקסטואלית. input יכול להיות מחרוזת, רשימה שמכילה אובייקטים של תוכן או רשימה של תורות עם תפקידים ואובייקטים של תוכן.
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."
}'
שיחה
יש שתי דרכים ליצור שיחות מרובות תפניות:
- עם שמירת מצב, על ידי הפניה לאינטראקציה קודמת
- ללא שמירת מצב, על ידי אספקת היסטוריית השיחות המלאה
שיחה עם מצב
כדי להמשיך שיחה, מעבירים את id מהאינטראקציה הקודמת לפרמטר previous_interaction_id. ה-API זוכר את היסטוריית השיחות, כך שצריך לשלוח רק את הקלט החדש. פרטים על השדות שמועברים בירושה ועל השדות שצריך לציין מחדש מופיעים במאמר ניהול מצב בצד השרת.
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"
# }'
אחזור אינטראקציות קודמות עם שמירת מצב
שימוש באינטראקציה id כדי לאחזר תורות קודמות בשיחה.
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"
הכללת הקלט המקורי
כברירת מחדל, הפונקציה interactions.get() מחזירה רק את הפלט של המודל. כדי לכלול את הקלט המקורי שעבר נורמליזציה בתשובה, מגדירים את include_input ל-true.
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"
שיחה ללא מצב
אתם יכולים לנהל את היסטוריית השיחות באופן ידני בצד הלקוח.
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?"
}
]
}'
יכולות מולטי-מודאליות
אפשר להשתמש ב-Interactions API לתרחישי שימוש מולטימודאליים כמו הבנת תמונות או יצירת סרטונים.
הבנה מולטי-מודאלית
אפשר לספק קלט מולטימודאלי כנתונים מוטבעים שמקודדים ב-Base64, באמצעות Files API לקבצים גדולים יותר, או על ידי העברת קישור שזמין לציבור בשדה uri. בדוגמאות הקוד הבאות מוצגת השיטה של כתובת URL ציבורית.
הבנת תמונות
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"
}
]
}'
הבנת אודיו
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"
}
]
}'
הבנת סרטונים
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"
}
]
}'
הבנת מסמכים (PDF)
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"
}
]
}'
יצירה מולטי-מודאלית
אתם יכולים להשתמש ב-Interactions API כדי ליצור פלט רב-אופני.
יצירת תמונות
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"]
}'
הגדרת פלט התמונה
אתם יכולים להתאים אישית את התמונות שנוצרו באמצעות image_config בתוך generation_config
כדי לשלוט ביחס הגובה-רוחב וברזולוציה.
| פרמטר | אפשרויות | תיאור |
|---|---|---|
aspect_ratio |
1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
הגדרה שקובעת את יחס הגובה-רוחב של תמונת הפלט. |
image_size |
1k, 2k, 4k |
ההגדרה הזו קובעת את הרזולוציה של תמונת הפלט. |
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"
}
}
}'
יצירת דיבור
יצירת דיבור שנשמע טבעי מטקסט באמצעות מודל להמרת טקסט לדיבור (TTS).
מגדירים את ההגדרות של הקול, השפה והרמקול באמצעות הפרמטר speech_config.
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
יצירת דיבור של כמה דוברים
כדי ליצור דיבור עם כמה דוברים, מציינים את שמות הדוברים בהנחיה
ומתאימים אותם ב-speech_config.
ההנחיה צריכה לכלול את שמות הדוברים:
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.
אחר כך מגדירים את speech_config עם רמקולים תואמים:
"generation_config": {
"speech_config": [
{"voice": "Zephyr", "speaker": "Alice", "language": "en-US"},
{"voice": "Puck", "speaker": "Bob", "language": "en-US"}
]
}
יצירת מוזיקה
אתם יכולים ליצור מוזיקה באיכות גבוהה מהנחיות טקסט באמצעות מודלים של Lyria 3. Interactions API תומך גם בקליפים קצרים וגם בשירים באורך מלא עם שירה, מילים ועיבודים אינסטרומנטליים.
מדריך מלא ליצירת מוזיקה, כולל מילים בהתאמה אישית, שליטה בתזמון ומוזיקה מתמונות, זמין במאמר יצירת מוזיקה באמצעות Lyria 3.
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="lyria-3-clip-preview",
input="Create a 30-second cheerful acoustic folk song with "
"guitar and harmonica.",
response_modalities=["AUDIO", "TEXT"]
)
for output in interaction.outputs:
if output.type == "audio":
print(f"Generated audio with mime_type: {output.mime_type}")
with open("music.mp3", "wb") as f:
f.write(base64.b64decode(output.data))
elif output.type == "text":
print(f"Lyrics: {output.text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'lyria-3-clip-preview',
input: 'Create a 30-second cheerful acoustic folk song with ' +
'guitar and harmonica.',
response_modalities: ['AUDIO', 'TEXT']
});
for (const output of interaction.outputs) {
if (output.type === 'audio') {
console.log(`Generated audio with mime_type: ${output.mime_type}`);
fs.writeFileSync('music.mp3', Buffer.from(output.data, 'base64'));
} else if (output.type === 'text') {
console.log(`Lyrics: ${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": "lyria-3-clip-preview",
"input": "Create a 30-second cheerful acoustic folk song with guitar and harmonica.",
"response_modalities": ["AUDIO", "TEXT"]
}'
לשירים באורך מלא (עד 4 דקות בערך), משתמשים במודל lyria-3-pro-preview:
Python
interaction = client.interactions.create(
model="lyria-3-pro-preview",
input="An epic cinematic orchestral piece about a journey home. "
"Starts with a solo piano intro, builds through sweeping "
"strings, and climaxes with a massive wall of sound.",
response_modalities=["AUDIO", "TEXT"]
)
JavaScript
const interaction = await client.interactions.create({
model: 'lyria-3-pro-preview',
input: 'An epic cinematic orchestral piece about a journey home. ' +
'Starts with a solo piano intro, builds through sweeping ' +
'strings, and climaxes with a massive wall of sound.',
response_modalities: ['AUDIO', '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": "lyria-3-pro-preview",
"input": "An epic cinematic orchestral piece about a journey home. Starts with a solo piano intro, builds through sweeping strings, and climaxes with a massive wall of sound.",
"response_modalities": ["AUDIO", "TEXT"]
}'
יכולות של AI אקטיבי
ממשק Interactions API מיועד ליצירת סוכנים ולתקשורת איתם, והוא כולל תמיכה בהפעלת פונקציות, בכלים מובנים, בפלט מובנה וב-Model Context Protocol (MCP).
סוכנים
אתם יכולים להשתמש בסוכנים ייעודיים כמו deep-research-pro-preview-12-2025 למשימות מורכבות. מידע נוסף על סוכן Deep Research של Gemini זמין במדריך בנושא Deep Research.
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"
כלים ובקשות להפעלת פונקציה
בקטע הזה מוסבר איך להשתמש בקריאות לפונקציות כדי להגדיר כלים בהתאמה אישית, ואיך להשתמש בכלים המובנים של Google ב-Interactions API.
בקשה להפעלת פונקציה
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."
# }]
# }'
בקשה להפעלת פונקציה עם מצב בצד הלקוח
אם לא רוצים להשתמש במצב בצד השרת, אפשר לנהל את הכל בצד הלקוח.
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}`);
}
}
תוצאות של פונקציות מרובות מצבים
השדה result באובייקט function_result יכול להכיל מחרוזת פשוטה או מערך של אובייקטים מסוג TextContent ו-ImageContent. האפשרות הזו מאפשרת לכם להחזיר תמונות, כמו צילומי מסך או תרשימים, לצד טקסט מבקשות להפעלת פונקציה, כדי שהמודל יוכל להסיק מסקנות לגבי הפלט החזותי.
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"}
# ]
# }]
# }'
כלים מובנים
Gemini כולל כלים מובנים כמו עיגון בנתונים באמצעות חיפוש Google, עיגון בנתונים באמצעות חיפוש תמונות ב-Google, עיגון בעזרת מפות Google, הרצת קוד, הקשר של כתובת URL ושימוש במחשב.
עיגון באמצעות חיפוש Google
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 (רק עבור מודל 3.1 Flash Image)
ההארקה באמצעות חיפוש התמונות ב-Google מאפשרת למודלים להשתמש בתמונות מהאינטרנט שאוחזרו באמצעות חיפוש התמונות ב-Google כהקשר חזותי ליצירת תמונות. חיפוש תמונות הוא סוג חיפוש חדש בכלי הקיים 'הצגת תוצאות מחיפוש Google', והוא פועל לצד חיפוש רגיל באינטרנט.
הפעלת חיפוש תמונות
כדי לבקש תוצאות של תמונות, מוסיפים "image_search" למערך search_types של הכלי google_search.
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"]
}]
}'
דרישות חובה להצגה
כדי לעמוד בדרישות התנאים וההגבלות של חיפוש Google, בממשק המשתמש שלכם צריכות להיות שתי רמות שונות של שיוך:
שיוך בחיפוש Google
אתם צריכים להציג את הצעות החיפוש 'בדיקה ב-Google' שמופיעות בבלוק
google_search_result.- שדה:
rendered_content(HTML/CSS) - פעולה: הצגת הצ'יפ הזה כמו שהוא ליד התשובה של המודל.
- שדה:
שיוך למקורות תנועה של בעלי תוכן דיגיטלי
עליכם לספק קישור ל'דף המכיל' (דף הנחיתה) של כל תמונה שמוצגת.
- שדה:
url(נמצא במערךresult) - דרישה: צריך לספק נתיב ישיר של קליק יחיד מהתמונה לדף האינטרנט המקורי שמכיל אותה. אסור להשתמש בכלי לצפייה בתמונות ביניים או בנתיבי קליקים מרובים.
- שדה:
איך מטפלים בתשובה מעוגנת
בקטע הקוד הבא אפשר לראות איך מטפלים בבלוקים של תגובות משולבות גם לנתוני תמונה גולמיים וגם לשיוך נדרש.
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}`);
}
}
}
סכימת הפלט הצפויה
בלוק התמונה (סוג: "image") מכיל את הנתונים החזותיים הגולמיים שנוצרו או שאוחזרו על ידי המודל.
{
"type": "image",
"mime_type": "image/png",
"data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB..." // Base64 content
}
בלוק התוצאות (סוג: "google_search_result") מכיל את מטא-נתוני השיוך (Attribution) שחובה לקשר לחיפוש.
{
"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
עיגון בעזרת מפות Google מאפשר למודלים להשתמש בנתונים של מפות Google כדי לספק הקשר חזותי, סיכות במפה וגילוי מבוסס-מיקום.
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"}]
}'
דרישות לשימוש בשירות
כשמציגים תוצאות של עיגון בעזרת מפות Google, צריך לפעול בהתאם לתנאים ולהגבלות של מפות Google. אתם צריכים להודיע למשתמשים שלכם על הדברים הבאים ולעמוד בדרישות ההצגה האלה:
- ליידע את המשתמש: מיד אחרי התוכן שנוצר, צריך לציין את המקורות הרלוונטיים במפות Google. המקורות צריכים להיות גלויים במהלך אינטראקציה אחת של המשתמש.
- הצגת קישורים: יצירת תצוגה מקדימה של קישור לכל מקור (כולל קטעי מידע על ביקורות, אם יש כאלה).
- ייחוס ל'מפות Google': פועלים לפי ההנחיות לייחוס טקסט.
- הצגת שם המקור.
- מקשרים למקור באמצעות כתובת ה-URL שסופקה.
- הנחיות לשיוך: אסור לשנות את הטקסט 'מפות Google' (למשל: שימוש באותיות רישיות, גלישת טקסט). משתמשים לא יוכלו לתרגם בדפדפן באמצעות
translate="no".
טיפול בתשובה
בקטע הקוד הבא אפשר לראות איך מעבדים את התגובה על ידי חילוץ הטקסט והציטוטים המוטבעים (כולל קטעי מידע מביקורות) כדי לעמוד בדרישות התצוגה.
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})`);
}
}
}
}
}
}
}
סכימת הפלט הצפויה
כשמשתמשים ב-עיגון בעזרת מפות Google, צפוי פלט עם סכימת הנתונים הבאה.
בלוק התוצאה (סוג: "google_maps_result") מכיל את הנתונים המובְנים של המקום.
{
"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": "..."
}
בלוק הטקסט (סוג: "text") מכיל את התוכן שנוצר עם אנוטציות מוטבעות.
{
"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
}
]
}
הרצת קוד
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
ההארקה באמצעות הקשר של כתובת URL מאפשרת למודל לקרוא כתובות URL ציבוריות שמופיעות בהנחיה או ברשימת הכלים.
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"}]
)
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' }]
});
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"}]
}'
טיפול בתשובה
בקטע הקוד הבא אפשר לראות איך לטפל בתגובה על ידי חילוץ הטקסט וההפניות המוטמעות (סוג url_citation).
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") == "url_citation":
print(f"- {annotation['title']}: {annotation['url']}")
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 === 'url_citation') {
console.log(`- ${annotation.title}: ${annotation.url}`);
}
}
}
}
}
סכימת הפלט הצפויה
כשמשתמשים בהקשר של כתובת URL, צפוי פלט עם סכימת הנתונים הבאה.
בלוק שיחות (סוג: "url_context_call") מכיל את כתובת ה-URL שהמודל ניסה לקרוא.
{
"type": "url_context_call",
"id": "browse_001",
"arguments": {
"urls": ["https://www.wikipedia.org/"]
},
"signature": "EkYKIGY5OT..."
}
בלוק התוצאה (סוג: "url_context_result") מכיל את סטטוס האחזור.
{
"type": "url_context_result",
"call_id": "browse_001",
"result": {
"url": "https://www.wikipedia.org/",
"status": "URL_RETRIEVAL_STATUS_SUCCESS"
},
"signature": "EkYKIGY5OT..."
}
בלוק הטקסט מכיל את הטקסט שנוצר ואת הציטוטים שמשולבים בטקסט.
{
"type": "text",
"text": "Wikipedia is a free online encyclopedia...",
"annotations": [
{
"type": "url_citation",
"url": "https://www.wikipedia.org/",
"title": "Wikipedia — Main Page",
"start_index": 0,
"end_index": 42
}
]
}
שימוש במחשב
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"]
}]
}'
התמודדות עם תוצאות של פונקציית השימוש במחשב
מכיוון שהשימוש במחשב הוא לולאה של כלי בצד הלקוח, צריך לבצע את הפעולה (לדוגמה, פתיחת דפדפן) ולשלוח את התוצאה בחזרה למודל. כששולחים את function_result לפעולות כמו open_web_browser, חשוב להעביר את תגובת כתובת ה-URL ברשימת התוצאות כמו שמוצג בהמשך:
{
"type": "function_result",
"name": "open_web_browser",
"call_id": "5q6h0z70",
"result": [
{
"type": "text",
"text": "{\"url\": \"https://google.com\", \"safety_acknowledgement\":true}"
},
{
"type": "image",
"data": "iVBORw0KGgoAAAANSUhEUgAA...",
"mime_type": "image/png"
}
]
}
חיפוש קבצים
ההארקה באמצעות חיפוש קבצים מאפשרת למודל לחפש את הקבצים שהעליתם במאגרי חיפוש קבצים.
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"]}]
)
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'] }]
});
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"]}]
}'
טיפול בתשובה
בקטע הקוד הבא אפשר לראות איך לטפל בתגובה על ידי חילוץ הטקסט וההפניות המוטמעות (סוג file_citation).
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") == "file_citation":
print(f"- {annotation['file_name']} ({annotation['document_uri']}):")
print(f" Snippet: {annotation['source']}")
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 === 'file_citation') {
console.log(`- ${annotation.fileName} (${annotation.documentUri}):`);
console.log(` Snippet: ${annotation.source}`);
}
}
}
}
}
סכימת הפלט הצפויה
כשמשתמשים בחיפוש קבצים, צפוי פלט עם סכימת הנתונים הבאה.
המאפיין Call Block (סוג: "file_search_call") מכיל את המטא-נתונים של השיחה.
{
"type": "file_search_call",
"id": "filesearch_001",
"signature": "EkYKIGY5OT..."
}
בלוק התוצאה (סוג: "file_search_result") מכיל את המטא-נתונים של התוצאה.
{
"type": "file_search_result",
"call_id": "filesearch_001",
"signature": "EkYKIGY5OT..."
}
בלוק הטקסט מכיל את הטקסט שנוצר ואת הציטוטים שמשולבים בטקסט.
{
"type": "text",
"text": "The book 'I, Claudius' is a historical novel by Robert Graves...",
"annotations": [
{
"type": "file_citation",
"document_uri": "fileSearchStores/my-store-name/documents/abc",
"file_name": "book_summaries.pdf",
"source": "Claudius is the narrator of this historical novel...",
"start_index": 0,
"end_index": 60
}
]
}
שילוב של כלים מובנים וקריאה לפונקציות
אפשר להשתמש בכלים מובנים ובהפעלת פונקציות ביחד באותה בקשה.
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.\"}"
}]
}'
הסבר על הפצת ההקשר של כלי
מודלים של Gemini 3 ומעלה תומכים בהעברת הקשר של כלי כדי לשמור על "זיכרון" מהימן של פעולות בצד השרת. כשמופעל כלי מובנה (כמו חיפוש Google), ה-API יוצר חלקים ספציפיים של toolCall ושל toolResponse. החלקים האלה מכילים את ההקשר המדויק שהמודל צריך כדי להסיק מסקנות לגבי התוצאות האלה בתור הבא.
- Stateful (מומלץ): אם אתם משתמשים ב-
previous_interaction_id, ה-API מנהל את המחזור הזה בשבילכם באופן אוטומטי. - ללא שמירת מצב: אם אתם מנהלים את ההיסטוריה באופן ידני, אתם צריכים לכלול את הבלוקים האלה בדיוק כמו שהם הוחזרו על ידי ה-API במערך הקלט.
פרוטוקול הקשר של מודל מרחוק (MCP)
שילוב מרחוק של MCP מפשט את פיתוח הסוכנים, כי הוא מאפשר ל-Gemini API להפעיל ישירות כלים חיצוניים שמתארחים בשרתים מרוחקים.
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>."
}'
הערות חשובות:
- ה-MCP המרוחק פועל רק עם שרתי HTTP שניתן להזרים מהם (אין תמיכה בשרתי SSE)
- MCP מרחוק לא פועל עם מודלים של Gemini 3 (התמיכה תהיה זמינה בקרוב)
- שמות של שרתי MCP לא יכולים לכלול את התו '-' (צריך להשתמש בשמות שרת בפורמט snake_case)
פלט מובנה (סכימת JSON)
כדי לאכוף פלט JSON ספציפי, צריך לספק סכימת JSON בפרמטר response_format. התכונה הזו שימושית למשימות כמו מיתון, סיווג או חילוץ נתונים.
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"]
}
}'
שילוב של כלים ופלט מובנה
אפשר לשלב בין כלים מובנים לבין פלט מובנה כדי לקבל אובייקט JSON מהימן שמבוסס על מידע שאוחזר על ידי כלי.
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"}
}
}
}'
תכונות מתקדמות
יש גם תכונות מתקדמות נוספות שמאפשרות לכם גמישות רבה יותר בעבודה עם Interactions API.
סטרימינג
לקבל תשובות מצטברות בזמן שהן נוצרות.
כשמגדירים את stream=true, אירוע interaction.complete הסופי לא מכיל את התוכן שנוצר בשדה outputs. הוא מכיל רק מטא-נתונים של שימוש ואת הסטטוס הסופי. צריך לצבור content.delta אירועים בצד הלקוח כדי לשחזר את התגובה המלאה או את הארגומנטים של קריאת הכלי.
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
}'
סוגי אירועים של סטרימינג
כשהסטרימינג מופעל, ה-API מחזיר אירועים שנשלחים מהשרת (SSE). לכל אירוע יש שדה event_type שמציין את המטרה שלו. רשימה מלאה של סוגי האירועים זמינה בהפניות API.
| סוג האירוע | תיאור |
|---|---|
interaction.start |
האירוע הראשון. מכיל את האינטראקציה id ואת status הראשוני (in_progress). |
interaction.status_update |
מציין שינויים בסטטוס (לדוגמה, in_progress). |
content.start |
מציין את ההתחלה של בלוק פלט חדש. כולל את index ואת התוכן type (לדוגמה, text, thought). |
content.delta |
עדכונים מצטברים של התוכן. מכיל את הנתונים החלקיים עם מפתח לפי delta.type. |
content.stop |
מסמן את סוף בלוק הפלט ב-index. |
interaction.complete |
אירוע סופי. כולל את id, status, usage ומטא-נתונים. הערה: outputs הוא None – צריך לשחזר את הפלט מאירועי content.*. |
error |
מציין שאירעה שגיאה. כולל את error.code ואת error.message. |
שחזור אובייקט האינטראקציה מאירועים בסטרימינג
בשונה מתשובות שאינן מוצגות באופן שוטף, תשובות שמוצגות באופן שוטף לא מכילות מערך outputs. צריך לשחזר את התוצאות על ידי צבירת התוכן מהאירועים content.delta.
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);
שיחות עם כלי סטרימינג
כשמשתמשים בכלים עם סטרימינג, המודל יוצר קריאות לפונקציות כרצף של אירועים בסטרימינג.content.delta בניגוד לטקסט, הארגומנטים של כלי מועברים כאובייקטים מלאים של JSON בתוך אירוע content.delta יחיד. המערך outputs ריק באירוע interaction.complete במהלך הסטרימינג, ולכן צריך לתעד קריאות לכלים מדלתאות כמו בדוגמה שלמטה.
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
}'
הגדרות אישיות
התאמה אישית של התנהגות המודל באמצעות generation_config.
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"
}
}'
מעמיק
מודלים של Gemini 2.5 ומודלים חדשים יותר משתמשים בתהליך פנימי של חשיבה רציונלית שנקרא 'חשיבה' לפני שהם יוצרים תשובה. כך המודל יכול לספק תשובות טובות יותר למשימות מורכבות כמו מתמטיקה, תכנות וחשיבה רציונלית מרובת שלבים.
רמת החשיבה
הפרמטר thinking_level מאפשר לכם לשלוט בעומק הנימוקים של המודל:
| רמה | תיאור | מודלים נתמכים |
|---|---|---|
minimal |
מתאים להגדרה 'ללא חשיבה' ברוב השאילתות. במקרים מסוימים, המודלים עשויים לחשוב בצורה מינימלית מאוד. מצמצם את זמן האחזור והעלות. | מודלים של Flash בלבד (לדוגמה, Gemini 3 Flash) |
low |
חשיבה רציונלית קלה שמתמקדת בשיפור זמן הטעינה וחיסכון בעלויות, כדי לבצע הוראות פשוטות ולנהל שיחות. | כל המודלים לחשיבה |
medium |
חשיבה מאוזנת לרוב המשימות. | מודלים מסוג Flash בלבד (לדוגמה, Gemini 3 Flash) |
high |
(ברירת מחדל) מעמיק את יכולת הנימוק. יכול להיות שייקח למודל הרבה יותר זמן להגיע לטוקן הראשון, אבל הפלט יהיה מנומק יותר. | כל המודלים לחשיבה |
סיכומי חשיבה
התהליך המחשבתי של המודל מיוצג כבלוקים של מחשבות (type: "thought") בפלט של התשובה. אפשר לקבוע אם לקבל סיכומים של תהליך החשיבה שקל לקרוא באמצעות הפרמטר thinking_summaries:
| ערך | תיאור |
|---|---|
auto |
(ברירת מחדל) מחזיר סיכומי מחשבות כשהם זמינים. |
none |
משבית את סיכומי המחשבות. |
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"
}
}'
כל בלוק מחשבה מכיל את השדה signature (גיבוב קריפטוגרפי של מצב הנימוק הפנימי) ואת השדה האופציונלי summary (סיכום של הנימוק של המודל, שניתן לקריאה על ידי בני אדם). השדה signature תמיד מופיע, אבל במקרים הבאים בלוק המחשבה עשוי להכיל רק חתימה ללא סיכום:
- בקשות פשוטות: המודל לא נימק מספיק כדי ליצור סיכום
-
thinking_summaries: "none": הסיכומים מושבתים באופן מפורש
הקוד צריך תמיד לטפל בבלוקים של מחשבות שבהם התוכן של summary ריק או לא קיים. כשמנהלים את היסטוריית השיחות באופן ידני (מצב בלי שמירת מצב), צריך לכלול בלוקים של מחשבות עם החתימות שלהם בבקשות הבאות כדי לאמת את האותנטיות.
עבודה עם קבצים
עבודה עם קבצים מרוחקים
גישה לקבצים באמצעות כתובות URL מרוחקות ישירות בקריאה ל-API.
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
לפני שמשתמשים בקבצים, צריך להעלות אותם אל Files API של Gemini.
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."}
]
}'
מודל נתונים
מידע נוסף על מודל הנתונים בהמשך מופיעה סקירה כללית של הרכיבים העיקריים.
אינטראקציה
| נכס | סוג | תיאור |
|---|---|---|
id |
string |
מזהה ייחודי של האינטראקציה. |
model / agent |
string |
המודל או הסוכן שבהם נעשה שימוש. אפשר לספק רק אחד. |
input |
Content[] |
הקלטים שסופקו. |
outputs |
Content[] |
התשובות של המודל. |
tools |
Tool[] |
הכלים שבהם נעשה שימוש. |
previous_interaction_id |
string |
המזהה של האינטראקציה הקודמת להקשר. |
stream |
boolean |
אם האינטראקציה היא סטרימינג. |
status |
string |
סטטוס: completed, in_progress, requires_action,failed וכו'. |
background |
boolean |
האם האינטראקציה מתבצעת במצב רקע. |
store |
boolean |
האם לאחסן את האינטראקציה. ברירת מחדל: true. מגדירים את האפשרות false כדי להפסיק את השימוש. |
usage |
שימוש | נתוני השימוש בטוקנים של בקשת האינטראקציה. |
מודלים וסוכנים נתמכים
| שם דגם | סוג | מזהה דגם |
|---|---|---|
| גרסת טרום-השקה (Preview) של Gemini 3.1 Flash-Lite | דגם | gemini-3.1-flash-lite-preview |
| Gemini 3.1 Pro Preview | דגם | gemini-3.1-pro-preview |
| Gemini 3 Flash Preview | דגם | gemini-3-flash-preview |
| Gemini 2.5 Pro | דגם | gemini-2.5-pro |
| Gemini 2.5 Flash | דגם | gemini-2.5-flash |
| Gemini 2.5 Flash-lite | דגם | gemini-2.5-flash-lite |
| תצוגה מקדימה של קליפ ב-Lyria 3 | דגם | lyria-3-clip-preview |
| Lyria 3 Pro (גרסת טרום-השקה) | דגם | lyria-3-pro-preview |
| תצוגה מקדימה של Deep Research | סוכן | deep-research-pro-preview-12-2025 |
איך Interactions API פועל
ממשק ה-API של Interactions מבוסס על משאב מרכזי: Interaction.
Interaction מייצג תור שלם בשיחה או במשימה. הוא משמש כתיעוד של סשן, ומכיל את כל ההיסטוריה של האינטראקציה, כולל כל נתוני הקלט של המשתמשים, המחשבות של המודל, קריאות הכלים, תוצאות הכלים והפלט הסופי של המודל.
כשמתקשרים אל interactions.create, נוצר משאב חדש של Interaction.
ניהול מצב בצד השרת
אפשר להשתמש בid של אינטראקציה שהסתיימה בקריאה הבאה באמצעות הפרמטר previous_interaction_id כדי להמשיך את השיחה. השרת משתמש במזהה הזה כדי לאחזר את היסטוריית השיחות, וכך לא צריך לשלוח מחדש את כל היסטוריית הצ'אט.
רק היסטוריית השיחות (הקלט והפלט) נשמרת באמצעות previous_interaction_id. הפרמטרים האחרים הם במסגרת האינטראקציה והם חלים רק על האינטראקציה הספציפית שאתם יוצרים כרגע:
toolssystem_instructiongeneration_config(כוללthinking_level,temperatureוכו')
כלומר, אם רוצים שהפרמטרים האלה יחולו, צריך לציין אותם מחדש בכל אינטראקציה חדשה. ניהול הסטטוס בצד השרת הוא אופציונלי. אפשר גם לפעול במצב חסר סטטוס על ידי שליחת היסטוריית השיחות המלאה בכל בקשה.
אחסון ושמירה של נתונים
כברירת מחדל, כל אובייקטי האינטראקציה מאוחסנים (store=true) כדי לפשט את השימוש בתכונות של ניהול מצב בצד השרת (עם previous_interaction_id), ביצוע ברקע (באמצעות background=true) ולמטרות יכולת צפייה.
- מהדורת בתשלום: האינטראקציות נשמרות למשך 55 ימים.
- תוכנית בחינם: האינטראקציות נשמרות למשך יום אחד.
אם אתם לא רוצים שהם יועתקו, אתם יכולים להגדיר store=false בבקשה שלכם. הפקד הזה נפרד מניהול מצב. אתם יכולים לבחור שלא לאחסן נתונים של אינטראקציות. עם זאת, חשוב לזכור ש-store=false לא תואם ל-background=true ומונע את השימוש ב-previous_interaction_id בתורות הבאות.
אתם יכולים למחוק את האינטראקציות השמורות מתי שתרצו באמצעות שיטת המחיקה שמופיעה במדריך העזר ל-API. אפשר למחוק אינטראקציות רק אם יודעים את מזהה האינטראקציה.
אחרי שתקופת השמירה תסתיים, הנתונים יימחקו באופן אוטומטי.
אובייקטים של אינטראקציות מעובדים בהתאם לתנאים.
שיטות מומלצות
- שיעור הפגיעות במטמון: שימוש ב-
previous_interaction_idכדי להמשיך שיחות מאפשר למערכת לנצל בקלות רבה יותר את השמירה במטמון המרומז של היסטוריית השיחות, וכך לשפר את הביצועים ולהפחית את העלויות. - שילוב אינטראקציות: אתם יכולים לשלב בין אינטראקציות עם נציג ועם מודל במהלך שיחה. לדוגמה, אפשר להשתמש בסוכן מיוחד, כמו סוכן Deep Research, לאיסוף נתונים ראשוני, ואז להשתמש במודל Gemini רגיל למשימות המשך כמו סיכום או עיצוב מחדש, ולקשר בין השלבים האלה באמצעות
previous_interaction_id.
ערכות SDK
אתם יכולים להשתמש בגרסה העדכנית של Google GenAI SDK כדי לגשת אל Interactions API.
- ב-Python, זו חבילת
google-genaiהחל מגרסה1.55.0. - ב-JavaScript, החבילה הזו היא
@google/genaiמגרסה1.33.0ואילך.
מידע נוסף על התקנת ערכות ה-SDK זמין בדף ספריות.
מגבלות
- סטטוס בטא: ממשק Interactions API נמצא בגרסת בטא או בתצוגה מקדימה. יכול להיות שיהיו שינויים בתכונות ובסכימות.
- MCP מרחוק: Gemini 3 לא תומך ב-MCP מרחוק, אבל התמיכה הזו תגיע בקרוב.
שינויי תוכנה שעלולים לגרום לכשלים
ה-Interactions API נמצא כרגע בשלב מוקדם של גרסת בטא. אנחנו מפתחים ומשפרים באופן פעיל את היכולות של ה-API, את סכימות המשאבים ואת ממשקי ה-SDK על סמך נתוני שימוש בפועל ומשוב ממפתחים.
כתוצאה מכך, יכולים להתרחש שינויים שעלולים לשבור את התאימות לאחור. העדכונים יכולים לכלול שינויים ב:
- סכימות לקלט ולפלט.
- חתימות של שיטות SDK ומבני אובייקטים.
- התנהגויות ספציפיות של תכונות.
בסביבות ייצור, צריך להמשיך להשתמש ב-API הרגיל generateContent. היא עדיין הדרך המומלצת לפריסות יציבות, ונמשיך לפתח ולתחזק אותה באופן פעיל.
משוב
המשוב שלכם חשוב מאוד לפיתוח של Interactions API. אתם יכולים לשתף את המחשבות שלכם, לדווח על באגים או לבקש תכונות בפורום הקהילה למפתחים של Google AI.
המאמרים הבאים
- אפשר לנסות את המדריך למתחילים לשימוש ב-Interactions API.
- מידע נוסף על Gemini Deep Research Agent