Interactions API menyediakan antarmuka stateful terpadu untuk membangun aplikasi AI generatif dengan model Gemini dan agen otonom di Gemini Enterprise Agent Platform. Gunakan Interactions API untuk mengelola penyimpanan sesi dan percakapan multi-turn, menstreaming respons real-time, menerapkan output terstruktur, memanggil alat bawaan dan grounding, menjalankan panggilan fungsi, serta mengorkestrasi tugas latar belakang yang berjalan lama.
Panduan ini menunjukkan cara menginstal Google Gen AI SDK, mengautentikasi klien, dan menerapkan alur kerja interaksi umum. Untuk mengetahui detail konseptual tentang siklus proses interaksi, lihat Ringkasan Interactions API.
Sebelum memulai
Sebelum mengirim permintaan ke Interactions API, siapkan project dan lingkungan pengembangan Google CloudAnda:
-
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.
-
Konsep utama
Tinjau konsep berikut untuk memahami cara Interactions API mengelola status dan respons:
Interaction: Interactions API berpusat pada resource inti:Interaction.Interactionmewakili giliran lengkap dalam percakapan atau tugas, yang melacak kronologi pemikiran model, panggilan alat, dan output akhir. API ini menyediakan envelope terpadu untuk interaksi perintah-respons dan alur kerja agen multilangkah yang kompleks.Retensi stateful: Interaksi disimpan di sisi server secara default (
store=Truedi Python ataustore: truedi TypeScript/JavaScript). Interaksi yang disimpan akan bertahan selama 7 hari dan otomatis dihapus setelah waktu tersebut. Menyetelstore=Falseakan mengaktifkan mode stateless, yang menonaktifkan retensi sisi server dan mematuhi Zero Data Retention (ZDR). Mode stateless juga menonaktifkan pengaitanprevious_interaction_iddan eksekusi asinkron (background=True).Helper respons: Google Gen AI SDK versi
2.3.0dan yang lebih baru menyediakan properti praktis pada respons interaksi, termasukinteraction.output_text,interaction.output_image, daninteraction.output_audio. Gunakaninteraction.output_textuntuk membaca respons teks, bukan mengindeks secara manual ke dalam array langkah (sepertiinteraction.steps[-1].content[0].text).
Persyaratan
Pastikan lingkungan dan permintaan Anda memenuhi persyaratan berikut sebelum melakukan integrasi dengan Interactions API:
Dukungan versi SDK: Gunakan salah satu Library Google Gen AI SDK yang didukung.
Model yang didukung: Gunakan model Gemini 3 yang didukung atau yang lebih baru. Kelompok model sebelumnya tidak mendukung API ini. Untuk mengetahui daftar lengkap model yang didukung, lihat Model yang didukung dan Melakukan migrasi ke versi model terbaru.
Parameter cakupan giliran: Parameter konfigurasi seperti
tools,system_instruction, dangeneration_confighanya berlaku untuk giliran saat ini. Teruskan parameter ini pada setiap giliran interaksi berikutnya jika alur kerja Anda memerlukannya di seluruh percakapan multi-turn.Dekode panjang di Gemini 4 Argon: Untuk menghasilkan output single-turn yang melebihi 65.536 token (hingga 1.048.576 token dikurangi token input) di
gemini-4-argonataugemini-4-argon-cyber-permissive, gunakan kelanjutan Google Gen AI SDK otomatis (google-genai >= 2.34.0untuk Python,@google/genai >= 2.32.0untuk TypeScript/JavaScript, Go>= 1.77.0, Java>= 1.80.0),background=True, ataucontinuation_tokendi endpointv1beta1. Untuk contoh kode dan aturan kelanjutan, lihat Dekode panjang dalam panduan developer untuk Gemini 4 Argon.
Menginstal Google Gen AI SDK
Instal atau upgrade Google Gen AI SDK untuk bahasa pilihan Anda:
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>
Mengautentikasi klien Anda
Anda dapat terhubung ke Interactions API di Agent Platform menggunakan salah satu metode autentikasi berikut:
Terhubung menggunakan project Google Cloud dengan Kredensial Default Aplikasi (ADC)
Gunakan metode autentikasi ini untuk workload perusahaan dan deployment produksi di Google Cloud. Untuk melakukan autentikasi dengan Kredensial Default Aplikasi (ADC), lakukan inisialisasi klien dengan properti berikut:
enterprise=Trueproject="PROJECT_ID"location="global"
Jika Anda belum mengonfigurasi kredensial lokal, jalankan
gcloud auth application-default login.
Dalam contoh kode berikut, ganti PROJECT_ID dengan project IDGoogle Cloud Anda.
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."
}]
}]
}'
Menghubungkan menggunakan mode ekspres (kunci API)
Gunakan metode autentikasi ini untuk pembuatan prototipe cepat, skrip ringan, atau
lingkungan yang melakukan autentikasi dengan kunci API. Teruskan kunci API Anda saat
melakukan inisialisasi klien atau di header HTTP x-goog-api-key.
Dalam contoh kode berikut, ganti API_KEY dengan kunci API Anda dan PROJECT_ID dengan project ID Google Cloud Anda.
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."
}]
}]
}'
Alur kerja interaksi umum
Setelah mengonfigurasi klien, Anda dapat menggunakan metode interactions.create untuk
mengelola penyimpanan sesi dan percakapan multi-turn, men-streaming token output secara
real time, membuat JSON yang divalidasi skema, memanggil alat bawaan dan grounding,
memanggil fungsi eksternal, dan menjalankan agen otonom.
Mengelola penyimpanan sesi dan status percakapan
Interactions API mendukung penyimpanan stateful sisi server
(store=True, default) dan eksekusi stateless yang dikelola klien (store=False).
Tabel berikut membandingkan mode interaksi stateful dan stateless:
| Fitur | Mode stateful (store=true, default) |
Mode stateless (store=false) |
|---|---|---|
| Persistensi sisi server | Menyimpan input, langkah-langkah perantara, dan output di server selama 7 hari. | Menonaktifkan penyimpanan interaksi sisi server untuk mendukung alur kerja Zero Retensi Data (ZDR). |
| Konteks multi-turn |
Merangkai giliran dengan meneruskan interaksi sebelumnya id di
previous_interaction_id.
|
Memerlukan penerusan array lengkap percakapan sebelumnya steps
di input pada setiap giliran. Meneruskan
previous_interaction_id akan menampilkan error 400 Bad
Request.
|
Eksekusi latar belakang (background=true)
|
Didukung untuk interaksi model dan agen yang berjalan lama. | Tidak didukung. Eksekusi latar belakang asinkron memerlukan persistensi status sisi server. |
| Metode siklus proses sesi |
Mendukung interaksi pengambilan (get), listingan (list), pembatalan (cancel), dan penghapusan (delete).
|
Tidak dapat diambil setelah respons sinkron atau streaming selesai. |
| Enkripsi dalam penyimpanan |
Dienkripsi secara default dengan Google-owned and Google-managed encryption key, atau dengan kunci enkripsi yang dikelola pelanggan (CMEK) di multi-region us dan eu.
|
Tidak ada status interaksi yang disimpan saat tidak aktif. |
Menjalankan percakapan multi-turn stateful
Secara default, Interactions API menyimpan status percakapan di server
(store=True di Python atau store: true di TypeScript/JavaScript). Untuk melanjutkan
percakapan yang ada, teruskan id interaksi sebelumnya ke
parameter previous_interaction_id. Agent Platform mengambil konteks percakapan yang disimpan, menambahkan giliran baru, dan menggunakan kembali token awalan yang di-cache.
Saat merangkai interaksi di seluruh endpoint, perhatikan aturan lokasi berikut:
Lokasi yang sama: Anda dapat merangkai interaksi dalam lokasi yang sama (seperti
globalkeglobal,uskeus, ataueukeeu).Di berbagai lokasi: Perantaian di berbagai lokasi endpoint (antara
globaldanusataueu, atau antarausdaneu) tidak didukung. Setiap endpoint menyimpan status interaksi dalam penyimpanan terisolasi, sehingga mereferensikan ID interaksi yang dibuat di lokasi lain akan menampilkan error404 Not Found.
Dalam contoh berikut, ganti PROJECT_ID dengan project ID Google Cloud Anda:
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?"
}'
Menjalankan percakapan multi-turn stateless
Jika workload Anda memerlukan Zero Data Retention (ZDR), tetapkan store=False (store: false di TypeScript/JavaScript atau "store": false di REST) secara eksplisit pada setiap permintaan.
Dalam mode stateless, Anda mengelola histori percakapan di klien dengan mempertahankan
daftar objek Step
(user_input, thought, function_call, function_result, dan
model_output) dan mengirimkan array steps yang terakumulasi di input pada setiap
giliran:
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?"}]
}
]
}'
Retensi dan siklus proses sesi
Interaksi yang disimpan (store=True) mengikuti aturan retensi dan percabangan berikut:
Time-to-live (TTL) 7 hari: Setiap interaksi yang disimpan akan bertahan selama 7 hari dari stempel waktu
createddan otomatis dihapus saat TTL 7 hari berakhir.Penyimpanan induk dan turunan independen: Saat Anda merantai giliran baru menggunakan
previous_interaction_id, Agent Platform akan menyalin histori percakapan ancestor ke dalam data interaksi baru. Karena setiap giliran menyimpan salinan histori percakapannya sendiri, masa berlaku atau penghapusan giliran sebelumnya akan memiliki efek berikut:Melanjutkan dari giliran berikutnya akan berhasil: Jika Giliran 1 (
interaction_1) berakhir atau dihapus setelah Giliran 2 (interaction_2) telah dibuat, Anda masih dapat membuat Giliran 3 menggunakanprevious_interaction_id=interaction_2.idhinggainteraction_2itu sendiri berakhir atau dihapus.Percabangan dari giliran yang sudah tidak berlaku atau dihapus akan gagal: Mencoba membuat interaksi baru yang langsung merujuk ke ID interaksi yang sudah tidak berlaku atau dihapus di
previous_interaction_idakan menampilkan error400 Bad Request(Previous Interaction ID not found).
Mengambil, mencantumkan, membatalkan, dan menghapus interaksi yang disimpan
Anda dapat memeriksa dan mengelola interaksi yang disimpan selama siklus prosesnya menggunakan metode berikut:
Mengambil interaksi (
interactions.get): Mengambil resourceInteractionlengkap berdasarkanid, termasuk langkah-langkahuser_input, langkah-langkahthoughtdan alat perantara, serta langkah-langkahmodel_output. Tetapkanstream=True(danlast_event_idopsional) untuk melakukan streaming atau melanjutkan interaksi yang sedang berlangsung.Mencantumkan interaksi (
interactions.list): Membuat kueri ID interaksi yang disimpan dalam project Anda melalui REST menggunakanpage_size(default10, maksimum500) danpage_token. Menampilkan daftar resourceInteractionMetadata.Membatalkan interaksi yang sedang berlangsung (
interactions.cancel): Menghentikan interaksi latar belakang asinkron (background=True) yang berada dalam statusin_progressataurequires_actiondan mentransisikan statusnya kecancelled. Anda akan ditagih untuk token yang dibuat sebelum pembatalan.Menghapus interaksi tersimpan (
interactions.delete): Menghapus interaksi tersimpan secara permanen sebelum TTL 7 harinya berakhir. Hanya interaksi dalam status terminal (completed,failed, ataucancelled) yang dapat dihapus; jika interaksi masih berjalan di latar belakang, batalkan sebelum menghapusnya.
Dalam contoh berikut, ganti PROJECT_ID dengan project ID Google Cloud Anda dan INTERACTION_ID dengan ID interaksi target:
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)"
Kuota dan batas penyimpanan stateful
Selain batas token model dan rasio permintaan, interaksi stateful
(store=True) tunduk pada batas penyimpanan dan konkurensi
level project berikut:
| Kuota atau batas sistem | Batas default (per project) | Deskripsi |
|---|---|---|
| Throughput pembuatan interaksi stateful per hari | 240 GiB per hari |
Volume total maksimum data interaksi yang ditulis ke penyimpanan sisi server per hari di seluruh permintaan interactions.create dengan store=true. |
| Throughput pengambilan interaksi stateful per hari | 480 GiB per hari |
Volume total maksimum data interaksi tersimpan yang dibaca per hari di seluruh permintaan interactions.get dan permintaan multi-giliran yang memuat giliran sebelumnya menggunakan previous_interaction_id. |
| Interaksi stateful serentak | 500 interaksi serentak |
Jumlah maksimum interaksi stateful aktif yang dijalankan secara serentak dalam sebuah project. |
Untuk mengetahui informasi selengkapnya tentang cara melihat dan mengelola kuota di Agent Platform, lihat Kuota dan batas sistem.
Men-streaming respons secara real time
Untuk mengurangi latensi yang dirasakan untuk aplikasi interaktif, Anda dapat melakukan streaming respons model saat respons tersebut dibuat. Tetapkan stream=True (stream: true di TypeScript/JavaScript) saat memanggil interactions.create untuk menerima aliran peristiwa yang dikirim server yang dapat diiterasi. Filter peristiwa step.delta untuk merender
potongan teks inkremental saat tiba:
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();
Membuat output terstruktur
Jika aplikasi Anda memerlukan respons dalam format yang dapat diprediksi dan dapat dibaca mesin,
Anda dapat membatasi output model agar sesuai dengan skema JSON tertentu. Teruskan
skema target Anda—seperti skema JSON model Pydantic di Python atau objek skema
Type di TypeScript/JavaScript—langsung ke parameter
response_format polimorfik:
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);
Menggunakan panggilan fungsi (penggunaan alat)
Pemanggilan fungsi memungkinkan model meminta eksekusi fungsi kustom atau API eksternal untuk mengumpulkan informasi sebelum merumuskan respons akhir. Dalam alur kerja interaksi stateful, pemanggilan fungsi mengikuti pola dua giliran:
Mendeklarasikan dan meneruskan alat: Berikan deklarasi fungsi Anda dalam parameter
toolspada permintaan awal.Menjalankan dan menampilkan hasil: Periksa langkah-langkah respons (
interaction.steps) untuk langkah-langkahfunction_call, jalankan fungsi lokal Anda menggunakanargumentsyang disediakan model, dan kirim interaksi lanjutan yang berisi itemfunction_resultyang ditautkan olehcall_iddanprevious_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);
}
}
Menggunakan alat bawaan
Selain pemanggilan fungsi sisi klien, Interactions API mendukung alat sisi server bawaan untuk model Gemini 3. Saat Anda mengaktifkan alat bawaan dalam parameter tools, Agent Platform akan menjalankan alat tersebut di server selama satu panggilan interactions.create dan mencatat langkah-langkah pemanggilan alat (*_call) dan output (*_result) di interaction.steps.
Interactions API mendukung alat bawaan berikut:
Eksekusi kode (
{"type": "code_execution"}): Membuat dan mengeksekusi kode Python di lingkungan sandbox untuk melakukan penghitungan, analisis data, dan penalaran berbasis kode. Untuk mengetahui library, penagihan, dan batasan yang didukung, lihat Eksekusi kode.Konteks URL (
{"type": "url_context"}): Mengambil dan menganalisis konten dari URL web publik yang disertakan dalam perintah Anda. Untuk mengetahui detail tentang caching indeks, pengambilan langsung, dan penggabungan konteks URL dengan penelusuran, lihat Konteks URL.Grounding dengan Google Penelusuran (
{"type": "google_search"}): Melakukan grounding respons model dalam informasi web real-time dan menampilkan kutipan inline. Lihat Melakukan grounding pada respons dengan Google Penelusuran.Penggunaan komputer (
{"type": "computer_use"}): Mengaktifkan alur kerja otomatisasi browser dan antarmuka pengguna. Untuk kontrol konfigurasi dan keamanan, lihat Penggunaan komputer.
Mengeksekusi kode Python
Untuk mengaktifkan eksekusi kode, sertakan {"type": "code_execution"} dalam daftar tools. Array interaction.steps yang ditampilkan berisi langkah-langkah code_execution_call (dengan arguments.code dan arguments.language), langkah-langkah code_execution_result (dengan result dan is_error), dan langkah model_output terakhir.
Dalam contoh berikut, ganti PROJECT_ID dengan project ID Google Cloud Anda:
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"}]
}'
Mengambil konten halaman web dengan konteks URL
Agar model dapat mengambil dan menganalisis halaman web yang dirujuk dalam perintah Anda,
sertakan {"type": "url_context"} dalam daftar tools. API mencatat URL yang diambil dalam langkah url_context_call dan url_context_result, serta melampirkan anotasi url_citation ke teks yang dihasilkan di model_output.
Dalam contoh berikut, ganti PROJECT_ID dengan project ID Google Cloud Anda, serta YOUR_URL_1 dan YOUR_URL_2 dengan URL publik yang akan dibandingkan:
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"}]
}'
Melakukan grounding respons dengan Google Penelusuran
Grounding menghubungkan model Gemini ke sumber eksternal yang dapat diverifikasi untuk mengurangi halusinasi dan memberikan jawaban terbaru dengan kutipan. Untuk mengetahui ringkasan opsi grounding di Agent Platform, lihat Ringkasan grounding, Grounding dengan Google Penelusuran, dan Grounding Web untuk Enterprise.
Saat Anda mengaktifkan Grounding dengan Google Penelusuran dengan meneruskan
{"type": "google_search"} dalam daftar tools, Interactions API akan menampilkan
data penelusuran dan atribusi langsung di linimasa interaction.steps:
google_search_call: Berisi kueri penelusuran yang dikeluarkan oleh model (step.arguments.queries).google_search_result: Berisi saran penelusuran (result[].search_suggestions), cuplikan HTML/CSS yang digunakan untuk merender saran penelusuran di antarmuka pengguna. Referensi web dengan URL dan judul sumber disediakan sebagai anotasiurl_citationinline pada blok teksmodel_output.Anotasi
url_citationinline: Setiap blok kontentext(TextContent) di dalam langkahmodel_outputdapat menyertakan arrayannotations. Setiap anotasiurl_citationmengidentifikasi rentang karakter atau byte (start_indexdanend_index) dalam teks respons beserta sumbertitledanurl.
Dalam contoh berikut, ganti PROJECT_ID dengan project ID Google Cloud Anda:
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"}]
}'
Responsnya mencakup langkah-langkah google_search_call, google_search_result, dan
model_output dengan anotasi url_citation inline:
{
"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"
}
]
}
]
}
]
}
Menjalankan agen dan tugas latar belakang yang berjalan lama
Selain model dasar, Interactions API memungkinkan Anda memanggil
agen otonom khusus menggunakan parameter agent:
antigravity-preview-05-2026: Agen terkelola untuk tujuan umum dengan eksekusi kode, pengelolaan file, dan browser web di lingkungan Linux dengan sandbox yang aman. Untuk mengetahui informasi selengkapnya, lihat Berinteraksi dengan agen.deep-research-preview-04-2026: Agen Deep Research Gemini, yang merencanakan dan menjalankan tugas riset web multi-langkah serta menyintesis temuan dari berbagai sumber menjadi laporan yang komprehensif. Untuk mengetahui informasi selengkapnya, lihat Menggunakan Agen Deep Research Gemini.- Agen kustom: Resource agen kustom yang dikonfigurasi dan disediakan dengan
client.agents.create().
Karena alur kerja agen sering kali memerlukan waktu beberapa menit untuk diselesaikan, jalankan alur kerja tersebut secara asinkron di latar belakang dengan menetapkan background=True. API akan segera menampilkan objek Interaction dengan id yang dapat Anda polling menggunakan client.interactions.get() hingga interaction.status bertransisi ke completed:
Sebelum mencoba contoh ini, ganti PROJECT_ID dengan project IDGoogle Cloud Anda.
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)
Mengakses file Cloud Storage yang diupload
Anda dapat menggunakan Interactions API untuk mengakses file Cloud Storage yang diupload. Dalam contoh berikut, ganti PROJECT_ID dengan project IDGoogle Cloud Anda:
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)
Saat meneruskan URI Cloud Storage (misalnya,
gs://bucket-name/path/to/file) ke Interactions API, permintaan
akan memverifikasi akses baca menggunakan kredensial pemanggil sebelum Agen Layanan Platform Agen
(service-PROJECT_NUMBER@gcp-sa-aiplatform.)
project pemanggil mengambil objek dari Cloud Storage.
Untuk meneruskan file Cloud Storage dalam permintaan interaksi, akun utama yang memanggil (akun pengguna, akun layanan, atau identitas gabungan) harus memiliki izin storage.objects.get untuk semua objek yang direferensikan. Untuk bucket Cloud Storage lintas project atau bucket Cloud Storage dengan kebijakan IAM kustom, berikan akses baca ke akun utama yang memanggil dan agen layanan project yang memanggil.
Setiap permintaan interaksi model Gemini standar mendukung hingga
100 URI Cloud Storage (gs://) yang berbeda (hingga 2 GiB dikurangi 500 KiB
per file). Saat Anda merangkai giliran stateful menggunakan previous_interaction_id,
Agent Platform menghitung URI gs:// yang berbeda secara kumulatif di seluruh
histori percakapan dan giliran saat ini. Interaksi agen terkelola (permintaan
yang menetapkan agent, bukan model), model Gemini Omni, dan
model Lyria 3 tidak termasuk dalam batas 100 URI ini.
Mengonfigurasi peran IAM untuk mengakses file Cloud Storage
Berikan salah satu peran standar yang telah ditetapkan yang mencakup
izin storage.objects.get:
Storage Object Viewer (
roles/storage.objectViewer): Akses baca ke objek (direkomendasikan).Storage Object User (
roles/storage.objectUser): Akses baca dan tulis ke objek.
Untuk memberikan akses ke akun pengguna menggunakan Google Cloud CLI, gunakan perintah berikut:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="user:user-email@example.com" \
--role="roles/storage.objectViewer"
Untuk memberikan akses ke akun layanan panggilan tertentu, gunakan perintah berikut:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="serviceAccount:sa-name@PROJECT_ID." \
--role="roles/storage.objectViewer"
Memecahkan masalah akses file Cloud Storage
Jika akun utama yang memanggil tidak memiliki izin yang memadai, Interactions API
akan menampilkan error 403 Forbidden yang mirip dengan berikut ini:
Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more Cloud Storage URIs.
Untuk mengatasi masalah ini, berikan peran Storage Object Viewer
(roles/storage.objectViewer) di bucket atau objek Cloud Storage kepada
pemanggil yang diautentikasi (dan ke Agen Layanan Agent Platform project panggilan untuk bucket Cloud Storage
lintas project atau IAM kustom).
Jika objek yang ditentukan tidak ada, atau jika izin bucket mencegah pemanggil melihat apakah objek tersebut ada, Interactions API akan menampilkan error 404 Not Found yang mirip dengan berikut ini:
Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.
Untuk mengatasi masalah ini, pastikan Cloud Storage URI sudah benar dan pastikan pemanggil yang diautentikasi memiliki akses baca ke bucket.
Jika permintaan interaksi model mereferensikan lebih dari 100 Cloud Storage URI yang berbeda di seluruh giliran saat ini dan histori previous_interaction_id yang ditautkan, Interactions API akan menampilkan error 400 Bad Request yang mirip dengan berikut ini:
INVALID_ARGUMENT - 400 Bad Request: Request references 101 distinct gs:// URIs, which exceeds the maximum of 100.
Untuk menyelesaikan masalah ini, lakukan salah satu tindakan berikut:
- Mulai interaksi baru tanpa
previous_interaction_idjika file dari giliran sebelumnya tidak lagi diperlukan. - Gabungkan dokumen yang lebih kecil atau teruskan file tambahan secara inline dalam
batas payload permintaan (256 MiB yang dikompresi untuk permintaan sinkron atau streaming,
atau 9,75 MiB yang tidak dikompresi jika
service_tierditetapkan kedeferreddenganbackgrounddanstoreditetapkan ketrue). - Gunakan
generateContentuntuk permintaan yang merujuk ke URIgs://hingga batas item model per modalitas (gabungan 3.000 gambar dan PDF, 1.000 file audio, dan 10 video, atau hingga 6.500 file jika menyertakan file teks biasa).
Mengenkripsi data interaksi dengan CMEK
Interaksi stateful (store=True di Python atau store: true di
TypeScript/JavaScript) menyimpan data interaksi dalam penyimpanan hingga 7 hari. Untuk melindungi data tersebut dengan kunci enkripsi Anda sendiri, bukanGoogle-owned and Google-managed encryption key, gunakan profil penyajian. Profil inferensi
menautkan kunci Cloud Key Management Service ke project, lokasi, dan cakupan API. Selama
profil penayangan ada, Agent Platform akan otomatis mengenkripsi data interaksi yang disimpan—format permintaan interaksi Anda tidak berubah.
CMEK profil inferensi untuk Interactions API didukung di multi-region us dan eu. Region global tidak didukung.
Untuk menyiapkan CMEK untuk Interactions API, lakukan hal berikut:
- Aktifkan Cloud KMS API dan Agent Platform API di project Anda. Lihat Sebelum memulai.
- Buat kunci Cloud KMS di multi-region
usataueu. Lihat Membuat key ring dan kunci. - Berikan peran
roles/cloudkms.cryptoKeyEncrypterDecrypterkepada agen layanan Gemini Enterprise Agent Platform pada kunci. Lihat Memberikan izin Agent Platform. Buat profil penayangan di multi-region yang sama (
usataueu) yang menetapkanscopekeINTERACTIONS_APIdancmekConfig.encryptionSpec.kmsKeyNameke kunci Anda: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" } } }'Tunggu hingga operasi pembuatan yang berjalan lama selesai (
"done": true). Untuk mengetahui detail selengkapnya tentang cara mengelola, memperbarui, atau menghapus profil penayangan, lihat Membuat profil penayangan.Kirim permintaan interaksi Anda ke multi-region
usataueuyang sama dengan profil penayangan Anda. CMEK profil penayangan tidak tersedia di endpointglobal.- Google Gen AI SDK: Lakukan inisialisasi klien dengan
location="us"ataulocation="eu"(location: "us"ataulocation: "eu"di TypeScript/JavaScript). - REST: Kirim permintaan ke endpoint multi-region
https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions, dengan LOCATION adalahusataueu.
Jika Anda menonaktifkan kunci atau mencabut akses agen layanan, permintaan yang membuat atau membaca interaksi yang disimpan akan gagal dengan error
FAILED_PRECONDITION.- Google Gen AI SDK: Lakukan inisialisasi klien dengan
Alur kerja REST lanjutan
Untuk otomatisasi berbasis shell, pipeline CI/CD, atau lingkungan tanpa runtime Python atau TypeScript/JavaScript, Anda dapat memanggil Interactions API secara langsung melalui HTTP menggunakan curl.
Endpoint REST
Kirim permintaan POST ke endpoint Interactions API berikut:
POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions
Ganti variabel berikut dalam permintaan Anda:
- PROJECT_ID: Project ID Google Cloud Anda.
- LOCATION: Tetapkan ke
global(atauusataueudengan host multi-regionhttps://aiplatform.LOCATION.rep.googleapis.comuntuk residensi data atau CMEK).
Menetapkan variabel lingkungan dan autentikasi
Sebelum menjalankan contoh curl di bagian berikut, ekspor project ID, model target, atau ID agen, dan token akses OAuth 2.0 yang dihasilkan dari Kredensial Default Aplikasi:
PROJECT_ID="PROJECT_ID"
MODEL_ID="gemini-3.8-flash"
AGENT_ID="deep-research-preview-04-2026"
ACCESS_TOKEN=$(gcloud auth print-access-token)
Format respons sinkron
Permintaan POST sinkron menampilkan objek interaction JSON yang menyertakan
metadata interaksi unik id, eksekusi status, percakapan steps, dan
token 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"
}
Melanjutkan interaksi stateful multi-turn
Untuk melanjutkan percakapan yang disimpan melalui REST, teruskan id dari respons sebelumnya di kolom previous_interaction_id pada isi permintaan JSON.
Sebelum mencoba contoh ini, ganti PREVIOUS_INTERACTION_ID dengan
id yang ditampilkan oleh interaksi sebelumnya.
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?"
}]
}]
}'
Men-streaming output dengan peristiwa yang dikirim server
Untuk melakukan streaming update inkremental melalui REST, sertakan "stream": true dalam isi permintaan JSON:
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"stream": true,
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Write a long story about space travel."
}]
}]
}'
Jika "stream": true ditetapkan, server akan merespons dengan
Transfer-Encoding: chunked dan Content-Type: text/event-stream (Server-Sent
Events). Setiap peristiwa dalam streaming menyertakan awalan data: yang berisi payload JSON dengan konten event_type dan delta langkah. curl secara otomatis
membuat koneksi HTTP tetap terbuka dan menulis potongan yang masuk ke stdout secara real
time hingga interaksi selesai.
Menjalankan agen terkelola di latar belakang
Untuk memulai tugas agen terkelola yang berjalan lama secara asinkron melalui REST, tentukan
agent target, tetapkan "background": true, dan konfigurasikan
"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."
}]
}]
}'
Langkah berikutnya
Pelajari referensi berikut untuk mempelajari lebih lanjut Interactions API, alat bawaan, dan grounding:
Pelajari lebih lanjut konsep utama dalam ringkasan Interactions API.
Pelajari skema permintaan dan respons di referensi Interactions API.
Pelajari lebih lanjut Eksekusi kode, Konteks URL, dan Grounding dengan Google Search.
Pelajari cara berinteraksi dengan agen terkelola dan menggunakan Agen Deep Research Gemini.