Interactions API מספק ממשק מאוחד עם שמירת מצב (stateful) לפיתוח אפליקציות של AI גנרטיבי באמצעות מודלים של Gemini וסוכנים אוטונומיים ב-Gemini Enterprise Agent Platform. אתם יכולים להשתמש ב-Interactions API כדי לנהל את האחסון של הסשן ושיחות עם כמה שלבים, להעביר תשובות בסטרימינג בזמן אמת, לאכוף פלט מובנה, להפעיל כלים מובנים ועיגון בנתונים, להריץ בקשות להפעלת פונקציות ולתזמר משימות ברקע שנמשכות זמן רב.
במדריך הזה מוסבר איך להתקין את Google Gen AI SDK, לאמת את הלקוח ולהטמיע תהליכי עבודה נפוצים של אינטראקציה. למידע על מחזור החיים של האינטראקציה, קראו את הסקירה הכללית על Interactions API.
לפני שמתחילים
לפני ששולחים בקשות ל-Interactions API, צריך להגדיר את הפרויקט וסביבת הפיתוח ב- Google Cloud:
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Make sure that you have the following role or roles on the project: Agent Platform User (
roles/aiplatform.user)Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.
- For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.
Grant the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
- Click Grant access.
-
In the New principals field, enter your user identifier. This is typically the identifier for a user in a workforce identity pool. For details, see Represent workforce pool users in IAM policies, or contact your administrator.
- Click Select a role, then search for the role.
- To grant additional roles, click Add another role and add each additional role.
- Click Save.
-
מושגים מרכזיים
כדי להבין איך Interactions API מנהל את המצב ואת התשובות, כדאי לעיין במושגים הבאים:
Interaction: ממשק Interactions API מתמקד במשאב ליבה:Interaction. Interactionמייצג תור שלם בשיחה או במשימה, ועוקב אחרי הכרונולוגיה של שלבים בתהליך החשיבה של המודל, קריאות API לכלי והפלט הסופי. הוא מספק מעטפת אחידה לאינטראקציות של פרומפט ותגובה ולתהליכי עבודה Agentic Workflows מורכבים עם כמה שלבים.שמירת מצב: האינטראקציות נשמרות בצד השרת כברירת מחדל (
store=Trueב-Python אוstore: trueב-TypeScript/JavaScript). האינטראקציות נשמרות למשך 7 ימים, ואז נמחקות באופן אוטומטי. ההגדרהstore=Falseמפעילה מצב בלי הקשר קודם, שמשבית את שמירת הנתונים בצד השרת ותואם למדיניות "אפס שמירת נתונים" (ZDR). במצב "בלי הקשר קודם" מושבתים גם שרשור שלprevious_interaction_idוהפעלה אסינכרונית (background=True).רכיבי עזר לתשובות: בגרסה
2.3.0ואילך של Google Gen AI SDK יש מאפיינים נוחים לתגובות לאינטראקציות, כוללinteraction.output_text,interaction.output_imageו-interaction.output_audio. כדי לקרוא תשובות טקסט, משתמשים ב-interaction.output_textבמקום להוסיף באופן ידני לאינדקס את מערך השלבים (כמוinteraction.steps[-1].content[0].text).
דרישות
לפני שמשלבים את Interactions API, צריך לוודא שהסביבה והבקשות עומדות בדרישות הבאות:
תמיכה בגרסת SDK: משתמשים באחת מספריות Google Gen AI SDK הנתמכות.
מודלים נתמכים: השתמשו במודלים נתמכים של Gemini 3 ואילך. משפחות מודלים ישנות יותר לא תומכות ב-API הזה. רשימה מלאה של המודלים הנתמכים מופיעה במאמרים מודלים נתמכים ומעבר לגרסאות המודלים העדכניות.
פרמטרים ברמת הפנייה: פרמטרים של הגדרה כמו
tools,system_instructionו-generation_configחלים רק על הפנייה הנוכחית. אם תהליך העבודה שלכם דורש את הפרמטרים האלה בשיחה עם כמה פניות, תצטרכו להעביר אותם בכל פנייה באינטראקציה.Long decodes on Gemini 4 Argon: כדי ליצור פלט של פנייה אחת עם יותר מ-65,536 טוקנים (עד 1,048,576 טוקנים פחות טוקנים של קלט) ב-
gemini-4-argonאו ב-gemini-4-argon-cyber-permissive, צריך להשתמש בהמשך אוטומטי של Google Gen AI SDK (google-genai >= 2.34.0ל-Python,@google/genai >= 2.32.0ל-TypeScript/JavaScript,>= 1.77.0ל-Go,>= 1.80.0ל-Java), ב-background=Trueאו ב-continuation_tokenבנקודת הקצה (endpoint) שלv1beta1. דוגמאות קוד וכללי המשך מופיעים בקטע פענוחים ארוכים במדריך למפתחים של Gemini 4 Argon.
התקנת Google Gen AI SDK
מתקינים או משדרגים את Google Gen AI SDK בשפה המועדפת:
Python
pip install --upgrade "google-genai>=2.3.0"
TypeScript או JavaScript
npm install "@google/genai>=2.3.0"
המשך
go get google.golang.org/genai
Java
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.78.0</version>
</dependency>
</dependencies>
אימות הלקוח
אתם יכולים להתחבר ל-Interactions API ב-Agent Platform באמצעות אחת משיטות האימות הבאות:
התחברות באמצעות פרויקט ב- Google Cloud עם Application Default Credentials (ADC)
השתמשו בשיטת האימות הזו לעומסי עבודה ארגוניים ולפריסות בסביבת הייצור ב- Google Cloud. כדי לבצע אימות באמצעות Application Default Credentials (ADC), צריך להפעיל את הלקוח עם המאפיינים הבאים:
enterprise=Trueproject="PROJECT_ID"location="global"
אם עדיין לא הגדרתם פרטי כניסה מקומיים, הריצו את הפקודה gcloud auth application-default login.
בדוגמת הקוד הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב-Google Cloud .
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain serverless computing in one sentence.",
)
print(interaction.output_text)
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain serverless computing in one sentence.",
});
console.log(interaction.output_text);
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
קישור באמצעות מצב אקספרס (מפתח API)
כדאי להשתמש בשיטת האימות הזו ליצירת אב טיפוס מהיר, לסקריפטים פשוטים או לסביבות שמאמתות באמצעות מפתח API. מעבירים את מפתח ה-API כשמפעילים את הלקוח או בכותרת ה-HTTP x-goog-api-key.
בדוגמת הקוד הבאה, מחליפים את API_KEY במפתח ה-API ואת PROJECT_ID במזהה הפרויקט ב- Google Cloud .
Python
from google import genai
client = genai.Client(
enterprise=True,
api_key="API_KEY",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain serverless computing in one sentence.",
)
print(interaction.output_text)
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
apiKey: "API_KEY",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain serverless computing in one sentence.",
});
console.log(interaction.output_text);
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "x-goog-api-key: API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
תהליכי עבודה נפוצים של אינטראקציות
אחרי שמגדירים את הלקוח, אפשר להשתמש ב-method interactions.create כדי לנהל את אחסון הסשנים ושיחות עם כמה פניות, להעביר אסימוני פלט בסטרימינג בזמן אמת, ליצור קובצי JSON מאומתים לפי סכימה, להפעיל כלים מובנים וקרקוע, להפעיל פונקציות חיצוניות ולהריץ סוכנים אוטונומיים.
ניהול אחסון הסשן ומצב השיחה
Interactions API תומך גם באחסון עם שמירת מצב (stateful) בצד השרת (store=True, ברירת המחדל) וגם בהפעלה ללא שמירת מצב (stateless) בצד הלקוח (store=False). בטבלה הבאה מוצגת השוואה בין מצבי אינטראקציה עם שמירת מצב וללא שמירת מצב:
| תכונה | מצב עם שמירת מצב (store=true, ברירת מחדל) |
בלי הקשר קודם (store=false) |
|---|---|---|
| שמירת נתונים בצד השרת | שומר בשרת את הקלט, שלבי הביניים והפלט למשך 7 ימים. | השבתת האחסון של אינטראקציות בצד השרת כדי לתמוך בתהליכי עבודה של אפס שמירת נתונים (ZDR). |
| הקשר רב-שלבי |
שרשור תורות על ידי העברת האינטראקציה הקודמת id ב-previous_interaction_id.
|
צריך להעביר את המערך המלא של השיחה הקודמת steps
ב-input בכל שלב. העברת הערך previous_interaction_id מחזירה את השגיאה 400 Bad
Request.
|
הרצה ברקע (background=true)
|
יש תמיכה באינטראקציות ארוכות עם המודל והנציג. | לא נתמך. כדי להפעיל ברקע באופן אסינכרוני, צריך לשמור את המצב בצד השרת. |
| שיטות מחזור חיים של סשן |
תמיכה באחזור (get), הצגה ברשימה (list), ביטול (cancel) ומחיקה (delete) של אינטראקציות.
|
אי אפשר לאחזר אותם אחרי שהתשובה הסינכרונית או התשובה בסטרימינג הושלמה. |
| הצפנה במנוחה |
מוצפנים כברירת מחדל באמצעות Google-owned and Google-managed encryption key, או באמצעות מפתחות הצפנה בניהול הלקוח (CMEK) במספר אזורים של us ו-eu.
|
מצב האינטראקציה לא נשמר במנוחה. |
לנהל שיחות רב-שלביות עם שמירת מצב
כברירת מחדל, ה-Interactions API שומר את מצב השיחה בשרת (store=True ב-Python או store: true ב-TypeScript או ב-JavaScript). כדי להמשיך שיחה קיימת, מעבירים את הערך id של האינטראקציה הקודמת לפרמטר previous_interaction_id. פלטפורמת הסוכן מאחזרת את ההקשר של השיחה שנשמר, מוסיפה את התור החדש ומשתמשת מחדש באסימוני הקידומת שנשמרו במטמון.
כשמשרשרים אינטראקציות בין נקודות קצה, צריך לפעול לפי כללי המיקום הבאים:
אותו מיקום: אפשר לשרשר אינטראקציות באותו מיקום (למשל,
globalל-global,usל-usאוeuל-eu).במיקומים שונים: אי אפשר לשרשר בין מיקומים שונים של נקודות קצה (בין
globalל-usאו ל-eu, או ביןusל-eu). כל נקודת קצה מאחסנת את מצב האינטראקציה באחסון מבודד, ולכן הפניה למזהה אינטראקציה שנוצר במיקום אחר מחזירה שגיאת404 Not Found.
בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
# Turn 1: Start a stateful conversation (store=True by default)
turn1 = client.interactions.create(
model="gemini-3.8-flash",
input="Hi! My name is John. I am working on AI agents.",
store=True,
)
print(f"Turn 1: {turn1.output_text}")
# Turn 2: Reference the stored conversation state using previous_interaction_id
turn2 = client.interactions.create(
model="gemini-3.8-flash",
input="What is my name?",
previous_interaction_id=turn1.id,
)
print(f"Turn 2: {turn2.output_text}")
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
// Turn 1: Start a stateful conversation (store: true by default)
const turn1 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Hi! My name is John. I am working on AI agents.",
store: true,
});
console.log(`Turn 1: ${turn1.output_text}`);
// Turn 2: Reference the stored conversation state using previous_interaction_id
const turn2 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "What is my name?",
previous_interaction_id: turn1.id,
});
console.log(`Turn 2: ${turn2.output_text}`);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
// Turn 1: Start a stateful conversation (store is true by default)
CreateModelInteraction req1 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Hi! My name is John. I am working on AI agents."))
.store(true)
.build();
Interaction turn1 =
client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));
// Turn 2: Reference the stored conversation state using previousInteractionId
CreateModelInteraction req2 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.previousInteractionId(turn1.id().orElseThrow())
.input(InteractionsInput.of("What is my name?"))
.build();
Interaction turn2 =
client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));
REST
# Turn 1: Start a stateful conversation
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"store": true,
"input": "Hi! My name is John. I am working on AI agents."
}'
# Turn 2: Pass the interaction ID from Turn 1 in previous_interaction_id
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"previous_interaction_id": "PREVIOUS_INTERACTION_ID",
"input": "What is my name?"
}'
ניהול שיחות עם זיכרון ללא שמירת מצב (stateless)
אם עומס העבודה שלכם דורש שמירת נתונים אפסית (ZDR), הגדירו באופן מפורש את store=False (store: false ב-TypeScript/JavaScript או "store": false ב-REST) בכל בקשה.
במצב בלי הקשר קודם, אתם מנהלים את היסטוריית השיחות בצד הלקוח על ידי שמירה על רשימה של אובייקטים מסוג Step (user_input, thought, function_call, function_result ו-model_output) ושליחת המערך המצטבר של steps ב-input בכל שלב:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
history = [
{
"type": "user_input",
"content": [{"type": "text", "text": "Hi! My name is John."}],
}
]
# Turn 1: Stateless request (store=False)
turn1 = client.interactions.create(
model="gemini-3.8-flash",
input=history,
store=False,
)
print(f"Turn 1: {turn1.output_text}")
# Append the model's generated steps and the next user turn to local history
history.extend(turn1.steps)
history.append(
{
"type": "user_input",
"content": [{"type": "text", "text": "What is my name?"}],
}
)
# Turn 2: Send the full step history with store=False
turn2 = client.interactions.create(
model="gemini-3.8-flash",
input=history,
store=False,
)
print(f"Turn 2: {turn2.output_text}")
TypeScript או JavaScript
import { GoogleGenAI, Step } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const history: Step[] = [
{
type: "user_input",
content: [{ type: "text", text: "Hi! My name is John." }],
},
];
// Turn 1: Stateless request (store: false)
const turn1 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: history,
store: false,
});
console.log(`Turn 1: ${turn1.output_text}`);
// Append the model's generated steps and the next user turn to local history
if (turn1.steps) {
history.push(...turn1.steps);
}
history.push({
type: "user_input",
content: [{ type: "text", text: "What is my name?" }],
});
// Turn 2: Send the full step history with store: false
const turn2 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: history,
store: false,
});
console.log(`Turn 2: ${turn2.output_text}`);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.UserInputContent;
import com.google.genai.gaos.models.interactions.UserInputStep;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.ArrayList;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
List<Step> history = new ArrayList<>();
history.add(
Step.of(
UserInputStep.builder()
.content(
List.of(
UserInputContent.of(
TextContent.builder().text("Hi! My name is John.").build())))
.build()));
// Turn 1: Stateless request (store(false))
CreateModelInteraction req1 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.ofSteps(history))
.store(false)
.build();
Interaction turn1 =
client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));
// Append the model's generated steps and the next user turn to local history
turn1.steps().ifPresent(history::addAll);
history.add(
Step.of(
UserInputStep.builder()
.content(
List.of(
UserInputContent.of(
TextContent.builder().text("What is my name?").build())))
.build()));
// Turn 2: Send the full step history with store(false)
CreateModelInteraction req2 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.ofSteps(history))
.store(false)
.build();
Interaction turn2 =
client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": [{"type": "text", "text": "Hi! My name is John."}]
},
{
"type": "model_output",
"content": [{"type": "text", "text": "Hello John! How can I help you today?"}]
},
{
"type": "user_input",
"content": [{"type": "text", "text": "What is my name?"}]
}
]
}'
שמירה ומחזור החיים של הסשן
אינטראקציות מאוחסנות (store=True) פועלות לפי כללי השמירה וההסתעפות הבאים:
אורך חיים (TTL) של 7 ימים: כל אינטראקציה שנשמרת נשארת למשך 7 ימים מחותמת הזמן של
created, ונמחקת באופן אוטומטי כשתקופת ה-TTL של 7 הימים מסתיימת.אחסון עצמאי של הורה וצאצא: כשמשרשרים תור חדש באמצעות
previous_interaction_id, פלטפורמת Agent מעתיקה את היסטוריית השיחות של האב הקדמון לרשומת האינטראקציה החדשה. בכל פנייה נשמר עותק משלה של היסטוריית השיחות, ולכן אם פנייה קודמת נמחקת או שתוקף השמירה שלה פג, קורים הדברים הבאים:המשך מתור מאוחר יותר מצליח: אם תור 1 (
interaction_1) פג או נמחק אחרי שכבר נוצר תור 2 (interaction_2), עדיין אפשר ליצור את תור 3 באמצעותprevious_interaction_id=interaction_2.idעד שתורinteraction_2עצמו פג או נמחק.הסתעפות ממהלך שפג תוקפו או נמחק נכשלת: ניסיון ליצור אינטראקציה חדשה שמפנה ישירות למזהה אינטראקציה שפג תוקפו או נמחק ב-
previous_interaction_idמחזיר שגיאה מסוג400 Bad Request(Previous Interaction ID not found).
אחזור, הצגה, ביטול ומחיקה של אינטראקציות מאוחסנות
אתם יכולים לבדוק ולנהל את האינטראקציות ששמרתם לאורך מחזור החיים שלהן בשיטות הבאות:
אחזור אינטראקציה (
interactions.get): אחזור של המשאב המלא שלInteractionלפיid, כולל שלביuser_input, שלבי ביניים שלthoughtושלבי כלים, ושלביmodel_output. מגדירים אתstream=True(ואתlast_event_idהאופציונלי) כדי להעביר בסטרימינג או להמשיך אינטראקציה שמתבצעת.הצגת רשימת אינטראקציות (
interactions.list): שאילתות של מזהי אינטראקציות שמאוחסנים בפרויקט באמצעות REST, עםpage_size(ברירת המחדל היא10, המקסימום הוא500) ו-page_token. החזרת רשימה של משאביInteractionMetadata.ביטול אינטראקציה שמתבצעת (
interactions.cancel): עצירת אינטראקציה אסינכרונית ברקע (background=True) שנמצאת במצבin_progressאוrequires_action, והעברת הסטטוס שלה למצבcancelled. תחויבו על כל הטוקנים שנוצרו לפני הביטול.מחיקת אינטראקציה שמורה (
interactions.delete): הסרה סופית של אינטראקציה שמורה לפני שתוקף ה-TTL שלה (7 ימים) פג. אפשר למחוק רק אינטראקציות במצב סופי (completed,failedאוcancelled). אם האינטראקציה עדיין פועלת ברקע, צריך לבטל אותה לפני שמוחקים אותה.
בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloudואת INTERACTION_ID במזהה האינטראקציה:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
# Retrieve a stored interaction by ID
interaction = client.interactions.get(id="INTERACTION_ID")
print(f"Status: {interaction.status}")
# Cancel an in-progress background interaction
cancelled = client.interactions.cancel(id="INTERACTION_ID")
print(f"After cancel: {cancelled.status}")
# Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(id="INTERACTION_ID")
print("Interaction deleted.")
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
// Retrieve a stored interaction by ID
const interaction = await ai.interactions.get("INTERACTION_ID");
console.log(`Status: ${interaction.status}`);
// Cancel an in-progress background interaction
const cancelled = await ai.interactions.cancel("INTERACTION_ID");
console.log(`After cancel: ${cancelled.status}`);
// Delete a completed, failed, or cancelled interaction before its 7-day TTL
await ai.interactions.delete("INTERACTION_ID");
console.log("Interaction deleted.");
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionStatus;
import com.google.genai.gaos.models.operations.CancelInteractionByIdResponse;
import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;
import com.google.genai.gaos.models.operations.GetInteractionByIdResponse;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
String interactionId = "INTERACTION_ID";
// Retrieve a stored interaction by ID
GetInteractionByIdResponse getResponse =
client.interactions.get(new GetInteractionByIdRequest(interactionId));
Interaction interaction = getResponse.interaction().orElseThrow();
System.out.println("Status: " + interaction.status().map(InteractionStatus::value).orElse(""));
// Cancel an in-progress background interaction
CancelInteractionByIdResponse cancelResponse = client.interactions.cancel(interactionId);
Interaction cancelled = cancelResponse.interaction().orElseThrow();
System.out.println("After cancel: " + cancelled.status().map(InteractionStatus::value).orElse(""));
// Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(interactionId);
System.out.println("Interaction deleted.");
REST
# Retrieve a stored interaction by ID
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# List stored interactions (up to 500 per page)
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions?page_size=10" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# Cancel an in-progress background interaction
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID/cancel" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# Delete a completed, failed, or cancelled interaction
curl -X DELETE "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
מכסות ומגבלות של אחסון עם שמירת מצב (stateful)
בנוסף למגבלות על קצב הבקשות והטוקנים של המודל, אינטראקציות עם שמירת מצב (store=True) כפופות למגבלות הבאות על האחסון והפעולות בו-זמנית ברמת הפרויקט:
| מכסה או מגבלת מערכת | מגבלת ברירת המחדל (לכל פרויקט) | תיאור |
|---|---|---|
| קצב יצירת אינטראקציות עם שמירת מצב ביום | 240 GiB ליום |
הנפח הכולל המקסימלי של נתוני אינטראקציות שנכתבים באחסון בצד השרת ביום ב-interactions.create בקשות עם store=true. |
| קצב העברת הנתונים של שליפת אינטראקציות עם שמירת מצב ביום | 480 GiB ליום |
הנפח הכולל המקסימלי של נתוני אינטראקציות מאוחסנים שנקראים ביום בבקשות interactions.get ובבקשות עם כמה פניות שטוענות פניות קודמות באמצעות previous_interaction_id. |
| אינטראקציות בו-זמניות עם שמירת מצב | 500 אינטראקציות בו-זמניות |
המספר המקסימלי של אינטראקציות פעילות עם שמירת מצב שפועלות בו-זמנית בפרויקט. |
למידע נוסף על הצגה וניהול של מכסות ב-Agent Platform, ראו מכסות ומגבלות מערכת.
הצגת תשובות באופן שוטף בזמן אמת
כדי לצמצם את זמן האחזור הנתפס באפליקציות אינטראקטיביות, אתם יכולים להעביר בסטרימינג את התשובות מהמודל בזמן שהן נוצרות. מגדירים את stream=True (stream: true ב-TypeScript או ב-JavaScript) כשקוראים ל-interactions.create כדי לקבל סטרימינג שניתן לחזור עליו של אירועים שנשלחו מהשרת. מסננים אירועי step.delta כדי להציג קטעי טקסט מצטברים כשהם מגיעים:
Python
response = client.interactions.create(
model="gemini-3.8-flash",
input="Write a short poem about debugging.",
stream=True,
)
for event in response:
if event.event_type == "step.delta" and hasattr(event.delta, "text"):
print(event.delta.text, end="", flush=True)
print()
TypeScript או JavaScript
const responseStream = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Write a short poem about debugging.",
stream: true,
});
for await (const event of responseStream) {
if (event.event_type === "step.delta" && event.delta && "text" in event.delta) {
process.stdout.write(event.delta.text);
}
}
console.log();
יצירת פלט מובנה
אם האפליקציה שלכם דורשת תשובות בפורמט צפוי וקריא למכונה, אתם יכולים להגביל את הפלט מהמודל כך שיתאים לסכימת JSON ספציפית. מעבירים את סכימת היעד – כמו סכימת JSON של מודל Pydantic ב-Python או אובייקט סכימה של Type ב-TypeScript או ב-JavaScript – ישירות לפרמטר הפולימורפי response_format:
Python
from pydantic import BaseModel, Field
class Book(BaseModel):
title: str = Field(description="The title of the book")
author: str = Field(description="The book's author")
year_published: int
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Recommend one famous sci-fi book.",
response_format=Book.model_json_schema(),
)
# The output text is valid JSON matching the Book schema
print(interaction.output_text)
TypeScript או JavaScript
import { Type } from "@google/genai";
const BookSchema = {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING, description: "The title of the book" },
author: { type: Type.STRING, description: "The book's author" },
yearPublished: { type: Type.INTEGER },
},
required: ["title", "author", "yearPublished"],
};
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Recommend one famous sci-fi book.",
response_format: BookSchema,
});
console.log(interaction.output_text);
שימוש בקריאה להפעלת פונקציות (שימוש בכלים)
קריאה לפונקציות מאפשרת למודל לבקש להפעיל פונקציות בהתאמה אישית או ממשקי API חיצוניים כדי לאסוף מידע לפני שהוא יוצר תשובה סופית. בתהליך עבודה של אינטראקציה עם שמירת מצב, הקריאה להפעלת פונקציות מתבצעת בתבנית של שני שלבים:
הצהרה על כלים והעברה שלהם: מספקים את הצהרות הפונקציות בפרמטר
toolsבבקשה הראשונית.הפעלה והחזרת תוצאות: בודקים את שלבי התגובה (
interaction.steps) כדי למצוא שלביfunction_call, מפעילים את הפונקציה המקומית באמצעות ה-argumentsשסופק על ידי המודל, ושולחים אינטראקציית המשך שמכילה פריטfunction_resultשמקושר באמצעותcall_idו-previous_interaction_id.
Python
# Define a declarative function tool schema
stock_tool = {
"type": "function",
"name": "get_stock_price",
"description": "Gets the stock price for a given ticker symbol.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string", "description": "The stock ticker symbol"}
},
"required": ["ticker"],
},
}
def get_stock_price(ticker: str) -> float:
"""Executes the local tool function."""
if ticker.upper() == "GOOG":
return 175.50
return 100.0
# Turn 1: Pass the tool declaration to the model
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="What is the stock price of GOOG?",
tools=[stock_tool],
)
# Inspect the interaction steps for function call requests
for step in interaction.steps:
if step.type == "function_call" and step.name == "get_stock_price":
ticker_arg = step.arguments.get("ticker")
price = get_stock_price(ticker_arg)
# Turn 2: Submit the function execution result to the conversation
final_turn = client.interactions.create(
model="gemini-3.8-flash",
input=[{
"type": "function_result",
"call_id": step.id,
"result": {"price": price},
}],
previous_interaction_id=interaction.id,
)
print(final_turn.output_text)
TypeScript או JavaScript
// Define a declarative function tool schema
const stockTool = {
type: "function",
name: "getStockPrice",
description: "Gets the stock price for a given ticker symbol.",
parameters: {
type: "object",
properties: {
ticker: { type: "string", description: "The stock ticker symbol" },
},
required: ["ticker"],
},
};
function getStockPrice({ ticker }: { ticker: string }): number {
if (ticker.toUpperCase() === "GOOG") return 175.50;
return 100.00;
}
// Turn 1: Pass the tool declaration to the model
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "What is the stock price of GOOG?",
tools: [stockTool],
});
// Inspect the interaction steps for function call requests
for (const step of interaction.steps ?? []) {
if (step.type === "function_call" && step.name === "getStockPrice") {
const tickerArg = step.arguments.ticker as string;
const price = getStockPrice({ ticker: tickerArg });
// Turn 2: Submit the function execution result to the conversation
const finalTurn = await ai.interactions.create({
model: "gemini-3.8-flash",
input: [{
type: "function_result",
call_id: step.id,
result: { price },
}],
previous_interaction_id: interaction.id,
});
console.log(finalTurn.output_text);
}
}
שימוש בכלים מובנים
בנוסף לקריאה להפעלת פונקציות בצד הלקוח, Interactions API תומך בכלים מובנים בצד השרת למודלים של Gemini 3. כשמפעילים כלי מובנה בפרמטר tools, פלטפורמת Agent מפעילה את הכלי בשרת במהלך קריאה אחת של interactions.create ומתעדת את שלבי ההפעלה (*_call) והפלט (*_result) של הכלי ב-interaction.steps.
Interactions API תומך בכלים המובנים הבאים:
הרצת קוד (
{"type": "code_execution"}): יוצר ומריץ קוד Python בסביבת ארגז חול כדי לבצע חישובים, ניתוח נתונים והסקת מסקנות על סמך קוד. במאמר הרצת קוד מפורט מידע על ספריות נתמכות, חיוב ומגבלות.הקשר של כתובת URL (
{"type": "url_context"}): מאחזר ומנתח תוכן מכתובות URL ציבוריות שכלולות בהנחיה. במאמר הקשר של כתובת URL מוסבר איך לשמור את האינדקס במטמון, לאחזר נתונים בזמן אמת ולשלב את ההקשר של כתובת ה-URL עם חיפוש Google.עיגון באמצעות חיפוש Google (
{"type": "google_search"}): מבסס את התשובות של המודל על מידע מהאינטרנט בזמן אמת ומחזיר ציטוטים מוטבעים. איך מבססים תשובות על חיפוש Googleשימוש במחשב (
{"type": "computer_use"}): מאפשר אוטומציה של זרימות עבודה בדפדפן ובממשק המשתמש. במאמר שימוש במחשב מוסבר איך להגדיר את המחשב ולהשתמש באמצעי הבטיחות.
הרצת קוד Python
כדי להפעיל את הרצת הקוד, צריך לכלול את {"type": "code_execution"} ברשימה tools. המערך interaction.steps שמוחזר מכיל את השלבים של code_execution_call (עם arguments.code ו-arguments.language), את השלבים של code_execution_result (עם result ו-is_error) ואת השלב הסופי של model_output.
בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Calculate the 50th Fibonacci number and find its closest prime.",
tools=[{"type": "code_execution"}],
)
for step in interaction.steps:
if step.type == "code_execution_call":
print(f"Generated code:\n{step.arguments.code}")
elif step.type == "code_execution_result":
print(f"Execution result:\n{step.result}")
elif step.type == "model_output":
for content in step.content:
if content.type == "text":
print(content.text)
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Calculate the 50th Fibonacci number and find its closest prime.",
tools: [{ type: "code_execution" }],
});
for (const step of interaction.steps ?? []) {
if (step.type === "code_execution_call") {
console.log(`Generated code:\n${step.arguments?.code}`);
} else if (step.type === "code_execution_result") {
console.log(`Execution result:\n${step.result}`);
} else if (step.type === "model_output") {
for (const content of step.content ?? []) {
if (content.type === "text") {
console.log(content.text);
}
}
}
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CodeExecution;
import com.google.genai.gaos.models.interactions.CodeExecutionCallStep;
import com.google.genai.gaos.models.interactions.CodeExecutionResultStep;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Calculate the 50th Fibonacci number and find its closest prime."))
.tools(List.of(CodeExecution.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
for (Step step : interaction.steps().orElse(List.of())) {
if (step instanceof CodeExecutionCallStep callStep) {
callStep
.arguments()
.flatMap(args -> args.code())
.ifPresent(code -> System.out.println("Generated code:\n" + code));
} else if (step instanceof CodeExecutionResultStep resultStep) {
resultStep
.result()
.ifPresent(res -> System.out.println("Execution result:\n" + res));
}
}
System.out.println(interaction.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Calculate the 50th Fibonacci number and find its closest prime.",
"tools": [{"type": "code_execution"}]
}'
אחזור תוכן של דף אינטרנט באמצעות URL Context
כדי לאפשר למודל לאחזר ולנתח דפי אינטרנט שמוזכרים בהנחיה, צריך לכלול את {"type": "url_context"} ברשימה tools. ה-API מתעד את כתובות ה-URL שאוחזרו בשלבים url_context_call ו-url_context_result ומצרף הערות url_citation לטקסט דינמי מבוסס-AI ב-model_output.
בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud, ואת YOUR_URL_1 ו-YOUR_URL_2 בכתובות ה-URL הציבוריות שרוצים להשוות:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
tools=[{"type": "url_context"}],
)
print(interaction.output_text)
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
tools: [{ type: "url_context" }],
});
console.log(interaction.output_text);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.URLContext;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Compare the key findings from YOUR_URL_1 and YOUR_URL_2."))
.tools(List.of(URLContext.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
System.out.println(interaction.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
"tools": [{"type": "url_context"}]
}'
עיגון תשובות באמצעות חיפוש Google
העיגון מחבר את מודלי Gemini למקורות חיצוניים שאפשר לאמת, כדי לצמצם את ההזיות ולספק תשובות עדכניות עם ציטוטים. במאמרים הבאים מוסבר על אפשרויות העיגון ב-Agent Platform: סקירה כללית על עיגון, עיגון באמצעות חיפוש Google ועיגון באמצעות חיפוש באינטרנט לארגונים.
כשמפעילים את התכונה "עיגון באמצעות חיפוש Google" על ידי העברת הערך {"type": "google_search"} ברשימה tools, ה-Interactions API מחזיר נתוני חיפוש ושיוך ישירות בציר הזמן של interaction.steps:
google_search_call: מכיל את שאילתות החיפוש שהמודל שלח (step.arguments.queries).
google_search_result: מכיל הצעות חיפוש (result[].search_suggestions), קטע קוד HTML/CSS שמשמש לעיבוד הצעות חיפוש בממשקי משתמש. מקורות מידע מהאינטרנט עם כתובות URL וכותרות של מקורות מסופקים כהערותurl_citationמוטבעות בבלוקים של טקסט ב-model_output.הערות
url_citationמוטבעות: כל בלוק תוכן שלtext(TextContent) בתוך שלב שלmodel_outputיכול לכלול מערך שלannotations. כל הערה מסוגurl_citationמזהה את טווח התווים או הבייטים (start_indexו-end_index) בטקסט התשובה, יחד עם המקורtitleו-url.
בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud:
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Who won the 2026 Super Bowl?",
tools=[{"type": "google_search"}],
)
print(interaction.output_text)
# Parse inline url_citation annotations from model_output steps
print("\nSources:")
for step in interaction.steps:
if step.type == "model_output" and step.content:
for content in step.content:
if content.type == "text" and getattr(content, "annotations", None):
for annotation in content.annotations:
if annotation.type == "url_citation":
span = content.text[annotation.start_index:annotation.end_index]
print(f"- [{annotation.title}]({annotation.url}) (cited text: {span!r})")
TypeScript או JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Who won the 2026 Super Bowl?",
tools: [{ type: "google_search" }],
});
console.log(interaction.output_text);
// Parse inline url_citation annotations from model_output steps
console.log("\nSources:");
for (const step of interaction.steps ?? []) {
if (step.type === "model_output") {
for (const content of step.content ?? []) {
if (content.type === "text" && content.annotations) {
for (const annotation of content.annotations) {
if (annotation.type === "url_citation") {
const span = content.text.slice(
annotation.start_index,
annotation.end_index,
);
console.log(
`- [${annotation.title}](${annotation.url}) (cited text: "${span}")`,
);
}
}
}
}
}
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Annotation;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.URLCitation;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Who won the 2026 Super Bowl?"))
.tools(List.of(GoogleSearch.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
System.out.println(interaction.outputText().orElse(""));
// Parse inline URLCitation annotations from ModelOutputStep blocks
System.out.println("\nSources:");
for (Step step : interaction.steps().orElse(List.of())) {
if (step instanceof ModelOutputStep outputStep) {
for (Content content : outputStep.content().orElse(List.of())) {
if (content instanceof TextContent textContent) {
for (Annotation annotation : textContent.annotations().orElse(List.of())) {
if (annotation instanceof URLCitation citation) {
System.out.printf(
"- %s: %s (span: %d..%d)%n",
citation.title().orElse(""),
citation.url().orElse(""),
citation.startIndex().orElse(0L),
citation.endIndex().orElse(0L));
}
}
}
}
}
}
REST
# Request
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Who won the 2026 Super Bowl?",
"tools": [{"type": "google_search"}]
}'
התשובה כוללת את השלבים google_search_call, google_search_result ו-model_output עם הערות url_citation מוטבעות:
{
"id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROA",
"model": "gemini-3.8-flash",
"status": "completed",
"steps": [
{
"type": "google_search_call",
"id": "search_call_1",
"arguments": {
"queries": ["2026 Super Bowl winner"]
}
},
{
"type": "google_search_result",
"call_id": "search_call_1",
"result": [
{
"search_suggestions": "<!-- HTML and CSS for search suggestions -->"
}
]
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "The Seattle Seahawks won Super Bowl LX on February 8, 2026.",
"annotations": [
{
"type": "url_citation",
"start_index": 0,
"end_index": 59,
"title": "Super Bowl LX",
"url": "https://example.com/super-bowl-lx"
}
]
}
]
}
]
}
להפעיל סוכנים ומשימות ארוכות ברקע
בנוסף למודלים בסיסיים, Interactions API מאפשר להפעיל סוכנים אוטונומיים ייעודיים באמצעות הפרמטר agent:
-
antigravity-preview-05-2026: סוכן מנוהל למטרות כלליות עם הרצת קוד, ניהול קבצים ודפדפן אינטרנט בסביבת Linux מאובטחת בארגז חול. מידע נוסף על אינטראקציה עם נציגים -
deep-research-preview-04-2026: סוכן Gemini Deep Research, שמתכנן ומבצע משימות מחקר באינטרנט בכמה שלבים, ומסכם ממצאים ממקורות מרובים בדוחות מקיפים. איך משתמשים ב-Gemini Deep Research Agent - סוכנים בהתאמה אישית: משאבים של סוכנים בהתאמה אישית שמוגדרים ומוקצים באמצעות
client.agents.create().
תהליכי עבודה של סוכנים נמשכים בדרך כלל כמה דקות, לכן כדאי להריץ אותם באופן אסינכרוני ברקע באמצעות הגדרת background=True. ה-API מחזיר מיד אובייקט Interaction עם id שאפשר לדגום באמצעות client.interactions.get() עד שהערך של interaction.status משתנה ל-completed:
לפני שמנסים את הדוגמה הזו, מחליפים את PROJECT_ID במזהה הפרויקט ב-Google Cloud .
import time
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
input="Analyze competitive positioning for solar energy providers.",
agent="deep-research-preview-04-2026",
background=True,
)
print(f"Research started: {interaction.id}")
while True:
interaction = client.interactions.get(interaction.id)
if interaction.status == "completed":
print(interaction.output_text)
break
elif interaction.status in ("failed", "cancelled"):
print(f"Research ended with status: {interaction.status}")
break
time.sleep(10)
גישה לקבצים שהועלו ל-Cloud Storage
אתם יכולים להשתמש ב-Interactions API כדי לגשת לקבצים שהועלו ל-Cloud Storage. בדוגמה הבאה, מחליפים את PROJECT_ID במזהה הפרויקט ב-Google Cloud :
from google import genai
# Credentials must belong to an identity with storage.objects.get permissions
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{
"type": "user_input",
"content": [
{"type": "text", "text": "Summarize the attached document:"},
{
"type": "document",
"uri": "gs://my-secure-bucket/quarterly_report.pdf",
"mime_type": "application/pdf",
},
],
}
],
)
print(interaction.output_text)
כשמעבירים ל-Interactions API מזהי URI של Cloud Storage (לדוגמה, gs://bucket-name/path/to/file), הבקשות מאמתות את הרשאת הקריאה באמצעות פרטי הכניסה של הגורם שמבצע את הקריאה, לפני שסוכן השירות של Agent Platform בפרויקט שמבצע את הקריאה (service-PROJECT_NUMBER@gcp-sa-aiplatform.) מאחזר את האובייקט מ-Cloud Storage.
כדי להעביר קובצי Cloud Storage בבקשת אינטראקציה, לחשבון המשתמש, לחשבון השירות או לזהות המאוחדת שמבצעים את הקריאה החוזרת צריכה להיות ההרשאה storage.objects.get לכל האובייקטים שאליהם מפנים. בקטגוריות של Cloud Storage בפרויקטים שונים או בקטגוריות של Cloud Storage עם מדיניות IAM בהתאמה אישית, צריך לתת גישת קריאה גם לחשבון הראשי שמבצע את הקריאה וגם לסוכן השירות של הפרויקט שמבצע את הקריאה.
כל בקשה לאינטראקציה עם מודל Gemini רגיל תומכת בעד 100 מזהי URI נפרדים של Cloud Storage (gs://) (עד 2GiB פחות 500KiB לכל קובץ). כשמשרשרים פניות עם שמירת מצב באמצעות previous_interaction_id, פלטפורמת Agent סופרת את מזהי ה-URI הייחודיים של gs:// באופן מצטבר בהיסטוריית השיחה ובפנייה הנוכחית. אינטראקציות עם סוכנים מנוהלים (בקשות שמוגדר בהן agent במקום model), מודלים של Gemini Omni ומודלים של Lyria 3 לא נכללים במגבלה הזו של 100 מזהי URI.
הגדרת תפקידי IAM לגישה לקובצי Cloud Storage
מקצים את אחד מהתפקידים הסטנדרטיים המוגדרים מראש שכוללים את ההרשאה storage.objects.get:
צפייה באובייקטים של אחסון (
roles/storage.objectViewer): גישת קריאה לאובייקטים (מומלץ).Storage Object User (
roles/storage.objectUser): גישת קריאה וכתיבה לאובייקטים.
כדי לתת גישה לחשבון משתמש באמצעות Google Cloud CLI, משתמשים בפקודה הבאה:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="user:user-email@example.com" \
--role="roles/storage.objectViewer"
כדי לתת גישה לחשבון שירות ספציפי, משתמשים בפקודה הבאה:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="serviceAccount:sa-name@PROJECT_ID." \
--role="roles/storage.objectViewer"
פתרון בעיות בגישה לקבצים ב-Cloud Storage
אם לחשבון המשתמש שמבצע את הקריאה אין מספיק הרשאות, Interactions API מחזיר שגיאת 403 Forbidden שדומה לזו:
Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more Cloud Storage URIs.
כדי לפתור את הבעיה, צריך להקצות את התפקיד "צפייה באובייקט אחסון" (roles/storage.objectViewer) בקטגוריה או באובייקט של Cloud Storage לגורם המאומת שמבצע את הקריאה (ולסוכן השירות של Agent Platform בפרויקט שמבצע את הקריאה, אם מדובר בקטגוריות של Cloud Storage בפרויקטים שונים או עם IAM בהתאמה אישית).
אם האובייקט שצוין לא קיים, או אם ההרשאות של הקטגוריה מונעות מהגורם המבקש לראות אם האובייקט קיים, Interactions API מחזיר שגיאת 404 Not Found שדומה לזו:
Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.
כדי לפתור את הבעיה, ודאו שה-URI של Cloud Storage נכון ושלגורם המאומת יש גישת קריאה לקטגוריה.
אם בקשה לאינטראקציה עם מודל מפנה ליותר מ-100 מזהי URI נפרדים של Cloud Storage בסבב הנוכחי ובהיסטוריית ה-previous_interaction_id המקושרת, Interactions API מחזיר שגיאת 400 Bad Request שדומה לזו:
INVALID_ARGUMENT - 400 Bad Request: Request references 101 distinct gs:// URIs, which exceeds the maximum of 100.
כדי לפתור את הבעיה תוכלו לנסות אחד מהפתרונות הבאים:
- כדי להתחיל אינטראקציה חדשה בלי
previous_interaction_id, כשהקבצים מהסבבים הקודמים כבר לא נחוצים. - אפשר לשלב מסמכים קטנים יותר או להעביר קבצים נוספים בתוך השורה, במסגרת מגבלת המטען הייעודי (payload) של הבקשה (256MiB דחוס לבקשות סינכרוניות או לבקשות סטרימינג, או 9.75MiB לא דחוס כש-
service_tierמוגדר ל-deferredעםbackgroundו-storeמוגדרים ל-true). - השתמשו ב-
generateContentלבקשות שמפנות ל-URI שלgs://עד למגבלות הפריטים במודל לכל אופן (3,000 תמונות וקובצי PDF ביחד, 1,000 קובצי אודיו ו-10 סרטונים, או עד 6,500 קבצים כשכוללים קובצי טקסט פשוט).
הצפנת נתוני אינטראקציה באמצעות CMEK
אינטראקציות עם שמירת מצב (store=True ב-Python או store: true ב-TypeScript או ב-JavaScript) שומרות את נתוני האינטראקציה במנוחה למשך עד 7 ימים. כדי להגן על הנתונים האלה באמצעות מפתח הצפנה משלכם במקוםGoogle-owned and Google-managed encryption key, אתם יכולים להשתמש בפרופיל הצגה. פרופיל הצגה מקשר בין מפתח של Cloud Key Management Service לבין פרויקט, מיקום והיקף הרשאות של API. כל עוד פרופיל ההצגה קיים, פלטפורמת Agent מצפינה באופן אוטומטי את נתוני האינטראקציה שמאוחסנים, ופורמט בקשת האינטראקציה לא משתנה.
אפשר להשתמש ב-CMEK לפרופיל הצגת המודעות ב-Interactions API באזורים us ו-eu. אין תמיכה באזור global.
כדי להגדיר CMEK ל-Interactions API:
- מפעילים בפרויקט את Cloud KMS API ואת Agent Platform API. לפני שמתחילים
- יוצרים מפתח Cloud KMS במיקום
usאוeuשכולל מספר אזורים. איך יוצרים אוסף מפתחות ומפתח - מקצים לסוכן השירות של Gemini Enterprise Agent Platform את התפקיד
roles/cloudkms.cryptoKeyEncrypterDecrypterבמפתח. איך נותנים הרשאות ל-Agent Platform יוצרים פרופיל הצגה באותו אזור (
usאוeu) שמגדיר אתscopeל-INTERACTIONS_APIואתcmekConfig.encryptionSpec.kmsKeyNameלמפתח שלכם:curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/servingProfiles?servingProfileId=SERVING_PROFILE_ID" \ -d '{ "displayName": "Interactions API CMEK profile", "description": "CMEK for Interactions API", "scope": "INTERACTIONS_API", "cmekConfig": { "encryptionSpec": { "kmsKeyName": "projects/KMS_PROJECT_ID/locations/LOCATION/keyRings/KEY_RING_NAME/cryptoKeys/KEY_NAME" } } }'מחכים עד שהפעולה הארוכה של יצירת הפרופיל תסתיים (
"done": true). למידע נוסף על ניהול, עדכון או מחיקה של פרופילי הצגה, קראו את המאמר יצירת פרופיל הצגה.שולחים את בקשות האינטראקציה לאותו אזור או לאותו אזור מרובה של
usאוeuכמו פרופיל הצגת המודעות. אי אפשר להשתמש ב-CMEK של פרופיל הצגת המודעות בנקודת הקצהglobal.- Google Gen AI SDK: מאתחלים את הלקוח באמצעות
location="us"אוlocation="eu"(location: "us"אוlocation: "eu"ב-TypeScript או ב-JavaScript). - REST: שולחים בקשות לנקודת הקצה במספר אזורים
https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions, כאשר LOCATION הואusאוeu.
אם תשביתו את המפתח או תבטלו את הגישה של סוכן השירות, בקשות ליצירה או לקריאה של אינטראקציות מאוחסנות ייכשלו עם השגיאה
FAILED_PRECONDITION.- Google Gen AI SDK: מאתחלים את הלקוח באמצעות
תהליכי עבודה מתקדמים של REST
כדי להשתמש באוטומציה מבוססת-מעטפת, בצינורות עיבוד נתונים של CI/CD או בסביבות בלי סביבת זמן ריצה של Python או TypeScript/JavaScript, אתם יכולים לקרוא ל-Interactions API ישירות דרך HTTP באמצעות curl.
נקודת קצה (endpoint) של REST
שולחים בקשות POST לנקודת קצה ל-API הבאה של Interactions API:
POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions
מחליפים את המשתנים הבאים בבקשות:
- PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
- LOCATION: צריך להגדיר את הערך
global(אוusאוeuעם המארח במספר אזוריםhttps://aiplatform.LOCATION.rep.googleapis.comלמיקום אחסון הנתונים או ל-CMEK).
הגדרה של משתני סביבה ואימות
לפני שמריצים את הדוגמאות של curl בקטעים הבאים, צריך לייצא את מזהה הפרויקט, את מזהה המודל או הנציג (agent) המטורגט ואת אסימון הגישה מסוג OAuth 2.0 שנוצר מ-Application Default Credentials (ADC):
PROJECT_ID="PROJECT_ID"
MODEL_ID="gemini-3.8-flash"
AGENT_ID="deep-research-preview-04-2026"
ACCESS_TOKEN=$(gcloud auth print-access-token)
פורמט תגובה סינכרוני
בקשה סינכרונית של POST מחזירה אובייקט interaction בפורמט JSON שכולל את המטא-נתונים הייחודיים של האינטראקציה id, הביצוע status, השיחה steps והטוקן usage:
{
"id": "your-interaction-id",
"status": "completed",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
}
]
}
],
"usage": {
"total_tokens": 24751,
"total_input_tokens": 23894,
"total_output_tokens": 857
},
"created": "2026-05-08T10:44:43Z",
"updated": "2026-05-08T10:44:43Z",
"environment_id": "your-environment-id",
"object": "interaction"
}
המשך של אינטראקציה רב-שלבית עם שמירת מצב
כדי להמשיך שיחה שמורה באמצעות REST, מעבירים את ה-id מתשובה קודמת בשדה previous_interaction_id של גוף הבקשה ב-JSON.
לפני שמנסים את הדוגמה הזו, מחליפים את PREVIOUS_INTERACTION_ID ב-id שהוחזר מאינטראקציה קודמת.
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"store": true,
"previous_interaction_id": "PREVIOUS_INTERACTION_ID",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Can you elaborate on that?"
}]
}]
}'
פלט סטרימינג עם אירועים שנשלחים מהשרת
כדי להעביר עדכונים מצטברים בסטרימינג דרך REST, צריך לכלול את "stream": true בגוף הבקשה ב-JSON:
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"stream": true,
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Write a long story about space travel."
}]
}]
}'
כאשר "stream": true מוגדר, השרת מגיב עם Transfer-Encoding: chunked ו-Content-Type: text/event-stream (אירועים שנשלחים מהשרת). כל אירוע בסטרימינג כולל קידומת data: שמכילה מטען ייעודי (payload) של JSON עם התוכן של event_type ושל השינוי בשלב. curl משאיר את חיבור ה-HTTP פתוח באופן אוטומטי וכותב קטעים נכנסים אל stdout בזמן אמת עד שהאינטראקציה מסתיימת.
הפעלת סוכן מנוהל ברקע
כדי להתחיל משימה ארוכה של סוכן מנוהל באופן אסינכרוני באמצעות REST, מציינים את היעד agent, מגדירים את "background": true ומגדירים את "environment": "remote":
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"environment": "remote",
"background": true,
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Analyze competitive positioning for commercial solar energy providers."
}]
}]
}'
המאמרים הבאים
במקורות המידע הבאים תוכלו לקרוא מידע נוסף על Interactions API, על הכלים המובנים ועל עיגון:
בסקירה הכללית על Interactions API מוסברים מושגי מפתח.
במאמרי העזרה של Interactions API מוסבר על סכמות של בקשות ותשובות.
מידע נוסף על הרצת קוד, URL Context ועיגון באמצעות חיפוש Google.
איך משתמשים בנציגים מנוהלים ואיך משתמשים ב-Gemini Deep Research Agent.