Interactions API מספק ממשק מאוחד עם שמירת מצב ליצירת אפליקציות של AI גנרטיבי עם מודלים של Gemini וסוכנים אוטונומיים בפלטפורמת הסוכנים של Gemini Enterprise. אפשר להשתמש ב-Interactions API כדי לנהל שיחות רב-שלביות, להזרים תשובות בזמן אמת, לאכוף פלט מובנה, להפעיל קריאות לפונקציות ולתזמר משימות ארוכות טווח ברקע.
במדריך הזה מוסבר איך להתקין את Google Gen AI SDK, לאמת את הלקוח וליישם תהליכי עבודה נפוצים של אינטראקציה. לפרטים על מחזור החיים של האינטראקציה, ראו סקירה כללית על Interactions API.
לפני שמתחילים
לפני ששולחים בקשות ל-Interactions API, צריך להגדיר את Google Cloud הפרויקט ואת סביבת הפיתוח:
- נכנסים לחשבון Google Cloud . אנחנו ממליצים למשתמשים חדשים ב- Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
-
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 email address for a Google Account.
- Click Select a role, then search for the role.
- To grant additional roles, click Add another role and add each additional role.
- Click Save.
-
-
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 email address for a Google Account.
- 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מייצג תור שלם בשיחה או במשימה, ומאפשר לעקוב אחר הכרונולוגיה של המחשבות של המודל, הקריאות לכלים והפלט הסופי. הוא מספק מעטפת מאוחדת לאינטראקציות של הנחיות ותשובות ולתהליכי עבודה מורכבים עם כמה שלבים של סוכנים. - שימור עם שמירת מצב: האינטראקציות מאוחסנות בצד השרת כברירת מחדל (
store=Trueב-Python אוstore: trueב-TypeScript/JavaScript). האינטראקציות המאוחסנות נשמרות למשך 7 ימים ואז נמחקות אוטומטית. ההגדרהstore=Falseמאפשרת להשתמש במצב חסר מצב (stateless), שמשבית את השמירה בצד השרת ועומד בדרישות של שמירת נתונים אפס (ZDR). במצב חסר מצב (Stateless) מושבתים גם שרשור של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 המאוחד (
>= 2.3.0ל-Python או@google/genai >= 2.3.0ל-TypeScript ול-JavaScript).- נדרשת גרסה
2.3.0ואילך כדי להשתמש במאפייני העזרה לתגובה וביכולות של נציגים, ואילו גרסה 2.0.0 תומכת בסכימה הבסיסיתsteps. - SDKs מדור קודם (
google-cloud-aiplatform,@google-cloud/vertexaiו-google-generativeai) לא תומכים ב-Interactions API.
- נדרשת גרסה
מודלים נתמכים: אפשר להשתמש במודלים נתמכים של Gemini 3 או במודלים מתקדמים יותר. משפחות דגמים קודמות לא תומכות ב-API הזה. רשימה מלאה של המודלים הנתמכים זמינה במאמרים מודלים נתמכים ומעבר לגרסאות העדכניות של המודלים.
פרמטרים בהיקף תור: פרמטרים להגדרה כמו
tools,system_instructionו-generation_configחלים רק על התור הנוכחי. אם זרימת העבודה שלכם דורשת את הפרמטרים האלה בשיחה רב-שלבית, צריך להעביר אותם בכל תור אינטראקציה עוקב.
התקנה של Google Gen AI SDK
מתקינים או משדרגים את Google Gen AI SDK (>= 2.3.0) בשפה המועדפת:
Python
pip install --upgrade "google-genai>=2.3.0"
TypeScript / JavaScript
npm install "@google/genai>=2.3.0"
אימות הלקוח
אפשר להתחבר ל-Interactions API ב-Agent Platform באמצעות אחת משיטות האימות הבאות:
חיבור באמצעות Google Cloud פרויקט עם Application Default Credentials (ADC)
אנחנו ממליצים להשתמש בשיטת האימות הזו לעומסי עבודה ארגוניים ולפריסות בסביבת ייצור ב- Google Cloud. כדי לבצע אימות באמצעות Application Default Credentials (ADC), צריך לאתחל את הלקוח עם המאפיינים הבאים:
enterprise=Trueproject= Google Cloud project IDlocation="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/v1beta1/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": [{
"role": "user",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
התחברות באמצעות מצב אקספרס (מפתח API)
מומלץ להשתמש בשיטת האימות הזו ליצירת אב טיפוס מהיר, לסקריפטים קלים או לסביבות שמתבצע בהן אימות באמצעות מפתח API. מעבירים את מפתח ה-API כשמפעילים את הלקוח או בכותרת ה-HTTP x-goog-api-key.
בדוגמת הקוד הבאה, מחליפים את הערך API_KEY במפתח ה-API שלכם.
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/v1beta1/locations/global/interactions" \
-H "x-goog-api-key: API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": [{
"role": "user",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
תהליכי עבודה נפוצים לאינטראקציות
אחרי שמגדירים את הלקוח, אפשר להשתמש בשיטה interactions.create כדי ליצור שיחות רב-שלביות, להציג טוקנים של פלט באופן שוטף בזמן אמת, ליצור JSON שעבר אימות סכמה, להפעיל פונקציות חיצוניות ולהריץ סוכנים אוטונומיים.
ניהול שיחות רב-שלביות עם שמירת מצב
בניגוד לממשקי API של צ'אט חסרי מצב (stateless) שבהם צריך לשלוח מחדש את היסטוריית ההודעות המלאה עם כל בקשה, ממשק Interactions API מנהל את מצב השיחה בשרת כברירת מחדל (store=True ב-Python או store: true ב-TypeScript/JavaScript).
כדי להמשיך שיחה קיימת, מעבירים את id של האינטראקציה הקודמת לפרמטר previous_interaction_id. Agent Platform מאחזרת באופן אוטומטי את ההקשר של השיחה שמאוחסן ומוסיפה את התור החדש. אם מגדירים את
store=False (store: false ב-TypeScript או ב-JavaScript), ההתמדה בצד השרת מושבתת ואי אפשר לשרשר תורות עוקבות עם
previous_interaction_id.
Python
# Turn 1: Start a 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
// Turn 1: Start a 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}`);
הצגת תשובות באופן שוטף בזמן אמת
כדי לצמצם את זמן האחזור שנתפס באפליקציות אינטראקטיביות, אפשר להזרים את התשובות של המודל בזמן שהן נוצרות. מגדירים את 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 מאפשר לכם להפעיל סוכנים אוטונומיים מיוחדים באמצעות הפרמטר agent:
-
antigravity-preview-05-2026: סוכן מנוהל לשימוש כללי עם ביצוע קוד, ניהול קבצים וגלישה באינטרנט בסביבת ארגז חול מאובטחת של Linux. מידע נוסף מופיע במאמר איך יוצרים אינטראקציה עם סוכנים. -
deep-research-preview-04-2026: Gemini Deep Research Agent, שמתכנן ומבצע משימות מחקר מורכבות באינטרנט, ומסכם את הממצאים מכמה מקורות בדוחות מקיפים. מידע נוסף זמין במאמר בנושא שימוש בסוכן Deep Research של Gemini. - סוכנים בהתאמה אישית: משאבים של סוכנים בהתאמה אישית שהוגדרו והוקצו באמצעות
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. מקרה לדוגמה:
from google import genai
# Credentials must belong to an identity with storage.objects.get permissions
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{"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)
כשמעבירים מזהי URI של Cloud Storage (לדוגמה, gs://bucket-name/path/to/file) אל Interactions API, הבקשות נבדקות באמצעות פרטי כניסה של משתמש קצה (EUC). ה-API מאחזר אובייקטים של Cloud Storage באמצעות הזהות של המתקשר המאומת, ולא באמצעות סוכן שירות של פרויקט ברקע.
כדי להעביר קבצים מ-Cloud Storage בבקשת אינטראקציה, למשתמש הראשי (חשבון משתמש, חשבון שירות או זהות מאוחדת) שמבצע את הקריאה צריכה להיות הרשאת storage.objects.get לכל האובייקטים שמפנים אליהם.
הגדרת תפקידי IAM לגישה לקבצים ב-Cloud Storage
נותנים אחד מהתפקידים המוגדרים מראש שכוללים את ההרשאה storage.objects.get:
- צפייה באובייקטים של אחסון (
roles/storage.objectViewer): גישת קריאה לאובייקטים (מומלץ). - משתמש באובייקט Storage (
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"
כדי להעניק גישה לחשבון שירות ספציפי שקורא ל-API, משתמשים בפקודה הבאה:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="serviceAccount:sa-name@PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/storage.objectViewer"
פתרון בעיות בגישה לקבצים ב-Cloud Storage
אם לחשבון המשתמש ששולח את הקריאה ל-API אין הרשאות מספיקות, Interactions API מחזיר שגיאה 403 Forbidden שדומה לזו:
Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more GCS URIs.
כדי לפתור את הבעיה, צריך להעניק את התפקיד 'צפייה באובייקט אחסון' (roles/storage.objectViewer) בקטגוריה או באובייקט למשתמש המאומת שביצע את הקריאה.
אם האובייקט שצוין לא קיים, או אם הרשאות הקטגוריה מונעות מהמתקשר לראות אם האובייקט קיים, 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 נכון ושלמתקשר המאומת יש גישת קריאה לדלי.
תהליכי עבודה מתקדמים של REST
כדי להשתמש באוטומציה מבוססת-shell, בצינורות CI/CD או בסביבות ללא זמן ריצה של Python או TypeScript/JavaScript, אפשר לקרוא ישירות ל-Interactions API דרך HTTP באמצעות curl.
נקודת קצה של REST
שולחים בקשות POST לנקודת קצה ל-API הבאה של Interactions API:
POST https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions
מחליפים את המשתנים הבאים בבקשות:
- PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
- LOCATION: הערך שמוגדר הוא
global(או אזור מותאם אישית נתמך אם נדרש בהגדרה).
הגדרת משתני סביבה ואימות
לפני שמריצים את הדוגמאות curl שבקטעים הבאים, צריך לייצא את מזהה הפרויקט, את מזהה המודל או הסוכן ואת אסימון הגישה מסוג OAuth 2.0 שנוצר מפרטי הכניסה שמוגדרים כברירת מחדל לאפליקציה:
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 סינכרונית מחזירה אובייקט JSON interaction שכולל את המטא-נתונים הייחודיים של האינטראקציה 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/v1beta1/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": [{
"role": "user",
"content": [{
"type": "text",
"text": "Can you elaborate on that?"
}]
}]
}'
הזרמת פלט באמצעות אירועים שנשלחים מהשרת
כדי להזרים עדכונים מצטברים באמצעות REST, צריך לכלול את "stream": true בגוף הבקשה ב-JSON:
curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"stream": true,
"input": [{
"role": "user",
"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/v1beta1/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": [{
"role": "user",
"content": [{
"type": "text",
"text": "Analyze competitive positioning for commercial solar energy providers."
}]
}]
}'
המאמרים הבאים
- סקירה כללית על Interactions API
- אפשר לעיין בסכימות של הבקשות והתגובות בהפניית Interactions API.
- איך מתקשרים עם סוכנים מנוהלים ואיך משתמשים בסוכן Deep Research של Gemini