Agente de Antigravity

El agente de Antigravity es un agente administrado de uso general en la API de Gemini. Una sola llamada a la API te proporciona un agente que razona, ejecuta código, administra archivos y navega por la Web dentro de tu propia zona de pruebas segura de Linux, alojada por Google.

Funciona con Gemini 3.5 Flash y usa el mismo arnés que el IDE de Antigravity. Está disponible a través de la API de Interactions y Google 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" \
-H "Api-Revision: 2026-05-20" \
-d '{
    "agent": "antigravity-preview-05-2026",
    "input": "Read Hacker News, summarize the top 10 stories, and save the results as a PDF.",
    "environment": "remote"
}'

Funciones

Cada llamada puede aprovisionar una zona de pruebas de Linux y comienza un bucle de uso de herramientas. El agente planifica, actúa, observa los resultados y repite hasta que se completa la tarea.

  • Ejecución de código: Ejecuta comandos de Bash, Python y Node.js. Instala paquetes, ejecuta pruebas y compila apps.
  • Administración de archivos: Lee, escribe, edita, busca y enumera archivos en la zona de pruebas. Los archivos persisten en todas las interacciones.
  • Acceso web: Búsqueda de Google y recuperación de URL para obtener datos.
  • Compresión de contexto: Compresión automática de contexto (activada en ~135, 000 tokens) para admitir sesiones de varios turnos de larga duración sin perder el contexto ni alcanzar los límites de tokens.

Consulta la guía de inicio rápido para obtener información sobre el uso de varios turnos y la transmisión.

Herramientas compatibles

De forma predeterminada, el agente tiene acceso a code_execution, google_search y url_context. Las herramientas del sistema de archivos se habilitan automáticamente cuando especificas el parámetro environment. También puedes definir funciones personalizadas para conectar el agente a tus propias APIs y herramientas. Solo necesitas especificar el parámetro tools cuando personalizas o restringes el conjunto predeterminado, o cuando agregas funciones personalizadas.

Herramienta Valor del tipo Descripción
Ejecución de código code_execution Ejecuta comandos de shell (bash, Python, Node) con captura de stdout/stderr.
Búsqueda de Google google_search Busca en la Web pública.
Contexto de URL url_context Recupera y lee páginas web.
Sistema de archivos (habilitado a través de environment) Lee, escribe, edita, busca y enumera archivos en la zona de pruebas. No hay un tipo de herramienta independiente; se habilita automáticamente cuando se establece environment.
Funciones personalizadas function Define funciones personalizadas que el agente puede solicitar para ejecutar. Consulta Llamadas a funciones.

Para limitar el agente a herramientas específicas, pasa solo las que necesites:

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" \
-H "Api-Revision: 2026-05-20" \
-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"}
    ]
}'

Entrada multimodal

El agente de Antigravity admite entradas multimodales. Actualmente, solo se admiten las entradas text y image. Las imágenes se deben proporcionar como cadenas codificadas en base64 intercaladas (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" \
-H "Api-Revision: 2026-05-20" \
-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\"
}"

Llamada a función

La llamada a función te permite conectar el agente de Antigravity a APIs y bases de datos externas mediante la definición de herramientas personalizadas que el agente puede invocar. Para obtener conceptos generales, consulta Llamada a función con la API de Gemini.

En el siguiente ejemplo, se muestra una interacción de 2 turnos. Primero, el agente solicita una llamada a la función get_weather personalizada, y el cliente la ejecuta y muestra el resultado en el segundo turno.

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" \
  -H "Api-Revision: 2026-05-20" \
  -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" \
  -H "Api-Revision: 2026-05-20" \
  -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\"
              }
          }
      ]
  }"

Personaliza el agente

Puedes extender el agente de Antigravity personalizando sus instrucciones, herramientas y entorno. El agente admite un enfoque nativo del sistema de archivos para la personalización: puedes activar archivos como AGENTS.md para obtener instrucciones y habilidades en .agents/skills/ directamente en la zona de pruebas o pasar la configuración intercalada en el momento de la interacción. Puedes iterar en tu configuración intercalada y, luego, guardarla como un agente administrado cuando estés listo.

Para obtener detalles completos sobre cómo compilar agentes personalizados, consulta Compila agentes administrados.

Entornos

Cada llamada crea o reutiliza una zona de pruebas de Linux. El parámetro environment toma tres formas:

Técnica Descripción
"remote" Aprovisiona una zona de pruebas nueva con la configuración predeterminada.
"env_abc123" Reutiliza un entorno existente por ID y conserva todos los archivos y el estado.
{...} EnvironmentConfig completo con fuentes personalizadas y reglas de red.

Consulta Entornos para obtener detalles sobre las fuentes (Git, GCS, intercaladas), las redes, el ciclo de vida y los límites de recursos.

Disponibilidad y precios

El agente de Antigravity está disponible en versión preliminar a través de la API de Interactions en Google AI Studio y la API de Gemini.

Los precios siguen un modelo de pago por uso basado en los tokens del modelo de Gemini subyacente y las herramientas que usa el agente. A diferencia de una solicitud de chat estándar que produce una sola salida, una interacción de Antigravity es un flujo de trabajo basado en agentes. Una sola solicitud activa un bucle autónomo de razonamiento, ejecución de herramientas, ejecución de código y administración de archivos.

Costos estimados

Los costos varían según la complejidad de la tarea. El agente determina de forma autónoma cuántas llamadas a herramientas, ejecuciones de código y operaciones de archivos son necesarias. Las siguientes estimaciones se basan en las ejecuciones.

Categoría de tarea Tokens de entrada Tokens de salida Costo habitual
Investigación y síntesis de información 100,000–500,000 10,000–40,000 $0.30–$1.00
Generación de documentos y contenido 100,000–500,000 15,000–50,000 $0.30–$1.30
Diseño de procesos y sistemas 100,000–400,000 10,000–30,000 $0.25–$0.80
Procesamiento y análisis de datos 300,000–3,000,000 30,000–150,000 $0.70–$3.25

Por lo general, se almacenan en caché entre el 50% y el 70% de los tokens de entrada. Los flujos de trabajo complejos basados en agentes con muchas llamadas a herramientas pueden acumular entre 3 y 5 millones de tokens en una sola interacción, con costos de hasta ~$5.

El procesamiento del entorno (CPU, memoria, ejecución de zona de pruebas) no se factura durante el período de versión preliminar.

Limitaciones

  • Estado de la versión preliminar: El agente de Antigravity y la API de Interactions están en versión preliminar. Las funciones y los esquemas pueden cambiar.
  • Configuración de generación no compatible: No se admiten los siguientes parámetros y muestran un error 400: temperature, top_p, top_k, stop_sequences, max_output_tokens.
  • Salida estructurada: El agente de Antigravity no admite salidas estructuradas.
  • Herramientas no disponibles: Aún no se admiten file_search, computer_use, google_maps y mcp.
  • Herramienta del sistema de archivos: No hay una herramienta del sistema de archivos en este momento. Forma parte del environment.
  • Segundo plano: El agente no admite el uso de background=True y requiere store=True.
  • Llamada a función solo con estado: La llamada a función solo se admite en el modo con estado. Debes usar previous_interaction_id para continuar el turno; no se admite la reconstrucción manual del historial (modo sin estado).
  • Tipos multimodales no compatibles. Por el momento, no se admiten las entradas de audio, video y documentos. Solo se permiten texto e imágenes.

¿Qué sigue?