Os ambientes são sandboxes gerenciados do Linux que oferecem aos agentes um lugar isolado para executar código e manter arquivos. Eles são dissociados 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 ambiente remoto novo e recuperar o ID dela:
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-09-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-09-2026",
input: "Install pandas and matplotlib, verify the imports, and print the versions.",
environment: "remote",
});
console.log(`Environment ID: ${interaction.environment_id}`);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Install pandas and matplotlib, verify the imports, and print the versions."))
.environment(CreateAgentInteractionEnvironment.of("remote"))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println("Environment ID: " + interaction.environmentId().orElse(""));
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-09-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:
| Formulário | Exemplo | Quando usar |
|---|---|---|
"remote" |
environment="remote" |
Provisione um novo sandbox. |
| ID do ambiente | environment="env_abc123" |
Reutilizar uma sandbox com todos os arquivos e pacotes. |
| Objeto de configuração | environment={...} |
Provisione um novo sandbox com fontes, regras de rede, variáveis de ambiente ou uma combinação. |
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-09-2026",
input="Write a hello world script.",
environment="remote",
)
# Reuse an existing sandbox
interaction_2 = client.interactions.create(
agent="antigravity-preview-09-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-09-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-09-2026",
input: "Write a hello world script.",
environment: "remote",
});
// Reuse an existing sandbox
const interaction2 = await client.interactions.create({
agent: "antigravity-preview-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Source;
import com.google.genai.gaos.models.interactions.SourceType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client = new Client();
// Fresh sandbox
CreateAgentInteraction params1 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Write a hello world script."))
.environment(CreateAgentInteractionEnvironment.of("remote"))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();
// Reuse an existing sandbox
CreateAgentInteraction params2 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Modify the script to accept a name argument."))
.environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))
.previousInteractionId(interaction.id().orElse(""))
.build();
Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();
// New sandbox with sources
Environment env3 = Environment.builder()
.sources(List.of(
Source.builder()
.type(SourceType.REPOSITORY)
.source("https://github.com/octocat/Spoon-Knife")
.target("/workspace/spoon-knife")
.build()
))
.build();
CreateAgentInteraction params3 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("List all files and summarize the project."))
.environment(CreateAgentInteractionEnvironment.of(env3))
.build();
Interaction interaction3 = client.interactions.create(CreateInteractionRequestBody.of(params3)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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-09-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-09-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 é dizer ao agente o que você precisa instalar.
Ele lida com 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-09-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-09-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-09-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-09-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-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
CreateAgentInteraction params1 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions."))
.environment(CreateAgentInteractionEnvironment.of("remote"))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();
// Reuse the configured environment
CreateAgentInteraction params2 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies."))
.environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))
.previousInteractionId(interaction.id().orElse(""))
.build();
Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();
// Reuse the configured environment
CreateAgentInteraction params3 = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Using the tools in /workspace/tools, list the files."))
.environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))
.previousInteractionId(interaction2.id().orElse(""))
.build();
Interaction interaction3 = client.interactions.create(CreateInteractionRequestBody.of(params3)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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 a sandbox em target. |
500 MB |
| Cloud Storage | gcs |
Copia um arquivo ou diretório do Cloud Storage para a sandbox em target. |
2 GB |
| Conteúdo inline | inline |
Grava conteúdo de texto bruto em um arquivo na 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-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Source;
import com.google.genai.gaos.models.interactions.SourceType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client = new Client();
Environment env = Environment.builder()
.sources(List.of(
Source.builder()
.type(SourceType.REPOSITORY)
.source("https://github.com/octocat/Spoon-Knife")
.target("/workspace/spoon-knife")
.build(),
Source.builder()
.type(SourceType.GCS)
.source("gs://cloud-samples-data/bigquery/us-states/")
.target("/workspace/gcs-data")
.build(),
Source.builder()
.type(SourceType.INLINE)
.content("# Project Notes\n\n- Analyze state population data\n- Create visualizations\n")
.target("/workspace/notes/readme.md")
.build()
))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("List all files under /workspace and describe what you find."))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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 fontes conhecidas de forma declarativa e 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 fonte 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 na sandbox para aplicar restriçõ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 Hooks.
Fontes particulares
Também é possível fazer o download de repositórios privados do GitHub ou de buckets privados do Cloud Storage autenticando o domínio de origem na configuração de rede.
Uma opção é uma credencial armazenada referenciada por ID. Assim, você armazena o secret uma vez, e todos os ambientes que precisam dessa fonte podem fazer referência a ele:
"network": {
"allowlist": [
{ "domain": "github.com", "credential": "github-production" },
{ "domain": "*" }
]
}
Você também pode definir o cabeçalho inline com transform, como mostram os exemplos a seguir. O proxy de saída aplica as duas formas da mesma maneira, e em nenhum dos casos o segredo fica dentro da sandbox.
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-09-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-09-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: "*"
}
]
}
},
});
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.Allowlist;
import com.google.genai.gaos.models.interactions.AllowlistEntry;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.Source;
import com.google.genai.gaos.models.interactions.SourceType;
import com.google.genai.gaos.models.interactions.Transform;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
import java.util.Map;
Client client = new Client();
Environment env = Environment.builder()
.sources(List.of(
Source.builder()
.type(SourceType.REPOSITORY)
.source("https://github.com/your-org/backend")
.target("/backend-app")
.build()
))
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("github.com")
.transform(Transform.of(Map.of(
"Authorization", "Basic YOUR_BASE64_TOKEN"
)))
.build(),
AllowlistEntry.builder()
.domain("*")
.build()
))
.build()
)))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Run the test for my backend app and fix any issue."))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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 privados 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-09-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-09-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: "*"
}
]
}
},
});
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.Allowlist;
import com.google.genai.gaos.models.interactions.AllowlistEntry;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.Source;
import com.google.genai.gaos.models.interactions.SourceType;
import com.google.genai.gaos.models.interactions.Transform;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
import java.util.Map;
Client client = new Client();
Environment env = Environment.builder()
.sources(List.of(
Source.builder()
.type(SourceType.GCS)
.source("gs://my-private-bucket/data")
.target("/workspace")
.build()
))
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("*.googleapis.com")
.transform(Transform.of(Map.of(
"Authorization", "Bearer YOUR_GCS_TOKEN"
)))
.build(),
AllowlistEntry.builder()
.domain("*")
.build()
))
.build()
)))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Analyze the discrepancies across the data in workspace"))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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 tempos de execução e pacotes comuns pré-instalados. O agente pode instalar outros pacotes durante a 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 do 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 |
Variáveis de ambiente
Use o campo env para definir variáveis de ambiente na sandbox. Cada entrada mapeia um nome de variável para uma string literal de configuração ou uma referência a uma credencial armazenada para um segredo. O agente os vê da mesma forma que em qualquer shell. Portanto, ferramentas e scripts
que leem do ambiente de processo os captam sem fiação extra.
| Campo | Tipo | Descrição |
|---|---|---|
env |
object |
Mapa do nome da variável para o valor. Um valor é um literal string ou uma referência de credencial do formulário {"credential": "credential-id"}. |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-09-2026",
input="Build the project and run the test suite.",
environment={
"type": "remote",
"env": {
"NODE_ENV": "production",
"LOG_LEVEL": "debug",
"API_TOKEN": {"credential": "my-api-token"},
},
},
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
agent: "antigravity-preview-09-2026",
input: "Build the project and run the test suite.",
environment: {
type: "remote",
env: {
NODE_ENV: "production",
LOG_LEVEL: "debug",
API_TOKEN: { credential: "my-api-token" },
},
},
});
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-09-2026",
"input": [{"type": "text", "text": "Build the project and run the test suite."}],
"environment": {
"type": "remote",
"env": {
"NODE_ENV": "production",
"LOG_LEVEL": "debug",
"API_TOKEN": {"credential": "my-api-token"}
}
}
}'
As variáveis se aplicam a todos os comandos que o agente executa nessa interação, incluindo comandos de shell, etapas de build e qualquer processo que ele inicie.
Os dois tipos de valores se comportam de maneira diferente. Uma string literal é gravada no container como texto simples. Uma referência de credencial não é: a variável recebe um marcador de posição, e o proxy de saída substitui o segredo real apenas em solicitações de saída para os domínios confiáveis dessa credencial. Consulte Usar credenciais como variáveis de ambiente para saber como isso funciona.
Configuração de rede
Por padrão, os ambientes têm acesso de saída irrestrito à rede. Use o campo
network para restringir o tráfego de saída a domínios específicos. Cada regra especifica um domain, além de um credential opcional para injetar um secreto armazenado e um objeto transform opcional para injetar 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. |
credential |
string |
ID de uma credencial armazenada. O proxy de saída resolve e injeta o cabeçalho de autenticação no momento da solicitação. |
transform |
object |
Objeto que contém pares de chave-valor simples representando cabeçalhos a serem injetados em solicitações correspondentes, por exemplo, {"Authorization": "Bearer ..."}. |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.Allowlist;
import com.google.genai.gaos.models.interactions.AllowlistEntry;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.Transform;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
import java.util.Map;
Client client = new Client();
Environment env = Environment.builder()
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("api.github.com")
.transform(Transform.of(Map.of(
"Authorization", "Bearer ghp_your_github_token"
)))
.build(),
AllowlistEntry.builder().domain("pypi.org").build(),
AllowlistEntry.builder().domain("*").build()
))
.build()
)))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Fetch the latest issues from the GitHub API for my-org/my-repo."))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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 solicitações para domínios explicitamente listados 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 outro tráfego, como
roteamento de domínios não listados sem cabeçalhos injetados, adicione {"domain": "*"} como uma
entrada de captura de tudo.
Credenciais
Há duas maneiras de autenticar o tráfego de saída: uma credencial armazenada referenciada por ID e um transform inline na regra de lista de permissões. O proxy de saída é aplicado no fio. Portanto, em ambos os casos, o secreto nunca entra no sandbox e nunca aparece nos payloads de interação.
Uma credencial gerenciada é a opção ideal quando você quer armazenar o secret uma vez e reutilizá-lo. Cada ambiente, agente e gatilho no seu projeto pode referenciar o mesmo ID, e você o gira em um só lugar.
Python
from google import genai
client = genai.Client()
# Store the secret once
client.credentials.create(
id="github-production",
type="bearer_token",
token="ghp_your_github_token",
)
interaction = client.interactions.create(
agent="antigravity-preview-09-2026",
input="Fetch the latest issues from the GitHub API for my-org/my-repo.",
environment={
"type": "remote",
"network": {
"allowlist": [
{"domain": "api.github.com", "credential": "github-production"},
{"domain": "*"},
]
},
},
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// Store the secret once
await client.credentials.create({
id: "github-production",
type: "bearer_token",
token: "ghp_your_github_token",
});
const interaction = await client.interactions.create({
agent: "antigravity-preview-09-2026",
input: "Fetch the latest issues from the GitHub API for my-org/my-repo.",
environment: {
type: "remote",
network: {
allowlist: [
{ domain: "api.github.com", credential: "github-production" },
{ domain: "*" },
]
}
},
});
console.log(interaction.output_text);
REST
# Store the secret once
curl -X POST "https://generativelanguage.googleapis.com/v1beta/credentials" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"id": "github-production",
"type": "bearer_token",
"token": "ghp_your_github_token"
}'
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-09-2026",
"input": "Fetch the latest issues from the GitHub API for my-org/my-repo.",
"environment": {
"type": "remote",
"network": {
"allowlist": [
{ "domain": "api.github.com", "credential": "github-production" },
{ "domain": "*" }
]
}
}
}'
Uma credencial oauth2 também atualiza o token de acesso por conta própria, para que uma
interação de longa duração não seja interrompida quando o token expirar. Consulte Credenciais para ver a lista completa de tipos de credenciais e operações de gerenciamento.
Também é possível definir cabeçalhos inline com transform. Isso é adequado quando o valor pertence a uma única chamada, por exemplo, um token gerado pouco antes de criar a interação. Os cabeçalhos definidos dessa forma são injetados pelo mesmo proxy de saída e nunca são expostos dentro da 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-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.Allowlist;
import com.google.genai.gaos.models.interactions.AllowlistEntry;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.Transform;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
// Fetch a short-lived access token from your local gcloud CLI
Process process = new ProcessBuilder("gcloud", "auth", "print-access-token").start();
String gcloudToken = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
Client client = new Client();
Environment env = Environment.builder()
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("storage.googleapis.com")
.transform(Transform.of(Map.of(
"Authorization", "Bearer " + gcloudToken
)))
.build()
))
.build()
)))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("List the files in gs://my-bucket/reports/ using the GCS JSON API."))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-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>"
}
}
]
}
}
}'
credential e transform podem aparecer na mesma regra. A credencial é
aplicada primeiro, e o transform é mesclado por cima. Portanto, um cabeçalho transform explícito
vence se ambos definirem a mesma chave. Um padrão comum é uma credencial para o
cabeçalho de autenticação mais um transform para os cabeçalhos extras que o serviço
espera junto com ele.
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-09-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-09-2026",
input: "Analyze the local files only.",
environment: {
type: "remote",
network: "disabled",
},
});
console.log(interaction.output_text);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.NetworkEnum;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client = new Client();
Environment env = Environment.builder()
.network(Network.of(NetworkEnum.DISABLED))
.build();
CreateAgentInteraction params = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Analyze the local files only."))
.environment(CreateAgentInteractionEnvironment.of(env))
.build();
Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
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-09-2026",
"input": "Analyze the local files only.",
"environment": {
"type": "remote",
"network": "disabled"
}
}'
Atualizar credenciais
Tokens inline, como tokens de acesso e chaves de API de curta duração, expiram.
Para atualizar, transmita o environment_id atual junto com uma nova configuração 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.
Se você usar uma credencial armazenada, não vai precisar disso. Uma credencial oauth2 se atualiza automaticamente, e a rotação de qualquer
credencial é uma PATCH na credencial que deixa todas as regras da lista de permissões
que a referenciam intactas.
Python
from google import genai
client = genai.Client()
# First interaction: use an initial token
first = client.interactions.create(
agent="antigravity-preview-09-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-09-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-09-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-09-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);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AgentOption;
import com.google.genai.gaos.models.interactions.Allowlist;
import com.google.genai.gaos.models.interactions.AllowlistEntry;
import com.google.genai.gaos.models.interactions.CreateAgentInteraction;
import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;
import com.google.genai.gaos.models.interactions.Environment;
import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Network;
import com.google.genai.gaos.models.interactions.Transform;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
import java.util.Map;
Client client = new Client();
// First interaction: use an initial token
Environment initialEnv = Environment.builder()
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("storage.googleapis.com")
.transform(Transform.of(Map.of(
"Authorization", "Bearer INITIAL_TOKEN"
)))
.build()
))
.build()
)))
.build();
CreateAgentInteraction firstParams = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("List the files in gs://my-bucket/reports/ using the GCS JSON API."))
.environment(CreateAgentInteractionEnvironment.of(initialEnv))
.build();
Interaction first = client.interactions.create(CreateInteractionRequestBody.of(firstParams)).interaction().get();
// Later: refresh the token on the same environment
Environment refreshedEnv = Environment.builder()
.environmentId(first.environmentId().orElse(""))
.network(Network.of(EnvironmentNetworkEgressAllowlist.of(
Allowlist.builder()
.allowlist(List.of(
AllowlistEntry.builder()
.domain("storage.googleapis.com")
.transform(Transform.of(Map.of(
"Authorization", "Bearer REFRESHED_TOKEN"
)))
.build()
))
.build()
)))
.build();
CreateAgentInteraction secondParams = CreateAgentInteraction.builder()
.agent(AgentOption.of("antigravity-preview-09-2026"))
.input(InteractionsInput.of("Now download the file reports/q1.csv from the same bucket."))
.environment(CreateAgentInteractionEnvironment.of(refreshedEnv))
.build();
Interaction result = client.interactions.create(CreateInteractionRequestBody.of(secondParams)).interaction().get();
System.out.println(result.outputText().orElse(""));
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-09-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 | Execução enquanto uma interação está em andamento. |
| Inativo | Snapshot automático e parada após 15 minutos de inatividade. |
| Off-line | Retidos por sete dias desde a última atividade. Pode ser retomada transmitindo o ID dela. |
| Excluída | Removidos automaticamente do sistema após o vencimento da retenção de TTL de sete dias ou após a exclusão manual. |
API Environments
Você pode usar a API Environments para gerenciar sessões de sandbox de maneira programática. 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. Você também pode inspecionar metadados de sessão e excluir ambientes explicitamente quando os fluxos de trabalho forem concluídos, em vez de esperar a expiração automática 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()
response = client.environments.list(page_size=10)
for env in response.environments:
print(f"Environment ID: {env.id}, Status: {env.status}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const response = await client.environments.list({ page_size: 10 });
for (const env of response.environments) {
console.log(`Environment ID: ${env.id}, Status: ${env.status}`);
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.environments.Environment;
import com.google.genai.gaos.models.environments.ListEnvironmentsResponse;
import java.util.List;
Client client = new Client();
ListEnvironmentsResponse response = client.environments.listEnvironments()
.pageSize(10)
.call()
.listEnvironmentsResponse()
.get();
for (Environment env : response.environments().orElse(List.of())) {
System.out.println("Environment ID: " + env.id().orElse("") + ", Status: " + env.status().orElse(null));
}
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": [
{
"id": "140128b2a13c12c00a5a0d8cf7af9469",
"status": "active"
},
{
"id": "362b738275a1d74af6f1c62bc050da73",
"status": "active"
}
],
"next_page_token": "Cj...5aE="
}
Acessar um ambiente
Recupera 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(id="YOUR_ENVIRONMENT_ID")
print(f"Environment ID: {env.id}, Status: {env.status}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const env = await client.environments.get("YOUR_ENVIRONMENT_ID");
console.log(`Environment ID: ${env.id}, Status: ${env.status}`);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.environments.Environment;
Client client = new Client();
Environment env = client.environments.getEnvironment("YOUR_ENVIRONMENT_ID").environment().get();
System.out.println("Environment ID: " + env.id().orElse("") + ", Status: " + env.status().orElse(null));
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:
{
"id": "140128b2a13c12c00a5a0d8cf7af9469",
"status": "active",
"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 suas tarefas ou pipelines forem concluídos.
Python
from google import genai
client = genai.Client()
client.environments.delete(id="YOUR_ENVIRONMENT_ID")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
await client.environments.delete("YOUR_ENVIRONMENT_ID");
Java
import com.google.genai.Client;
Client client = new Client();
client.environments.deleteEnvironment("YOUR_ENVIRONMENT_ID");
REST
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Gerenciar arquivos no ambiente
O agente cria e modifica arquivos dentro do sandbox durante a execução. É possível navegar pelo conteúdo do diretório, receber metadados de arquivos, fazer o download de arquivos individuais ou de diretórios inteiros como arquivos tar e fazer upload de arquivos ou extrair arquivos diretamente no ambiente. O armazenamento em ambientes de sandbox está sujeito a limites de uso aceitável.
Listar arquivos em um diretório
Liste o conteúdo de um diretório no ambiente. Por padrão, lista o diretório raiz.
Parâmetros de consulta
| Parâmetro | Tipo | Descrição |
|---|---|---|
recursive |
booleano | Quando true, lista todos os arquivos e diretórios de forma recursiva. Padrão: false. |
Python
from google import genai
client = genai.Client()
# List root directory
response = client.environments.files.list(
environment="YOUR_ENVIRONMENT_ID",
path="",
)
for file in response.files:
print(f"{file.name} ({file.type}) - {file.path}")
# List a subdirectory recursively
response = client.environments.files.list(
environment="YOUR_ENVIRONMENT_ID",
path="src",
recursive=True,
)
for file in response.files:
print(f"{file.name} ({file.type}) - {file.path}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// List root directory
const response = await client.environments.files.list({
environment: "YOUR_ENVIRONMENT_ID",
path: "",
});
for (const file of response.files) {
console.log(`${file.name} (${file.type}) - ${file.path}`);
}
// List a subdirectory recursively
const srcResponse = await client.environments.files.list({
environment: "YOUR_ENVIRONMENT_ID",
path: "src",
recursive: true,
});
for (const file of srcResponse.files) {
console.log(`${file.name} (${file.type}) - ${file.path}`);
}
REST
# List root directory
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files" \
-H "x-goog-api-key: $GEMINI_API_KEY"
# List a subdirectory
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src" \
-H "x-goog-api-key: $GEMINI_API_KEY"
# List all files recursively
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?recursive=true" \
-H "x-goog-api-key: $GEMINI_API_KEY"
A resposta retorna uma matriz files com metadados para cada entrada:
{
"files": [
{
"name": "config",
"path": "config",
"type": "DIRECTORY",
"created": "2026-08-12T07:44:18Z",
"modified": "2026-08-12T07:44:18Z"
},
{
"name": "main.py",
"path": "src/main.py",
"type": "FILE",
"size_bytes": "15",
"mime_type": "text/x-python; charset=utf-8",
"created": "2026-08-12T07:44:20Z",
"modified": "2026-08-12T07:44:20Z"
}
]
}
Campos de entrada de arquivo
| Campo | Tipo | Descrição |
|---|---|---|
name |
string | O nome do arquivo ou diretório. |
path |
string | O caminho completo relativo à raiz do ambiente. |
type |
string | FILE ou DIRECTORY. |
size_bytes |
string | Tamanho do arquivo em bytes (somente arquivos). |
mime_type |
string | Tipo MIME (somente arquivos). |
created |
string | Carimbo de data/hora de criação ISO 8601. |
modified |
string | Carimbo de data e hora da última modificação ISO 8601. |
Acessar metadados de arquivo
Recebe metadados de um arquivo específico por caminho.
Python
from google import genai
client = genai.Client()
response = client.environments.files.list(
environment="YOUR_ENVIRONMENT_ID",
path="src/main.py",
)
file = response.files[0]
print(f"Name: {file.name}, Size: {file.size_bytes} bytes, Type: {file.mime_type}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const response = await client.environments.files.list({
environment: "YOUR_ENVIRONMENT_ID",
path: "src/main.py",
});
const file = response.files[0];
console.log(`Name: ${file.name}, Size: ${file.size_bytes} bytes, Type: ${file.mime_type}`);
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src/main.py" \
-H "x-goog-api-key: $GEMINI_API_KEY"
A resposta retorna os metadados do arquivo envolvidos em uma matriz files:
{
"files": [
{
"name": "main.py",
"path": "src/main.py",
"type": "FILE",
"size_bytes": "15",
"mime_type": "text/x-python; charset=utf-8",
"created": "2026-08-12T07:44:20Z",
"modified": "2026-08-12T07:44:20Z"
}
]
}
Se o arquivo não existir, a API vai retornar um erro 404:
{
"error": {
"message": "Path 'nonexistent.txt' not found in environment 'ENV_ID'.",
"code": "not_found"
}
}
Baixar um único arquivo
Baixe o conteúdo de um arquivo específico. Nos SDKs, use o método download(). Em solicitações REST, adicione o parâmetro de consulta ?alt=media ao caminho do arquivo. O servidor responde com 200 OK e transmite o conteúdo bruto do arquivo.
Python
from google import genai
client = genai.Client()
content = client.environments.files.download(
environment="YOUR_ENVIRONMENT_ID",
path="src/main.py",
)
with open("main.py", "wb") as f:
f.write(content)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";
const client = new GoogleGenAI({});
const bytes = await client.environments.files.download({
environment: "YOUR_ENVIRONMENT_ID",
path: "src/main.py",
});
fs.writeFileSync("main.py", Buffer.from(bytes));
REST
curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src/main.py?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o main.py
Baixar um diretório como um arquivo tar
Baixe um diretório inteiro como um arquivo tar solicitando o caminho do diretório
com ?alt=media. Isso retorna um arquivo tar POSIX (não compactado com gzip). Use
recursive=true para incluir subdiretórios aninhados.
Python
import tarfile
from google import genai
client = genai.Client()
# Download a subdirectory archive
archive = client.environments.files.download(
environment="YOUR_ENVIRONMENT_ID",
path="src",
)
with open("src.tar", "wb") as f:
f.write(archive)
with tarfile.open("src.tar") as tar:
tar.extractall(path="./extracted")
JavaScript
import { GoogleGenAI } from "@google/genai";
import { execSync } from "child_process";
import * as fs from "fs";
const client = new GoogleGenAI({});
// Download a subdirectory archive
const bytes = await client.environments.files.download({
environment: "YOUR_ENVIRONMENT_ID",
path: "src",
});
fs.writeFileSync("src.tar", Buffer.from(bytes));
execSync("tar -xf src.tar -C ./extracted");
REST
# Download a subdirectory (top-level files only)
curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o src.tar
# Download a subdirectory recursively (includes nested directories)
curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/config?alt=media&recursive=true" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o config.tar
# Download root directory
curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o snapshot.tar
# Extract the archive
tar xf snapshot.tar -C ./extracted
Matriz de comportamento
A matriz de comportamento a seguir resume a resposta esperada e o comportamento de arquivamento em endpoints de arquivo e diretório, métodos HTTP e parâmetros de consulta:
| Solicitação | alt |
recursive |
extract |
overwrite |
Resposta |
|---|---|---|---|---|---|
GET /files |
(nenhum) | (nenhum) | - | - | Listagem JSON do diretório raiz |
GET /files/{path} (arquivo) |
(nenhum) | - | - | - | Metadados JSON do arquivo |
GET /files/{path} (dir) |
(nenhum) | false |
- | - | Listagem JSON de filhos imediatos |
GET /files/{path} (dir) |
(nenhum) | true |
- | - | Listagem JSON de todos os descendentes |
GET /files/{path}?alt=media (arquivo) |
media |
- | - | - | Conteúdo do arquivo bruto |
GET /files/{path}?alt=media (dir) |
media |
false |
- | - | Arquivo tar de arquivos imediatos no diretório |
GET /files/{path}?alt=media (dir) |
media |
true |
- | - | Arquivo tar de todos os arquivos recursivamente |
GET /files?alt=media |
media |
false |
- | - | Arquivo tar somente de arquivos no nível da raiz |
PUT /files/{path} (arquivo) |
- | - | false |
false |
Grava o arquivo no caminho. Retorna 409 Conflict se ele já existir. |
PUT /files/{path}?overwrite=true |
- | - | false |
true |
Grava ou substitui o arquivo no caminho |
PUT /files/{path}?extract=true |
- | - | true |
false |
Descompacta o arquivo no diretório de destino. Retorna 409 Conflict se algum arquivo de destino existir |
PUT /files/{path}?extract=true&overwrite=true |
- | - | true |
true |
Descompacta o arquivo, substituindo os arquivos atuais |
Fazer upload de arquivos para o ambiente
Faça upload de arquivos individuais ou arquivos de diretório diretamente para um ambiente
sandbox usando HTTP PUT. Os diretórios principais são criados automaticamente se não existirem. O armazenamento em ambientes está sujeito a limites de uso aceitável.
Fazer upload de um único arquivo
Python
from google import genai
client = genai.Client()
with open("local_file.txt", "rb") as f:
result = client.environments.files.upload(
environment="YOUR_ENVIRONMENT_ID",
path="workspace/data/file.txt",
file=f,
mime_type="text/plain",
overwrite=True,
)
file = result.files[0]
print(f"Uploaded: {file.name} ({file.size_bytes} bytes)")
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";
const client = new GoogleGenAI({});
const content = fs.readFileSync("local_file.txt");
const result = await client.environments.files.upload({
environment: "YOUR_ENVIRONMENT_ID",
path: "workspace/data/file.txt",
file: content,
mime_type: "text/plain",
overwrite: true,
});
const file = result.files[0];
console.log(`Uploaded: ${file.name} (${file.size_bytes} bytes)`);
REST
curl -X PUT "https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/data/file.txt" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: text/plain" \
--data-binary @local_file.txt
A resposta retorna metadados do arquivo enviado, envolvidos em uma matriz files para consistência com os endpoints de lista e get:
{
"files": [
{
"name": "file.txt",
"path": "workspace/data/file.txt",
"type": "FILE",
"size_bytes": "1024",
"mime_type": "text/plain"
}
]
}
Fazer upload e extrair um arquivo de diretório
Para inserir uma codebase ou estrutura de diretório inteira em uma única solicitação, faça upload de um arquivo .tar ou .tar.gz com extract=true.
Python
from google import genai
client = genai.Client()
with open("source.tar.gz", "rb") as f:
result = client.environments.files.upload(
environment="YOUR_ENVIRONMENT_ID",
path="workspace/src/",
file=f,
extract=True,
)
for entry in result.files:
print(f"Extracted: {entry.path}")
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";
const client = new GoogleGenAI({});
const archive = fs.readFileSync("source.tar.gz");
const result = await client.environments.files.upload({
environment: "YOUR_ENVIRONMENT_ID",
path: "workspace/src/",
file: archive,
extract: true,
});
for (const entry of result.files) {
console.log(`Extracted: ${entry.path}`);
}
REST
curl -X PUT "https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/src/?extract=true" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/x-tar" \
--data-binary @source.tar.gz
A resposta lista todos os arquivos gravados pelo arquivo:
{
"files": [
{
"name": "app.py",
"path": "workspace/src/app.py",
"type": "FILE",
"size_bytes": "15",
"mime_type": "text/x-python"
},
{
"name": "requirements.txt",
"path": "workspace/src/requirements.txt",
"type": "FILE",
"size_bytes": "17",
"mime_type": "text/plain"
}
]
}
Fazer upload de arquivos grandes com uma sessão retomável
Para payloads grandes ou ao fazer upload por uma conexão não confiável, use uma sessão retomável em vez de enviar todo o corpo em uma solicitação. Um upload retomável divide a transferência em partes que podem ser repetidas individualmente. Assim, uma falha no meio do processo não obriga você a começar de novo.
Comece iniciando a sessão com uploadType=resumable. Envie um corpo vazio
e use os cabeçalhos X-Upload-Content-Type e X-Upload-Content-Length para
declarar o tipo de mídia e o tamanho total da carga útil que você pretende fazer upload:
PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable HTTP/1.1
Host: generativelanguage.googleapis.com
X-Upload-Content-Type: application/octet-stream
X-Upload-Content-Length: 20971520
Content-Length: 0
x-goog-api-key: $GEMINI_API_KEY
A resposta carrega o URL da sessão no cabeçalho Location. Este URL já
contém um upload_id, então não precisa da chave de API novamente:
HTTP/1.1 200 OK
Location: https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY
Content-Length: 0
Faça upload do payload para esse URL em partes. Cada parte declara o intervalo de bytes e o tamanho total com um cabeçalho Content-Range:
PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY HTTP/1.1
Host: generativelanguage.googleapis.com
Content-Type: application/octet-stream
Content-Range: bytes 0-10485759/20971520
Content-Length: 10485760
<10 MB binary payload>
Todos os blocos, exceto o último, retornam 308 Resume Incomplete. O cabeçalho Range informa quantos bytes o servidor confirmou, que é de onde você retoma se um trecho falhar:
HTTP/1.1 308 Resume Incomplete
Range: bytes=0-10485759
Content-Length: 0
Envie os outros blocos da mesma forma:
PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY HTTP/1.1
Host: generativelanguage.googleapis.com
Content-Type: application/octet-stream
Content-Range: bytes 10485760-20971519/20971520
Content-Length: 10485760
<remaining 10 MB binary payload>
O bloco final conclui o upload e retorna os metadados do arquivo, no mesmo
envelope files de um upload único:
{
"files": [
{
"name": "large_dataset.bin",
"path": "workspace/data/large_dataset.bin",
"type": "FILE",
"size_bytes": "20971520",
"mime_type": "application/octet-stream"
}
]
}
As sessões retomáveis também funcionam com extract e overwrite. Defina esses parâmetros de consulta na solicitação inicial, não nos blocos individuais.
Proteção contra substituição
Por padrão, overwrite é false. Se o caminho de destino já existir, a
solicitação vai retornar um erro 409 Conflict e nada será gravado:
{
"error": {
"message": "Requested entity already exists",
"code": "aborted"
}
}
Para substituir um arquivo ou diretório, defina overwrite=true (ou adicione
?overwrite=true em REST). Com extract=true, a verificação de conflitos se aplica a
todos os arquivos do arquivo. Portanto, a solicitação falha se algum arquivo de destino existir.
Baixar o snapshot completo (descontinuado)
Para migrar o código atual para a API de arquivos de ambiente:
Python: substitua as solicitações de download de arquivos legados por:
archive = client.environments.files.download( environment="YOUR_ENVIRONMENT_ID", path="workspace", ) with open("snapshot.tar", "wb") as f: f.write(archive)JavaScript: substitua as solicitações de download de arquivos legados por:
const bytes = await client.environments.files.download({ environment: "YOUR_ENVIRONMENT_ID", path: "workspace", }); fs.writeFileSync("snapshot.tar", Buffer.from(bytes));REST: substitua
GET /v1beta/files/environment-$ENV_ID:download?alt=mediapor:curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?alt=media" \ -H "x-goog-api-key: $GEMINI_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 ambiente de computação (CPU, memória, execução de sandbox) não é cobrado durante o período de prévia. Consulte Preços para saber os custos de tokens do agente.
Limitações
- Status da prévia:os ambientes e agentes gerenciados estão em prévia. Os recursos e esquemas podem mudar.
- Tamanho da fonte inline:as fontes 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 retidos por sete dias antes de expirar usando a limpeza automática de TTL. Transmitir um ID de ambiente expirado ou
inválido retorna um erro
404 Not Found. - Suporte a arquivos:no momento, o agente só pode ler arquivos de texto e imagem. O suporte a arquivos binários ainda não está disponível.
- Sem montagem da raiz:não é possível definir a raiz (
/) como destino ao adicionar uma fonte personalizada. Sempre especifique um subdiretório.
A seguir
- Visão geral dos agentes: conheça os conceitos principais dos agentes gerenciados.
- Guia de início rápido: comece a criar com conversas multiturno e streaming.
- Agente antigravidade: 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. - Hooks: aplicam proteções de segurança e executam validações de efeitos colaterais no sandbox.