Antigravity Agent

Antigravity 智能体是 Gemini API 上的通用托管式智能体。只需一次 API 调用,您就能获得一个智能体,该智能体可在 Google 托管的您自己的安全 Linux 沙盒中进行推理、执行代码、管理文件和浏览网页。

它由 Gemini 3.5 Flash 提供支持,并使用与 Antigravity IDE 相同的框架。可通过 Interactions APIGoogle AI Studio 使用。

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Read Hacker News, summarize the top 10 stories, and save the results as a PDF.",
    environment="remote",
)

print(interaction.output_text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Read Hacker News, summarize the top 10 stories, and save the results as a PDF.",
    environment: "remote",
}, { timeout: 300000 });

console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "antigravity-preview-05-2026",
    "input": "Read Hacker News, summarize the top 10 stories, and save the results as a PDF.",
    "environment": "remote"
}'

功能

每次调用都可以预配一个 Linux 沙盒,并启动一个工具使用循环。智能体规划、行动、观察结果,然后重复此过程,直到任务完成。

  • 代码执行:运行 Bash、Python 和 Node.js 命令。安装软件包、运行测试、构建应用。
  • 文件管理:在沙盒中读取、写入、修改、搜索和列出文件。文件会在多次交互之间持久保留。
  • Web 访问权限:用于获取数据的 Google 搜索和网址提取。
  • 上下文压缩:自动上下文压缩(在约 13.5 万个令牌时触发),支持长时间运行的多轮会话,而不会丢失上下文或达到令牌限制。

如需了解多轮对话使用和流式传输,请参阅快速入门

支持的工具

默认情况下,代理可以访问 code_executiongoogle_searchurl_context。指定 environment 参数后,系统会自动启用文件系统工具。您还可以定义自定义函数,将智能体连接到您自己的 API 和工具。只有在自定义或限制默认集时,或者在添加自定义函数时,才需要指定 tools 参数。

工具 类型值 说明
代码执行 code_execution 运行 shell 命令(bash、Python、Node),并捕获 stdout/stderr。
Google 搜索 google_search 在公共网络中搜索。
网址上下文 url_context 提取和读取网页。
文件系统 (通过 environment 启用) 读取、写入、修改、搜索和列出沙盒中的文件。没有单独的工具类型;设置 environment 后会自动启用。
自定义函数 function 定义智能体可以请求执行的自定义函数。请参阅函数调用
远程 MCP 服务器 mcp_server 将外部 Model Context Protocol (MCP) 服务器注册为工具。请参阅 MCP 服务器

如需将代理限制为仅使用特定工具,请仅传递所需的工具:

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Search for the latest AI research papers on reasoning and summarize them.",
    environment="remote",
    tools=[
        {"type": "google_search"},
        {"type": "url_context"},
    ],
)

print(interaction.output_text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Search for the latest AI research papers on reasoning and summarize them.",
    environment: "remote",
    tools: [
        { type: "google_search" },
        { type: "url_context" },
    ],
}, { timeout: 300000 });

console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "agent": "antigravity-preview-05-2026",
    "input": "Search for the latest AI research papers on reasoning and summarize them.",
    "environment": "remote",
    "tools": [
        {"type": "google_search"},
        {"type": "url_context"}
    ]
}'

多模态输入

Antigravity 智能体支持多模态输入。目前,仅支持 textimage 输入。图片必须以内嵌的 base64 编码字符串 (data) 形式提供。

Python

import base64
from google import genai

client = genai.Client()

with open("path/to/chart.png", "rb") as f:
    image_bytes = f.read()

interaction_inline = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input=[
        {"type": "text", "text": "Analyze this chart and summarize the trends."},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode("utf-8"),
            "mime_type": "image/png",
        },
    ],
    environment="remote",
)

JavaScript


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

import * as fs from "node:fs";

const client = new GoogleGenAI({});
const base64Image = fs.readFileSync("path/to/chart.png", { encoding: "base64" });

const interactionInline = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: [
        { type: "text", text: "Analyze this chart and summarize the trends." },
        {
            type: "image",
            data: base64Image,
            mime_type: "image/png",
        },
    ],
    environment: "remote",
}, { timeout: 300000 });

REST

BASE64_IMAGE=$(base64 -w0 /path/to/chart.png)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d "{
    \"agent\": \"antigravity-preview-05-2026\",
    \"input\": [
        {\"type\": \"text\", \"text\": \"Analyze this chart and summarize the trends.\"},
        {
            \"type\": \"image\",
            \"mime_type\": \"image/png\",
            \"data\": \"$BASE64_IMAGE\"
        }
    ],
    \"environment\": \"remote\"
}"

函数调用

通过函数调用,您可以定义智能体可调用的自定义工具,将 Antigravity 智能体连接到外部 API 和数据库。如需了解一般概念,请参阅使用 Gemini API 进行函数调用

以下示例演示了 2 轮对话。智能体首先请求自定义 get_weather 函数调用,客户端执行该函数并在第二轮中返回结果。

Python

from google import genai

client = genai.Client()

# 1. Define the custom function
get_weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the current weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city and country, e.g. San Francisco, USA",
            }
        },
        "required": ["location"],
    },
}

# 2. Call the agent with the custom tool (Turn 1)
interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="What is the weather in Tokyo?",
    environment="remote",
    tools=[
        {"type": "code_execution"},  # Enable default code execution
        get_weather_tool,            # Add custom function
    ],
)

# Check if the agent requested a function call
if interaction.status == "requires_action":
    # Find function calls that do not have a matching function result.
    # Filesystem tools (like write_file) are also represented as function calls
    # but are executed automatically by the environment.
    executed_calls = {step.call_id for step in interaction.steps if step.type == "function_result"}
    pending_calls = [step for step in interaction.steps if step.type == "function_call" and step.id not in executed_calls]

    if pending_calls:
        fc_step = pending_calls[0]
        print(f"Function to call: {fc_step.name} (ID: {fc_step.id})")
        print(f"Arguments: {fc_step.arguments}")

        # 3. Execute the function locally (simulated get_weather()) and send the result back (Turn 2)
        function_result = {
            "temperature": 23,
            "unit": "celsius"
        }

        final_interaction = client.interactions.create(
            agent="antigravity-preview-05-2026",
            previous_interaction_id=interaction.id,  # Reference the interaction ID
            environment=interaction.environment_id,
            input=[
                {
                    "type": "function_result",
                    "name": fc_step.name,
                    "call_id": fc_step.id,
                    "result": function_result,
                }
            ],
        )

        print(final_interaction.output_text)
        # Output: The current weather in Tokyo, Japan is 23°C (Celsius).
    else:
        print("No pending function calls.")
else:
    print(f"Interaction completed with status: {interaction.status}")

JavaScript

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

const client = new GoogleGenAI({});

// 1. Define the custom function
const get_weather_tool = {
  type: "function",
  name: "get_weather",
  description: "Gets the current weather for a given location.",
  parameters: {
    type: "object",
    properties: {
      location: {
        type: "string",
        description: "The city and country, e.g. San Francisco, USA",
      },
    },
    required: ["location"],
  },
};

// 2. Call the agent with the custom tool (Turn 1)
const interaction = await client.interactions.create({
  agent: "antigravity-preview-05-2026",
  input: "What is the weather in Tokyo?",
  environment: "remote",
  tools: [
    { type: "code_execution" },
    get_weather_tool,
  ],
}, { timeout: 300000 });

if (interaction.status === "requires_action") {
  // Find function calls that do not have a matching function result.
  // Filesystem tools (like write_file) are also represented as function calls
  // but are executed automatically by the environment.
  const executedCalls = new Set(
    interaction.steps
      .filter(s => s.type === "function_result")
      .map(s => s.call_id)
  );
  const pendingCalls = interaction.steps.filter(
    s => s.type === "function_call" && !executedCalls.has(s.id)
  );

  if (pendingCalls.length > 0) {
    const fcStep = pendingCalls[0];
    console.log(`Function to call: ${fcStep.name} (ID: ${fcStep.id})`);

    // 3. Execute the function locally (simulated get_weather()) and send the result back (Turn 2)
    const functionResult = {
      temperature: 23,
      unit: "celsius"
    };

    const finalInteraction = await client.interactions.create({
      agent: "antigravity-preview-05-2026",
      previous_interaction_id: interaction.id, // Reference the interaction ID
      environment: interaction.environment_id,
      input: [
        {
          type: "function_result",
          name: fcStep.name,
          call_id: fcStep.id,
          result: functionResult,
        }
      ],
    }, { timeout: 300000 });

    console.log(finalInteraction.output_text);
  } else {
    console.log("No pending function calls.");
  }
} else {
  console.log(`Interaction completed with status: ${interaction.status}`);
}

REST

# 1. Turn 1: Request function call
RESPONSE=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
      "agent": "antigravity-preview-05-2026",
      "input": "What is the weather in Tokyo?",
      "environment": "remote",
      "tools": [
          {"type": "code_execution"},
          {
              "type": "function",
              "name": "get_weather",
              "description": "Gets the current weather for a given location.",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {"type": "string"}
                  },
                  "required": ["location"]
              }
          }
      ]
  }')

# Extract interaction ID, environment ID, and call ID (requires jq)
INTERACTION_ID=$(echo $RESPONSE | jq -r '.id')
ENVIRONMENT_ID=$(echo $RESPONSE | jq -r '.environment_id')
CALL_ID=$(echo $RESPONSE | jq -r '.steps[] | select(.type=="function_call") | .id')

# 2. Turn 2: Send function result back using variables
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d "{
      \"agent\": \"antigravity-preview-05-2026\",
      \"previous_interaction_id\": \"$INTERACTION_ID\",
      \"environment\": \"$ENVIRONMENT_ID\",
      \"input\": [
          {
              \"type\": \"function_result\",
              \"name\": \"get_weather\",
              \"call_id\": \"$CALL_ID\",
              \"result\": {
                  \"temperature\": 23,
                  \"unit\": \"celsius\"
              }
          }
      ]
  }"

MCP 服务器

您可以通过注册远程 Model Context Protocol (MCP) 服务器,将 Antigravity 智能体连接到外部工具。代理支持通过可流式传输的 HTTP 连接到远程 MCP 服务器。

注册 MCP 服务器时,您必须在 tools 数组中指定以下字段:

字段 类型 是否必需 说明
type 字符串 必须为 "mcp_server"
name 字符串 服务器的唯一标识符。必须严格采用小写字母和数字(与 ^[a-z0-9_-]+$ 匹配)。
url 字符串 远程 MCP 服务器的端点网址。
headers 对象 随请求发送的自定义标头(例如,身份验证)。
allowed_tools 数组 允许执行的工具名称列表。如果省略,则允许使用所有工具。

Python

from google import genai

client = genai.Client()

# Register a remote HTTP MCP server
interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="What is the weather in Tokyo?",
    environment="remote",
    tools=[{
        "type": "mcp_server",
        "name": "weather", # Must be lowercase
        "url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
    }]
)

print(interaction.output_text)

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "What is the weather in Tokyo?",
    environment: "remote",
    tools: [{
        type: "mcp_server",
        name: "weather", // Must be lowercase
        url: "https://gemini-api-demos.uc.r.appspot.com/mcp"
    }]
}, { timeout: 300000 });

console.log(interaction.output_text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
      "agent": "antigravity-preview-05-2026",
      "input": "What is the weather in Tokyo?",
      "environment": "remote",
      "tools": [{
          "type": "mcp_server",
          "name": "weather",
          "url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
      }]
  }'

自定义代理

您可以通过自定义 Antigravity 智能体的指令、工具和环境来扩展该智能体。该代理支持一种文件系统原生自定义方法:您可以将 AGENTS.md 等文件(用于提供指令和技能)装载到 .agents/skills/ 下的沙盒中,也可以在互动时以内嵌方式传递配置。您可以内嵌迭代配置,然后在准备就绪后将其另存为受管理的代理。

如需详细了解如何构建自定义代理,请参阅构建受管理的代理

后台执行

涉及多步推理、代码执行或文件操作的智能体任务可能需要几分钟才能完成。使用 background=True 异步运行互动。该 API 会立即返回一个互动 ID,您需要轮询该 ID,直到状态为 completedfailed

Python

import time
from google import genai

client = genai.Client()

# 1. Start the interaction in the background
interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Run a complex analysis on the repository.",
    environment="remote",
    background=True,
)

print(f"Interaction started in background: {interaction.id}")

# 2. Poll for completion
while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(id=interaction.id)

if interaction.status == "completed":
    print(interaction.output_text)
else:
    print(f"Finished with status: {interaction.status}")

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Run a complex analysis on the repository.",
    environment: "remote",
    background: true,
});

console.log(`Interaction started in background: ${interaction.id}`);

let result = interaction;
while (result.status === "in_progress") {
    await new Promise(resolve => setTimeout(resolve, 5000));
    result = await client.interactions.get(interaction.id);
}

if (result.status === "completed") {
    console.log(result.output_text);
} else {
    console.log(`Finished with status: ${result.status}`);
}

REST

# 1. Start the interaction in the background
RESPONSE=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
      "agent": "antigravity-preview-05-2026",
      "input": "Run a complex analysis on the repository.",
      "environment": "remote",
      "background": true
  }')

INTERACTION_ID=$(echo $RESPONSE | jq -r '.id')

# 2. Poll for results (repeat until status is "completed")
curl -s -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

后台执行需要 store=True,这是默认设置。如需了解在后台执行期间的实时进度更新,请参阅流式后台互动

您可以使用 cancel 方法取消正在运行的后台互动。

Python

client.interactions.cancel(id="INTERACTION_ID")

JavaScript

await client.interactions.cancel({ id: "INTERACTION_ID" });

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID:cancel" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

在后台执行的多轮对话

当后台互动涉及有状态的工具(例如在沙盒中执行代码)时,请使用已完成互动的 environment_id 在同一环境中继续操作。这样可确保代理从上次中断的地方继续运行,同时所有文件和状态保持不变。

Python

import time
from google import genai

client = genai.Client()

# First turn: run a task in the background
interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Clone https://github.com/google/generative-ai-python and run its tests.",
    environment="remote",
    background=True,
)

while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(id=interaction.id)

# Second turn: continue in the same environment
followup = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Fix any failing tests and re-run them.",
    previous_interaction_id=interaction.id,
    environment=interaction.environment_id,
    background=True,
)

while followup.status == "in_progress":
    time.sleep(5)
    followup = client.interactions.get(id=followup.id)

print(followup.output_text)

JavaScript

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

const client = new GoogleGenAI({});

// First turn: run a task in the background
let interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Clone https://github.com/google/generative-ai-python and run its tests.",
    environment: "remote",
    background: true,
});

while (interaction.status === "in_progress") {
    await new Promise(resolve => setTimeout(resolve, 5000));
    interaction = await client.interactions.get(interaction.id);
}

// Second turn: continue in the same environment
let followup = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Fix any failing tests and re-run them.",
    previous_interaction_id: interaction.id,
    environment: interaction.environment_id,
    background: true,
});

while (followup.status === "in_progress") {
    await new Promise(resolve => setTimeout(resolve, 5000));
    followup = await client.interactions.get(followup.id);
}

console.log(followup.output_text);

REST

# 1. Start first interaction in the background
RESPONSE=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
      "agent": "antigravity-preview-05-2026",
      "input": "Clone https://github.com/google/generative-ai-python and run its tests.",
      "environment": "remote",
      "background": true
  }')

INTERACTION_ID=$(echo $RESPONSE | jq -r '.id')

# 2. Poll until completed (repeat until status is "completed")
RESULT=$(curl -s -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/$INTERACTION_ID" \
  -H "x-goog-api-key: $GEMINI_API_KEY")

ENVIRONMENT_ID=$(echo $RESULT | jq -r '.environment_id')

# 3. Continue in the same environment
curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Api-Revision: 2026-05-20" \
  -d "{
      \"agent\": \"antigravity-preview-05-2026\",
      \"input\": \"Fix any failing tests and re-run them.\",
      \"previous_interaction_id\": \"$INTERACTION_ID\",
      \"environment\": \"$ENVIRONMENT_ID\",
      \"background\": true
  }"

环境

每次调用都会创建或重复使用 Linux 沙盒。environment 参数有三种形式:

表单 说明
"remote" 使用默认设置配置全新的沙盒。
"env_abc123" 按 ID 重用现有环境,保留所有文件和状态。
{...} 具有自定义来源和网络规则的完整 EnvironmentConfig

如需详细了解来源(Git、GCS、内嵌)、网络、生命周期和资源限制,请参阅环境

适用范围和定价

Antigravity 智能体现已在 Google AI Studio 和 Gemini API 中通过 Interactions API 提供预览版。

价格遵循随用随付模式,具体取决于底层 Gemini 模型 token 和智能体使用的工具。与生成单个输出的标准聊天请求不同,Antigravity 互动是一种智能体工作流。单个请求会触发推理、工具执行、代码运行和文件管理的自主循环。

估算费用

费用因任务复杂程度而异。智能体可自主确定需要多少次工具调用、代码执行和文件操作。以下估算值基于跑步活动。

任务类别 输入令牌 输出令牌 典型费用
研究与信息整合 10 万 - 50 万 1 万 - 4 万 0.30 美元 - 1.00 美元
文档和内容生成 10 万 - 50 万 1.5 万 - 5 万 0.30 美元 - 1.30 美元
流程和系统设计 10 万 - 40 万 1 万 - 3 万 0.25 美元 - 0.80 美元
数据处理和分析 30 万 - 300 万 3 万 - 15 万 0.70 美元 - 3.25 美元

通常会缓存 50% 到 70% 的输入令牌。包含多次工具调用的复杂智能体工作流在单次互动中可能会累积 300 万到 500 万个令牌,费用最高可达 5 美元左右。

在预览版期间,环境计算资源(CPU、内存、沙盒执行)不计费

限制

  • 预览版状态:Antigravity 智能体和 Interactions API。功能和架构可能会发生变化。
  • 不支持的生成配置:以下参数不受支持,并会返回 400 错误:temperaturetop_ptop_kstop_sequencesmax_output_tokens
  • 结构化输出:Antigravity 智能体不支持结构化输出。
  • 不可用的工具file_searchcomputer_usegoogle_maps 尚不受支持。
  • 远程 MCP 限制:不支持服务器发送的事件 (SSE) 传输(请使用可流式传输的 HTTP)。此外,服务器 name 必须严格采用小写字母和数字(使用大写字母会触发一般性 400 Bad Request 错误)。
  • 文件系统工具:目前没有文件系统工具。它是 environment 的一部分。
  • 商店要求:使用 background=True 执行代理需要 store=True
  • 仅支持有状态的函数调用:函数调用仅在有状态模式下受支持。您必须使用 previous_interaction_id 继续对话轮次;不支持手动重建历史记录(无状态模式)。
  • 不支持的多模态类型。目前不支持音频、视频和文档输入。仅允许使用文字和图片。

后续步骤