与代理互动

本指南介绍了如何使用 Interactions API 在 Agent Platform 上与 Managed Agents API 中的已部署智能体进行交互。您将了解如何与使用 Agents API 和预建的 Antigravity 基本代理构建的自定义代理互动,包括动态配置。本文还介绍了如何使用环境 ID (env_id) 管理和重复使用沙盒环境,以及如何在互动期间动态替换配置(例如 Model Context Protocol [MCP] 服务器)。

如需详细了解该 API,请参阅互动 API 参考文档。

准备工作

在开始与代理互动之前,请设置您的环境:

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud新手,请 创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 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

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

  4. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

    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 email address for a Google Account.

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

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

  8. Enable the Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

    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 email address for a Google Account.

    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.
  10. 如果您的代理使用 Google Cloud Model Context Protocol (MCP) 工具,请向您的用户账号和关联的服务账号授予 MCP Tool User (roles/mcp.toolUser) 角色。

与 Antigravity 智能体互动

在 Agent Platform 上使用 Managed Agents API 的最简单方法是直接与第一方 Antigravity 基本代理进行交互。您无需创建自定义代理资源,即可随时调用代理。

如需发起互动,请指定基本代理目标,例如 antigravity-preview-05-2026(或最新的预览版变体),并请求临时远程环境:

REST

请求变量

在调用 API 之前,请替换以下变量:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:互动所处的区域位置。仅支持 global 区域。

HTTP 方法和网址

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

请求 JSON 正文

{
  "stream": true,
  "background": true,
  "store": true,
  "agent": "antigravity-preview-05-2026",
  "environment": {
    "type": "remote"
  },
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "Who are you, can you execute python code? Show me an example."
        }
      ]
    }
  ]
}

curl 命令

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
      "stream": true,
      "background": true,
      "store": true,
      "agent": "antigravity-preview-05-2026",
      "environment": {"type": "remote"},
      "input": [
          {
              "type": "user_input",
              "content": [
                  {
                      "type": "text",
                      "text": "Who are you, can you execute python code? Show me an example."
                  }
              ]
          }
      ]
  }'

示例响应

在初始互动之后,该服务会返回流式响应。interaction.complete 数据中包含的 interaction.idenvironment_id 可用于后续调用,以保持会话状态。interaction.id 用于继续对话历史记录,而 environment_id 允许重复使用同一沙盒环境。如需了解详情,请参阅管理会话状态

event: interaction.complete
data: {
  "interaction": {
    "id": "1234567890",
    "status": "completed",
    "usage": {
      "total_tokens": 51132,
      "total_input_tokens": 48984,
      "input_tokens_by_modality": [
        {
          "modality": "text",
          "tokens": 48984
        }
      ],
      "total_output_tokens": 769,
      "output_tokens_by_modality": [
        {
          "modality": "text",
          "tokens": 769
        }
      ],
      "total_thought_tokens": 1379
    },
    "created": "2026-05-15T22:26:05Z",
    "updated": "2026-05-15T22:26:05Z",
    "environment_id": "env_CAE1234567890",
    "object": "interaction"
  },
  "event_type": "interaction.complete"
}

Python

在运行此代码之前,请设置“REST”标签页中描述的变量。

from google import genai

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

stream = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Who are you, can you execute python code? Show me an example.",
    environment={"type": "remote"},
    stream=True,
    background=True,
    store=True,
)

for event in stream:
    print(event)

流式响应会生成 InteractionSSEEvent 对象。最终的 interaction.complete 事件包含 environment_id 和互动 id,您可以在后续调用中重复使用这些内容,以保持会话状态和对话历史记录。如需了解详情,请参阅管理会话状态

JavaScript

在运行此代码之前,请设置“REST”标签页中描述的变量。

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

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

const stream = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Who are you, can you execute python code? Show me an example.",
    environment: { type: "remote" },
    stream: true,
    background: true,
    store: true,
});

for await (const event of stream) {
    console.log(event);
}

流式传输响应会生成事件对象。最终的 interaction.complete 事件包含 environment_id 和互动 id,您可以在后续调用中重复使用这些内容,以保持会话状态和对话历史记录。如需了解详情,请参阅管理会话状态

与使用 Agents API 创建的自定义代理互动

如需与按照创建和管理代理中所述创建的自定义代理互动,您必须使用其代理 ID 指定该代理。

如需详细了解如何检索或列出自定义代理以查找其 ID,请参阅列出代理

环境配置和初始化

与自定义代理互动时:

  • 默认行为:如果您使用默认环境创建代理,请在请求中指定 AGENT_ID

  • 明确定义环境:如果您在创建智能体时未定义环境配置,则需要在初始互动请求的 environment 块中明确定义环境。

    例如:

    "environment": {"type": "remote"}
    

您可以在初始互动 API 调用期间动态配置沙盒环境中的功能,以满足特定任务要求。例如:

  • 使用 Cloud Storage 附加技能:附加 Cloud Storage 存储分区,以将大量数据或持久性文件目录加载到容器文件系统中。

  • 使用技能注册表附加技能:提供自定义工具、脚本或预打包的智能体技能列表,以提供特定的功能或运行时工作流。请参阅技能注册表

如需查看环境配置结构的列表以及有关如何维护多轮对话状态的示例,请参阅使用环境 ID 管理会话状态

向自定义代理发送互动

通过指定代理 ID 向自定义代理发送互动:

REST

请求变量

在调用 API 之前,请替换以下变量:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:仅支持 global 区域。
  • AGENT_ID:已注册的代理资源的自定义标识符。如需详细了解如何检索或列出自定义代理以查找其 ID,请参阅列出代理

HTTP 方法和网址

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

请求 JSON 正文

{
  "stream": true,
  "background": true,
  "store": true,
  "agent": "AGENT_ID",
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "Tell me the name of python packages used for data analysis."
        }
      ]
    }
  ]
}

curl 命令

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
      "stream": true,
      "background": true,
      "store": true,
      "agent": "AGENT_ID",
      "input": [
          {
              "type": "user_input",
              "content": [
                  {
                      "type": "text",
                      "text": "Tell me the name of python packages used for data analysis."
                  }
              ]
          }
      ]
  }'

示例响应

在初始互动之后,该服务会返回流式响应。interaction.complete 数据中包含的 interaction.idenvironment_id 可用于后续调用,以保持会话状态。interaction.id 用于继续对话历史记录,而 environment_id 允许重复使用同一沙盒环境。如需了解详情,请参阅管理会话状态

data: {
  "interaction": {
    "id": "1234567890",
    "status": "completed",
    "usage": {
      "total_tokens": 7558,
      "total_input_tokens": 6822,
      "input_tokens_by_modality": [
        {
          "modality": "text",
          "tokens": 6822
        }
      ],
      "total_output_tokens": 278,
      "output_tokens_by_modality": [
        {
          "modality": "text",
          "tokens": 278
        }
      ],
      "total_thought_tokens": 458
    },
    "created": "2026-05-15T22:38:56Z",
    "updated": "2026-05-15T22:38:56Z",
    "environment_id": "env_CAE1234567890",
    "object": "interaction"
  },
  "event_type": "interaction.complete"
}

Python

在运行此代码之前,请设置“REST”标签页中描述的变量。

from google import genai

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

stream = client.interactions.create(
    agent="AGENT_ID",
    input="Tell me the name of python packages used for data analysis.",
    stream=True,
    background=True,
    store=True,
)

for event in stream:
    print(event)

JavaScript

在运行此代码之前,请设置“REST”标签页中描述的变量。

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

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

const stream = await client.interactions.create({
    agent: "AGENT_ID",
    input: "Tell me the name of python packages used for data analysis.",
    stream: true,
    background: true,
    store: true,
});

for await (const event of stream) {
    console.log(event);
}

管理会话状态和多轮互动

默认情况下,互动是无状态的,除非您以特定环境容器或对话历史记录为目标。在多轮助理流程中,您可以跨对话保留本地文件、代码执行上下文、系统修改、运行时安装的开源软件库和对话历史记录:

  • 继续对话:将上一次互动中的 ID 传递给 previous_interaction_id 参数。
  • 如需继续使用已创建的环境:请将上次互动返回的环境 ID 传递给 environment 参数。

您可以使用 environment 字段中的以下参数选择关键环境配置:

JSON 结构 说明
"environment": {"type": "remote"} 预配全新的标准沙盒环境。在初始互动期间使用此选项。
"environment": "env_CAEQ..." 重用现有的持久性沙盒容器,保留与此环境 ID 关联的所有库、脚本、文件和状态。
"environment": {"type": "remote", "sources": [{"type": "gcs", "source": "gs://YOUR_BUCKET/YOUR_FILE", "target": "YOUR_TARGET_PATH"}]} 预配新的远程沙盒,并使用指定来源(例如存储在 Google Cloud Storage 中的来源)中的自定义技能或文件预加载该沙盒。

如需发送后续互动请求,以重用同一沙盒容器并继续对话,请在 environment 字段中传递返回的 environment_id,并指定 previous_interaction_id。以下示例演示了在与代理互动时如何继续有状态会话。

REST

请求变量

在调用 API 之前,请替换以下变量:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:仅支持 global 区域。
  • AGENT_ID:已注册的代理资源(或 antigravity-preview-05-2026)的自定义标识符。
  • PREVIOUS_INTERACTION_ID:上一次互动返回的互动 ID。
  • ENV_ID:上一次互动返回的环境 ID。

HTTP 方法和网址

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

请求 JSON 正文

{
  "stream": true,
  "background": true,
  "store": true,
  "agent": "AGENT_ID",
  "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
  "environment": "ENV_ID",
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "What did I ask you before and what did you do?"
        }
      ]
    }
  ]
}

curl 命令

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
      "stream": true,
      "background": true,
      "store": true,
      "agent": "AGENT_ID",
      "previous_interaction_id": "PREVIOUS_INTERACTION_ID",
      "environment": "ENV_ID",
      "input": [
          {
              "type": "user_input",
              "content": [
                  {
                      "type": "text",
                      "text": "What did I ask you before and what did you do?"
                  }
              ]
          }
      ]
  }'

Python

在运行此代码之前,请设置“REST”标签页中描述的变量。

from google import genai

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

stream = client.interactions.create(
    agent="AGENT_ID",
    input="What did I ask you before and what did you do?",
    previous_interaction_id="PREVIOUS_INTERACTION_ID",
    environment="ENV_ID",
    stream=True,
    background=True,
    store=True,
)

for event in stream:
    print(event)

在 Python SDK 中,直接传递 environment_id 字符串作为 environment 参数,以重用现有的沙盒容器。使用 previous_interaction_id 继续对话记录。

JavaScript

在运行此代码之前,请设置“REST”标签页中描述的变量。

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

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

const stream = await client.interactions.create({
    agent: "AGENT_ID",
    input: "What did I ask you before and what did you do?",
    previous_interaction_id: "PREVIOUS_INTERACTION_ID",
    environment: "ENV_ID",
    stream: true,
    background: true,
    store: true,
});

for await (const event of stream) {
    console.log(event);
}

在 JavaScript SDK 中,直接将 environment_id 字符串作为 environment 参数传递,以重用现有的沙盒容器。使用 previous_interaction_id 继续对话记录。

在互动期间替换配置

虽然自定义智能体定义通常包含工具、技能和第三方连接的默认配置,但您可以根据每次互动动态调整这些定义,而无需修改底层智能体资源配置。

一个常见的使用场景是在运行时动态替换与 Model Context Protocol (MCP) 服务器的连接。在互动请求正文中指定的任何工具或 MCP 服务器都会在相应互动回合中完全替换智能体的预配置工具。

如需在互动时替换或定义 MCP 服务器,请在互动请求的 tools 列表中添加 mcp_server 类型工具:

REST

请求变量

在调用 API 之前,请替换以下变量:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION:互动的位置。仅支持 global 区域。
  • AGENT_ID:代理资源的自定义标识符。
  • MCP_SERVER_URL:新 MCP 服务器的远程 HTTP 网关网址。
  • MCP_SERVER_NAME:目标 MCP 主机网域的描述性标签。
  • MCP_HEADER_KEY:可选。标头键名称(例如 Authorization)。
  • MCP_HEADER_VALUE:可选。凭据值(例如 Bearer <token>)。

HTTP 方法和网址

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

请求 JSON 正文

{
  "stream": true,
  "background": true,
  "store": true,
  "agent": "agents/AGENT_ID",
  "input": [
    {
      "type": "user_input",
      "content": [
        {
          "type": "text",
          "text": "Analyze our database and summarize recent purchase events."
        }
      ]
    }
  ],
  "tools": [
    {
      "type": "mcp_server",
      "url": "MCP_SERVER_URL",
      "name": "MCP_SERVER_NAME",
      "headers": {
        "MCP_HEADER_KEY": "MCP_HEADER_VALUE"
      }
    }
  ]
}

curl 命令

curl -X POST "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/interactions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
     "stream": true,
     "background": true,
     "store": true,
     "agent": "agents/AGENT_ID",
     "input": [
         {
             "type": "user_input",
             "content": [
                 {
                     "type": "text",
                     "text": "Analyze our database and summarize recent purchase events."
                 }
             ]
         }
     ],
     "tools": [
         {
             "type": "mcp_server",
             "url": "MCP_SERVER_URL",
             "name": "MCP_SERVER_NAME",
             "headers": {
                 "MCP_HEADER_KEY": "MCP_HEADER_VALUE"
             }
         }
     ]
  }'

Python

在运行此代码之前,请设置“REST”标签页中描述的变量。

from google import genai

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

stream = client.interactions.create(
    agent="AGENT_ID",
    input="Analyze our database and summarize recent purchase events.",
    tools=[
        {
            "type": "mcp_server",
            "url": "MCP_SERVER_URL",
            "name": "MCP_SERVER_NAME",
            "headers": {
                "MCP_HEADER_KEY": "MCP_HEADER_VALUE"
            },
        }
    ],
    stream=True,
    background=True,
    store=True,
)

for event in stream:
    print(event)

JavaScript

在运行此代码之前,请设置“REST”标签页中描述的变量。

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

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

const stream = await client.interactions.create({
    agent: "AGENT_ID",
    input: "Analyze our database and summarize recent purchase events.",
    tools: [
        {
            type: "mcp_server",
            url: "MCP_SERVER_URL",
            name: "MCP_SERVER_NAME",
            headers: {
                "MCP_HEADER_KEY": "MCP_HEADER_VALUE",
            },
        },
    ],
    stream: true,
    background: true,
    store: true,
});

for await (const event of stream) {
    console.log(event);
}

后续步骤

概览

了解 Agent Platform 上的 Managed Agents API,这是一个配置驱动的 REST 优先环境,用于构建自主智能体。

参考文档

了解隔离的沙盒容器、权限和预安装的软件包/工具。