Interactions API デベロッパー ガイド

Interactions API は、Gemini Enterprise Agent Platform で Gemini モデルと自律型エージェントを使用して生成 AI アプリケーションを構築するための、統合されたステートフルなインターフェースを提供します。Interactions API を使用して、セッション ストレージとマルチターン会話の管理、リアルタイム レスポンスのストリーミング、構造化出力の適用、組み込みツールとグラウンディングの呼び出し、関数呼び出しの実行、長時間実行バックグラウンド タスクのオーケストレーションを行います。

このガイドでは、Google Gen AI SDK のインストール、クライアントの認証、一般的なインタラクション ワークフローの実装方法について説明します。インタラクションのライフサイクルのコンセプトの詳細については、Interactions API の概要をご覧ください。

始める前に

Interactions API にリクエストを送信する前に、 Google Cloudプロジェクトと開発環境を設定します。

  1. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

  4. Make sure that you have the following role or roles on the project: Agent Platform User (roles/aiplatform.user)

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. 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.

    4. 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

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. 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.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.

主なコンセプト

Interactions API が状態とレスポンスを管理する方法を理解するには、次のコンセプトを確認してください。

  • Interaction: Interactions API は、Interaction というコアリソースを中心に構築されています。Interaction は、会話またはタスクの完全なターンを表し、モデルの思考、ツール呼び出し、最終出力の時系列を追跡します。プロンプトとレスポンスのやり取りと、複雑なマルチステップの Agentic Workflows に、統合されたエンベロープを提供します。

  • ステートフルな保持: インタラクションはデフォルトでサーバーサイドに保存されます(Python では store=True、TypeScript / JavaScript では store: true)。保存されたインタラクションは 7 日間保持され、その後自動的に削除されます。store=False を設定すると、ステートレス モードが有効になります。これにより、サーバーサイドでのデータの保持が無効になり、ゼロデータ保持(ZDR)に準拠します。ステートレス モードでは、previous_interaction_id のチェーンと非同期実行(background=True)も無効になります。

  • レスポンス ヘルパー: Google Gen AI SDK バージョン 2.3.0 以降では、interaction.output_text、interaction.output_image、interaction.output_audio などのインタラクション レスポンスに便利なプロパティが用意されています。interaction.output_text を使用して、ステップ配列(interaction.steps[-1].content[0].text など)に手動でインデックスを付けるのではなく、テキスト レスポンスを読み取ります。

要件

Interactions API と統合する前に、環境とリクエストが次の要件を満たしていることを確認してください。

  • SDK バージョンのサポート: サポートされている Google Gen AI SDK ライブラリのいずれかを使用します。

  • サポートされているモデル: サポートされている Gemini 3 モデル以降を使用します。以前のモデル ファミリーは、この API をサポートしていません。サポートされているモデルの一覧については、サポートされているモデルと最新のモデル バージョンに移行するをご覧ください。

  • ターン スコープのパラメータ: tools、system_instruction、generation_config などの構成パラメータは、現在のターンにのみ適用されます。ワークフローでマルチターンの会話全体でこれらのパラメータが必要な場合は、後続の各インタラクション ターンでこれらのパラメータを渡します。

  • Gemini 4 Argon での長いデコード: gemini-4-argon または gemini-4-argon-cyber-permissive で 65,536 トークンを超えるシングルターン出力(最大 1,048,576 トークンから入力トークンを差し引いた数)を生成するには、v1beta1 エンドポイントで Google Gen AI SDK の自動継続(Python の場合は google-genai >= 2.34.0、TypeScript/JavaScript の場合は @google/genai >= 2.32.0、Go の場合は >= 1.77.0、Java の場合は >= 1.80.0)、background=True、または continuation_token を使用します。コードサンプルと継続ルールについては、Gemini 4 Argon のデベロッパー ガイドの長いデコードをご覧ください。

Google Gen AI SDK をインストールする

任意の言語の Google Gen AI SDK をインストールまたはアップグレードします。

Python

pip install --upgrade "google-genai>=2.3.0"

TypeScript / JavaScript

npm install "@google/genai>=2.3.0"

Go

go get google.golang.org/genai

Java

<dependencies>
  <dependency>
    <groupId>com.google.genai</groupId>
    <artifactId>google-genai</artifactId>
    <version>1.78.0</version>
  </dependency>
</dependencies>

クライアントを認証する

Agent Platform の Interactions API に接続するには、次のいずれかの認証方法を使用します。

アプリケーションのデフォルト認証情報(ADC)を使用して Google Cloud プロジェクトに接続する

この認証方法は、 Google Cloudのエンタープライズ ワークロードと本番環境のデプロイに使用します。アプリケーションのデフォルト認証情報(ADC)で認証するには、次のプロパティを使用してクライアントを初期化します。

  • enterprise=True
  • project="PROJECT_ID"
  • location="global"

ローカル認証情報をまだ構成していない場合は、gcloud auth application-default login を実行します。

次のコードサンプルで、PROJECT_ID はGoogle Cloud プロジェクト ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Explain serverless computing in one sentence.",
)

print(interaction.output_text)

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Explain serverless computing in one sentence.",
});

console.log(interaction.output_text);

REST

curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [{
      "type": "user_input",
      "content": [{
        "type": "text",
        "text": "Explain serverless computing in one sentence."
      }]
    }]
  }'

エクスプレス モード(API キー)を使用して接続する

この認証方法は、迅速なプロトタイピング、軽量スクリプト、API キーで認証する環境で使用します。クライアントの初期化時、または x-goog-api-key HTTP ヘッダーで API キーを渡します。

次のコードサンプルで、API_KEY を API キーに、PROJECT_ID を Google Cloud プロジェクト ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    api_key="API_KEY",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Explain serverless computing in one sentence.",
)

print(interaction.output_text)

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    apiKey: "API_KEY",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Explain serverless computing in one sentence.",
});

console.log(interaction.output_text);

REST

curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "x-goog-api-key: API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [{
      "type": "user_input",
      "content": [{
        "type": "text",
        "text": "Explain serverless computing in one sentence."
      }]
    }]
  }'

一般的なやり取りのワークフロー

クライアントを構成したら、interactions.create メソッドを使用して、セッション ストレージとマルチターンの会話の管理、出力トークンのリアルタイムでのストリーミング、スキーマ検証済みの JSON の生成、組み込みツールとグラウンディングの呼び出し、外部関数の呼び出し、自律型エージェントの実行を行うことができます。

セッション ストレージと会話の状態を管理する

Interactions API は、サーバーサイドのステートフル ストレージ(store=True、デフォルト)とクライアント管理のステートレス実行(store=False)の両方をサポートしています。次の表は、ステートフル インタラクション モードとステートレス インタラクション モードを比較したものです。

機能 ステートフル モード(store=true、デフォルト) ステートレス モード(store=false)
サーバーサイドの永続性 入力、中間ステップ、出力をサーバーに 7 日間保存します。 サーバーサイドのインタラクション ストレージを無効にして、ゼロデータ保持(ZDR)ワークフローをサポートします。
マルチターン コンテキスト previous_interaction_id で前のインタラクション id を渡すことで、ターンをチェーンします。 各ターンで input の以前の会話 steps の完全な配列を渡す必要があります。previous_interaction_id を渡すと、400 Bad Request エラーが返されます。
バックグラウンド実行(background=true) 長時間実行されるモデルとエージェントのインタラクションでサポートされています。 サポートされていません。非同期のバックグラウンド実行には、サーバーサイドの状態の永続性が必要です。
セッション ライフサイクル メソッド インタラクションの取得(get)、一覧表示(list)、キャンセル(cancel)、削除(delete)をサポートします。 同期レスポンスまたはストリーミング レスポンスが完了した後は取得できません。
保存データの暗号化 デフォルトでは Google-owned and Google-managed encryption keyで暗号化されます。または、us マルチリージョンと eu マルチリージョンで顧客管理の暗号鍵(CMEK)を使用して暗号化されます。 インタラクションの状態は保存されません。

ステートフルなマルチターン会話を実行する

デフォルトでは、Interactions API は会話の状態をサーバーに保存します(Python では store=True、TypeScript/JavaScript では store: true)。既存の会話を続行するには、前のインタラクションの id を previous_interaction_id パラメータに渡します。エージェント プラットフォームは、保存されている会話コンテキストを取得し、新しいターンを追加して、キャッシュに保存されたプレフィックス トークンを再利用します。

エンドポイント間でインタラクションをチェーンする場合は、次のロケーション ルールを遵守してください。

  • 同じロケーション: 同じロケーション内でインタラクションをチェーンできます(global から global、us から us、eu から eu など)。

  • 異なるロケーション間: 異なるエンドポイント ロケーション間(global と us または eu の間、または us と eu の間)のチェーンはサポートされていません。各エンドポイントは、インタラクションの状態を分離されたストレージに保存します。そのため、別の場所で作成されたインタラクション ID を参照すると、404 Not Found エラーが返されます。

次の例では、PROJECT_ID を Google Cloudプロジェクト ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# Turn 1: Start a stateful conversation (store=True by default)
turn1 = client.interactions.create(
    model="gemini-3.8-flash",
    input="Hi! My name is John. I am working on AI agents.",
    store=True,
)
print(f"Turn 1: {turn1.output_text}")

# Turn 2: Reference the stored conversation state using previous_interaction_id
turn2 = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is my name?",
    previous_interaction_id=turn1.id,
)
print(f"Turn 2: {turn2.output_text}")

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

// Turn 1: Start a stateful conversation (store: true by default)
const turn1 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Hi! My name is John. I am working on AI agents.",
    store: true,
});
console.log(`Turn 1: ${turn1.output_text}`);

// Turn 2: Reference the stored conversation state using previous_interaction_id
const turn2 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "What is my name?",
    previous_interaction_id: turn1.id,
});
console.log(`Turn 2: ${turn2.output_text}`);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

// Turn 1: Start a stateful conversation (store is true by default)
CreateModelInteraction req1 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Hi! My name is John. I am working on AI agents."))
        .store(true)
        .build();

Interaction turn1 =
    client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));

// Turn 2: Reference the stored conversation state using previousInteractionId
CreateModelInteraction req2 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .previousInteractionId(turn1.id().orElseThrow())
        .input(InteractionsInput.of("What is my name?"))
        .build();

Interaction turn2 =
    client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));

REST

# Turn 1: Start a stateful conversation
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "store": true,
    "input": "Hi! My name is John. I am working on AI agents."
  }'

# Turn 2: Pass the interaction ID from Turn 1 in previous_interaction_id
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
    "input": "What is my name?"
  }'

ステートレス マルチターンの会話を実行する

ワークロードでゼロデータ保持(ZDR)が必要な場合は、すべてのリクエストで store=False(TypeScript/JavaScript では store: false、REST では "store": false)を明示的に設定します。

ステートレス モードでは、Step オブジェクト(user_input、thought、function_call、function_result、model_output)のリストを保持し、各ターンで input に累積された steps 配列を送信することで、クライアントで会話履歴を管理します。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

history = [
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "Hi! My name is John."}],
    }
]

# Turn 1: Stateless request (store=False)
turn1 = client.interactions.create(
    model="gemini-3.8-flash",
    input=history,
    store=False,
)
print(f"Turn 1: {turn1.output_text}")

# Append the model's generated steps and the next user turn to local history
history.extend(turn1.steps)
history.append(
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "What is my name?"}],
    }
)

# Turn 2: Send the full step history with store=False
turn2 = client.interactions.create(
    model="gemini-3.8-flash",
    input=history,
    store=False,
)
print(f"Turn 2: {turn2.output_text}")

TypeScript / JavaScript

import { GoogleGenAI, Step } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const history: Step[] = [
    {
        type: "user_input",
        content: [{ type: "text", text: "Hi! My name is John." }],
    },
];

// Turn 1: Stateless request (store: false)
const turn1 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: history,
    store: false,
});
console.log(`Turn 1: ${turn1.output_text}`);

// Append the model's generated steps and the next user turn to local history
if (turn1.steps) {
    history.push(...turn1.steps);
}
history.push({
    type: "user_input",
    content: [{ type: "text", text: "What is my name?" }],
});

// Turn 2: Send the full step history with store: false
const turn2 = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: history,
    store: false,
});
console.log(`Turn 2: ${turn2.output_text}`);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.UserInputContent;
import com.google.genai.gaos.models.interactions.UserInputStep;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.ArrayList;
import java.util.List;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

List<Step> history = new ArrayList<>();
history.add(
    Step.of(
        UserInputStep.builder()
            .content(
                List.of(
                    UserInputContent.of(
                        TextContent.builder().text("Hi! My name is John.").build())))
            .build()));

// Turn 1: Stateless request (store(false))
CreateModelInteraction req1 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofSteps(history))
        .store(false)
        .build();

Interaction turn1 =
    client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));

// Append the model's generated steps and the next user turn to local history
turn1.steps().ifPresent(history::addAll);
history.add(
    Step.of(
        UserInputStep.builder()
            .content(
                List.of(
                    UserInputContent.of(
                        TextContent.builder().text("What is my name?").build())))
            .build()));

// Turn 2: Send the full step history with store(false)
CreateModelInteraction req2 =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofSteps(history))
        .store(false)
        .build();

Interaction turn2 =
    client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));

REST

curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "store": false,
    "input": [
      {
        "type": "user_input",
        "content": [{"type": "text", "text": "Hi! My name is John."}]
      },
      {
        "type": "model_output",
        "content": [{"type": "text", "text": "Hello John! How can I help you today?"}]
      },
      {
        "type": "user_input",
        "content": [{"type": "text", "text": "What is my name?"}]
      }
    ]
  }'

保持とセッションのライフサイクル

保存されたインタラクション(store=True)は、次の保持ルールと分岐ルールに従います。

  • 7 日間の有効期間(TTL): 保存された各インタラクションは、created タイムスタンプから 7 日間保持され、7 日間の TTL が期限切れになると自動的に削除されます。

  • 独立した親ストレージと子ストレージ: previous_interaction_id を使用して新しいターンをチェーンすると、Agent Platform は祖先の会話履歴を新しいインタラクション レコードにコピーします。各ターンには会話履歴の独自のコピーが保存されるため、以前のターンを期限切れにするか削除すると、次のようになります。

    • 後のターンから続行すると成功する: ターン 2(interaction_2)がすでに作成された後にターン 1(interaction_1)が期限切れになるか削除された場合でも、interaction_2 自体が期限切れになるか削除されるまで、previous_interaction_id=interaction_2.id を使用してターン 3 を作成できます。

    • 期限切れまたは削除されたターンからの分岐が失敗する: 期限切れまたは削除されたインタラクション ID を previous_interaction_id で直接参照して新しいインタラクションを作成しようとすると、400 Bad Request(Previous Interaction ID not found)エラーが返されます。

保存されたインタラクションの取得、一覧表示、キャンセル、削除

保存されたインタラクションは、次の方法でライフサイクル全体にわたって検査および管理できます。

  • インタラクションを取得する(interactions.get): id で完全な Interaction リソースを取得します。これには、user_input ステップ、中間 thought ステップとツールステップ、model_output ステップが含まれます。stream=True(およびオプションの last_event_id)を設定して、進行中のインタラクションをストリーミングまたは再開します。

  • インタラクションを一覧表示する(interactions.list): page_size(デフォルトは 10、最大 500)と page_token を使用して、REST 経由でプロジェクトに保存されているインタラクション ID をクエリします。InteractionMetadata リソースのリストを返します。

  • 進行中のインタラクションをキャンセルする(interactions.cancel): in_progress 状態または requires_action 状態の非同期バックグラウンド インタラクション(background=True)を停止し、ステータスを cancelled に移行します。解約前に生成されたトークンは請求の対象となります。

  • 保存されたインタラクションを削除する(interactions.delete): 7 日間の TTL が期限切れになる前に、保存されたインタラクションを完全に削除します。削除できるのは、ターミナル状態(completed、failed、cancelled)のインタラクションのみです。インタラクションがバックグラウンドで実行されている場合は、削除する前にキャンセルしてください。

次の例では、PROJECT_ID を Google Cloudプロジェクト ID に、INTERACTION_ID をターゲット インタラクション ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# Retrieve a stored interaction by ID
interaction = client.interactions.get(id="INTERACTION_ID")
print(f"Status: {interaction.status}")

# Cancel an in-progress background interaction
cancelled = client.interactions.cancel(id="INTERACTION_ID")
print(f"After cancel: {cancelled.status}")

# Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(id="INTERACTION_ID")
print("Interaction deleted.")

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

// Retrieve a stored interaction by ID
const interaction = await ai.interactions.get("INTERACTION_ID");
console.log(`Status: ${interaction.status}`);

// Cancel an in-progress background interaction
const cancelled = await ai.interactions.cancel("INTERACTION_ID");
console.log(`After cancel: ${cancelled.status}`);

// Delete a completed, failed, or cancelled interaction before its 7-day TTL
await ai.interactions.delete("INTERACTION_ID");
console.log("Interaction deleted.");

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionStatus;
import com.google.genai.gaos.models.operations.CancelInteractionByIdResponse;
import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;
import com.google.genai.gaos.models.operations.GetInteractionByIdResponse;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

String interactionId = "INTERACTION_ID";

// Retrieve a stored interaction by ID
GetInteractionByIdResponse getResponse =
    client.interactions.get(new GetInteractionByIdRequest(interactionId));
Interaction interaction = getResponse.interaction().orElseThrow();
System.out.println("Status: " + interaction.status().map(InteractionStatus::value).orElse(""));

// Cancel an in-progress background interaction
CancelInteractionByIdResponse cancelResponse = client.interactions.cancel(interactionId);
Interaction cancelled = cancelResponse.interaction().orElseThrow();
System.out.println("After cancel: " + cancelled.status().map(InteractionStatus::value).orElse(""));

// Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(interactionId);
System.out.println("Interaction deleted.");

REST

# Retrieve a stored interaction by ID
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)"

# List stored interactions (up to 500 per page)
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions?page_size=10" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)"

# Cancel an in-progress background interaction
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID/cancel" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)"

# Delete a completed, failed, or cancelled interaction
curl -X DELETE "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)"

ステートフル ストレージの保存容量と上限

モデルのトークンとリクエスト率の上限に加えて、ステートフルなインタラクション(store=True)には、次のプロジェクト レベルのストレージと同時実行の上限が適用されます。

割り当てまたはシステム上限 デフォルトの上限(プロジェクトごと) 説明
1 日あたりのステートフル インタラクション作成スループット 240 GiB 便/日 store=true を使用した interactions.create リクエスト全体で、1 日あたりにサーバーサイド ストレージに書き込まれるインタラクション データの合計量の上限。
1 日あたりのステートフル インタラクションの取得スループット 480 GiB 便/日 interactions.get リクエストと、previous_interaction_id を使用して以前のターンを読み込むマルチターン リクエスト全体で、1 日に読み取られる保存済みインタラクション データの合計量の上限。
同時ステートフル インタラクション 500 件の同時インタラクション プロジェクトで同時に実行されるアクティブなステートフル インタラクションの最大数。

Agent Platform での割り当ての表示と管理の詳細については、割り当てとシステムの上限をご覧ください。

回答をリアルタイムでストリーミングする

インタラクティブなアプリケーションでユーザーが感じるレイテンシを短縮するには、モデルのレスポンスを生成時にストリーミングします。interactions.create を呼び出すときに stream=True(TypeScript / JavaScript では stream: true)を設定して、サーバー送信イベントの反復可能なストリームを受信します。step.delta イベントをフィルタして、増分テキスト チャンクが到着したときにレンダリングします。

Python

response = client.interactions.create(
    model="gemini-3.8-flash",
    input="Write a short poem about debugging.",
    stream=True,
)

for event in response:
    if event.event_type == "step.delta" and hasattr(event.delta, "text"):
        print(event.delta.text, end="", flush=True)
print()

TypeScript / JavaScript

const responseStream = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Write a short poem about debugging.",
    stream: true,
});

for await (const event of responseStream) {
    if (event.event_type === "step.delta" && event.delta && "text" in event.delta) {
        process.stdout.write(event.delta.text);
    }
}
console.log();

構造化出力を生成する

アプリケーションで予測可能で機械で読み取り可能な形式のレスポンスが必要な場合は、モデル出力を特定の JSON スキーマに一致するように制限できます。ターゲット スキーマ(Python の Pydantic モデル JSON スキーマや TypeScript/JavaScript の Type スキーマ オブジェクトなど)を、多態的な response_format パラメータに直接渡します。

Python

from pydantic import BaseModel, Field

class Book(BaseModel):
    title: str = Field(description="The title of the book")
    author: str = Field(description="The book's author")
    year_published: int

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Recommend one famous sci-fi book.",
    response_format=Book.model_json_schema(),
)

# The output text is valid JSON matching the Book schema
print(interaction.output_text)

TypeScript / JavaScript

import { Type } from "@google/genai";

const BookSchema = {
    type: Type.OBJECT,
    properties: {
        title: { type: Type.STRING, description: "The title of the book" },
        author: { type: Type.STRING, description: "The book's author" },
        yearPublished: { type: Type.INTEGER },
    },
    required: ["title", "author", "yearPublished"],
};

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Recommend one famous sci-fi book.",
    response_format: BookSchema,
});

console.log(interaction.output_text);

関数呼び出し(ツールの使用)を使用する

関数呼び出しを使用すると、モデルはカスタム関数または外部 API の実行をリクエストして、最終的なレスポンスを作成する前に情報を収集できます。ステートフルなインタラクション ワークフローでは、関数呼び出しは 2 ターンのパターンに従います。

  1. ツールを宣言して渡す: 最初のリクエストの tools パラメータに関数宣言を指定します。

  2. 実行して結果を返す: function_call ステップのレスポンス ステップ(interaction.steps)を検査し、モデルから提供された arguments を使用してローカル関数を実行します。call_id と previous_interaction_id でリンクされた function_result アイテムを含むフォローアップ インタラクションを送信します。

Python

# Define a declarative function tool schema
stock_tool = {
    "type": "function",
    "name": "get_stock_price",
    "description": "Gets the stock price for a given ticker symbol.",
    "parameters": {
        "type": "object",
        "properties": {
            "ticker": {"type": "string", "description": "The stock ticker symbol"}
        },
        "required": ["ticker"],
    },
}

def get_stock_price(ticker: str) -> float:
    """Executes the local tool function."""
    if ticker.upper() == "GOOG":
        return 175.50
    return 100.0

# Turn 1: Pass the tool declaration to the model
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="What is the stock price of GOOG?",
    tools=[stock_tool],
)

# Inspect the interaction steps for function call requests
for step in interaction.steps:
    if step.type == "function_call" and step.name == "get_stock_price":
        ticker_arg = step.arguments.get("ticker")
        price = get_stock_price(ticker_arg)

        # Turn 2: Submit the function execution result to the conversation
        final_turn = client.interactions.create(
            model="gemini-3.8-flash",
            input=[{
                "type": "function_result",
                "call_id": step.id,
                "result": {"price": price},
            }],
            previous_interaction_id=interaction.id,
        )
        print(final_turn.output_text)

TypeScript / JavaScript

// Define a declarative function tool schema
const stockTool = {
    type: "function",
    name: "getStockPrice",
    description: "Gets the stock price for a given ticker symbol.",
    parameters: {
        type: "object",
        properties: {
            ticker: { type: "string", description: "The stock ticker symbol" },
        },
        required: ["ticker"],
    },
};

function getStockPrice({ ticker }: { ticker: string }): number {
    if (ticker.toUpperCase() === "GOOG") return 175.50;
    return 100.00;
}

// Turn 1: Pass the tool declaration to the model
const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "What is the stock price of GOOG?",
    tools: [stockTool],
});

// Inspect the interaction steps for function call requests
for (const step of interaction.steps ?? []) {
    if (step.type === "function_call" && step.name === "getStockPrice") {
        const tickerArg = step.arguments.ticker as string;
        const price = getStockPrice({ ticker: tickerArg });

        // Turn 2: Submit the function execution result to the conversation
        const finalTurn = await ai.interactions.create({
            model: "gemini-3.8-flash",
            input: [{
                type: "function_result",
                call_id: step.id,
                result: { price },
            }],
            previous_interaction_id: interaction.id,
        });
        console.log(finalTurn.output_text);
    }
}

組み込みツールを使用する

Interactions API は、クライアントサイドの関数呼び出しに加えて、Gemini 3 モデルの組み込みサーバーサイド ツールをサポートしています。tools パラメータで組み込みツールを有効にすると、Agent Platform は 1 回の interactions.create 呼び出し中にサーバーでツールを実行し、ツールの呼び出し(*_call)と出力(*_result)のステップを interaction.steps に記録します。

Interactions API は、次の組み込みツールをサポートしています。

  • コード実行({"type": "code_execution"}): サンドボックス環境で Python コードを生成して実行し、計算、データ分析、コードベースの推論を行います。サポートされているライブラリ、課金、制限事項については、コード実行をご覧ください。

  • URL コンテキスト({"type": "url_context"}): プロンプトに含まれる公開ウェブ URL からコンテンツを取得して分析します。インデックス キャッシュ、ライブフェッチ、URL コンテキストと検索の組み合わせの詳細については、URL コンテキストをご覧ください。

  • Google 検索によるグラウンディング({"type": "google_search"}): モデルの回答をリアルタイムのウェブ情報でグラウンディングし、インライン引用を返します。Google 検索で回答をグラウンディングするをご覧ください。

  • コンピュータの使用({"type": "computer_use"}): ブラウザとユーザー インターフェースの自動化ワークフローを有効にします。構成と安全管理については、パソコンの使用をご覧ください。

Python コードを実行する

コード実行を有効にするには、tools リストに {"type": "code_execution"} を含めます。返される interaction.steps 配列には、code_execution_call ステップ(arguments.code と arguments.language を含む)、code_execution_result ステップ(result と is_error を含む)、最後の model_output ステップが含まれます。

次の例では、PROJECT_ID を Google Cloudプロジェクト ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Calculate the 50th Fibonacci number and find its closest prime.",
    tools=[{"type": "code_execution"}],
)

for step in interaction.steps:
    if step.type == "code_execution_call":
        print(f"Generated code:\n{step.arguments.code}")
    elif step.type == "code_execution_result":
        print(f"Execution result:\n{step.result}")
    elif step.type == "model_output":
        for content in step.content:
            if content.type == "text":
                print(content.text)

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Calculate the 50th Fibonacci number and find its closest prime.",
    tools: [{ type: "code_execution" }],
});

for (const step of interaction.steps ?? []) {
    if (step.type === "code_execution_call") {
        console.log(`Generated code:\n${step.arguments?.code}`);
    } else if (step.type === "code_execution_result") {
        console.log(`Execution result:\n${step.result}`);
    } else if (step.type === "model_output") {
        for (const content of step.content ?? []) {
            if (content.type === "text") {
                console.log(content.text);
            }
        }
    }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CodeExecution;
import com.google.genai.gaos.models.interactions.CodeExecutionCallStep;
import com.google.genai.gaos.models.interactions.CodeExecutionResultStep;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

CreateModelInteraction request =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(
            InteractionsInput.of(
                "Calculate the 50th Fibonacci number and find its closest prime."))
        .tools(List.of(CodeExecution.builder().build()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();

for (Step step : interaction.steps().orElse(List.of())) {
    if (step instanceof CodeExecutionCallStep callStep) {
        callStep
            .arguments()
            .flatMap(args -> args.code())
            .ifPresent(code -> System.out.println("Generated code:\n" + code));
    } else if (step instanceof CodeExecutionResultStep resultStep) {
        resultStep
            .result()
            .ifPresent(res -> System.out.println("Execution result:\n" + res));
    }
}
System.out.println(interaction.outputText().orElse(""));

REST

curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": "Calculate the 50th Fibonacci number and find its closest prime.",
    "tools": [{"type": "code_execution"}]
  }'

URL コンテキストを使用してウェブページのコンテンツを取得する

モデルがプロンプトで参照されているウェブページを取得して分析できるようにするには、tools リストに {"type": "url_context"} を含めます。API は、取得した URL を url_context_call ステップと url_context_result ステップに記録し、model_output で生成されたテキストに url_citation アノテーションを添付します。

次の例では、PROJECT_ID を Google Cloudプロジェクト ID に置き換え、YOUR_URL_1 と YOUR_URL_2 を比較する公開 URL に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
    tools=[{"type": "url_context"}],
)

print(interaction.output_text)

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
    tools: [{ type: "url_context" }],
});

console.log(interaction.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.URLContext;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

CreateModelInteraction request =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(
            InteractionsInput.of(
                "Compare the key findings from YOUR_URL_1 and YOUR_URL_2."))
        .tools(List.of(URLContext.builder().build()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();

System.out.println(interaction.outputText().orElse(""));

REST

curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
    "tools": [{"type": "url_context"}]
  }'

Google 検索で回答をグラウンディングする

グラウンディングは、Gemini モデルを検証可能な外部ソースに接続して、ハルシネーションを減らし、引用付きの最新の回答を提供します。Agent Platform のグラウンディング オプションの概要については、グラウンディングの概要、Google 検索によるグラウンディング、エンタープライズ向けウェブ グラウンディングをご覧ください。

tools リストに {"type": "google_search"} を渡して Google 検索によるグラウンディングを有効にすると、Interactions API は検索データとアトリビューション データを interaction.steps タイムラインに直接返します。

  • google_search_call: モデル(step.arguments.queries)によって発行された検索クエリが含まれます。

  • google_search_result: 検索候補(result[].search_suggestions)が含まれます。これは、ユーザー インターフェースで検索候補をレンダリングするために使用される HTML / CSS スニペットです。ソース URL とタイトルを含むウェブリソースは、model_output テキスト ブロックのインライン url_citation アノテーションとして提供されます。

  • インライン url_citation アノテーション: model_output ステップ内の各 text コンテンツ ブロック(TextContent)に annotations 配列を含めることができます。各 url_citation アノテーションは、レスポンス テキスト内の文字またはバイトスパン(start_index と end_index)を、ソース title と url とともに識別します。

次の例では、PROJECT_ID を Google Cloudプロジェクト ID に置き換えます。

Python

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Who won the 2026 Super Bowl?",
    tools=[{"type": "google_search"}],
)

print(interaction.output_text)

# Parse inline url_citation annotations from model_output steps
print("\nSources:")
for step in interaction.steps:
    if step.type == "model_output" and step.content:
        for content in step.content:
            if content.type == "text" and getattr(content, "annotations", None):
                for annotation in content.annotations:
                    if annotation.type == "url_citation":
                        span = content.text[annotation.start_index:annotation.end_index]
                        print(f"- [{annotation.title}]({annotation.url}) (cited text: {span!r})")

TypeScript / JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "PROJECT_ID",
    location: "global",
});

const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Who won the 2026 Super Bowl?",
    tools: [{ type: "google_search" }],
});

console.log(interaction.output_text);

// Parse inline url_citation annotations from model_output steps
console.log("\nSources:");
for (const step of interaction.steps ?? []) {
    if (step.type === "model_output") {
        for (const content of step.content ?? []) {
            if (content.type === "text" && content.annotations) {
                for (const annotation of content.annotations) {
                    if (annotation.type === "url_citation") {
                        const span = content.text.slice(
                            annotation.start_index,
                            annotation.end_index,
                        );
                        console.log(
                            `- [${annotation.title}](${annotation.url}) (cited text: "${span}")`,
                        );
                    }
                }
            }
        }
    }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Annotation;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.URLCitation;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;

Client client =
    Client.builder()
        .enterprise(true)
        .project("PROJECT_ID")
        .location("global")
        .build();

CreateModelInteraction request =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Who won the 2026 Super Bowl?"))
        .tools(List.of(GoogleSearch.builder().build()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();

System.out.println(interaction.outputText().orElse(""));

// Parse inline URLCitation annotations from ModelOutputStep blocks
System.out.println("\nSources:");
for (Step step : interaction.steps().orElse(List.of())) {
    if (step instanceof ModelOutputStep outputStep) {
        for (Content content : outputStep.content().orElse(List.of())) {
            if (content instanceof TextContent textContent) {
                for (Annotation annotation : textContent.annotations().orElse(List.of())) {
                    if (annotation instanceof URLCitation citation) {
                        System.out.printf(
                            "- %s: %s (span: %d..%d)%n",
                            citation.title().orElse(""),
                            citation.url().orElse(""),
                            citation.startIndex().orElse(0L),
                            citation.endIndex().orElse(0L));
                    }
                }
            }
        }
    }
}

REST

# Request
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": "Who won the 2026 Super Bowl?",
    "tools": [{"type": "google_search"}]
  }'

レスポンスには、インライン url_citation アノテーションを含む google_search_call、google_search_result、model_output のステップが含まれます。

{
  "id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROA",
  "model": "gemini-3.8-flash",
  "status": "completed",
  "steps": [
    {
      "type": "google_search_call",
      "id": "search_call_1",
      "arguments": {
        "queries": ["2026 Super Bowl winner"]
      }
    },
    {
      "type": "google_search_result",
      "call_id": "search_call_1",
      "result": [
        {
          "search_suggestions": "<!-- HTML and CSS for search suggestions -->"
        }
      ]
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "The Seattle Seahawks won Super Bowl LX on February 8, 2026.",
          "annotations": [
            {
              "type": "url_citation",
              "start_index": 0,
              "end_index": 59,
              "title": "Super Bowl LX",
              "url": "https://example.com/super-bowl-lx"
            }
          ]
        }
      ]
    }
  ]
}

エージェントと長時間実行のバックグラウンド タスクを実行する

Interactions API では、基盤モデルに加えて、agent パラメータを使用して、特殊な自律型エージェントを呼び出すことができます。

  • antigravity-preview-05-2026: 安全なサンドボックス化された Linux 環境でコード実行、ファイル管理、ウェブ ブラウジングを行う汎用マネージド エージェント。詳細については、エージェントを操作するをご覧ください。
  • deep-research-preview-04-2026: Gemini Deep Research エージェント。複数ステップのウェブリサーチ タスクを計画して実行し、複数のソースから得られた調査結果を包括的なレポートにまとめます。詳細については、Gemini Deep Research エージェントを使用するをご覧ください。
  • カスタム エージェント: client.agents.create() で構成およびプロビジョニングされたカスタム エージェント リソース。

Agentic Workflows の完了には数分かかることが多いため、background=True を設定してバックグラウンドで非同期に実行します。API は、id を含む Interaction オブジェクトをすぐに返します。interaction.status が completed に移行するまで、client.interactions.get() を使用してポーリングできます。

このサンプルを試す前に、PROJECT_ID をGoogle Cloud プロジェクト ID に置き換えます。

import time
from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    input="Analyze competitive positioning for solar energy providers.",
    agent="deep-research-preview-04-2026",
    background=True,
)

print(f"Research started: {interaction.id}")

while True:
    interaction = client.interactions.get(interaction.id)
    if interaction.status == "completed":
        print(interaction.output_text)
        break
    elif interaction.status in ("failed", "cancelled"):
        print(f"Research ended with status: {interaction.status}")
        break
    time.sleep(10)

アップロードされた Cloud Storage ファイルにアクセスする

Interactions API を使用して、アップロードされた Cloud Storage ファイルにアクセスできます。次の例では、PROJECT_ID をGoogle Cloud プロジェクト ID に置き換えます。

from google import genai

# Credentials must belong to an identity with storage.objects.get permissions
client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "user_input",
            "content": [
                {"type": "text", "text": "Summarize the attached document:"},
                {
                    "type": "document",
                    "uri": "gs://my-secure-bucket/quarterly_report.pdf",
                    "mime_type": "application/pdf",
                },
            ],
        }
    ],
)

print(interaction.output_text)

Cloud Storage URI(gs://bucket-name/path/to/file など)を Interactions API に渡すと、呼び出し元プロジェクトの Agent Platform サービス エージェント(service-PROJECT_NUMBER@gcp-sa-aiplatform.)が Cloud Storage からオブジェクトを取得する前に、リクエストは呼び出し元の認証情報を使用して読み取りアクセス権を確認します。

インタラクション リクエストで Cloud Storage ファイルを渡すには、呼び出し元のプリンシパル(ユーザー アカウント、サービス アカウント、またはフェデレーション ID)が、参照されるすべてのオブジェクトに対する storage.objects.get 権限を保持している必要があります。プロジェクト間の Cloud Storage バケットまたはカスタム IAM ポリシーを持つ Cloud Storage バケットの場合は、呼び出し元のプリンシパルと呼び出し元のプロジェクトのサービス エージェントの両方に読み取りアクセス権を付与します。

標準の Gemini モデルのインタラクション リクエストごとに、最大 100 個の個別の Cloud Storage(gs://)URI(ファイルあたり最大 2 GiB から 500 KiB を差し引いた値)がサポートされます。previous_interaction_id を使用してステートフル ターンをチェーンすると、Agent Platform は会話履歴と現在のターンで個別の gs:// URI を累積的にカウントします。マネージド エージェントのインタラクション(model ではなく agent を設定するリクエスト)、Gemini Omni モデル、Lyria 3 モデルは、この 100 URI の上限から除外されます。

Cloud Storage ファイルにアクセスするための IAM ロールを構成する

storage.objects.get 権限を含む標準の事前定義ロールのいずれかを付与します。

  • ストレージ オブジェクト閲覧者(roles/storage.objectViewer): オブジェクトに対する読み取りアクセス権(推奨)。

  • Storage オブジェクト ユーザー(roles/storage.objectUser): オブジェクトに対する読み取りと書き込みのアクセス権。

Google Cloud CLI を使用してユーザー アカウントにアクセス権を付与するには、次のコマンドを使用します。

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
    --member="user:user-email@example.com" \
    --role="roles/storage.objectViewer"

特定の呼び出し元サービス アカウントにアクセス権を付与するには、次のコマンドを使用します。

gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
    --member="serviceAccount:sa-name@PROJECT_ID." \
    --role="roles/storage.objectViewer"

Cloud Storage ファイル アクセスのトラブルシューティング

呼び出し元のプリンシパルに十分な権限がない場合、Interactions API は次のような 403 Forbidden エラーを返します。

Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more Cloud Storage URIs.

この問題を解決するには、Cloud Storage バケットまたはオブジェクトに対するストレージ オブジェクト閲覧者ロール(roles/storage.objectViewer)を、認証された呼び出し元(および、プロジェクト間またはカスタム IAM Cloud Storage バケットの呼び出し元プロジェクトの Agent Platform サービス エージェント)に付与します。

指定されたオブジェクトが存在しない場合、またはバケットの権限により呼び出し元がオブジェクトの存在を確認できない場合、Interactions API は次のような 404 Not Found エラーを返します。

Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.

この問題を解決するには、Cloud Storage URI が正しいことを確認し、認証された呼び出し元にバケットへの読み取りアクセス権があることを確認します。

モデル インタラクション リクエストが、現在のターンとリンクされた previous_interaction_id 履歴全体で 100 を超える個別の Cloud Storage URI を参照している場合、Interactions API は次のような 400 Bad Request エラーを返します。

INVALID_ARGUMENT - 400 Bad Request: Request references 101 distinct gs:// URIs, which exceeds the maximum of 100.

この問題を解決するには、以下のいずれかを行います。

  • 以前のターンのファイルが不要になったら、previous_interaction_id を使用せずに新しいインタラクションを開始します。
  • 小さなドキュメントを結合するか、リクエスト ペイロードの上限(同期リクエストまたはストリーミング リクエストの場合は圧縮された 256 MiB、service_tier が deferred に設定され、background と store が true に設定されている場合は圧縮されていない 9.75 MiB)内で追加のファイルをインラインで渡します。
  • モダリティごとのモデルアイテムの上限(画像と PDF の合計 3,000 個、音声ファイル 1,000 個、動画 10 個、または書式なしテキスト ファイルを含む場合は最大 6,500 個)までの gs:// URI を参照するリクエストには、generateContent を使用します。

CMEK を使用してインタラクション データを暗号化する

ステートフル インタラクション(Python の store=True、TypeScript / JavaScript の store: true)では、インタラクション データが最大 7 日間保存されます。Google-owned and Google-managed encryption keyではなく独自の暗号鍵でデータを保護するには、サービス プロファイルを使用します。サービス提供プロファイルは、Cloud Key Management Service 鍵をプロジェクト、ロケーション、API スコープにリンクします。サービス提供プロファイルが存在する間、Agent Platform は保存されたインタラクション データを自動的に暗号化します。インタラクション リクエストの形式は変更されません。

Interactions API のサービス プロファイル CMEK は、us と eu のマルチリージョンでサポートされています。global リージョンはサポートされていません。

Interactions API に CMEK を設定する手順は次のとおりです。

  1. プロジェクトで Cloud KMS API と Agent Platform API を有効にします。始める前にをご覧ください。
  2. us または eu マルチリージョンに Cloud KMS 鍵を作成します。キーリングと鍵の作成をご覧ください。
  3. Gemini Enterprise Agent Platform サービス エージェントに、鍵に対する roles/cloudkms.cryptoKeyEncrypterDecrypter ロールを付与します。Agent Platform の権限を付与するをご覧ください。
  4. scope を INTERACTIONS_API に設定し、cmekConfig.encryptionSpec.kmsKeyName を鍵に設定する同じマルチリージョン(us または eu)にサービス プロファイルを作成します。

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/servingProfiles?servingProfileId=SERVING_PROFILE_ID" \
      -d '{
        "displayName": "Interactions API CMEK profile",
        "description": "CMEK for Interactions API",
        "scope": "INTERACTIONS_API",
        "cmekConfig": {
          "encryptionSpec": {
            "kmsKeyName": "projects/KMS_PROJECT_ID/locations/LOCATION/keyRings/KEY_RING_NAME/cryptoKeys/KEY_NAME"
          }
        }
      }'
    

    長時間実行される作成オペレーションが完了するまで待ちます("done": true)。サービス提供プロファイルの管理、更新、削除の詳細については、サービス提供プロファイルを作成するをご覧ください。

  5. インタラクション リクエストは、サービス プロファイルと同じ us または eu マルチリージョンに送信します。サービス提供プロファイルの CMEK は、global エンドポイントでは使用できません。

    • Google Gen AI SDK: location="us" または location="eu"(TypeScript/JavaScript の場合は location: "us" または location: "eu")を使用してクライアントを初期化します。
    • REST: マルチリージョン エンドポイント https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions にリクエストを送信します。ここで、LOCATION は us または eu です。

    鍵を無効にするか、サービス エージェントのアクセス権を取り消すと、保存されたインタラクションを作成または読み取るリクエストが FAILED_PRECONDITION エラーで失敗します。

高度な REST ワークフロー

シェルベースの自動化、CI / CD パイプライン、Python または TypeScript / JavaScript ランタイムのない環境では、curl を使用して HTTP 経由で Interactions API を直接呼び出すことができます。

REST エンドポイント

次の Interactions API エンドポイントに POST リクエストを送信します。

POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions

リクエストの次の変数を置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION: global に設定します(または、データ所在地または CMEK のマルチリージョン ホスト https://aiplatform.LOCATION.rep.googleapis.com を使用する場合は us または eu)。

環境変数と認証を設定する

次のセクションの curl の例を実行する前に、プロジェクト ID、ターゲット モデルまたはエージェント ID、アプリケーションのデフォルト認証情報から生成された OAuth 2.0 アクセス トークンをエクスポートします。

PROJECT_ID="PROJECT_ID"
MODEL_ID="gemini-3.8-flash"
AGENT_ID="deep-research-preview-04-2026"
ACCESS_TOKEN=$(gcloud auth print-access-token)

同期レスポンスの形式

同期 POST リクエストは、一意のインタラクション id、実行 status、会話 steps、トークン usage メタデータを含む JSON interaction オブジェクトを返します。

{
  "id": "your-interaction-id",
  "status": "completed",
  "steps": [
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
        }
      ]
    }
  ],
  "usage": {
    "total_tokens": 24751,
    "total_input_tokens": 23894,
    "total_output_tokens": 857
  },
  "created": "2026-05-08T10:44:43Z",
  "updated": "2026-05-08T10:44:43Z",
  "environment_id": "your-environment-id",
  "object": "interaction"
}

マルチターンのステートフルなやり取りを続行する

REST で保存された会話を続行するには、JSON リクエスト本文の previous_interaction_id フィールドに、以前のレスポンスの id を渡します。

このサンプルを試す前に、PREVIOUS_INTERACTION_ID を前のインタラクションで返された id に置き換えます。

curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"${MODEL_ID}"'",
    "store": true,
    "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
    "input": [{
      "type": "user_input",
      "content": [{
        "type": "text",
        "text": "Can you elaborate on that?"
      }]
    }]
  }'

サーバー送信イベントを使用して出力をストリーミングする

REST 経由で増分アップデートをストリーミングするには、JSON リクエストの本文に "stream": true を含めます。

curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"${MODEL_ID}"'",
    "stream": true,
    "input": [{
      "type": "user_input",
      "content": [{
        "type": "text",
        "text": "Write a long story about space travel."
      }]
    }]
  }'

"stream": true が設定されている場合、サーバーは Transfer-Encoding: chunked と Content-Type: text/event-stream(サーバー送信イベント)で応答します。ストリーム内の各イベントには、event_type とステップ デルタの内容を含む JSON ペイロードを含む data: 接頭辞が含まれています。curl は、HTTP 接続を自動的に開いたままにし、インタラクションが完了するまで、受信チャンクをリアルタイムで stdout に書き込みます。

マネージド エージェントをバックグラウンドで実行する

REST を介して長時間実行マネージド エージェント タスクを非同期で開始するには、ターゲット agent を指定し、"background": true を設定して、"environment": "remote" を構成します。

curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "agent": "'"${AGENT_ID}"'",
    "environment": "remote",
    "background": true,
    "input": [{
      "type": "user_input",
      "content": [{
        "type": "text",
        "text": "Analyze competitive positioning for commercial solar energy providers."
      }]
    }]
  }'

次のステップ

Interactions API、組み込みツール、グラウンディングの詳細については、次のリソースをご覧ください。