1
---
2
name: gemini-interactions-api
3
metadata:
4
version: "2.0.2"
5
category: AiAndMachineLearning
6
description: Guides the usage of Gemini Interactions API on Gemini Enterprise Agent Platform. Use when the user wants to use the stateful, server-managed Interactions API for multi-turn conversations, background execution, streaming, structured output, and function calling on the Agent Platform.
7
---
8
9
# Gemini Interactions API Skill
10
11
This skill provides instructions for authenticating, connecting to, and utilizing the stateful, server-managed **Gemini Interactions API** on Gemini Enterprise Agent Platform.
12
13
14
The Interactions API is the modern, recommended way to execute Generative AI agent conversations, background research tasks, multi-turn chats, and structured, multi-step workflows.
15
16
> [!IMPORTANT] **CRITICAL: Unified SDK, Latest Models & Model/Agent Targeting** *
17
> **Unified SDK**: Use the Google Gen AI SDK (**`google-genai >= 2.3.0`** for
18
> Python, **`@google/genai >= 2.3.0`** for JS/TS). SDK versions `>= 2.0.0` are
19
> the minimum floor at which the steps schema activates, but `>= 2.3.0` is the
20
> supported/recommended floor. Legacy SDKs like `google-cloud-aiplatform`,
21
> `@google-cloud/vertexai`, `google-generativeai`, and `@google/generative-ai`
22
> are strictly unsupported for Interactions. * *Mandatory Instruction*: When
23
> explaining client initialization or writing import code, you **must**
24
> explicitly state/warn the user that legacy packages like
25
> `google-cloud-aiplatform` or `google-generativeai` are strictly unsupported
26
> for interactions. * **Latest Models Only**: Use `gemini-3.8-flash` (fast,
27
> balanced, multimodal — the recommended default), `gemini-3.1-pro-preview`
28
> (complex reasoning, coding, research), or `gemini-3.5-flash-lite`
29
> (cost-efficient, high-frequency lightweight tasks). Refer to the
30
> [latest model versions](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/migrate)
31
> to check for new updates. Legacy models (`gemini-3-flash-preview`,
32
> `gemini-2.5-*`, `gemini-2.0-*`, `gemini-1.5-*`) are deprecated and do not
33
> support interactions. * *Mandatory Instruction*: In any interaction response,
34
> you **must** warn the user that legacy models like `gemini-2.5-*`,
35
> `gemini-2.0-*`, or `gemini-1.5-*` are deprecated and unsupported for the
36
> Interactions API. If a user asks for a deprecated model, use
37
> `gemini-3.8-flash` instead and note the substitution. * **Model & Agent
38
> Targeting**: Target foundation models directly using
39
> `model="gemini-3.8-flash"`, or target autonomous managed/custom agents
40
> (`antigravity-preview-09-2026`, `deep-research-preview-04-2026`, or custom
41
> agents provisioned via `client.agents.create()`) using `agent="<AGENT_ID>"`.
42
> Managed agents (`antigravity-preview-09-2026` and custom agents) require
43
> `environment="remote"` to provision a sandbox. * **Turn-Scoped Parameters**:
44
> Parameters like `tools`, `system_instruction`, and `generation_config` are
45
> turn-scoped. They **MUST** be passed with each interaction request.
46
47
## Attribution
48
49
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
50
MUST read [Usage Attribution](references/attribution.md). For commands executed
51
directly in the terminal (never in generated scripts, Terraform, or user code),
52
prefix `gcloud` with
53
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gemini-interactions-api)"`
54
and append
55
`agent-skills/1.0 (skill:gemini-interactions-api)`
56
to `User-Agent` headers.
57
58
## 1. Authentication
59
60
Before running any code, ensure you are authenticated with Application Default Credentials (ADC) and have the necessary API enabled.
61
62
1. **Login**:
63
64
```bash
65
gcloud auth application-default login
66
```
67
2. **Enable API** (if not already enabled):
68
69
```bash
70
gcloud services enable aiplatform.googleapis.com
71
```
72
73
---
74
75
## 2. Client Initialization
76
77
You can initialize the client using environment variables (recommended) or by passing explicit configuration parameters.
78
79
### Option A: Environment Variables (Recommended)
80
81
Configure environment variables to let the SDK automatically resolve settings:
82
83
```bash
84
export GOOGLE_GENAI_USE_ENTERPRISE=true
85
export GOOGLE_CLOUD_PROJECT="your-project-id"
86
export GOOGLE_CLOUD_LOCATION="global"
87
```
88
89
#### Python
90
91
```python
92
from google import genai
93
94
# The SDK automatically picks up the environment variables
95
client = genai.Client()
96
```
97
98
#### TypeScript/JavaScript
99
100
```typescript
101
import { GoogleGenAI } from "@google/genai";
102
103
// The SDK automatically picks up the environment variables
104
const ai = new GoogleGenAI();
105
```
106
107
### Option B: Explicit Inline Parameters
108
109
Alternatively, pass configuration values directly inside your code:
110
111
#### Python
112
113
```python
114
from google import genai
115
import google.auth
116
117
_, project_id = google.auth.default()
118
client = genai.Client(enterprise=True, project=project_id, location="global")
119
```
120
121
#### TypeScript/JavaScript
122
123
```typescript
124
import { GoogleGenAI } from "@google/genai";
125
126
const ai = new GoogleGenAI({
127
enterprise: true,
128
project: "your-project-id",
129
location: "global"
130
});
131
```
132
133
### Option C: Express Mode (API Key)
134
135
Recommended for lightweight scripts or environments using an API key:
136
137
#### Python
138
139
```python
140
from google import genai
141
142
client = genai.Client(enterprise=True, api_key="YOUR_API_KEY")
143
```
144
145
#### TypeScript/JavaScript
146
147
```typescript
148
import { GoogleGenAI } from "@google/genai";
149
150
const ai = new GoogleGenAI({
151
enterprise: true,
152
apiKey: "YOUR_API_KEY"
153
});
154
```
155
156
---
157
158
## 3. Core Interactions API Usage
159
160
### Quick Start (Single-Turn)
161
162
Submit a single prompt and read the final text response. Under the modern schema, output content is retrieved from the `steps` list.
163
164
#### Python
165
166
```python
167
interaction = client.interactions.create(
168
model="gemini-3.8-flash",
169
input="Explain serverless computing in one sentence."
170
)
171
# Use the output_text convenience accessor (combined text from the trailing model_output steps)
172
print(interaction.output_text)
173
```
174
175
#### TypeScript/JavaScript
176
177
```typescript
178
const interaction = await ai.interactions.create({
179
model: "gemini-3.8-flash",
180
input: "Explain serverless computing in one sentence."
181
});
182
console.log(interaction.output_text);
183
```
184
185
---
186
187
### Stateful Conversation (Multi-Turn)
188
189
Interactions are stateful by default. Store the conversation state in the cloud and reference it in the subsequent turn using `previous_interaction_id`.
190
191
#### Python
192
193
```python
194
# Turn 1: Introduce ourselves
195
# Interactions are stored by default (store=True, retained for 7 days); pass store=False to disable
196
# server-side retention (which also disables previous_interaction_id and background).
197
turn1 = client.interactions.create(
198
model="gemini-3.8-flash",
199
input="Hi! My name is John. I am working on AI agents.",
200
store=True
201
)
202
print(f"Turn 1: {turn1.output_text}")
203
204
# Turn 2: Refer back to the stored turn state
205
turn2 = client.interactions.create(
206
model="gemini-3.8-flash",
207
input="What is my name?",
208
previous_interaction_id=turn1.id
209
)
210
print(f"Turn 2: {turn2.output_text}")
211
```
212
213
#### TypeScript/JavaScript
214
215
```typescript
216
// Turn 1 (interactions are stored by default; pass store: false to disable)
217
const turn1 = await ai.interactions.create({
218
model: "gemini-3.8-flash",
219
input: "Hi! My name is John. I am working on AI agents.",
220
store: true
221
});
222
223
// Turn 2
224
const turn2 = await ai.interactions.create({
225
model: "gemini-3.8-flash",
226
input: "What is my name?",
227
previous_interaction_id: turn1.id
228
});
229
console.log(turn2.output_text);
230
```
231
232
---
233
234
### Real-Time Streaming
235
236
Stream responses in real-time. Passing `stream=True` returns an iterable chunk generator.
237
238
#### Python
239
240
```python
241
# The stream yields typed events, not full interaction snapshots. The sequence is:
242
# interaction.created -> (step.start -> step.delta(s) -> step.stop)+ -> interaction.completed
243
for event in client.interactions.create(
244
model="gemini-3.8-flash",
245
input="Write a short poem about debugging.",
246
stream=True
247
):
248
if event.event_type == "step.delta":
249
if event.delta.type == "text":
250
print(event.delta.text, end="", flush=True)
251
elif event.event_type == "interaction.completed":
252
print()
253
```
254
255
#### TypeScript/JavaScript
256
257
```typescript
258
// The stream yields typed events, not full interaction snapshots. The sequence is:
259
// interaction.created -> (step.start -> step.delta(s) -> step.stop)+ -> interaction.completed
260
const responseStream = await ai.interactions.create({
261
model: "gemini-3.8-flash",
262
input: "Write a short poem about debugging.",
263
stream: true
264
});
265
266
for await (const event of responseStream) {
267
if (event.event_type === "step.delta") {
268
if (event.delta.type === "text") {
269
process.stdout.write(event.delta.text);
270
}
271
} else if (event.event_type === "interaction.completed") {
272
console.log();
273
}
274
}
275
```
276
277
---
278
279
### Structured Output (Pydantic / Polymorphic `response_format`)
280
281
Retrieve structured, type-safe JSON matching a schema. Under the modern Interactions API, a polymorphic `response_format` argument directly takes the target schema structure.
282
283
#### Python
284
285
```python
286
from pydantic import BaseModel, Field
287
288
class Book(BaseModel):
289
title: str = Field(description="The title of the book")
290
author: str = Field(description="The book's author")
291
year_published: int
292
293
interaction = client.interactions.create(
294
model="gemini-3.8-flash",
295
input="Recommend one famous sci-fi book.",
296
response_format=Book
297
)
298
299
# The text will be a valid JSON matching the Book schema
300
print(interaction.output_text)
301
```
302
303
#### TypeScript/JavaScript
304
305
```typescript
306
import { Type } from "@google/genai";
307
308
const BookSchema = {
309
type: Type.OBJECT,
310
properties: {
311
title: { type: Type.STRING, description: "The title of the book" },
312
author: { type: Type.STRING, description: "The book's author" },
313
yearPublished: { type: Type.INTEGER }
314
},
315
required: ["title", "author", "yearPublished"]
316
};
317
318
const interaction = await ai.interactions.create({
319
model: "gemini-3.8-flash",
320
input: "Recommend one famous sci-fi book.",
321
response_format: BookSchema
322
});
323
324
console.log(interaction.output_text);
325
```
326
327
---
328
329
### Function Calling (Agent Tool Use)
330
331
Define local tools (functions) and submit execution results to the stateful interaction history.
332
333
#### Python
334
335
```python
336
import json
337
338
def get_stock_price(ticker: str) -> float:
339
"""Gets the stock price for a given ticker symbol."""
340
if ticker.upper() == "GOOG":
341
return 175.50
342
return 100.0
343
344
# Turn 1: Pass tools to the model
345
interaction = client.interactions.create(
346
model="gemini-3.8-flash",
347
input="What is the stock price of GOOG?",
348
tools=[get_stock_price]
349
)
350
351
# In the flat steps schema, a tool request is a top-level step of type
352
# "function_call" with flat `name` and `arguments` fields (no nested tool_calls).
353
for step in interaction.steps:
354
if step.type == "function_call" and step.name == "get_stock_price":
355
ticker_arg = step.arguments.get("ticker")
356
price = get_stock_price(ticker_arg)
357
358
# Turn 2: Submit the result back as a function_result step. Reference the
359
# originating call via call_id=step.id, and pass tools again (turn-scoped).
360
final_turn = client.interactions.create(
361
model="gemini-3.8-flash",
362
input=[
363
{
364
"type": "function_result",
365
"name": step.name,
366
"call_id": step.id,
367
"result": [{"type": "text", "text": json.dumps(price)}],
368
}
369
],
370
tools=[get_stock_price],
371
previous_interaction_id=interaction.id
372
)
373
print(final_turn.output_text)
374
```
375
376
#### TypeScript/JavaScript
377
378
```typescript
379
// Define local tool and flat function tool declaration
380
function getStockPrice({ ticker }: { ticker: string }): number {
381
if (ticker.toUpperCase() === "GOOG") {
382
return 175.50;
383
}
384
return 100.00;
385
}
386
387
const stockTool = {
388
type: "function",
389
name: "getStockPrice",
390
description: "Gets the stock price for a given ticker symbol.",
391
parameters: {
392
type: "object",
393
properties: {
394
ticker: { type: "string", description: "The stock ticker symbol" }
395
},
396
required: ["ticker"]
397
}
398
};
399
400
// Turn 1: Pass tools to the model
401
const interaction = await ai.interactions.create({
402
model: "gemini-3.8-flash",
403
input: "What is the stock price of GOOG?",
404
tools: [stockTool]
405
});
406
407
// In the flat steps schema, a tool request is a top-level step of type
408
// "function_call" with flat `name` and `arguments` fields (no nested toolCalls).
409
const fcStep = interaction.steps.find(s => s.type === "function_call");
410
if (fcStep && fcStep.name === "getStockPrice") {
411
const tickerArg = fcStep.arguments.ticker as string;
412
const price = getStockPrice({ ticker: tickerArg });
413
414
// Turn 2: Submit the result back as a function_result step. Reference the
415
// originating call via call_id=fcStep.id, and pass tools again (turn-scoped).
416
const finalTurn = await ai.interactions.create({
417
model: "gemini-3.8-flash",
418
input: [{
419
type: "function_result",
420
name: fcStep.name,
421
call_id: fcStep.id,
422
result: [{ type: "text", text: JSON.stringify(price) }]
423
}],
424
tools: [stockTool],
425
previous_interaction_id: interaction.id
426
});
427
console.log(finalTurn.output_text);
428
}
429
```
430
431
---
432
433
### Agents & Long-Running Tasks
434
435
Beyond foundation models, the Interactions API provides access to specialized, autonomous agents via the `agent` parameter:
436
437
* **`antigravity-preview-09-2026`**: Antigravity Agent — general-purpose
438
managed agent with code execution, file management, and web browsing in a
439
secure sandboxed Linux environment (pass `environment="remote"` to
440
provision a sandbox).
441
* **`deep-research-preview-04-2026`**: Deep Research Agent — executes multi-step web research tasks, synthesizing information from multiple sources into comprehensive reports.
442
* **Custom agents**: Configured and managed via `client.agents.create()`, `list()`, `get()`, and `delete()` (pass `environment="remote"` when invoking).
443
444
Agents typically run asynchronously in the background using `background=True`. Poll the interaction status to retrieve the completed result:
445
446
#### Python
447
448
```python
449
import time
450
451
interaction = client.interactions.create(
452
input="Analyze competitive positioning for solar energy providers.",
453
agent="deep-research-preview-04-2026",
454
background=True
455
)
456
print(f"Research started: {interaction.id}")
457
458
while True:
459
interaction = client.interactions.get(interaction.id)
460
if interaction.status == "completed":
461
print(interaction.output_text)
462
break
463
elif interaction.status in ("failed", "cancelled"):
464
print(f"Research ended with status: {interaction.status}")
465
break
466
time.sleep(10)
467
```
468
469
#### TypeScript/JavaScript
470
471
```typescript
472
const initialInteraction = await ai.interactions.create({
473
agent: "deep-research-preview-04-2026",
474
input: "Analyze competitive positioning for solar energy providers.",
475
background: true
476
});
477
478
while (true) {
479
const interaction = await ai.interactions.get(initialInteraction.id);
480
if (interaction.status === "completed") {
481
console.log(interaction.output_text);
482
break;
483
} else if (["failed", "cancelled"].includes(interaction.status)) {
484
console.log(`Research ended with status: ${interaction.status}`);
485
break;
486
}
487
await new Promise(resolve => setTimeout(resolve, 10000));
488
}
489
```
490
491
---
492
493
## 4. Accessing the Interactions API via REST
494
495
For shell-based scripts, debugging, or non-Python/JS environments, communicate with the stateful Interactions API over HTTP/REST (`curl`) at `POST https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactions` (or `POST https://aiplatform.googleapis.com/v1beta1/locations/global/interactions` with `x-goog-api-key` for Express Mode). Pass `"model"` or `"agent"`, `"input"` steps with `"type": "user_input"`, and optional `"previous_interaction_id"`, `"background": true`, or `"stream": true` (which streams Server-Sent Events via `Content-Type: text/event-stream` and `Transfer-Encoding: chunked` that `curl` prints continuously in real time).
496
497
For complete `curl` examples (single-turn, multi-turn stateful, SSE streaming, and background managed agents) and response schemas, read [references/rest_api.md](references/rest_api.md).
498
499
---
500
501
## 5. Data Model & Step Types Reference
502
503
An `Interaction` response contains a flat `steps` timeline (`user_input`, `model_output`, `thought`, `function_call`, `function_result`, and built-in tool steps) along with convenience accessors (`output_text`, `output_image`, `output_audio`) and SSE streaming events (`interaction.created`, `step.start`, `step.delta`, `step.stop`, `interaction.completed`).
504
505
For the complete step types, content types, streaming event table, and 7-day retention rules, read [references/data_model.md](references/data_model.md).
506
507