Interactions API 提供統一的有狀態介面,可在 Gemini Enterprise Agent Platform 上,使用 Gemini 模型和自主代理建構生成式 AI 應用程式。使用 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代表對話或工作中的完整回合,會追蹤模型思考、工具呼叫和最終輸出的時間順序。為提示/回覆互動和複雜的多步驟 Agentic Workflows,提供統一的封裝。- 有狀態保留:互動預設會儲存在伺服器端 (Python 為
store=True,TypeScript/JavaScript 為store: true)。儲存的互動記錄會保留 7 天,之後就會自動刪除。設定store=False會啟用無狀態模式,停用伺服器端保留功能,並符合零資料保留 (ZDR) 規範。無狀態模式也會停用previous_interaction_id鏈結和非同步執行 (background=True)。 - 回應輔助函式:Google Gen AI SDK
2.3.0以上版本提供互動回應的便利屬性,包括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 (Python 適用
>= 2.3.0,TypeScript 和 JavaScript 適用@google/genai >= 2.3.0)。- 如要使用回覆輔助屬性和代理能力,必須使用
2.3.0以上版本,而 2.0.0 版則支援基本steps結構定義。 - 舊版 SDK (
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"
驗證用戶端
您可以使用下列任一驗證方式,連線至 Agent Platform 上的 Interactions API:
使用 Google Cloud 專案和應用程式預設憑證 (ADC) 建立連線
建議您在 Google Cloud上,使用這種驗證方式處理企業工作負載和正式環境部署作業。如要使用應用程式預設憑證 (ADC) 進行驗證,請使用下列屬性初始化用戶端:
enterprise=Trueproject= Google Cloud project IDlocation="global"
如果尚未設定本機憑證,請執行 gcloud auth application-default login。
在下列程式碼範例中,將 PROJECT_ID 替換為您的Google Cloud 專案 ID。
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 金鑰驗證的環境中,採用這種驗證方式。初始化用戶端時,或在 x-goog-api-key HTTP 標頭中,傳遞 API 金鑰。
在下列程式碼範例中,請將 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 要求每次要求都必須重新傳送完整訊息記錄,但 Interactions API 預設會在伺服器上管理對話狀態 (Python 為 store=True,TypeScript/JavaScript 為 store: true)。
如要繼續現有對話,請將前一個互動的 id 傳遞至 previous_interaction_id 參數。Agent Platform 會自動擷取儲存的對話內容,並附加新的對話。如果設定 store=False (TypeScript/JavaScript 中為 store: false),系統會停用伺服器端持續性,且您無法使用 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}`);
即時串流回覆
如要縮短互動式應用程式的感知延遲時間,可以在生成模型回覆時,以串流方式輸出。呼叫 interactions.create 時,請設定 stream=True (在 TypeScript/JavaScript 中為 stream: true),接收伺服器傳送事件的可疊代串流。篩選 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 結構定義。將目標結構定義 (例如 Python 中的 Pydantic 模型 JSON 結構定義,或 TypeScript/JavaScript 中的 Type 結構定義物件) 直接傳遞至多型 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執行本機函式,然後傳送後續互動,其中包含由call_id和previous_interaction_id連結的function_result項目。
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 代理,可規劃及執行多步驟網路研究工作,並將多個來源的結果彙整成詳盡報告。詳情請參閱「使用 Gemini Deep Research 代理」。- 自訂代理:使用
client.agents.create()設定及佈建的自訂代理資源。
代理工作流程通常需要幾分鐘才能完成,因此請設定 background=True,在背景以非同步方式執行。API 會立即傳回 Interaction 物件,其中包含 id,您可以使用 client.interactions.get() 輪詢,直到 interaction.status 轉換為 completed:
嘗試這個範例前,請將 PROJECT_ID 替換為您的Google Cloud 專案 ID。
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)
將 Cloud Storage URI (例如 gs://bucket-name/path/to/file) 傳遞至 Interactions API 時,系統會使用使用者憑證 (EUC) 評估要求。API 會使用已驗證呼叫者的身分 (而非背景專案服務代理) 擷取 Cloud Storage 物件。
如要在互動要求中傳遞 Cloud Storage 檔案,呼叫主體 (使用者帳戶、服務帳戶或聯合身分) 必須具備所有參照物件的 storage.objects.get 權限。
設定存取 Cloud Storage 檔案的 IAM 角色
授予包含 storage.objects.get 權限的其中一個標準預先定義角色:
- Storage 物件檢視者 (
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"
如要將存取權授予特定呼叫服務帳戶,請使用下列指令:
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 檔案存取問題
如果呼叫主體的權限不足,Interactions API 會傳回類似下列的 403 Forbidden 錯誤:
Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more Cloud Storage URIs.
如要解決這個問題,請將 bucket 或物件的 Storage 物件檢視者角色 (roles/storage.objectViewer) 授予已驗證的呼叫端。
如果指定的物件不存在,或 bucket 權限導致呼叫端無法查看物件是否存在,Interactions API 會傳回類似下方的 404 Not Found 錯誤:
Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.
如要解決這個問題,請確認 Cloud Storage URI 正確無誤,且經過驗證的呼叫端具備 bucket 的讀取權限。
使用 CMEK 加密互動資料
有狀態互動 (Python 中的 store=True 或 TypeScript/JavaScript 中的 store: true) 會將互動資料儲存最多 7 天。如要使用自己的加密金鑰 (而非Google-owned and Google-managed encryption key) 保護資料,請使用服務設定檔。服務設定檔會將 Cloud Key Management Service 金鑰連結至專案、位置和 API 範圍。只要有服務設定檔,Agent Platform 就會自動加密儲存的互動資料,互動要求格式不會改變。
Interactions API 的供應設定檔 CMEK 支援 us 和 eu 多區域。不支援「global」區域。
如要為 Interactions API 設定 CMEK,請按照下列步驟操作:
- 在專案中啟用 Cloud KMS API 和 Agent Platform API。請參閱事前準備一節。
- 在
us或eu多區域中建立 Cloud KMS 金鑰。請參閱「建立金鑰環和金鑰」。 - 將金鑰的
roles/cloudkms.cryptoKeyEncrypterDecrypter角色授予 Gemini Enterprise Agent Platform 服務代理。請參閱「授予 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/v1beta1/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多區域。global端點不支援供應設定檔 CMEK。- Google Gen AI SDK:使用
location="us"或location="eu"(TypeScript/JavaScript 為location: "us"或location: "eu") 初始化用戶端。 - REST:將要求傳送至多區域端點
https://aiplatform.LOCATION.rep.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions,其中 LOCATION 為us或eu。
如果停用金鑰或撤銷服務代理的存取權,建立或讀取儲存互動的要求會失敗,並傳回
FAILED_PRECONDITION錯誤。- Google Gen AI SDK:使用
進階 REST 工作流程
如果是以殼層為基礎的自動化作業、CI/CD 管道,或沒有 Python 或 TypeScript/JavaScript 執行階段的環境,您可以使用 curl,直接透過 HTTP 呼叫 Interactions API。
REST 端點
將 POST 要求傳送至下列 Interactions API 端點:
POST https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions
請替換要求中的下列變數:
- PROJECT_ID: Google Cloud 專案 ID。
- LOCATION:設為
global(或us或eu,並搭配多區域主機https://aiplatform.LOCATION.rep.googleapis.com,使用 CMEK 加密互動資料)。
設定環境變數和驗證
執行下列各節中的 curl 範例之前,請先匯出專案 ID、目標模型或代理 ID,以及從應用程式預設憑證產生的 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 傳遞至 JSON 要求主體的 previous_interaction_id 欄位。
嘗試這個範例前,請先將 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 串流傳輸增量更新,請在 JSON 要求主體中加入 "stream": true:
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: 前置字元,其中含有 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 參考資料,瞭解要求和回覆結構定義。
- 瞭解如何與代管代理互動,以及使用 Gemini Deep Research 代理。