Como criar agentes gerenciados

Com os agentes gerenciados na API Gemini, é possível agrupar instruções, habilidades e um ambiente em um agente reutilizável que pode ser invocado por ID. Defina um revisor de código, um analista de dados ou um bot de implantação uma vez e chame-o de qualquer cliente sem repetir a configuração.

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);

REST

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

Criar um agente gerenciado

Um agente gerenciado combina um base_agent, um system_instruction, um base_environment e um tools em uma única configuração que você chama por ID. A estrutura do agente do Antigravity fornece o ambiente de execução. Em cada invocação, a plataforma ramifica o base_environment em um novo sandbox com todos os recursos do base_agent (execução de código, gerenciamento de arquivos, acesso à Web).

É possível criar um agente com base em fontes, como Git, Cloud Storage ou inline, ou fazer um fork de um ambiente já configurado. De fontes Especifique system_instruction e base_environment com fontes. A plataforma provisiona um novo sandbox com seus arquivos em cada invocação. Consulte "Ambientes" para ver os tipos de origem disponíveis (Git, Cloud Storage, 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", # 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}`);

REST

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

De um ambiente atual (fork)

Itere com o agente base do Antigravity até que o ambiente esteja correto (pacotes instalados, arquivos no lugar) e crie um fork para um agente gerenciado.

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}`);

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

Configurar regras de rede

Use o campo network para restringir o tráfego de saída a domínios específicos. As credenciais passam pelo proxy de saída e nunca são expostas dentro do sandbox. Para mais informações sobre como configurar o acesso à rede, consulte Configuração de rede no documento "Ambientes":

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}`);

REST

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

Quando uma lista de permissões é definida, apenas as solicitações para os domínios listados são permitidas. Consulte Ambientes: configuração de rede para ver o esquema completo da lista de permissões e os padrões de credenciais. É possível usar caracteres curinga para corresponder a subdomínios (por exemplo, {"domain": "*.example.com"}), mas isso não corresponde ao domínio raiz example.com, que precisa ser adicionado separadamente. Para permitir todo o outro tráfego, como o roteamento de domínios não listados sem cabeçalhos injetados, adicione {"domain": "*"} como uma entrada catch-all.

Referência de definição do agente

A tabela a seguir descreve todos os parâmetros configuráveis em um agente:

Campo Tipo Obrigatório Descrição
id string Sim Identificador exclusivo do agente. Usado para invocar o agente.
description string Não Descrição do agente legível por humanos.
base_agent string Sim ID do agente de base (por exemplo, antigravity-preview-05-2026).
system_instruction string Não Comando do sistema que define o comportamento e o perfil.
tools string ou objeto Não Ferramentas que o agente pode usar. Se omitidas, ele terá acesso a code_execution, google_search e url_context.
base_environment string ou objeto Não "remote", um environment_id ou um objeto de configuração com sources e network. Consulte "Ambientes".

Instruções do sistema: AGENTS.md

O harness pesquisa dois caminhos para AGENTS.md na inicialização:

Caminho Escopo
.agents/AGENTS.md Raiz do espaço de trabalho atual.
/.agents/AGENTS.md Raiz do sistema de arquivos.

Se ambos existirem, os dois serão carregados como instruções do sistema.

Para montar um AGENTS.md usando uma origem inline:

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}`);

REST

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

Habilidades: SKILL.md

As habilidades são arquivos que ampliam os recursos do agente. Coloque-os em .agents/skills/<skill-name>/SKILL.md. O conector vai descobrir e registrar automaticamente.

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

Para montar uma habilidade usando uma fonte inline:

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}`);

REST

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

Invocar o agente

Para invocar seu agente gerenciado personalizado, chame client.interactions.create com o ID do agente. Cada invocação ramifica o ambiente de base, então cada execução começa do zero.

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);

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

Para conversas e streaming em várias etapas, consulte o guia de início rápido. Os mesmos padrões previous_interaction_id e environment se aplicam a agentes gerenciados.

Como modificar a configuração na invocação

É possível substituir o system_instruction e o tools padrão do agente ao criar uma interação. Isso permite modificar o comportamento ou as capacidades do agente em uma execução específica sem alterar a definição armazenada.

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);

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

Gerenciar agentes

É possível listar, receber e excluir agentes.

Listar agentes

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}`);
    }
}

REST

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

Obter um agente

Python

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

JavaScript

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

REST

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

Excluir um agente

A exclusão remove a configuração. Os ambientes e as interações criados pelo agente não são afetados.

Python

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

JavaScript

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

REST

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

Fluxo de trabalho de iteração

  1. Prototipar com o agente base do Antigravity. Testar instruções, habilidades e configuração do ambiente de forma interativa.
  2. Estabilize o ambiente. Instale pacotes, monte fontes e verifique se tudo funciona.
  3. Persista como um agente gerenciado com client.agents.create, de fontes ou bifurcando o ambiente.
  4. Atualize a definição do agente. Mude system_instruction, troque habilidades ou adicione fontes. A próxima invocação vai usar a nova configuração.

Limitações

  • Status da prévia: os agentes gerenciados estão em prévia. Os recursos e esquemas podem mudar.
  • Agente de base: somente antigravity-preview-05-2026 é aceito como base_agent.
  • Sem controle de versões: o controle de versões e o rollback do agente ainda não estão disponíveis.
  • Sem aninhamento de subagentes: a delegação de subagentes ainda não é compatível.
  • É possível ter até 1.000 agentes gerenciados por projeto a qualquer momento.

A seguir