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 用法,涵盖对话、流式响应、结构化输出、函数调用与 Agent。

主要功能

  1. 01Python 和 JavaScript SDK 配置
  2. 02有状态多轮对话
  3. 03实时响应流式传输
  4. 04基于 Schema 的结构化输出
  5. 05函数调用与 Agent 任务

适用场景

  1. 01构建 Gemini 多轮对话
  2. 02流式接收生成响应
  3. 03解析符合 Schema 的输出
  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 Agent 对话、后台研究任务、多轮聊天和结构化多步骤工作流的现代推荐方式。

重要

关键:统一 SDK、最新模型以及模型 / Agent 目标选择 * 统一 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。旧版 SDK(例如 google-cloud-aiplatform、 @google-cloud/vertexai、google-generativeai 和 @google/generative-ai)严格不支持 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,并说明替换情况。* 模型和 Agent 目标选择:通过 model="gemini-3.8-flash" 直接指定基础模型,或使用 agent="<AGENT_ID>" 指定自主托管 Agent / 自定义 Agent(antigravity-preview-05-2026、deep-research-preview-04-2026,或通过 client.agents.create() 配置的自定义 Agent)。托管 Agent(antigravity-preview-05-2026 和自定义 Agent)需要 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)" 并将 agent-skills/1.0 (skill:gemini-interactions-api) 追加到 User-Agent 标头中。

1. 身份验证

运行任何代码之前,请确保已通过应用默认凭据(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:快捷模式(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);

函数调用(Agent 工具使用)

定义本地工具(函数),并将执行结果提交到有状态交互历史中。

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);
}

Agent 与长时间运行任务

除了基础模型,Interactions API 还可通过 agent 参数访问专用的自主 Agent:

  • antigravity-preview-05-2026:Antigravity Agent——通用托管 Agent,可在安全的沙盒 Linux 环境中执行代码、管理文件和浏览网页(传入 environment="remote" 以配置沙盒)。
  • deep-research-preview-04-2026:Deep Research Agent——执行多步骤网页研究任务,从多个来源综合信息并生成全面报告。
  • 自定义 Agent:通过 client.agents.create()、list()、get() 和 delete() 配置和管理(调用时传入 environment="remote")。

Agent 通常通过 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

对于基于 shell 的脚本、调试或非 Python/JS 环境,可通过 HTTP/REST(curl)与有状态 Interactions API 通信,地址为 POST https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/interactions(Express Mode 可使用 POST https://aiplatform.googleapis.com/v1beta1/locations/global/interactions,并附带 x-goog-api-key)。传入 "model" 或 "agent"、包含 "type": "user_input" 的 "input" 步骤,以及可选的 "previous_interaction_id"、"background": true 或 "stream": true(后者会通过 Content-Type: text/event-stream 和 Transfer-Encoding: chunked 流式传输服务器发送事件,curl 会持续实时打印这些事件)。

有关完整的 curl 示例(单轮、有状态多轮、SSE 流式传输和后台托管 Agent)及响应架构,请阅读 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。

评论

支持 Markdown