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

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

Python


from google import genai

client = genai.Client()

agent = client.agents.create(
    id="code-reviewer",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities.",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "repository",
                "source": "https://github.com/my-org/backend",
                "target": "/workspace/repo",
            }
        ],
    },
)

result = client.interactions.create(
    agent="code-reviewer",
    input="Review the latest changes in /workspace/repo/src and file a summary.",
    environment="remote",
)
print(result.output_text)

JavaScript

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

const client = new GoogleGenAI({});

const agent = await client.agents.create({
    id: "code-reviewer",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities.",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "repository",
                source: "https://github.com/my-org/backend",
                target: "/workspace/repo",
            }
        ],
    },
});

const result = await client.interactions.create({
    agent: "code-reviewer",
    input: "Review the latest changes in /workspace/repo/src and file a summary.",
    environment: "remote",
}, { timeout: 300000 });

console.log(result.output_text);

ОТДЫХ

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": "code-reviewer",
    "base_agent": "antigravity-preview-05-2026",
    "system_instruction": "You are a senior code reviewer. Check every file for bugs, style issues, and security vulnerabilities.",
    "base_environment": {
        "type": "remote",
        "sources": [
            {
                "type": "repository",
                "source": "https://github.com/my-org/backend",
                "target": "/workspace/repo"
            }
        ]
    }
}'

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": "code-reviewer",
    "input": "Review the latest changes in /workspace/repo/src and file a summary.",
    "environment": "remote"
}'

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

Управляемый агент объединяет base_agent , system_instruction , base_environment и tools в единую конфигурацию, которую вы вызываете по идентификатору (ID). Среда выполнения обеспечивается агентом Antigravity. При каждом вызове платформа создает форк base_environment в новую песочницу со всеми возможностями base_agent (выполнение кода, управление файлами, доступ к веб-интерфейсу).

Вы можете создать агент из исходных файлов , таких как Git, Cloud Storage или встроенные, или создать форк из уже настроенной среды. При создании агента укажите system_instruction и base_environment . Платформа автоматически создаст новую песочницу с вашими файлами при каждом запуске. См. раздел «Среды» для получения информации о доступных типах исходных файлов (Git, Cloud Storage, встроенные).

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", # This is appended to the system instruction
                "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 named 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"
  }'

Настройка сетевых правил

С помощью поля network можно ограничить исходящий трафик определенными доменами. Учетные данные передаются через исходящий прокси-сервер и никогда не раскрываются внутри песочницы. Дополнительную информацию о настройке доступа к сети см. в разделе «Настройка сети» в документации по средам:

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"}
              ]
          }
      }
  }'

Если задан список разрешенных запросов, разрешены только запросы к указанным доменам. Полную схему списка разрешенных запросов и шаблоны учетных данных см. в разделе «Среды: Настройка сети» . Вы можете использовать подстановочные знаки для сопоставления поддоменов (например, {"domain": "*.example.com"} ), но обратите внимание, что это не соответствует корневому домену example.com , который необходимо добавить отдельно. Чтобы разрешить весь остальной трафик, например, маршрутизацию неуказанных доменов без внедрения заголовков, добавьте {"domain": "*"} в качестве записи для перехвата всех запросов.

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

В таблице ниже описаны все настраиваемые параметры агента:

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

Системные инструкции: AGENTS.md

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

Путь Объем
.agents/AGENTS.md Корневой каталог текущей рабочей области.
/.agents/AGENTS.md Корневой каталог файловой системы.

Если оба существуют, оба загружаются как системные инструкции.

Для монтирования файла AGENTS.md с использованием встроенного источника:

Python

from google import genai

client = genai.Client()

agent = client.agents.create(
    id="styled-writer",
    base_agent="antigravity-preview-05-2026",
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/AGENTS.md",
                "content": "# Writing Style\n\n- Use active voice\n- Keep paragraphs under 3 sentences\n- Include code examples for every concept",
            },
        ],
    },
)

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

JavaScript

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

const client = new GoogleGenAI({});

const agent = await client.agents.create({
    id: "styled-writer",
    base_agent: "antigravity-preview-05-2026",
    base_environment: {
        type: "remote",
        sources: [
            {
                type: "inline",
                target: ".agents/AGENTS.md",
                content: "# Writing Style\n\n- Use active voice\n- Keep paragraphs under 3 sentences\n- Include code examples for every concept",
            },
        ],
    },
});

console.log(`Created styled-writer 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": "styled-writer",
      "base_agent": "antigravity-preview-05-2026",
      "base_environment": {
          "type": "remote",
          "sources": [
              {
                  "type": "inline",
                  "target": ".agents/AGENTS.md",
                  "content": "# Writing Style\n\n- Use active voice\n- Keep paragraphs under 3 sentences\n- Include code examples for every concept"
              }
          ]
      }
  }'

Навыки: SKILL.md

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

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

Для монтирования навыка с использованием встроенного источника:

Python

from google import genai

client = genai.Client()

agent = client.agents.create(
    id="presenter",
    base_agent="antigravity-preview-05-2026",
    system_instruction="You create presentations from data.",
    base_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(f"Created presenter: {agent.id}")

JavaScript

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

const client = new GoogleGenAI({});

const agent = await client.agents.create({
    id: "presenter",
    base_agent: "antigravity-preview-05-2026",
    system_instruction: "You create presentations from data.",
    base_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",
            },
        ],
    },
});

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

ОТДЫХ

# Create agent with skill
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": "presenter",
      "base_agent": "antigravity-preview-05-2026",
      "system_instruction": "You create presentations from data.",
      "base_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"
              }
          ]
      }
  }'

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

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

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"

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

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

Ограничения

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

Что дальше?