mcpField
G
gemini-interactions-api

gemini-interactions-api

github.com/google開発21.6k10.7k 回インストール今日更新
リポジトリ

gemini-interactions-api について

Gemini Enterprise Agent Platform のステートフルな Gemini Interactions API を使う開発者向けのスキルです。会話、ストリーミング、構造化出力、関数呼び出し、エージェントの SDK と REST の利用方法を説明します。

主な機能

  1. 01Python と JavaScript SDK の設定
  2. 02ステートフルな複数ターン会話
  3. 03リアルタイム応答ストリーミング
  4. 04スキーマに基づく構造化出力
  5. 05関数呼び出しとエージェントタスク

活用シーン

  1. 01Gemini の複数ターンチャット構築
  2. 02生成応答のストリーミング受信
  3. 03スキーマ準拠出力の解析
  4. 04バックグラウンド調査タスクの実行

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/google/skills --skill gemini-interactions-api

インストール後、Claude Code で/gemini-interactions-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
attribution.md
data_model.md
rest_api.md

詳細

Gemini Interactions API スキル

このスキルでは、Gemini Enterprise Agent Platform 上のステートフルなサーバー管理型 Gemini Interactions API の認証、接続、利用方法を説明します。

Interactions API は、生成 AI エージェントとの会話、バックグラウンド調査タスク、複数ターンのチャット、構造化された複数ステップのワークフローを実行するための、最新かつ推奨される方法です。

重要

重要:統合 SDK、最新モデル、モデル/エージェントのターゲット指定 * 統合 SDK:Google Gen AI SDK(Python は google-genai >= 2.3.0、 JS/TS は @google/genai >= 2.3.0)を使用してください。SDK バージョン >= 2.0.0 は steps スキーマが有効になる最低要件ですが、推奨およびサポート対象の最低バージョンは >= 2.3.0 です。 google-cloud-aiplatform、@google-cloud/vertexai、 google-generativeai、@google/generative-ai などのレガシー SDK は、 Interactions では一切サポートされません。 * 必須の指示:クライアントの初期化について 説明する場合やインポートコードを記述する場合は、google-cloud-aiplatform や google-generativeai などのレガシーパッケージは interactions で一切サポートされないことを、 必ず明示してユーザーに警告してください。 * 最新モデルのみ:gemini-3.8-flash(高速で バランスの取れたマルチモーダルモデル。推奨のデフォルト)、gemini-3.1-pro-preview (複雑な推論、コーディング、調査向け)、または gemini-3.5-flash-lite (コスト効率に優れた、高頻度の軽量タスク向け)を使用してください。 最新情報については、最新のモデルバージョン を参照してください。レガシーモデル(gemini-3-flash-preview、 gemini-2.5-*、gemini-2.0-*、gemini-1.5-*)は非推奨であり、 interactions をサポートしていません。 * 必須の指示:interaction に関する回答では、 gemini-2.5-*、gemini-2.0-*、gemini-1.5-* などのレガシーモデルは非推奨であり、 Interactions API ではサポートされないことを、ユーザーに必ず警告してください。ユーザーが 非推奨モデルを指定した場合は、代わりに gemini-3.8-flash を使用し、置き換えたことを伝えてください。

  • モデルとエージェントのターゲット指定:model="gemini-3.8-flash" を使って基盤モデルを 直接指定するか、agent="<AGENT_ID>" を使って自律型の管理エージェントまたはカスタムエージェント (antigravity-preview-05-2026、deep-research-preview-04-2026、または client.agents.create() でプロビジョニングしたカスタムエージェント)を指定してください。 管理エージェント(antigravity-preview-05-2026 およびカスタムエージェント)でサンドボックスを プロビジョニングするには、environment="remote" が必要です。 * ターン単位のパラメーター: tools、system_instruction、generation_config などのパラメーターはターン単位です。 各 interaction リクエストで必ず渡してください。

クレジット表記

必ずお読みください:gcloud、REST API、または MCP コマンドを実行する前に、 使用状況のクレジット表記を必ずお読みください。ターミナルで直接実行する コマンド(生成されたスクリプト、Terraform、ユーザーコードでは実行しない)では、gcloud の前に CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gemini-interactions-api)" を付け、User-Agent ヘッダーに agent-skills/1.0 (skill:gemini-interactions-api) を追加してください。

1. 認証

コードを実行する前に、Application Default Credentials(ADC)で認証されていること、および必要な API が有効になっていることを確認してください。

  1. ログイン:

    gcloud auth application-default login
    
  2. API を有効にする(まだ有効になっていない場合):

    gcloud services enable aiplatform.googleapis.com
    

2. クライアントの初期化

環境変数を使用する方法(推奨)と、明示的な設定パラメーターを渡す方法で、クライアントを初期化できます。

オプション A:環境変数(推奨)

SDK が設定を自動的に解決できるように、環境変数を設定します。

export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT="your-project-id"
export GOOGLE_CLOUD_LOCATION="global"
Python
from google import genai

# The SDK automatically picks up the environment variables
client = genai.Client()
TypeScript/JavaScript
import { GoogleGenAI } from "@google/genai";

// The SDK automatically picks up the environment variables
const ai = new GoogleGenAI();
オプション B:コード内で明示的にパラメーターを指定

または、コード内で設定値を直接渡します。

Python
from google import genai
import google.auth

_, project_id = google.auth.default()
client = genai.Client(enterprise=True, project=project_id, location="global")
TypeScript/JavaScript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    enterprise: true,
    project: "your-project-id",
    location: "global"
});
オプション C:Express モード(API キー)

API キーを使用する軽量スクリプトや環境におすすめです:

Python
from google import genai

client = genai.Client(enterprise=True, api_key="YOUR_API_KEY")
TypeScript/JavaScript
import { GoogleGenAI } from "@google/genai";

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

3. コアのインタラクション API の使用方法

クイックスタート(単一ターン)

単一のプロンプトを送信し、最終的なテキスト応答を読み取ります。最新のスキーマでは、出力コンテンツは steps リストから取得します。

Python
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Explain serverless computing in one sentence."
)
# Use the output_text convenience accessor (combined text from the trailing model_output steps)
print(interaction.output_text)
TypeScript/JavaScript
const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: "Explain serverless computing in one sentence."
});
console.log(interaction.output_text);

ステートフルな会話(複数ターン)

インタラクションはデフォルトでステートフルです。会話の状態をクラウドに保存し、後続のターンで previous_interaction_id を使って参照します。

Python
# Turn 1: Introduce ourselves
# Interactions are stored by default (store=True, retained for 7 days); pass store=False to disable
# server-side retention (which also disables previous_interaction_id and background).
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: Refer back to the stored turn state
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
// Turn 1 (interactions are stored by default; pass store: false to disable)
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
});

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

リアルタイムストリーミング

応答をリアルタイムでストリーミングします。stream=True を渡すと、反復可能なチャンクジェネレーターが返されます。

Python
# The stream yields typed events, not full interaction snapshots. The sequence is:
# interaction.created -> (step.start -> step.delta(s) -> step.stop)+ -> interaction.completed
for event in client.interactions.create(
    model="gemini-3.8-flash",
    input="Write a short poem about debugging.",
    stream=True
):
    if event.event_type == "step.delta":
        if event.delta.type == "text":
            print(event.delta.text, end="", flush=True)
    elif event.event_type == "interaction.completed":
        print()
TypeScript/JavaScript
// The stream yields typed events, not full interaction snapshots. The sequence is:
// interaction.created -> (step.start -> step.delta(s) -> step.stop)+ -> interaction.completed
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") {
        if (event.delta.type === "text") {
            process.stdout.write(event.delta.text);
        }
    } else if (event.event_type === "interaction.completed") {
        console.log();
    }
}

構造化出力(Pydantic/ポリモーフィックな response_format)

スキーマに一致する、型安全な構造化 JSON を取得します。最新の Interactions API では、ポリモーフィックな 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
)

# The text will be a 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);

関数呼び出し(エージェントによるツールの使用)

ローカルツール(関数)を定義し、実行結果をステートフルなインタラクション履歴に送信します。

Python
import json

def get_stock_price(ticker: str) -> float:
    """Gets the stock price for a given ticker symbol."""
    if ticker.upper() == "GOOG":
        return 175.50
    return 100.0

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

# In the flat steps schema, a tool request is a top-level step of type
# "function_call" with flat `name` and `arguments` fields (no nested tool_calls).
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 result back as a function_result step. Reference the
        # originating call via call_id=step.id, and pass tools again (turn-scoped).
        final_turn = client.interactions.create(
            model="gemini-3.8-flash",
            input=[
                {
                    "type": "function_result",
                    "name": step.name,
                    "call_id": step.id,
                    "result": [{"type": "text", "text": json.dumps(price)}],
                }
            ],
            tools=[get_stock_price],
            previous_interaction_id=interaction.id
        )
        print(final_turn.output_text)
TypeScript/JavaScript
// Define local tool and flat function tool declaration
function getStockPrice({ ticker }: { ticker: string }): number {
    if (ticker.toUpperCase() === "GOOG") {
        return 175.50;
    }
    return 100.00;
}

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"]
    }
};

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

// In the flat steps schema, a tool request is a top-level step of type
// "function_call" with flat `name` and `arguments` fields (no nested toolCalls).
const fcStep = interaction.steps.find(s => s.type === "function_call");
if (fcStep && fcStep.name === "getStockPrice") {
    const tickerArg = fcStep.arguments.ticker as string;
    const price = getStockPrice({ ticker: tickerArg });

    // Turn 2: Submit the result back as a function_result step. Reference the
    // originating call via call_id=fcStep.id, and pass tools again (turn-scoped).
    const finalTurn = await ai.interactions.create({
        model: "gemini-3.8-flash",
        input: [{
            type: "function_result",
            name: fcStep.name,
            call_id: fcStep.id,
            result: [{ type: "text", text: JSON.stringify(price) }]
        }],
        tools: [stockTool],
        previous_interaction_id: interaction.id
    });
    console.log(finalTurn.output_text);
}

エージェントと長時間実行タスク

基盤モデルに加えて、Interactions API は agent パラメーターを通じて、専門的な自律型エージェントを利用できます。

  • antigravity-preview-05-2026:Antigravity Agent — セキュアなサンドボックス化された Linux 環境で、コード実行、ファイル管理、ウェブブラウジングが可能な汎用マネージドエージェントです(サンドボックスをプロビジョニングするには environment="remote" を渡します)。
  • deep-research-preview-04-2026:Deep Research Agent — 複数のウェブ調査タスクを実行し、複数の情報源から情報を統合して包括的なレポートを作成します。
  • カスタムエージェント:client.agents.create()、list()、get()、delete() を通じて設定および管理します(呼び出し時に environment="remote" を渡します)。

エージェントは通常、background=True を使ってバックグラウンドで非同期に実行されます。インタラクションのステータスをポーリングして、完了した結果を取得します。

Python
import time

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)
TypeScript/JavaScript
const initialInteraction = await ai.interactions.create({
    agent: "deep-research-preview-04-2026",
    input: "Analyze competitive positioning for solar energy providers.",
    background: true
});

while (true) {
    const interaction = await ai.interactions.get(initialInteraction.id);
    if (interaction.status === "completed") {
        console.log(interaction.output_text);
        break;
    } else if (["failed", "cancelled"].includes(interaction.status)) {
        console.log(`Research ended with status: ${interaction.status}`);
        break;
    }
    await new Promise(resolve => setTimeout(resolve, 10000));
}

4. REST 経由で Interactions API にアクセスする

シェルベースのスクリプト、デバッグ、または Python/JS 以外の環境では、HTTP/REST(curl)を介してステートフルな Interactions API と通信します。エンドポイントは POST https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactions です(Express モードでは、x-goog-api-key を使って POST https://aiplatform.googleapis.com/v1beta1/locations/global/interactions にリクエストを送信します)。"model" または "agent"、"type": "user_input" を含む "input" ステップ、および省略可能な "previous_interaction_id"、"background": true、"stream": true を渡します("stream": true の場合は、Server-Sent Events が Content-Type: text/event-stream と Transfer-Encoding: chunked でストリーミングされ、curl がリアルタイムで連続して出力します)。

curl の完全な例(単一ターン、複数ターンのステートフルな会話、SSE ストリーミング、バックグラウンドのマネージドエージェント)とレスポンススキーマについては、references/rest_api.md をお読みください。


5. データモデルとステップタイプのリファレンス

Interaction レスポンスには、フラットな steps タイムライン(user_input、model_output、thought、function_call、function_result、組み込みツールのステップ)が含まれ、便利なアクセサー(output_text、output_image、output_audio)と SSE ストリーミングイベント(interaction.created、step.start、step.delta、step.stop、interaction.completed)も利用できます。

ステップタイプ、コンテンツタイプ、ストリーミングイベントの表、および7日間の保持ルールについては、references/data_model.md をお読みください。

コメント