Os ambientes são sandboxes Linux gerenciados que oferecem aos agentes um lugar isolado para executar código e manter arquivos. Eles são separados do contexto de interação, então você pode reutilizar o mesmo ambiente em várias interações ou começar do zero a qualquer momento.
O exemplo a seguir demonstra como criar uma interação com um novo ambiente remoto e recuperar o ID dele:
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Install pandas and matplotlib, verify the imports, and print the versions.",
environment="remote",
)
print(f"Environment ID: {interaction.environment_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 and matplotlib, verify the imports, and print the versions.",
environment: "remote",
});
console.log(`Environment ID: ${interaction.environment_id}`);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Install pandas and matplotlib, verify the imports, and print the versions.",
"environment": "remote"
}'
Parâmetro environment
O parâmetro environment aceita três formas:
| Postura | Exemplo | Quando usar |
|---|---|---|
"remote" |
environment="remote" |
Provisionar um novo sandbox. |
| ID do ambiente | environment="env_abc123" |
Reutilizar um sandbox atual com todos os arquivos e pacotes. |
| Objeto de configuração | environment={...} |
Provisionar um novo sandbox com origens, regras de rede ou ambos. |
Os exemplos a seguir demonstram as três maneiras de usar o parâmetro environment.
Python
from google import genai
client = genai.Client()
# Fresh sandbox
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Write a hello world script.",
environment="remote",
)
# Reuse an existing sandbox
interaction_2 = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Modify the script to accept a name argument.",
environment=interaction.environment_id,
previous_interaction_id=interaction.id,
)
# New sandbox with sources
interaction_3 = client.interactions.create(
agent="antigravity-preview-05-2026",
input="List all files and summarize the project.",
environment={
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/octocat/Spoon-Knife",
"target": "/workspace/spoon-knife",
}
],
},
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// Fresh sandbox
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Write a hello world script.",
environment: "remote",
});
// Reuse an existing sandbox
const interaction2 = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Modify the script to accept a name argument.",
environment: interaction.environment_id,
previous_interaction_id: interaction.id,
});
// New sandbox with sources
const interaction3 = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "List all files and summarize the project.",
environment: {
type: "remote",
sources: [
{
type: "repository",
source: "https://github.com/octocat/Spoon-Knife",
target: "/workspace/spoon-knife",
},
],
},
});
console.log(interaction.output_text);
REST
# Fresh sandbox
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": [{"type": "text", "text": "Write a hello world script."}],
"environment": "remote"
}'
# Reuse an existing sandbox (replace $ENV_ID and $INTERACTION_ID with values from the previous response)
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d "{
\"agent\": \"antigravity-preview-05-2026\",
\"input\": [{\"type\": \"text\", \"text\": \"Modify the script to accept a name argument.\"}],
\"environment\": \"$ENV_ID\",
\"previous_interaction_id\": \"$INTERACTION_ID\"
}"
# New sandbox with sources
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": [{"type": "text", "text": "List all files and summarize the project."}],
"environment": {
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/octocat/Spoon-Knife",
"target": "/workspace/spoon-knife"
}
]
}
}'
Configurar um ambiente
Uma maneira de configurar um ambiente é informar ao agente o que você precisa instalar.
Ele processa a resolução de dependências e a solução de problemas. Quando o ambiente estiver pronto, salve o environment_id e reutilize-o.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",
environment="remote",
)
# Reuse the configured environment
interaction_2 = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.",
environment=interaction.environment_id,
previous_interaction_id=interaction.id,
)
# Reuse the configured environment
interaction_3 = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Using the tools in /workspace/tools, list the files.",
environment=interaction.environment_id,
previous_interaction_id=interaction_2.id,
)
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: "Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",
environment: "remote",
});
const interaction2 = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.",
environment: interaction.environment_id,
previous_interaction_id: interaction.id,
});
const interaction3 = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Using the tools in /workspace/tools, list the files.",
environment: interaction.environment_id,
previous_interaction_id: interaction2.id,
});
console.log(interaction.output_text);
REST
# Create interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",
"environment": "remote"
}'
Montar de uma origem
Se você souber exatamente quais arquivos o agente precisa, monte-os em uma única chamada em vez de iterar. O objeto de configuração environment aceita uma matriz sources com três tipos:
| Tipo de origem | Valor de type |
Descrição | Limite |
|---|---|---|---|
| Repositório do Git | repository |
Clona um repositório de um URL para o sandbox em target. |
500 MB |
| Cloud Storage | gcs |
Copia um arquivo ou diretório do Cloud Storage para o sandbox em target. |
2 GB |
| Conteúdo inline | inline |
Grava conteúdo de texto bruto em um arquivo no sandbox em target. |
1 MB por arquivo, 2 MB no total |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="List all files under /workspace and describe what you find.",
environment={
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/octocat/Spoon-Knife",
"target": "/workspace/spoon-knife",
},
{
"type": "gcs",
"source": "gs://cloud-samples-data/bigquery/us-states/",
"target": "/workspace/gcs-data",
},
{
"type": "inline",
"content": "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",
"target": "/workspace/notes/readme.md",
},
],
},
)
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: "List all files under /workspace and describe what you find.",
environment: {
type: "remote",
sources: [
{
type: "repository",
source: "https://github.com/octocat/Spoon-Knife",
target: "/workspace/spoon-knife",
},
{
type: "gcs",
source: "gs://cloud-samples-data/bigquery/us-states/",
target: "/workspace/gcs-data",
},
{
type: "inline",
content: "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",
target: "/workspace/notes/readme.md",
},
],
},
});
console.log(interaction.output_text);
REST
# Create interaction with sources
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "List all files under /workspace and describe what you find.",
"environment": {
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/octocat/Spoon-Knife",
"target": "/workspace/spoon-knife"
},
{
"type": "gcs",
"source": "gs://cloud-samples-data/bigquery/us-states/",
"target": "/workspace/gcs-data"
},
{
"type": "inline",
"content": "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",
"target": "/workspace/notes/readme.md"
}
]
}
}'
É possível combinar as duas abordagens: montar origens conhecidas de forma declarativa e, em seguida, iterar com interações de acompanhamento para instalar pacotes ou executar scripts de configuração. Não é possível definir a raiz (/) como destino ao adicionar uma origem personalizada. Sempre especifique um subdiretório.
Ganchos
Também é possível montar um arquivo de configuração .agents/hooks.json e scripts de interceptação personalizados no sandbox para aplicar proteções de segurança ou executar validações automatizadas sempre que as ferramentas forem executadas. Para definições de esquema e exemplos de código, consulte Ganchos.
Origens particulares
Também é possível fazer o download de repositórios particulares do GitHub ou buckets particulares do Cloud Storage adicionando as credenciais na configuração de rede:
Para repositórios Git particulares, use a autenticação Basic com seu
token de acesso pessoal
(PAT) do GitHub.
Codifique o token usando x-oauth-basic como nome de usuário:
echo -n "x-oauth-basic:ghp_YourPATHere" | base64
Python
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Run the test for my backend app and fix any issue.",
environment={
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/your-org/backend",
"target": "/backend-app"
}
],
"network": {
"allowlist": [
{
"domain": "github.com",
"transform": {
"Authorization": "Basic YOUR_BASE64_TOKEN"
}
},
{
"domain": "*"
}
]
}
}
)
JavaScript
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Run the test for my backend app and fix any issue.",
environment: {
type: "remote",
sources: [
{
type: "repository",
source: "https://github.com/your-org/backend",
target: "/backend-app"
}
],
network: {
allowlist: [
{
domain: "github.com",
transform: {
"Authorization": "Basic YOUR_BASE64_TOKEN"
}
},
{
domain: "*"
}
]
}
},
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Run the test for my backend app and fix any issue.",
"environment": {
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/your-org/backend",
"target": "/backend-app"
}
],
"network": {
"allowlist": [
{
"domain": "github.com",
"transform": {
"Authorization": "Basic YOUR_BASE64_TOKEN"
}
},
{
"domain": "*"
}
]
}
}
}'
Para buckets particulares do Cloud Storage, use um token do portador OAuth 2.0 padrão:
gcloud auth print-access-token
Python
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Analyze the discrepancies across the data in workspace",
environment={
"type": "remote",
"sources": [
{
"type": "gcs",
"source": "gs://my-private-bucket/data",
"target": "/workspace",
}
],
"network": {
"allowlist": [
{
"domain": "*.googleapis.com",
"transform": {
"Authorization": "Bearer YOUR_GCS_TOKEN"
}
},
{
"domain": "*"
}
]
}
},
)
JavaScript
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Analyze the discrepancies across the data in workspace",
environment: {
type: "remote",
sources: [
{
type: "gcs",
source: "gs://my-private-bucket/data",
target: "/workspace",
}
],
network: {
allowlist: [
{
domain: "storage.googleapis.com",
transform: {
"Authorization": "Bearer YOUR_GCS_TOKEN"
}
},
{
domain: "*"
}
]
}
},
});
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Analyze the discrepancies across the data in workspace",
"environment": {
"type": "remote",
"sources": [
{
"type": "gcs",
"source": "gs://my-private-bucket/data",
"target": "/workspace"
}
],
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": "Bearer YOUR_GCS_TOKEN"
}
},
{
"domain": "*"
}
]
}
}
}'
Software pré-instalado
O sandbox é executado no Ubuntu e vem com ambientes de execução e pacotes comuns pré-instalados. O agente pode instalar pacotes adicionais no ambiente de execução usando pip
install ou npm install. Os pacotes instalados durante uma interação persistem quando você reutiliza o mesmo environment_id.
| Categoria | Pacotes pré-instalados |
|---|---|
| Ferramentas UNIX | curl, wget, git, rsync, unzip, ripgrep, fd-find, gawk, bc, tree, which, lsof, htop, jq, iproute2, procps, gcloud CLI |
| Python 3.12 | numpy, pandas, requests, google-genai, beautifulsoup4, pyyaml, ast-grep-cli |
| Node.js 22 | create-next-app, create-vite, typescript |
Configuração de rede
Por padrão, os ambientes têm acesso de rede de saída irrestrito. Use o campo network para restringir o tráfego de saída a domínios específicos. Cada regra especifica um domain e um objeto transform opcional para inserir cabeçalhos em solicitações correspondentes. Esses cabeçalhos podem ser exclusivos por interação, e você pode atualizá-los para o mesmo ambiente.
| Campo | Tipo | Descrição |
|---|---|---|
domain |
string |
Domínio a ser correspondido. Use um nome de host exato ou * para todos os domínios. |
transform |
object |
Objeto que contém pares de chave-valor simples que representam cabeçalhos a serem inseridos em solicitações correspondentes, por exemplo, {"Authorization": "Bearer ..."}. |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Fetch the latest issues from the GitHub API for my-org/my-repo.",
environment={
"type": "remote",
"network": {
"allowlist": [
{
"domain": "api.github.com",
"transform": {
"Authorization": "Bearer ghp_your_github_token"
},
},
{"domain": "pypi.org"},
{"domain": "*"},
]
},
},
)
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: "Fetch the latest issues from the GitHub API for my-org/my-repo.",
environment: {
type: "remote",
network: {
allowlist: [
{
domain: "api.github.com",
transform: {
"Authorization": "Bearer ghp_your_github_token"
},
},
{ domain: "pypi.org" },
{ domain: "*" },
]
}
},
});
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" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": [{"type": "text", "text": "Fetch the latest issues from the GitHub API for my-org/my-repo."}],
"environment": {
"type": "remote",
"network": {
"allowlist": [
{
"domain": "api.github.com",
"transform": {
"Authorization": "Bearer ghp_your_github_token"
}
},
{"domain": "pypi.org"},
{"domain": "*"}
]
}
}
}'
Quando uma lista de permissões é definida, apenas as solicitações para domínios listados explicitamente são permitidas. É 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 tráfego, como o roteamento de domínios não listados sem cabeçalhos injetados, adicione {"domain": "*"} como uma
entrada de captura.
Credenciais
É possível adicionar credenciais para o agente usar adicionando transformações de cabeçalho. As credenciais são injetadas nos respectivos cabeçalhos HTTP por um proxy de saída. Elas nunca são expostas dentro do sandbox como variáveis de ambiente ou arquivos.
Python
import subprocess
from google import genai
# Fetch a short-lived access token from your local gcloud CLI
gcloud_token = subprocess.check_output(
["gcloud", "auth", "print-access-token"], text=True
).strip()
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="List the files in gs://my-bucket/reports/ using the GCS JSON API.",
environment={
"type": "remote",
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": f"Bearer {gcloud_token}"
},
}
]
},
},
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import { execSync } from "child_process";
const gcloudToken = execSync("gcloud auth print-access-token").toString().trim();
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "List the files in gs://my-bucket/reports/ using the GCS JSON API.",
environment: {
type: "remote",
network: {
allowlist: [
{
domain: "storage.googleapis.com",
transform: {
"Authorization": `Bearer ${gcloudToken}`
},
}
]
}
},
});
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" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "List the files in gs://my-bucket/reports/ using the GCS JSON API.",
"environment": {
"type": "remote",
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": "Bearer <YOUR_GCLOUD_TOKEN>"
}
}
]
}
}
}'
Desativar o acesso à rede
Para bloquear todo o acesso de rede de saída, defina network como disabled:
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Analyze the local files only.",
environment={
"type": "remote",
"network": "disabled",
},
)
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 local files only.",
environment: {
type: "remote",
network: "disabled",
},
});
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" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Analyze the local files only.",
"environment": {
"type": "remote",
"network": "disabled"
}
}'
Atualizar credenciais
Credenciais como tokens de acesso e chaves de API de curta duração expiram.
É possível atualizá-las transmitindo o environment_id atual com uma nova configuração de network na próxima interação. As novas regras de rede substituem totalmente as anteriores, enquanto o estado do sistema de arquivos do ambiente (pacotes instalados, arquivos, repositórios) é preservado.
Python
from google import genai
client = genai.Client()
# First interaction: use an initial token
first = client.interactions.create(
agent="antigravity-preview-05-2026",
input="List the files in gs://my-bucket/reports/ using the GCS JSON API.",
environment={
"type": "remote",
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": "Bearer INITIAL_TOKEN"
},
}
]
},
},
)
# Later: refresh the token on the same environment
result = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Now download the file reports/q1.csv from the same bucket.",
environment={
"type": "remote",
"environment_id": first.environment_id,
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": "Bearer REFRESHED_TOKEN"
},
}
]
},
},
)
print(result.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// First interaction: use an initial token
const first = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "List the files in gs://my-bucket/reports/ using the GCS JSON API.",
environment: {
type: "remote",
network: {
allowlist: [
{
domain: "storage.googleapis.com",
transform: {
"Authorization": "Bearer INITIAL_TOKEN"
},
}
]
}
},
});
// Later: refresh the token on the same environment
const result = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Now download the file reports/q1.csv from the same bucket.",
environment: {
type: "remote",
environment_id: first.environment_id,
network: {
allowlist: [
{
domain: "storage.googleapis.com",
transform: {
"Authorization": "Bearer REFRESHED_TOKEN"
},
}
]
}
},
});
console.log(result.output_text);
REST
# Use the environment_id from a previous interaction
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Now download the file reports/q1.csv from the same bucket.",
"environment": {
"type": "remote",
"environment_id": "<ENVIRONMENT_ID_FROM_PREVIOUS_INTERACTION>",
"network": {
"allowlist": [
{
"domain": "storage.googleapis.com",
"transform": {
"Authorization": "Bearer REFRESHED_TOKEN"
}
}
]
}
}
}'
Ciclo de vida do ambiente
Os ambientes seguem este ciclo de vida:
| Estado | Comportamento |
|---|---|
| Criada | Provisionado quando uma interação especifica environment: "remote" ou um objeto de configuração. |
| Ativa | Em execução enquanto uma interação está em andamento. |
| Inativo | Snapshot automático e interrompido após 15 minutos de inatividade. |
| Off-line | Mantido por sete dias desde a última atividade. Pode ser retomado transmitindo o ID. |
| Excluída | Removido do sistema automaticamente após o prazo de validade de retenção de TTL de sete dias ou após a exclusão manual. |
API Environments
É possível usar a API Environments para gerenciar programaticamente as sessões do sandbox. A enumeração de ambientes permite descobrir IDs de sessão ativos e recuperar o estado se uma conexão de cliente for encerrada durante uma tarefa de longa duração. Também é possível inspecionar os metadados da sessão e excluir ambientes explicitamente quando os fluxos de trabalho forem concluídos, em vez de esperar o prazo de validade automático do TTL.
Listar ambientes
Liste os ambientes ativos pertencentes ao seu projeto. Use parâmetros de paginação para controlar o tamanho do lote de respostas.
Python
from google import genai
client = genai.Client()
for env in client.environments.list(page_size=10):
print(f"Environment ID: {env.environment_id}, Type: {env.type}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const response = await client.environments.list({ pageSize: 10 });
for (const env of response.environments) {
console.log(`Environment ID: ${env.environment_id}, Type: ${env.type}`);
}
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments?pageSize=10" \
-H "x-goog-api-key: $GEMINI_API_KEY"
A resposta será semelhante a:
{
"environments": [
{
"environment_id": "140128b2a13c12c00a5a0d8cf7af9469",
"type": "remote"
},
{
"environment_id": "362b738275a1d74af6f1c62bc050da73",
"type": "remote"
}
],
"next_page_token": "Cj...5aE="
}
Acessar um ambiente
Recupere metadados e detalhes de configuração de um ambiente específico pelo nome do recurso.
Python
from google import genai
client = genai.Client()
env = client.environments.get(name="environments/YOUR_ENVIRONMENT_ID")
print(f"Environment ID: {env.environment_id}, Type: {env.type}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const env = await client.environments.get({ name: "environments/YOUR_ENVIRONMENT_ID" });
console.log(`Environment ID: ${env.environment_id}, Type: ${env.type}`);
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
A resposta será semelhante a:
{
"environment_id": "140128b2a13c12c00a5a0d8cf7af9469",
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/octocat/Spoon-Knife",
"target": "/workspace/spoon-knife"
}
],
"network": {
"allowlist": [
{
"domain": "api.github.com"
},
{
"domain": "github.com"
}
]
}
}
Excluir um ambiente
Encerre e exclua explicitamente um ambiente para limpar os recursos do sandbox quando as tarefas ou os pipelines forem concluídos.
Python
from google import genai
client = genai.Client()
client.environments.delete(name="environments/YOUR_ENVIRONMENT_ID")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
await client.environments.delete({ name: "environments/YOUR_ENVIRONMENT_ID" });
REST
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Fazer o download de arquivos do ambiente
O agente cria arquivos dentro do sandbox durante a execução. É possível fazer o download do snapshot completo do ambiente como um arquivo tar usando a API Files:
Python
import os
import requests
import tarfile
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Write a file environments_test.txt with content 'Environments' inside the sandbox.",
environment="remote",
)
env_id = interaction.environment_id
api_key = os.environ.get("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_env.tar", "wb") as f:
f.write(response.content)
os.makedirs("extracted_env_snapshot", exist_ok=True)
with tarfile.open("snapshot_env.tar") as tar:
tar.extractall(path="extracted_env_snapshot")
print(os.listdir("extracted_env_snapshot"))
JavaScript
import { GoogleGenAI } from "@google/genai";
import { execSync } from "child_process";
import * as fs from "fs";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Write a file environments_test.txt with content 'Environments' inside the sandbox.",
environment: "remote",
});
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_env.tar", buffer);
if (!fs.existsSync("extracted_env_snapshot")) {
fs.mkdirSync("extracted_env_snapshot");
}
execSync("tar -xf snapshot_env.tar -C extracted_env_snapshot");
console.log(fs.readdirSync("extracted_env_snapshot"));
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Write a file environments_test.txt with content '\''Environments'\'' inside the sandbox.",
"environment": "remote"
}'
# Step 2: Download snapshot (reusing environment ID from Step 1)
# curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media" \
# -H "x-goog-api-key: $API_KEY" \
# -o snapshot.tar
Preços e recursos
Cada ambiente é executado com alocações de recursos fixas:
| Recurso | Valor |
|---|---|
| CPU | 4 núcleos |
| Memória | 16 GB |
O cálculo do ambiente (CPU, memória, execução do sandbox) não é cobrado durante o período de prévia. Consulte Preços para custos de token de agente.
Limitações
- Status da prévia:os ambientes e os agentes gerenciados estão em prévia. Os recursos e esquemas podem mudar.
- Tamanho da origem inline:as origens inline são limitadas a 1 MB por arquivo e 2 MB no total em todos os arquivos.
- Tamanho da origem: os repositórios Git são limitados a 500 MB e os repositórios do Cloud Storage a 2 GB.
- Inicialização do ambiente:o provisionamento de um novo ambiente leva até ~5 segundos. Repositórios de origem grandes podem aumentar esse tempo.
- Expiração do ambiente:os ambientes off-line inativos são mantidos por sete dias antes de expirar usando a limpeza automática do TTL. A transmissão de um ID de ambiente expirado ou inválido retorna um erro
404 Not Found. - Suporte a arquivos:o agente está atualmente restrito à leitura de arquivos de texto e imagem. O suporte a arquivos binários ainda não está disponível.
- Nenhuma montagem da raiz: não é possível definir a raiz (
/) como destino ao adicionar uma origem personalizada. Sempre especifique um subdiretório.
A seguir
- Visão geral dos agentes: saiba mais sobre os conceitos básicos dos agentes gerenciados.
- Guia de início rápido: comece a criar com conversas multiturno e streaming.
- Agente Antigravity: conheça os recursos, as ferramentas, a seleção de modelos e os preços do agente padrão.
- Como criar agentes personalizados: defina seus próprios agentes usando
AGENTS.mdeSKILL.md. - Ganchos: aplique proteções de segurança e execute validações de efeitos colaterais dentro do sandbox.