Interactions API 提供了一个统一的有状态接口,用于在 Gemini Enterprise Agent Platform 上使用 Gemini 模型和自主智能体构建生成式 AI 应用。使用 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表示对话或任务中的一个完整轮次,用于跟踪模型思考、工具调用和最终输出的时间顺序。它为提示-回答交互和复杂的多步骤 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 库之一。
支持的模型:使用受支持的 Gemini 3 或更高版本模型。早期模型系列不支持此 API。如需查看受支持模型的完整列表,请参阅受支持的模型和迁移到最新模型版本。
轮次级参数:
tools、system_instruction和generation_config等配置参数仅适用于当前轮次。如果您的工作流在多轮对话中需要这些参数,请在后续的每一轮互动中传递这些参数。Gemini 4 Argon 上的长解码:如需在
gemini-4-argon或gemini-4-argon-cyber-permissive上生成超过 65,536 个词元(最多 1,048,576 个词元减去输入词元)的单轮输出,请在v1beta1端点上使用自动 Google Gen AI SDK 延续(Python 版google-genai >= 2.34.0、TypeScript/JavaScript 版@google/genai >= 2.32.0、Go 版>= 1.77.0、Java 版>= 1.80.0)、background=True或continuation_token。如需查看代码示例和延续规则,请参阅 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
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>
对客户端进行身份验证
您可以使用以下任一身份验证方法连接到 Agent Platform 上的 Interactions API:
使用 Google Cloud 项目和应用默认凭据 (ADC) 建立连接
对于 Google Cloud上的企业工作负载和生产部署,请使用此身份验证方法。如需使用应用默认凭证 (ADC) 进行身份验证,请使用以下属性初始化客户端:
enterprise=Trueproject="PROJECT_ID"location="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/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 密钥进行身份验证的环境,请使用此身份验证方法。在初始化客户端时或在 x-goog-api-key HTTP 标头中传递 API 密钥。
在以下代码示例中,将 API_KEY 替换为您的 API 密钥,并将 PROJECT_ID 替换为您的 Google Cloud 项目 ID。
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."
}]
}]
}'
常见互动工作流
配置客户端后,您可以使用 interactions.create 方法管理会话存储和多轮对话、实时流式传输输出 token、生成经过架构验证的 JSON、调用内置工具和接地、调用外部函数以及运行自主智能体。
管理会话存储和对话状态
Interactions API 同时支持服务器端有状态存储(store=True,默认)和客户端管理的无状态执行 (store=False)。下表比较了有状态和无状态互动模式:
| 功能 | 有状态模式(store=true,默认) |
无状态模式 (store=false) |
|---|---|---|
| 服务器端持久性 | 在服务器上存储输入、中间步骤和输出 7 天。 | 停用服务器端互动存储,以支持零数据保留 (ZDR) 工作流。 |
| 多轮对话上下文 |
通过在 previous_interaction_id 中传递之前的互动 id 来链接轮次。
|
需要在每轮对话中,在 input 中传递先前对话 steps 的完整数组。传递 previous_interaction_id 会返回 400 Bad
Request 错误。
|
后台执行 (background=true)
|
支持长时间运行的模型和智能体互动。 | 不受支持。异步后台执行需要服务器端状态持久性。 |
| 会话生命周期方法 |
支持检索 (get)、列出 (list)、取消 (cancel) 和删除 (delete) 互动。
|
在同步或流式响应完成后无法检索。 |
| 静态加密 |
默认使用 Google-owned and Google-managed encryption key或客户管理的加密密钥 (CMEK) 在us和eu多区域中加密。
|
系统不会存储任何互动状态。 |
运行有状态多轮对话
默认情况下,Interactions API 会将对话状态存储在服务器上(Python 中为 store=True,TypeScript/JavaScript 中为 store: true)。如需继续现有对话,请将前一个互动的 id 传递给 previous_interaction_id 参数。智能体平台会检索存储的对话上下文,附加新的对话轮次,并重复使用缓存的前缀词元。
在跨端点链接互动时,请遵循以下位置规则:
同一位置:您可以在同一位置内链接互动(例如
global到global、us到us或eu到eu)。跨不同位置:不支持跨不同端点位置(
global与us或eu之间,或者us与eu之间)进行链接。每个端点都会将互动状态存储在隔离的存储空间中,因此引用在其他位置创建的互动 ID 会返回404 Not Found错误。
在以下示例中,将 PROJECT_ID 替换为您的 Google Cloud项目 ID:
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?"
}'
运行无状态多轮对话
如果您的工作负载需要零数据保留 (ZDR),请在每个请求中明确设置 store=False(在 TypeScript/JavaScript 中为 store: false,在 REST 中为 "store": false)。
在无状态模式下,您可以通过维护 Step 对象(user_input、thought、function_call、function_result 和 model_output)的列表,并在每个轮次中发送 input 中累积的 steps 数组,在客户端管理对话记录:
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) 遵循以下保留和分支规则:
7 天存留时间 (TTL):每条存储的互动记录都会从其
created时间戳开始保留 7 天,并在 7 天 TTL 到期后自动删除。独立的父级和子级存储:当您使用
previous_interaction_id链接新轮次时,智能体平台会将祖先对话历史记录复制到新的互动记录中。由于每轮对话都会存储自己的对话记录副本,因此使较早的对话轮次过期或将其删除会产生以下影响:从后续轮次继续操作会成功:如果轮次 1 (
interaction_1) 在轮次 2 (interaction_2) 创建后过期或被删除,您仍然可以使用previous_interaction_id=interaction_2.id创建轮次 3,直到interaction_2本身过期或被删除。从已过期或已删除的轮次分支失败:尝试直接引用
previous_interaction_id中已过期或已删除的互动 ID 创建新互动会返回400 Bad Request(Previous Interaction ID not found) 错误。
检索、列出、取消和删除存储的互动
您可以使用以下方法在存储的互动记录的整个生命周期内对其进行检查和管理:
检索互动 (
interactions.get):按id提取完整的Interaction资源,包括user_input步骤、中间thought和工具步骤以及model_output步骤。设置stream=True(以及可选的last_event_id)以流式传输或恢复正在进行的互动。列出互动 (
interactions.list):使用page_size(默认值为10,最大值为500)和page_token,通过 REST 查询项目中存储的互动 ID。返回InteractionMetadata资源列表。取消正在进行的互动 (
interactions.cancel):停止处于in_progress或requires_action状态的异步后台互动 (background=True),并将其状态转换为cancelled。您需要支付取消订阅前生成的任何令牌的费用。删除存储的互动 (
interactions.delete):在存储的互动 7 天 TTL 到期之前将其永久移除。只有处于终止状态(completed、failed或cancelled)的互动才能删除;如果互动仍在后台运行,请先取消互动,然后再将其删除。
在以下示例中,将 PROJECT_ID 替换为您的 Google Cloud项目 ID,并将 INTERACTION_ID 替换为目标互动 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)"
有状态存储空间配额和限制
除了模型词元和请求速率限制之外,有状态互动 (store=True) 还受以下项目级存储空间和并发限制的约束:
| 配额或系统限制 | 默认上限(每个项目) | 说明 |
|---|---|---|
| 每天的有状态互动创建吞吐量 | 每天 240 GiB |
每天通过 interactions.create 请求写入服务器端存储空间的互动数据总量上限(使用 store=true)。 |
| 每天的有状态互动检索吞吐量 | 每天 480 GiB |
每天通过 interactions.get 请求和使用 previous_interaction_id 加载先前对话轮次的多轮对话请求读取的存储互动数据总量上限。 |
| 并发有状态互动 | 500 次并发互动 |
项目中同时执行的有状态互动数上限。 |
如需详细了解如何在 Agent Platform 上查看和管理配额,请参阅配额和系统限制。
实时流式传输回答
为了缩短互动式应用的感知延迟时间,您可以在生成模型回答时流式传输这些回答。在调用 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 还支持适用于 Gemini 3 模型的内置服务器端工具。在 tools 参数中启用内置工具后,Agent Platform 会在单次 interactions.create 调用期间在服务器上执行该工具,并在 interaction.steps 中记录工具调用 (*_call) 和输出 (*_result) 步骤。
Interactions API 支持以下内置工具:
代码执行 (
{"type": "code_execution"}):在沙盒环境中生成并执行 Python 代码,以执行计算、数据分析和基于代码的推理。如需了解支持的库、结算和限制,请参阅代码执行。网址上下文 (
{"type": "url_context"}):检索并分析提示中包含的公开网址中的内容。如需详细了解索引缓存、实时提取以及将网址上下文与搜索相结合,请参阅网址上下文。依托 Google 搜索进行接地 (
{"type": "google_search"}):根据实时网络信息为模型回答提供依据,并返回内嵌引用。请参阅依托 Google 搜索为回答接地。Computer use (
{"type": "computer_use"}):启用浏览器和界面自动化工作流。如需了解配置和安全控制,请参阅计算机使用。
执行 Python 代码
如需启用代码执行功能,请在 tools 列表中添加 {"type": "code_execution"}。返回的 interaction.steps 数组包含 code_execution_call 步(具有 arguments.code 和 arguments.language)、code_execution_result 步(具有 result 和 is_error)以及最终的 model_output 步。
在以下示例中,将 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="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"}]
}'
根据网址上下文检索网页内容
如需使模型能够提取和分析提示中引用的网页,请在 tools 列表中添加 {"type": "url_context"}。API 会在 url_context_call 和 url_context_result 步骤中记录提取的网址,并在 model_output 中将 url_citation 注解附加到生成的文本。
在以下示例中,将 PROJECT_ID 替换为您的 Google Cloud项目 ID,并将 YOUR_URL_1 和 YOUR_URL_2 替换为要比较的公开网址:
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 搜索进行接地和适用于企业的 Web 接地。
通过在 tools 列表中传递 {"type": "google_search"} 来启用依托 Google 搜索进行接地后,Interactions API 会直接在 interaction.steps 时间轴中返回搜索和归因数据:
google_search_call:包含模型发出的搜索查询 (step.arguments.queries)。google_search_result:包含搜索建议 (result[].search_suggestions),这是一个 HTML/CSS 代码段,用于在界面中呈现搜索建议。包含来源网址和标题的网络资源会以model_output文本块上的内嵌url_citation注解形式提供。内嵌
url_citation注解:model_output步骤中的每个text内容块 (TextContent) 都可以包含一个annotations数组。每个url_citation注解都会标识回答文本中的字符或字节范围(start_index和end_index),以及来源title和url。
在以下示例中,将 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="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 会立即返回一个包含 id 的 Interaction 对象,您可以使用 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 文件。在以下示例中,将 PROJECT_ID 替换为您的Google Cloud 项目 ID:
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)
将 Cloud Storage URI(例如 gs://bucket-name/path/to/file)传递给 Interactions API 时,请求会先使用调用方的凭证验证读取权限,然后调用项目的 Agent Platform Service Agent (service-PROJECT_NUMBER@gcp-sa-aiplatform.) 才会从 Cloud Storage 提取对象。
如需在互动请求中传递 Cloud Storage 文件,调用主账号(用户账号、服务账号或联合身份)必须对所有引用的对象拥有 storage.objects.get 权限。对于跨项目 Cloud Storage 存储桶或具有自定义 IAM 政策的 Cloud Storage 存储桶,请向调用主账号和调用项目的服务代理授予读取权限。
每个标准 Gemini 模型交互请求最多支持 100 个不同的 Cloud Storage (gs://) URI(每个文件最多 2 GiB 减去 500 KiB)。当您使用 previous_interaction_id 串联有状态轮次时,Agent Platform 会在对话记录和当前轮次中累计计算不同的 gs:// URI。托管式代理互动(设置 agent 而不是 model 的请求)、Gemini Omni 模型和 Lyria 3 模型不在此 100 个 URI 的限制范围内。
配置用于访问 Cloud Storage 文件的 IAM 角色
授予包含 storage.objects.get 权限的标准预定义角色之一:
Storage Object Viewer (
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.
如需解决此问题,请向经过身份验证的调用方(以及调用项目的 Agent Platform Service Agent,适用于跨项目或自定义 IAM Cloud Storage 存储桶)授予 Cloud Storage 存储桶或对象的 Storage Object Viewer 角色 (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.
如需解决此问题,请验证 Cloud Storage URI 是否正确,并确认经过身份验证的调用方对存储桶具有读取权限。
如果模型互动请求在当前轮次和任何关联的 previous_interaction_id 历史记录中引用了超过 100 个不同的 Cloud Storage URI,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的情况下开始新的互动。 - 合并较小的文档,或在请求载荷限制内以内嵌方式传递其他文件(对于同步或流式传输请求,压缩后为 256 MiB;当
service_tier设置为deferred,且background和store设置为true时,未压缩时为 9.75 MiB)。 - 对于引用
gs://URI 的请求,请使用generateContent,但不得超过每种模态的模型项限制(图片和 PDF 合计 3,000 个、音频文件 1,000 个、视频 10 个,如果包含纯文本文件,则最多 6,500 个文件)。
使用 CMEK 加密互动数据
有状态互动(Python 中的 store=True 或 TypeScript/JavaScript 中的 store: true)最多可将互动数据存储 7 天。如需使用您自己的加密密钥(而非Google-owned and Google-managed encryption key)保护这些数据,请使用服务配置文件。服务配置文件会将 Cloud Key Management Service 密钥与项目、位置和 API 范围相关联。只要存在服务配置文件,Agent Platform 就会自动加密存储的互动数据,而互动请求格式不会发生变化。
us 和 eu 多区域支持 Interactions API 的服务配置 CMEK。global 区域不受支持。
如需为 Interactions API 设置 CMEK,请执行以下操作:
- 在项目中启用 Cloud KMS API 和 Agent Platform API。请参阅准备工作。
- 在
us或eu多区域中创建 Cloud KMS 密钥。请参阅创建密钥环和密钥。 - 为 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多区域。global端点上不提供服务配置 CMEK。- Google Gen AI SDK:使用
location="us"或location="eu"(TypeScript/JavaScript 中为location: "us"或location: "eu")初始化客户端。 - REST:向多区域端点
https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions发送请求,其中 LOCATION 为us或eu。
如果您停用密钥或撤消服务代理的访问权限,则创建或读取存储的互动的请求会失败,并显示
FAILED_PRECONDITION错误。- Google Gen AI SDK:使用
高级 REST 工作流
对于基于 shell 的自动化、CI/CD 流水线或没有 Python 或 TypeScript/JavaScript 运行时的环境,您可以使用 curl 通过 HTTP 直接调用 Interactions API。
REST 端点
向以下 Interactions API 端点发送 POST 请求:
POST https://aiplatform.googleapis.com/v1/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 继续已存储的对话,请在 JSON 请求正文的 previous_interaction_id 字段中传递先前回答中的 id。
在尝试此示例之前,请将 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 流式传输增量更新,请在 JSON 请求正文中添加 "stream": true:
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: 前缀,该前缀包含一个 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 参考文档中探索请求和响应 schema。
详细了解代码执行、网址上下文和依托 Google 搜索进行接地。