Быстрый старт использования управляемых агентов

В этом руководстве вы узнаете, как создавать и использовать управляемых агентов в API Gemini с помощью агента Antigravity . Вы совершите свой первый звонок агенту, продолжите многоэтапный разговор, получите ответ в потоковом режиме, загрузите файлы из песочницы и будете работать с управляемым агентом Antigravity.

Выполните первое взаимодействие с агентом.

Один вызов API взаимодействия подготавливает песочницу Linux, запускает цикл работы агента и возвращает результат. Вам потребуется определить три параметра:

  • Передайте в качестве agent "antigravity-preview-05-2026", что соответствует текущей версии нашего предопределенного и универсального управляемого агента.
  • Определите environment="remote" , чтобы создать новую, чистую тестовую среду.
  • Создайте поле ввода, указав, что именно вы хотите, чтобы агент сделал.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
    environment="remote",
)

# Print the agent's final output
print(f"Interaction ID: {interaction.id}")
print(f"Environment ID: {interaction.environment_id}")
print(f"Output: {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: "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
    environment: "remote",
});

console.log(`Interaction ID: ${interaction.id}`);
console.log(`Environment ID: ${interaction.environment_id}`);

console.log(`Output: ${interaction.output_text}`);

ОТДЫХ

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": "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents."}],
    "environment": {"type": "remote"}
}'

В ответе возвращается объект Interaction . Сохраните interaction.id и interaction.environment_id , чтобы продолжить диалог в той же песочнице. Используйте interaction.output_text для доступа к окончательному ответу агента. interaction.steps перечисляет каждый шаг, предпринятый агентом (рассуждение, вызовы инструментов, выполнение кода).

Продолжить разговор (многоходовый)

API отслеживает два независимых параметра состояния:

  • Контекст разговора: история чата, трассировка логики, использование инструмента, использование previous_interaction_id .
  • Состояние среды: файлы, установленные пакеты и состояние песочницы, используется environment .

Для продолжения выполните оба действия в соответствующих местах:

Python

interaction_2 = client.interactions.create(
    agent="antigravity-preview-05-2026",
    previous_interaction_id=interaction.id,
    environment=interaction.environment_id,
    input="Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
)

print(interaction_2.output_text)

JavaScript

const interaction2 = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    previous_interaction_id: interaction.id,
    environment: interaction.environment_id,
    input: "Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
}, { timeout: 300_000 });

console.log(interaction2.output_text);

ОТДЫХ

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_from_step_1",
    "environment": "environment_id_from_step_1",
    "input": [{"type": "text", "text": "Now plot the Fibonacci sequence as a line chart and save it as chart.png."}]
}'

Файлы из первого хода ( fibonacci.txt ) сохраняются во втором ходу. Агент также сохраняет контекст разговора.

Вы можете комбинировать эти элементы по отдельности:

  • Очистить беседу, сохранить файлы: опустить previous_interaction_id , передавать идентификатор среды только с помощью environment для новой беседы в том же рабочем пространстве.
  • Сохранить диалог, новое рабочее пространство: Передайте previous_interaction_id , установите environment="remote" для создания новой песочницы.

Автоматическое сжатие контекста

В длительных, многоэтапных диалогах история шагов рассуждений, вызовов инструментов и содержимого больших файлов может быстро разрастаться и занимать значительное контекстное пространство. Чтобы предотвратить ошибки, связанные с ограничением количества токенов, и поддерживать фокус агента (предотвращая «застой контекста»), API управляемых агентов включает в себя встроенный этап сжатия контекста примерно после 135 000 токенов. Это происходит автоматически.

Трансляция ответа

Для длительных задач можно передавать ответ в потоковом режиме, чтобы наблюдать за работой агента в реальном времени:

Python

from google import genai

client = genai.Client()

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

for event in stream:
    print(event)

JavaScript

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

const client = new GoogleGenAI({});

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

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

ОТДЫХ

curl -N -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": "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
    "environment": "remote",
    "stream": true
}'

Функция Streaming возвращает итерируемый объект, содержащий изменения шагов, которые представляют собой пошаговый текст, токены рассуждений и обновления вызовов инструментов. Подробнее о том, как передавать ответы в потоковом режиме, см. в руководстве по Streaming .

Загрузка файлов из окружающей среды

Когда агент создает файлы внутри песочницы, загрузите их, используя API файлов с помощью прямого HTTP-запроса (метода SDK пока нет):

Python

import os
import requests
import tarfile

env_id = interaction.environment_id
api_key = os.environ["GEMINI_API_KEY"]

response = requests.get(
    f"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download",
    params={"alt": "media"},
    headers={"x-goog-api-key": api_key},
    allow_redirects=True,
)

with open("snapshot.tar", "wb") as f:
    f.write(response.content)

with tarfile.open("snapshot.tar") as tar:
    tar.extractall(path="extracted_snapshot")

JavaScript

import fs from "fs";
import { execSync } from "child_process";

const envId = interaction.environment_id;
const apiKey = process.env.GEMINI_API_KEY || "";

const url = `https://generativelanguage.googleapis.com/v1beta/files/environment-${envId}:download?alt=media`;
const response = await fetch(url, {
    headers: {
        "x-goog-api-key": apiKey,
    },
});

if (!response.ok) {
    throw new Error(`Failed to download file: ${response.statusText}`);
}

const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync("snapshot.tar", buffer);

if (!fs.existsSync("extracted_snapshot")) {
    fs.mkdirSync("extracted_snapshot");
}
execSync("tar -xf snapshot.tar -C extracted_snapshot");

console.log(fs.readdirSync("extracted_snapshot"));

ОТДЫХ

curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o snapshot.tar

tar -xf snapshot.tar -C extracted_snapshot

Сохранить управляемого агента

На предыдущих шагах мы использовали стандартного агента Antigravity и настроили его непосредственно в коде. После того, как вы внесете изменения в конфигурацию (инструкции, навыки и окружение), вы можете сохранить ее как управляемый агент. Это позволит вам вызывать его по идентификатору без повторного выполнения настройки.

При сохранении агента вы определяете base_environment (либо из исходного кода, либо путем создания форка существующей среды). Агент будет использовать эту среду для каждого нового взаимодействия.

Из источников: Укажите источники непосредственно в коде или из других источников, таких как GitHub или Cloud Storage.

Python

agent = client.agents.create(
    id="fibonacci-analyst",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always include a chart and a summary table in your reports.",
            },
            {
                "type": "repository",
                "source": "https://github.com/your-org/skills",
                "target": ".agents/skills"
            }
        ],
    },
)

print(f"Saved agent: {agent.id}")

JavaScript

const agent = await client.agents.create({
    id: "fibonacci-analyst",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "Always include a chart and a summary table in your reports.",
            },
            {
                type: "repository",
                source: "https://github.com/your-org/skills",
                target: ".agents/skills"
            }
        ],
    },
});

console.log(`Saved agent: ${agent.id}`);

ОТДЫХ

curl -X POST "https://generativelanguage.googleapis.com/v1beta/agents" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
    "id": "fibonacci-analyst",
    "base_agent": "antigravity-preview-05-2026",
    "system_instruction": "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
    "base_environment": {
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always include a chart and a summary table in your reports."
            },
            {
                "type": "repository",
                "source": "https://github.com/your-org/skills",
                "target": ".agents/skills"
            }
        ]
    }
}'

Запустите управляемый агент.

После сохранения управляемого агента вы можете запустить его по идентификатору. Каждый запуск создает форк базовой среды, поэтому каждый запуск начинается с чистого листа:

Python

result = client.interactions.create(
    agent="fibonacci-analyst",
    input="Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
    environment="remote",
)

print(result.output_text)

JavaScript

const result = await client.interactions.create({
    agent: "fibonacci-analyst",
    input: "Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
    environment: "remote",
}, {
    timeout: 300_000,
});

console.log(result.output_text);

ОТДЫХ

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": "fibonacci-analyst",
    "environment": "remote",
    "input": "Generate the first 50 prime numbers, plot their distribution, and save a PDF report."
}'

Что дальше?