Skip to content
Back to skills

Gemini Interactions Api

ASecurity

Guides usage of the stateful, server-managed Gemini Interactions API on Gemini platform. Use for multi-turn conversations (`previous_interaction_id`), multi-model Planner + Executor orchestration, background execution, Long Decode continuation, streaming, structured output, function calling, and Managed Agents (`antigravity-preview-09-2026`, `deep-research-preview-04-2026`). Don't use for stateless `generate_content`, embeddings, Veo/Nano Banana/TTS, batch, or model tuning (gemini-api), Manag...

  • 177 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 5, 2026
ai-agentstypescriptpythongobashdebuggingapi

Works with

  • cli
  • api
  • mcp

Security analysis

A92/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro shows the line behind each finding and how to fix it

Scanned December 5, 2026

npx -y skills add aicodedecode/awesome-muse-skills --skill gemini-interactions-api --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Gemini Interactions Api?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Gemini Interactions Api
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/aicodedecode-gemini-interactions-api/badge)](https://www.skillsdirectory.com/skills/aicodedecode-gemini-interactions-api)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: gemini-interactions-api
metadata:
  version: "2.1.0"
  publisher: google
  category: AiAndMachineLearning
description: >-
  Guides usage of the stateful, server-managed Gemini Interactions API on
  Gemini platform. Use for multi-turn conversations
  (`previous_interaction_id`), multi-model Planner + Executor orchestration,
  background execution, Long Decode continuation, streaming, structured output,
  function calling, and Managed Agents (`antigravity-preview-09-2026`,
  `deep-research-preview-04-2026`). Don't use for stateless `generate_content`,
  embeddings, Veo/Nano Banana/TTS, batch, or model tuning (gemini-api), Managed
  Agent CRUD (gemini-agents-api), or raw BidiGenerateContent WebSockets
  (gemini-live-api).
compatibility: Requires active Google Cloud credentials, billing enabled, and the Gemini platform API (aiplatform.googleapis.com) enabled.
---

# Gemini Interactions API Skill

Use the stateful, server-managed **Gemini Interactions API** on Gemini platform
for multi-turn agent loops, cross-model handoffs, Long Decode continuation,
background research, streaming, structured output, and function calling.

> [!IMPORTANT]
> **CRITICAL: Unified SDK, Gemini 4 Models & Turn-Scoped Parameters**
>
> - **Unified SDK ONLY**: Use **`google-genai>=3.5.0,<4`** (`pip install
>   "google-genai>=3.5.0,<4"`; minimum `>= 2.34.0` for automatic Long Decode;
>   `>= 3.3.0` for Gemini 4 and `xhigh` types) or **`@google/genai@^3.3.0`**
>   (`>= 3.3.0, < 4`; minimum `>= 2.32.0` for automatic Long Decode; `>= 3.3.0`
>   for Gemini 4 and `xhigh` types). Legacy SDKs (`google-cloud-aiplatform`,
>   `@google-cloud/vertexai`, `google-generativeai`, `@google/generative-ai`)
>   are **strictly unsupported** for Interactions. *Mandatory Instruction*: When
>   explaining client initialization or writing import code, explicitly warn
>   that legacy packages like `google-cloud-aiplatform` and
>   `google-generativeai` are strictly unsupported for interactions.
> - **Supported Models (Gemini 4 Default)**: Default to
>   **`gemini-4-hydrogen`** (fast, balanced, `low`–`xhigh`),
>   **`gemini-4-neon`** (complex coding, reasoning, reviews, `low`–`xhigh`),
>   **`gemini-4-carbon`** (max multi-file/research depth, `low`–`high`;
>   `"xhigh"` returns `HTTP 400`), or **`gemini-3.5-flash-lite`**
>   (lightweight). Interactions relies on `previous_interaction_id` and implicit
>   prefix caching; for explicit `cached_content`, use `generate_content` with
>   `gemini-3.8-flash` (see `gemini-api`). Refer to
>   [latest model versions](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/migrate.md.txt).
>   Legacy models (`gemini-2.5-*`, `gemini-2.0-*`, `gemini-1.5-*`,
>   `gemini-3-flash-preview`) are deprecated and unsupported for Interactions.
>   *Mandatory Instruction*: In any interaction response, warn that legacy
>   models like `gemini-2.5-*`, `gemini-2.0-*`, or `gemini-1.5-*` are
>   deprecated and unsupported; substitute `gemini-4-hydrogen` if asked for a
>   deprecated model.
> - **Model & Agent Targeting**: Target foundation models via
>   `model="gemini-4-hydrogen"` (or `gemini-4-neon`/`gemini-4-carbon`), or
>   managed/custom agents (`antigravity-preview-09-2026`,
>   `deep-research-preview-04-2026`, or custom agents from
>   `client.agents.create()`) via `agent="<AGENT_ID>"`. Managed agents
>   (`antigravity-preview-09-2026` and custom agents) require
>   `environment="remote"`.
> - **Turn-Scoped Parameters & Lowercase `thinking_level`**:
>   `system_instruction`, `tools`, and `generation_config` are **strictly
>   per-request** (never inherited across `previous_interaction_id`). Pass
>   identical `system_instruction` and `tools` on every turn to preserve 95%
>   implicit caching. Pass **lowercase** `thinking_level` (`"low"`, `"medium"`,
>   `"high"`, `"xhigh"`) in `generation_config`; uppercase returns `HTTP 400`.
> - **Shared State vs. Per-Model KV Caches**: `previous_interaction_id` shares
>   conversation state across Carbon, Neon, and Hydrogen, **NOT KV caches** (KV
>   caches are strictly per-model) and **NOT hidden thought traces**. Batch
>   turns per model (or scope Executor subagents) and write key decisions into
>   visible text before switching models.

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).

## 1. Authentication & Client Initialization

Prerequisites:
[install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt),
verify an active Cloud Billing account
([Pricing](https://cloud.google.com/pricing)) and `roles/aiplatform.user`,
authenticate with `gcloud auth login` and Application Default Credentials
(ADC) (`gcloud auth application-default login`), then select your project
(`gcloud config set project {project_id}`) and enable the API
(`gcloud services enable aiplatform.googleapis.com`). Set environment variables
(recommended), using `global` (default) or multi-region `us`/`eu` for data
residency and Customer-managed encryption keys (CMEK) — see
[supported locations](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations.md.txt)
(single-region locations like `us-central1` are not supported for Interactions
and return `HTTP 400`):

```bash
export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global"  # or "us" / "eu" for data residency & CMEK
```

```python
from google import genai

# Recommended: reads GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION
client = genai.Client()

# Explicit inline ADC: genai.Client(enterprise=True, project="your-project-id", location="global")
# API Key Auth:        genai.Client(enterprise=True, api_key="YOUR_API_KEY")  # omit project/location
```

## 2. Core Python Patterns

### Single-Turn & Multi-Turn Stateful (`previous_interaction_id`)

Interactions are stored on the server by default (`store=True`, retained for 7
days) and resolved across turns via `previous_interaction_id` (pass
`store=False` for Zero Data Retention (ZDR), which disables
`previous_interaction_id` and `background`). Read responses via
`interaction.output_text`:

```python
SYS = "Be concise."

# Turn 1 (single-turn or start of stateful chain)
turn1 = client.interactions.create(
    model="gemini-4-hydrogen",
    system_instruction=SYS,
    input="Hi! My name is John. I am working on AI agents.",
    store=True,
    generation_config={"thinking_level": "high"},  # lowercase required
)
print(turn1.output_text)

# Turn 2: server resolves prior state via previous_interaction_id
turn2 = client.interactions.create(
    model="gemini-4-hydrogen",
    system_instruction=SYS,  # turn-scoped: resend identical string for 95% cache hit
    input="What is my name?",
    previous_interaction_id=turn1.id,
    generation_config={"thinking_level": "high"},
)
print(turn2.output_text)
```

### Real-Time Streaming

```python
# Event sequence: interaction.created -> (step.start -> step.delta(s) -> step.stop)+ -> interaction.completed
for event in client.interactions.create(
    model="gemini-4-hydrogen",
    input="Write a short poem about debugging.",
    stream=True,
):
    if event.event_type == "step.delta" and event.delta.type == "text":
        print(event.delta.text, end="", flush=True)
    elif event.event_type == "interaction.completed":
        print()
```

### Structured Output (`response_format`)

Pass a `TextResponseFormat` dict (`{"type": "text", "mime_type":
"application/json", "schema": Book.model_json_schema()}`) or
`TextResponseFormat(mime_type="application/json", schema=...)` from
`google.genai.interactions` to `response_format` (or pass
`response_format=Book.model_json_schema()` with
`response_mime_type="application/json"`, though top-level
`response_mime_type` is deprecated). Do **not** pass a raw Pydantic class
(`Book`) directly (`ValidationError`) or omit `mime_type="application/json"`
on a `TextResponseFormat` dict (`HTTP 400`). When answering structured-output
questions, explicitly explain that `interaction.output_text` returns valid JSON
matching the schema:

```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-4-hydrogen",
    input="Recommend one famous sci-fi book.",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Book.model_json_schema(),
    },
)
# interaction.output_text returns valid JSON matching the Book schema
print(interaction.output_text)
book = Book.model_validate_json(interaction.output_text)
```

### Function Calling (Agent Tool Use)

Declare tools as flat `{"type": "function", ...}` dicts (or
`google.genai.interactions.Function(...)`); raw Python callables are not
accepted by `interactions.create`. Tool requests appear as flat
`"function_call"` steps (`step.id`, `step.name`, `step.arguments`). Return
results as `"function_result"` steps referencing `call_id=step.id` and resend
`tools` (turn-scoped):

```python
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:
    return 175.50 if ticker.upper() == "GOOG" else 100.0

turn1 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What is the stock price of GOOG?",
    tools=[stock_tool],
)
tool_results = []
for step in turn1.steps or []:
    if step.type == "function_call" and step.name == "get_stock_price":
        price = get_stock_price(step.arguments.get("ticker"))
        tool_results.append({
            "type": "function_result",
            "name": step.name,
            "call_id": step.id,
            "result": {"price": price},
        })
if tool_results:
    final_turn = client.interactions.create(
        model="gemini-4-hydrogen",
        input=tool_results,
        tools=[stock_tool],  # turn-scoped: resend identical tools on every turn
        previous_interaction_id=turn1.id,
    )
    print(final_turn.output_text)
```

### Managed Agents & Background Execution (`background=True`)

Target autonomous managed agents (`antigravity-preview-09-2026` with
`environment="remote"`, `deep-research-preview-04-2026`, or custom agents from
`client.agents.create()`):

```python
import time

job = client.interactions.create(
    input="Analyze competitive positioning for solar energy providers.",
    agent="deep-research-preview-04-2026",
    background=True,
)
while True:
    job = client.interactions.get(job.id)
    if job.status == "completed":
        print(job.output_text)
        break
    elif job.status in ("failed", "cancelled"):
        print(f"Ended with status: {job.status}")
        break
    time.sleep(10)
```

## 3. REST Endpoint & Reference Routing

For HTTP/REST (`curl`), send `POST` to
`https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactions`
(`locations/global`, or multi-region `locations/us` on
`aiplatform.us.rep.googleapis.com` and `locations/eu` on
`aiplatform.eu.rep.googleapis.com`; single-region endpoints are unsupported; or
`/v1beta1/locations/global/interactions` with `x-goog-api-key` for API Key
Auth) with `"model"` or `"agent"`, `"input"` steps (`"type": "user_input"`),
and optional `"previous_interaction_id"`, `"background": true`, or
`"stream": true` (Server-Sent Events via `Content-Type: text/event-stream` and
`Transfer-Encoding: chunked` printed continuously by `curl`).

Read **only** the matching line range below when needed:

| Topic | Reference & Line Range |
| :--- | :--- |
| Thinking levels (`L11-L32`), Multi-model Planner + Executor & 3-gate escalation (`L34-L92`), Per-model KV caching & chunk resets (`L94-L130`), Long Decode >64K-1M & `ContinuationInterruptedError` (`L132-L201`), Reverse-order `delete()` (`L203-L214`) | [references/orchestration_and_long_decode.md](references/orchestration_and_long_decode.md) |
| TypeScript/JS: Client init & stateful gotchas (`L16-L48`), Streaming & structured output (`L50-L80`), Function calling & agents (`L82-L130`) | [references/typescript.md](references/typescript.md) |
| REST (`curl`): Endpoint, auth & gotchas (`L15-L42`), SSE streaming (`L44-L74`), Background managed agent (`L76-L98`) | [references/rest_api.md](references/rest_api.md) |
| Data model: Step types (`L10-L32`), Content types (`L34-L38`), Accessors & continuation fields (`L40-L52`), Streaming events (`L54-L63`), Delta types (`L65-L76`), Retention & delete order (`L78-L88`) | [references/data_model.md](references/data_model.md) |

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.