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

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

Настройте антигравитационного агента

Самый быстрый способ создать собственного агента — передать конфигурацию непосредственно при создании нового взаимодействия без необходимости регистрации. Расширить функциональность агента можно тремя способами:

  • Системные инструкции : Передайте встроенный текст через system_instruction для формирования поведения.
  • Инструменты : Переопределить инструменты по умолчанию (Выполнение кода, Поиск, Контекст URL).
  • Файлы и навыки : Смонтируйте файлы, такие как AGENTS.md и SKILL.md в среду.

Вот пример передачи всех трёх параметров в одной строке:

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Analyze the Q1 revenue data and create a slide deck.",
    system_instruction="You are a data analyst. Always include visualizations and export results as PDF.",        
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always use matplotlib for charts. Include a summary table in every report.",
            },
            {
                "type": "inline",
                "target": ".agents/skills/slide-maker/SKILL.md",
                "content": "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results.",
            },
        ],
    },
)

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: "Analyze the Q1 revenue data and create a slide deck.",
    system_instruction: "You are a data analyst. Always include visualizations and export results as PDF.",        
    environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "Always use matplotlib for charts. Include a summary table in every report.",
            },
            {
                type: "inline",
                target: ".agents/skills/slide-maker/SKILL.md",
                content: "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results.",
            },
        ],
    },
}, { timeout: 300000 });

console.log(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": "Analyze the Q1 revenue data and create a slide deck.",
    "system_instruction": "You are a data analyst. Always include visualizations and export results as PDF.",
    "environment": {
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always use matplotlib for charts. Include a summary table in every report."
            },
            {
                "type": "inline",
                "target": ".agents/skills/slide-maker/SKILL.md",
                "content": "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results."
            }
        ]
    }
}'

Все определяется во время взаимодействия. Нет необходимости что-либо регистрировать предварительно. Агент Antigravity предоставляет среду выполнения (выполнение кода, управление файлами, веб-доступ) и ваши собственные уровни конфигурации.

Инструменты и инструкции по использованию системы

Вы можете настроить поведение и возможности агента для конкретного взаимодействия, используя параметры system_instruction и tools .

  • Системные инструкции : Используйте параметр system_instruction для передачи встроенного текста, определяющего поведение агента. Это идеально подходит для быстрых настроек, которые вы хотите изменить для каждого вызова. Файлы system_instruction и AGENTS.md являются аддитивными; оба применяются, если присутствуют.
  • Инструменты : По умолчанию агент Antigravity имеет доступ к code_execution , google_search и url_context . Вы можете переопределить этот список, передав параметр tools во время взаимодействия. Подробную информацию о доступных инструментах и ​​способах их использования см. в разделе «Агент Antigravity: Поддерживаемые инструменты» .

Настройка на основе файлов

Структура каталога агента

Хотя вы можете передавать конфигурацию непосредственно в файл, мы рекомендуем организовывать файлы вашего агента в структурированном каталоге. Это упростит управление, контроль версий и монтирование в среду агента.

Типичная директория проекта агента выглядит следующим образом:

my-agent/
├── AGENTS.md        # Instructions on how the agent should operate
├── skills/          # Custom skills (subfolders and SKILL.md files)
│   └── slide-maker/
│       └── SKILL.md
└── workspace/       # Initial data files and knowledge

Среда выполнения Antigravity сканирует папку .agents/ (и корневую папку среды выполнения) на наличие этих файлов.

AGENTS.md

Агент автоматически загружает файл .agents/AGENTS.md (или /.agents/AGENTS.md ) из среды выполнения в качестве системных инструкций при запуске. Используйте AGENTS.md для подробных определений пользователей, детальных рекомендаций и инструкций, которые вы хотите контролировать с помощью системы версионирования вместе с вашим кодом.

Подключите файл AGENTS.md , используя встроенный источник:

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Analyze the Q1 revenue data and create a report.",
    system_instruction="You are a data analyst. Always include visualizations and export results as PDF.",
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always use matplotlib for charts. Include a summary table in every report.",
            },
        ],
    },
)

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: "Analyze the Q1 revenue data and create a report.",
    system_instruction: "You are a data analyst. Always include visualizations and export results as PDF.",
    environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "Always use matplotlib for charts. Include a summary table in every report.",
            },
        ],
    },
}, { timeout: 300000 });

console.log(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": "Analyze the Q1 revenue data and create a report.",
      "system_instruction": "You are a data analyst. Always include visualizations and export results as PDF.",
      "environment": {
          "type": "remote",
          "sources": [
              {
                  "type": "inline",
                  "target": ".agents/AGENTS.md",
                  "content": "Always use matplotlib for charts. Include a summary table in every report."
              }
          ]
      }
  }'

Навыки: SKILL.md

Навыки — это файлы, расширяющие возможности агента. Разместите их в папке .agents/skills/<skill-name>/SKILL.md , и система автоматически обнаружит и зарегистрирует их.

.agents/
├── AGENTS.md
└── skills/
    └── slide-maker/
        └── SKILL.md

Запустите навык, используя встроенный источник:

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Create a presentation about our Q1 results.",
    system_instruction="You create presentations from data.",
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/skills/slide-maker/SKILL.md",
                "content": "---\nname: slide-maker\ndescription: Create HTML slide decks\n---\n# Slide Maker\n\nWhen asked to create a presentation:\n1. Analyze the input data\n2. Create an HTML slide deck with reveal.js\n3. Save to /workspace/output/slides.html",
            },
        ],
    },
)

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: "Create a presentation about our Q1 results.",
    system_instruction: "You create presentations from data.",
    environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/skills/slide-maker/SKILL.md",
                content: "---\nname: slide-maker\ndescription: Create HTML slide decks\n---\n# Slide Maker\n\nWhen asked to create a presentation:\n1. Analyze the input data\n2. Create an HTML slide deck with reveal.js\n3. Save to /workspace/output/slides.html",
            },
        ],
    },
}, { timeout: 300000 });

console.log(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": "Create a presentation about our Q1 results.",
      "system_instruction": "You create presentations from data.",
      "environment": {
          "type": "remote",
          "sources": [
              {
                  "type": "inline",
                  "target": ".agents/skills/slide-maker/SKILL.md",
                  "content": "---\nname: slide-maker\ndescription: Create HTML slide decks\n---\n# Slide Maker\n\nWhen asked to create a presentation:\n1. Analyze the input data\n2. Create an HTML slide deck with reveal.js\n3. Save to /workspace/output/slides.html"
              }
          ]
      }
  }'

Навыки, загруженные из папок .agents/skills/ и /.agents/skills/ , обнаруживаются автоматически.

Создайте управляемого агента

После того, как вы внесете изменения в конфигурацию, вы можете создать управляемый агент с помощью agents.create . Это позволит вам вызывать агента по идентификатору, не повторяя настройку каждый раз.

Из источников

Укажите base_agent , id , system_instruction и base_environment вместе с исходными файлами. Платформа создает новую песочницу с вашими файлами при каждом запуске. См. раздел «Среды» для получения информации о доступных типах исходных файлов (Git, GCS, inline).

Python

from google import genai

client = genai.Client()

agent = client.agents.create(
    id="data-analyst",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You are a data analyst. Always include visualizations and export results as PDF.",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always use matplotlib for charts. Include a summary table in every report.",
            },
            {
                "type": "inline",
                "target": ".agents/skills/slide-maker/SKILL.md",
                "content": "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results.",
            },
            {
                "type": "repository",
                "source": "https://github.com/my-org/analysis-templates",
                "target": "/workspace/templates",
            },
        ],
    },
)

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

JavaScript

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

const client = new GoogleGenAI({});

const agent = await client.agents.create({
    id: "data-analyst",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You are a data analyst. Always include visualizations and export results as PDF.",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "Always use matplotlib for charts. Include a summary table in every report.",
            },
            {
                type: "inline",
                target: ".agents/skills/slide-maker/SKILL.md",
                content: "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results.",
            },
            {
                type: "repository",
                source: "https://github.com/my-org/analysis-templates",
                target: "/workspace/templates",
            },
        ],
    },
});

console.log(`Created 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": "data-analyst",
    "base_agent": "antigravity-preview-05-2026",
    "system_instruction": "You are a data analyst. Always include visualizations and export results as PDF.",
    "base_environment": {
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "Always use matplotlib for charts. Include a summary table in every report."
            },
            {
                "type": "inline",
                "target": ".agents/skills/slide-maker/SKILL.md",
                "content": "---\nname: slide-maker\n---\n# Slide Maker\nCreate HTML slide decks from data analysis results."
            },
            {
                "type": "repository",
                "source": "https://github.com/my-org/analysis-templates",
                "target": "/workspace/templates"
            }
        ]
    }
}'

Из существующей среды (форка)

Продолжайте работу с базовым агентом Antigravity, пока среда не будет настроена должным образом (пакеты установлены, файлы на месте), затем создайте его форк в управляемый агент.

Python

from google import genai

client = genai.Client()

# Step 1: set up the environment interactively
interaction = client.interactions.create(
    agent="antigravity-preview-05-2026",
    input="Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.",
    environment="remote",
)

# Step 2: fork that environment into a managed agent

agent = client.agents.create(
    id="my-data-analyst",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You are a data analyst. Use the template at /workspace/template.py for all reports.",
    base_environment=interaction.environment_id,
)

print(f"Forked agent successfully: {agent.id}")

JavaScript

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

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    agent: "antigravity-preview-05-2026",
    input: "Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.",
    environment: "remote",
}, { timeout: 300000 });

const agent = await client.agents.create({
    id: "my-data-analyst",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You are a data analyst. Use the template at /workspace/template.py for all reports.",
    base_environment: interaction.environment_id,
});

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

ОТДЫХ

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": "Install pandas, matplotlib, and seaborn. Create an analysis template at /workspace/template.py.",
      "environment": "remote"
  }'

С использованием сетевых правил

Вы можете ограничить исходящий доступ или внедрить учетные данные при сохранении управляемого агента. Полную схему разрешенного списка, шаблоны учетных данных и подстановочные знаки см. в разделе «Среды: Настройка сети» .

В следующем примере создается агент issue-resolver , который может получить доступ только к GitHub и PyPI, при этом учетные данные для GitHub внедряются следующим образом:

Python

from google import genai

client = genai.Client()

agent = client.agents.create(
    id="issue-resolver",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "repository",
                "source": "https://github.com/my-org/backend",
                "target": "/workspace/repo",
            }
        ],
        "network": {
            "allowlist": [
                {
                    "domain": "api.github.com",
                    "transform": {
                        "Authorization": "Basic YOUR_BASE64_TOKEN"
                    },
                },
                {"domain": "pypi.org"},
            ]
        },
    },
)

print(f"Created issue-resolver agent successfully: {agent.id}")

JavaScript

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

const client = new GoogleGenAI({});

const agent = await client.agents.create({
    id: "issue-resolver",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "repository",
                source: "https://github.com/my-org/backend",
                target: "/workspace/repo",
            }
        ],
        network: {
            allowlist: [
                {
                    domain: "api.github.com",
                    transform: {
                        "Authorization": "Basic YOUR_BASE64_TOKEN"
                    },
                },
                { domain: "pypi.org" },
            ]
        }
    },
});

console.log(`Created issue-resolver agent successfully: ${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": "issue-resolver",
      "base_agent": "antigravity-preview-05-2026",
      "system_instruction": "You resolve GitHub issues. Clone the repo, find the bug, write the fix, run the tests, and open a PR.",
      "base_environment": {
          "type": "remote",
          "sources": [
              {
                  "type": "repository",
                  "source": "https://github.com/my-org/backend",
                  "target": "/workspace/repo"
              }
          ],
          "network": {
              "allowlist": [
                  {
                      "domain": "api.github.com",
                      "transform": {
                          "Authorization": "Basic YOUR_BASE64_TOKEN"
                      }
                  },
                  {"domain": "pypi.org"}
              ]
          }
      }
  }'

Вызовите агента

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

Python

result = client.interactions.create(
    agent="data-analyst",
    input="Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.",
    environment="remote",
)

print(result.output_text)

JavaScript

const result = await client.interactions.create({
    agent: "data-analyst",
    input: "Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.",
    environment: "remote",
}, { timeout: 300000 });

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": "data-analyst",
      "input": "Analyze Q1 revenue data from /workspace/templates/sample.csv and create a slide deck.",
      "environment": "remote"
  }'

Для многоходовых диалогов и потоковой передачи данных см. раздел «Быстрый старт» . Те же шаблоны previous_interaction_id и environment применяются и к управляемым агентам.

Переопределение конфигурации при вызове

При создании взаимодействия вы можете переопределить system_instruction и tools агента по умолчанию. Это позволяет изменять поведение или возможности агента для конкретного запуска без изменения сохраненного определения агента.

Python

result = client.interactions.create(
    agent="data-analyst",
    input="Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.",
    system_instruction="You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.",
    tools=[{"type": "code_execution"}], # Override to only use code execution
    environment="remote",
)
print(result.output_text)

JavaScript

const result = await client.interactions.create({
    agent: "data-analyst",
    input: "Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.",
    system_instruction: "You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.",
    tools: [{ type: "code_execution" }], // Override to only use code execution
    environment: "remote",
}, { timeout: 300000 });

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": "data-analyst",
      "input": "Analyze Q1 revenue data, but do not create a slide deck. Just output a summary table.",
      "system_instruction": "You are a data analyst. Focus ONLY on summary tables. Ignore default instructions about slides.",
      "tools": [{"type": "code_execution"}],
      "environment": "remote"
  }'

Управление агентами

Вы можете составлять списки агентов, получать и удалять их.

Список агентов

Python

agents = client.agents.list()
for a in agents.agents:
    print(f"{a.id}: {a.description}")

JavaScript

const agents = await client.agents.list();
if (agents.agents) {
    for (const a of agents.agents) {
        console.log(`${a.id}: ${a.description}`);
    }
}

ОТДЫХ

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

Найдите агента

Python

agent = client.agents.get(id="data-analyst")
print(agent)

JavaScript

const agent = await client.agents.get("data-analyst");
console.log(agent);

ОТДЫХ

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

Удалить агента

Удаление приводит к удалению конфигурации. Существующие среды и взаимодействия, созданные агентом, остаются без изменений.

Python

client.agents.delete(id="data-analyst")

JavaScript

await client.agents.delete("data-analyst");

ОТДЫХ

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

Справочник по определению агента

Поле Тип Необходимый Описание
id нить Да Уникальный идентификатор агента. Используется для вызова агента.
description нить Нет Удобочитаемое описание агента.
base_agent нить Да Базовый идентификатор агента (например, antigravity-preview-05-2026 ).
system_instruction нить Нет Системные подсказки, определяющие поведение и личность.
tools строка или объект Нет Инструменты, которые может использовать агент (опущенные), будут иметь доступ к code_execution , google_search и url_context .
base_environment строка или объект Нет "remote" , environment_id или объект конфигурации с sources и network . См. раздел "Окружения".

Итерационный рабочий процесс

  1. Прототип с базовым агентом «Антигравитация». Передача системных инструкций и источников среды осуществляется непосредственно в систему. Тестирование инструкций, навыков и настроек среды в интерактивном режиме.
  2. Стабилизируйте среду. Установите пакеты, смонтируйте исходные файлы, проверьте работоспособность всего.
  3. Для сохранения статуса управляемого агента необходимо создать нового агента, используя исходные файлы или создав форк среды.
  4. Обновите определение агента. Измените системную инструкцию, замените навыки или добавьте источники. При следующем запуске будет применена новая конфигурация.

Ограничения

  • Статус предварительного просмотра : Управляемые агенты находятся в режиме предварительного просмотра. Функции и схемы могут изменяться.
  • Базовый агент : В качестве base_agent поддерживается только antigravity-preview-05-2026 .
  • Отсутствует версионирование : версионирование агента и откат пока недоступны.
  • Вложенность субагентов отсутствует : делегирование полномочий субагентам пока не поддерживается.
  • Вы можете управлять до 1000 агентами.

Что дальше?