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 命令。安装软件包、运行测试、构建应用。
  • 文件管理:在沙盒中读取、写入、修改、搜索和列出文件。文件会在多次交互之间持久保留。
  • 网页访问权限: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("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、内嵌)、网络、生命周期和资源限制,请参阅环境

触发器

利用触发器,您可以安排代理按 cron 时间表自动运行。触发器将代理、环境、提示和时间表绑定到持久性资源,该资源无需人工干预即可触发。每次执行都会重复使用同一环境,因此在一次运行中创建的文件会保留下来,并对下一次运行可见。

创建触发器

通过指定 cron 时间表、时区和互动配置来创建触发器。触发器以 active 状态启动,并将在下一个匹配的 cron 时间触发。保存返回的 id,以便在后续调用中管理触发器。

Python

from google import genai

client = genai.Client()

trigger = client.triggers.create(
    schedule="0 9 * * *",
    time_zone="America/Argentina/Buenos_Aires",
    display_name="issue-solver",
    interaction={
        "agent": "antigravity-preview-05-2026",
        "input": "Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled 'accepted', skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/.",
        "environment": {
            "type": "remote",
            "network": {
                "allowlist": [
                    {
                        "domain": "api.github.com",
                        "transform": {
                            "Authorization": "Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                        },
                    },
                    {"domain": "github.com"},
                ]
            },
        },
    },
)

print(f"Trigger created: {trigger.id}")
print(f"Next run: {trigger.next_run_time}")

JavaScript

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

const client = new GoogleGenAI({});

const trigger = await client.triggers.create({
    schedule: "0 9 * * *",
    time_zone: "America/Argentina/Buenos_Aires",
    display_name: "issue-solver",
    interaction: {
        agent: "antigravity-preview-05-2026",
        input: [{
            type: "text",
            text: "Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled 'accepted', skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/.",
        }],
        environment: {
            type: "remote",
            network: {
                allowlist: [
                    {
                        domain: "api.github.com",
                        transform: {
                            "Authorization": "Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                        },
                    },
                    { domain: "github.com" },
                ],
            },
        },
    },
});

console.log(`Trigger created: ${trigger.id}`);
console.log(`Next run: ${trigger.next_run_time}`);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/triggers" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
      "schedule": "0 9 * * *",
      "time_zone": "America/Argentina/Buenos_Aires",
      "display_name": "issue-solver",
      "interaction": {
          "agent": "antigravity-preview-05-2026",
          "input": [{"type": "text", "text": "Review open PRs in my-org/my-app for new comments and address feedback. Close issues whose PRs were merged. Then check for new issues labeled accepted, skip any already tracked in /workspace/solved-issues/, fix the rest, and open a PR for each. Save reports to /workspace/solved-issues/."}],
          "environment": {
              "type": "remote",
              "network": {
                  "allowlist": [
                      {
                          "domain": "api.github.com",
                          "transform": {
                              "Authorization": "Bearer ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                          }
                      },
                      {"domain": "github.com"}
                  ]
              }
          }
      }
  }'

CreateTrigger 请求接受以下字段:

字段 类型 是否必需 说明
schedule 字符串 Cron 表达式(例如,0 * * * * 表示每小时,0 9 * * 1-5 表示工作日早晨)。
time_zone 字符串 IANA 时区(例如 UTCAmerica/Argentina/Buenos_Aires)。
display_name 字符串 触发器的简单易懂的名称。
max_consecutive_failures integer 触发器自动暂停前的最大失败次数。默认值:5。
execution_timeout_seconds integer 每次执行的超时时间(以秒为单位)。默认值:600。
interaction 对象 用于定义代理、输入、工具和环境的 CreateInteractionRequest

响应包括以下关键字段:

字段 类型 说明
id 字符串 触发器的唯一标识符。在所有后续操作中使用此 shell。
status 字符串 当前状态:activepauseddisabled
next_run_time 字符串 下一次预定执行的 ISO 8601 时间戳。
consecutive_failure_count integer 自上次成功以来连续执行失败的次数。

列出触发器

检索与您的项目关联的所有触发器。

Python

triggers = client.triggers.list()
for trigger in triggers.triggers:
    print(f"{trigger.id}: {trigger.display_name} ({trigger.status})")

JavaScript

const triggers = await client.triggers.list();
for (const trigger of triggers.triggers) {
    console.log(`${trigger.id}: ${trigger.display_name} (${trigger.status})`);
}

REST

curl -X GET "https://generativelanguage.googleapis.com/v1beta/triggers" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

获取触发器

获取单个触发器的完整配置和当前状态。

Python

trigger = client.triggers.get(id="TRIGGER_ID")
print(f"Schedule: {trigger.schedule}")
print(f"Next run: {trigger.next_run_time}")

JavaScript

const trigger = await client.triggers.get("TRIGGER_ID");
console.log(`Schedule: ${trigger.schedule}`);
console.log(`Next run: ${trigger.next_run_time}`);

REST

curl -X GET "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

暂停和恢复

您可以暂停触发器以停止预定执行,也可以恢复触发器以重新激活时间表。暂停不会影响手动执行。

Python

# Pause
client.triggers.update(id="TRIGGER_ID", status="paused")

# Resume
client.triggers.update(id="TRIGGER_ID", status="active")

JavaScript

// Pause
await client.triggers.update("TRIGGER_ID", { status: "paused" });

// Resume
await client.triggers.update("TRIGGER_ID", { status: "active" });

REST

# Pause
curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{"status": "paused"}'

# Resume
curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{"status": "active"}'

删除触发器

永久移除触发器。系统不会删除过往的执行历史记录。

Python

client.triggers.delete(id="TRIGGER_ID")

JavaScript

await client.triggers.delete("TRIGGER_ID");

REST

curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

立即运行触发器

按需触发触发器,无需等待下一个预定时间。即使触发器处于暂停状态,此功能也能正常运行。

Python

client.triggers.run(trigger_id="TRIGGER_ID")

JavaScript

await client.triggers.run("TRIGGER_ID");

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID/executions" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

列出执行任务

查看触发器的执行历史记录。每次执行都包含一个 status、时间戳、一个可用于获取完整互动输出的 interaction_id,以及一个用于确认所有运行都共享同一沙盒的 environment_id

Python

executions = client.triggers.list_executions(trigger_id="TRIGGER_ID")
for ex in executions.trigger_executions:
    print(f"{ex.id}: {ex.status} ({ex.start_time} - {ex.end_time})")

# Fetch the full interaction for an execution
interaction = client.interactions.get(id=ex.interaction_id)
print(interaction.output_text)

JavaScript

const executions = await client.triggers.listExecutions("TRIGGER_ID");
for (const ex of executions.trigger_executions) {
    console.log(`${ex.id}: ${ex.status} (${ex.start_time} - ${ex.end_time})`);
}

// Fetch the full interaction for an execution
const interaction = await client.interactions.get(ex.interaction_id);
console.log(interaction.output_text);

REST

curl -X GET "https://generativelanguage.googleapis.com/v1beta/triggers/TRIGGER_ID/executions" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

适用范围和定价

Antigravity 智能体现已推出预览版,可通过 Google AI Studio 中的 Interactions API 和 Gemini API(免费层级和付费层级项目均可使用)使用。

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

反重力互动会运行多轮自主循环,并可能会消耗大量 token。为请求设置预算控制,以限制令牌用量。您还可以通过 SSE 流式传输实时监控进度,或取消正在运行的请求。

预算控制

agent_config 内(使用 "type": "antigravity")设置 max_total_tokens,以限制一次互动可消耗的 token 总数(输入 + 输出 + 思考)。缓存的令牌不计入此限额。当代理达到限制时,互动会停止并返回 status: "incomplete"。此限制是尽力而为的:实际用量可能会略微超出此限制,具体取决于代理在各步骤之间检查预算的时间。

agent_config 中,将互动请求的预算设置为 agentinput

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Analyze the dataset in /workspace/data.csv and generate a summary report.",
    agent_config={
        "type": "antigravity",
        "max_total_tokens": 50000
    },
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": "/workspace/data.csv",
                "content": "id,name,value\n1,alpha,100\n2,beta,200\n",
            }
        ],
    }
)
print(f"Status: {interaction.status}")  # "incomplete" if budget was hit
print(f"Tokens used: {interaction.usage.total_tokens}")

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Analyze the dataset in /workspace/data.csv and generate a summary report.",
    agent_config: {
        type: "antigravity",
        max_total_tokens: 50000
    },
    environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: "/workspace/data.csv",
                content: "id,name,value\n1,alpha,100\n2,beta,200\n",
            },
        ],
    },
});
console.log(`Status: ${interaction.status}`);
console.log(`Tokens used: ${interaction.usage.total_tokens}`);

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": "Analyze the dataset in /workspace/data.csv and generate a summary report.",
    "agent_config": {
      "type": "antigravity",
      "max_total_tokens": 50000
    },
    "environment": {
      "type": "remote",
      "sources": [
        {
          "type": "inline",
          "target": "/workspace/data.csv",
          "content": "id,name,value\n1,alpha,100\n2,beta,200\n"
        }
      ]
    }
  }'

继续未完成的互动

当互动返回 status: "incomplete" 时,智能体的工作和上下文会保留。发送引用原始互动 idenvironment_id 的新互动,以便从上次中断的地方继续。新互动有自己的 max_total_tokens 预算。

Python

# Continue from where the agent stopped
continuation = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="continue",
    previous_interaction_id=interaction.id,
    environment=interaction.environment_id,
    agent_config={
        "type": "antigravity",
        "max_total_tokens": 50000
    }
)
print(f"Status: {continuation.status}")

JavaScript

const continuation = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "continue",
    previous_interaction_id: interaction.id,
    environment: interaction.environment_id,
    agent_config: {
        type: "antigravity",
        max_total_tokens: 50000
    }
});
console.log(`Status: ${continuation.status}`);

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": "continue",
    "previous_interaction_id": "INTERACTION_ID",
    "environment": "ENVIRONMENT_ID",
    "agent_config": {
      "type": "antigravity",
      "max_total_tokens": 50000
    }
  }'

估算费用

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

任务类别 输入令牌 输出令牌 典型费用
研究与信息整合 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% 的输入 token。包含多次工具调用的复杂智能体工作流在单次互动中可能会累积 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 继续对话轮次;不支持手动重建历史记录(无状态模式)。
  • 不支持的多模态类型。目前不支持音频、视频和文档输入。仅允许使用文字和图片。

后续步骤