Среды – это управляемые изолированные среды Linux, в которых агенты могут выполнять код и сохранять файлы. Они не зависят от контекста взаимодействия, поэтому вы можете использовать одну и ту же среду для нескольких взаимодействий или начать с нуля в любое время.
В примере ниже показано, как создать взаимодействие с новой удаленной средой и получить ее идентификатор:
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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Install pandas and matplotlib, verify the imports, and print the versions."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment("remote")),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.EnvironmentID != nil {
fmt.Printf("Environment ID: %s\n", *res.Interaction.EnvironmentID)
}
}
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"
}'
Параметр environment
Параметр environment может принимать три значения:
| Форма | Пример | Когда использовать |
|---|---|---|
"remote" |
environment="remote" |
Инициализируйте новую изолированную среду. |
| Идентификатор среды | environment="env_abc123" |
Повторно использовать существующую песочницу со всеми ее файлами и пакетами. |
| Объект конфигурации | environment={...} |
Создайте новую изолированную среду с источниками, правилами сети, переменными среды или их сочетанием. |
Ниже приведены примеры использования параметра 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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Fresh sandbox
res1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Write a hello world script."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment("remote")),
}),
})
if err != nil {
log.Fatal(err)
}
interaction := res1.Interaction
// Reuse an existing sandbox
res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Modify the script to accept a name argument."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(*interaction.EnvironmentID)),
PreviousInteractionID: interaction.ID,
}),
})
if err != nil {
log.Fatal(err)
}
_ = res2
// New sandbox with sources
env3 := interactions.Environment{
Sources: []interactions.Source{
{
Type: interactions.SourceTypeRepository.ToPointer(),
Source: genai.Ptr("https://github.com/octocat/Spoon-Knife"),
Target: genai.Ptr("/workspace/spoon-knife"),
},
},
}
res3, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("List all files and summarize the project."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env3)),
}),
})
if err != nil {
log.Fatal(err)
}
_ = res3
if interaction.OutputText != nil {
fmt.Println(*interaction.OutputText)
}
}
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"
}
]
}
}'
Как настроить среду
Один из способов настроить среду – указать агенту, что нужно установить.
Он обрабатывает зависимости и устраняет неполадки. Когда среда будет готова, сохраните environment_id и используйте его повторно.
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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
res1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment("remote")),
}),
})
if err != nil {
log.Fatal(err)
}
interaction := res1.Interaction
// Reuse the configured environment
res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(*interaction.EnvironmentID)),
PreviousInteractionID: interaction.ID,
}),
})
if err != nil {
log.Fatal(err)
}
interaction2 := res2.Interaction
// Reuse the configured environment
res3, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Using the tools in /workspace/tools, list the files."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(*interaction.EnvironmentID)),
PreviousInteractionID: interaction2.ID,
}),
})
if err != nil {
log.Fatal(err)
}
_ = res3
if interaction.OutputText != nil {
fmt.Println(*interaction.OutputText)
}
}
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"
}'
Как подключить источник
Если вы знаете, какие файлы нужны агенту, смонтируйте их за один вызов, а не итеративно. Объект конфигурации environment принимает массив sources с тремя типами:
| Тип источника | На сумму type |
Описание | Ограничение |
|---|---|---|---|
| Хранилище Git | repository |
Клонирует репозиторий из URL в песочницу по адресу target. |
500 МБ |
| Cloud Storage | gcs |
Копирует файл или каталог из Cloud Storage в изолированную среду в target. |
2 ГБ |
| Встроенный контент | inline |
Записывает текстовый контент в файл в песочнице по адресу target. |
1 МБ на файл, 2 МБ всего |
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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Sources: []interactions.Source{
{
Type: interactions.SourceTypeRepository.ToPointer(),
Source: genai.Ptr("https://github.com/octocat/Spoon-Knife"),
Target: genai.Ptr("/workspace/spoon-knife"),
},
{
Type: interactions.SourceTypeGcs.ToPointer(),
Source: genai.Ptr("gs://cloud-samples-data/bigquery/us-states/"),
Target: genai.Ptr("/workspace/gcs-data"),
},
{
Type: interactions.SourceTypeInline.ToPointer(),
Content: genai.Ptr("# Project Notes\n\n- Analyze state population data\n- Create visualizations\n"),
Target: genai.Ptr("/workspace/notes/readme.md"),
},
},
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("List all files under /workspace and describe what you find."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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"
}
]
}
}'
Вы можете использовать оба подхода: сначала декларативно подключить известные источники, а затем с помощью дополнительных взаимодействий установить пакеты или запустить скрипты настройки. При добавлении специального источника нельзя задать в качестве цели корневой каталог (/). Необходимо всегда указывать подкаталог.
Приманки
Вы также можете смонтировать в песочницу файл конфигурации .agents/hooks.json и специальные скрипты перехвата, чтобы обеспечить соблюдение правил безопасности или выполнять автоматическую проверку при каждом запуске инструментов. Определения схем и примеры кода можно найти в разделе Хуки.
Частные источники
Вы также можете скачивать данные из частных репозиториев GitHub или частных сегментов Cloud Storage, выполнив аутентификацию исходного домена в конфигурации сети.
Один из вариантов – использовать сохраненные учетные данные, на которые ссылается идентификатор. В этом случае секрет сохраняется один раз, и все среды, которым нужен этот источник, могут ссылаться на него:
"network": {
"allowlist": [
{ "domain": "github.com", "credential": "github-production" },
{ "domain": "*" }
]
}
Вы также можете задать заголовок встроенным образом с помощью transform, как показано в примерах ниже. Прокси-сервер исходящего трафика применяет обе формы одинаково, и ни в одном из случаев секрет не попадает в песочницу.
Для частных репозиториев Git используйте аутентификацию Basic с токеном личного доступа GitHub (PAT).
Закодируйте токен, используя x-oauth-basic в качестве имени пользователя:
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.builder()
.allowlist(Allowlist.of(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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Sources: []interactions.Source{
{
Type: interactions.SourceTypeRepository.ToPointer(),
Source: genai.Ptr("https://github.com/your-org/backend"),
Target: genai.Ptr("/backend-app"),
},
},
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "github.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Basic YOUR_BASE64_TOKEN",
})),
},
{
Domain: "*",
},
})),
})),
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Run the test for my backend app and fix any issue."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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": "*"
}
]
}
}
}'
Для частных сегментов Cloud Storage используйте стандартный токен OAuth 2.0 Bearer:
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.builder()
.allowlist(Allowlist.of(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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Sources: []interactions.Source{
{
Type: interactions.SourceTypeGcs.ToPointer(),
Source: genai.Ptr("gs://my-private-bucket/data"),
Target: genai.Ptr("/workspace"),
},
},
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "*.googleapis.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Bearer YOUR_GCS_TOKEN",
})),
},
{
Domain: "*",
},
})),
})),
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Analyze the discrepancies across the data in workspace"),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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": "*"
}
]
}
}
}'
Предустановленное ПО
Песочница работает на Ubuntu и поставляется с предустановленными средами выполнения и распространенными пакетами. Агент может устанавливать дополнительные пакеты во время выполнения, используя pip
install или npm install. Пакеты, установленные во время взаимодействия, сохраняются при повторном использовании того же environment_id.
| Категория | Предустановленные пакеты |
|---|---|
| Инструменты 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 |
Переменные среды
Используйте поле env, чтобы задать переменные среды в изолированной среде. Каждая запись сопоставляет имя переменной с литеральной строкой для конфигурации или ссылкой на сохраненные учетные данные для секрета. Агент видит их так же, как и в любой оболочке, поэтому инструменты и скрипты, которые считывают данные из среды процесса, получают их без дополнительных настроек.
| Поле | Тип | Описание |
|---|---|---|
env |
object |
Сопоставление названия переменной со значением. Значение может быть либо литералом string, либо ссылкой на учетные данные в формате {"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"}
}
}
}'
Переменные применяются ко всем командам, которые агент выполняет в рамках взаимодействия, включая команды оболочки, шаги сборки и любые запущенные им процессы.
Эти два типа значений работают по-разному. Строка записывается в контейнер как обычный текст. Ссылка на учетные данные – это не переменная, которая получает плейсхолдер. Прокси-сервер исходящего трафика подставляет реальный секрет только в исходящих запросах к доверенным доменам этих учетных данных. Подробнее о том, как использовать учетные данные в качестве переменных среды…
Конфигурация сети
По умолчанию у сред нет ограничений на исходящий сетевой трафик. Используйте поле network, чтобы ограничить исходящий трафик определенными доменами. Каждое правило содержит domain, а также необязательные credential для вставки сохраненного секрета и объект transform для вставки заголовков в соответствующие запросы.
Эти заголовки могут быть уникальными для каждого взаимодействия, и вы можете обновлять их для одной и той же среды.
| Поле | Тип | Описание |
|---|---|---|
domain |
string |
Домен для сопоставления. Используйте точное имя хоста или * для всех доменов. |
credential |
string |
Идентификатор сохраненных учетных данных. Прокси-сервер исходящего трафика разрешает его и вставляет заголовок авторизации во время запроса. |
transform |
object |
Объект, содержащий плоские пары "ключ-значение", представляющие заголовки, которые нужно внедрить в соответствующие запросы, например {"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.builder()
.allowlist(Allowlist.of(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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "api.github.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Bearer ghp_your_github_token",
})),
},
{
Domain: "pypi.org",
},
{
Domain: "*",
},
})),
})),
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Fetch the latest issues from the GitHub API for my-org/my-repo."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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": "*"}
]
}
}
}'
Если белый список настроен, разрешены только запросы к доменам, которые в нем указаны. Вы можете использовать подстановочные знаки для сопоставления субдоменов (например, {"domain":
"*.example.com"}), но помните, что это не относится к корневому домену
example.com, который необходимо добавить отдельно. Чтобы разрешить весь остальной трафик, например маршрутизацию доменов, не указанных в списке, без добавленных заголовков, добавьте {"domain": "*"} в качестве записи для всех остальных случаев.
Учетные данные
Исходящий трафик можно аутентифицировать двумя способами: с помощью сохраненных учетных данных, на которые ссылается идентификатор, и с помощью встроенного тега transform в правиле белого списка. Прокси-сервер исходящего трафика применяется как к проводному, так и к беспроводному подключению, поэтому секретный ключ никогда не попадает в песочницу и не появляется в полезной нагрузке.
Управляемые учетные данные позволяют сохранить секрет один раз и использовать его повторно. Каждая среда, агент и триггер в вашем проекте могут ссылаться на один и тот же идентификатор, который вы можете изменить в одном месте.
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": "*" }
]
}
}
}'
Учетные данные oauth2 также самостоятельно обновляют токен доступа, поэтому длительное взаимодействие не прерывается, когда срок действия токена истекает. Полный список типов учетных данных и операций по управлению ими приведен в разделе Учетные данные.
Вы также можете задать заголовки встроенными в transform. Этот вариант подходит, если значение относится к одному вызову, например к токену, который вы создаете непосредственно перед взаимодействием. Заголовки, заданные таким образом, внедряются тем же исходящим прокси-сервером и никогда не предоставляются в изолированной среде в виде переменных среды или файлов.
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.builder()
.allowlist(Allowlist.of(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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"os/exec"
"strings"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
// Fetch a short-lived access token from your local gcloud CLI
out, err := exec.Command("gcloud", "auth", "print-access-token").Output()
if err != nil {
log.Fatal(err)
}
gcloudToken := strings.TrimSpace(string(out))
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "storage.googleapis.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Bearer " + gcloudToken,
})),
},
})),
})),
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("List the files in gs://my-bucket/reports/ using the GCS JSON API."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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 и transform могут быть указаны в одном правиле. Сначала применяется учетные данные, а затем объединяется заголовок transform, поэтому, если оба задают один и тот же ключ, приоритет имеет явный заголовок transform. Часто используется шаблон, в котором учетные данные для заголовка аутентификации дополняются transform для дополнительных заголовков, которые сервис ожидает получить вместе с ним.
Как отключить доступ к сети
Чтобы заблокировать весь исходящий сетевой трафик, задайте для параметра network значение 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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
env := interactions.Environment{
Network: genai.Ptr(interactions.NewNetwork(interactions.NetworkEnumDisabled)),
}
res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Analyze the local files only."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(env)),
}),
})
if err != nil {
log.Fatal(err)
}
if res.Interaction.OutputText != nil {
fmt.Println(*res.Interaction.OutputText)
}
}
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"
}
}'
Как обновить учетные данные
Встроенные токены, например токены доступа и ключи API с коротким сроком действия, имеют ограниченный срок действия.
Чтобы обновить их, передайте существующий параметр environment_id вместе с новой конфигурацией network при следующем взаимодействии. Новые правила сети полностью заменяют предыдущие, а состояние файловой системы среды (установленные пакеты, файлы, репозитории) сохраняется.
Если вы используете сохраненные учетные данные, этот шаг не нужен. Учетные данные oauth2 обновляются автоматически, а при смене любых учетных данных PATCH не затрагивает правила белого списка, в которых они упоминаются.
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.builder()
.allowlist(Allowlist.of(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.builder()
.allowlist(Allowlist.of(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(""));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
"google.golang.org/genai/interactions/models/interactions"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// First interaction: use an initial token
initialEnv := interactions.Environment{
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "storage.googleapis.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Bearer INITIAL_TOKEN",
})),
},
})),
})),
}
firstRes, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("List the files in gs://my-bucket/reports/ using the GCS JSON API."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(initialEnv)),
}),
})
if err != nil {
log.Fatal(err)
}
first := firstRes.Interaction
// Later: refresh the token on the same environment
refreshedEnv := interactions.Environment{
EnvironmentID: first.EnvironmentID,
Network: genai.Ptr(interactions.NewNetwork(interactions.EnvironmentNetworkEgressAllowlist{
Allowlist: genai.Ptr(interactions.NewAllowlist([]interactions.AllowlistEntry{
{
Domain: "storage.googleapis.com",
Transform: genai.Ptr(interactions.NewTransform(map[string]string{
"Authorization": "Bearer REFRESHED_TOKEN",
})),
},
})),
})),
}
secondRes, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
Body: operations.NewCreateInteractionRequestBody(interactions.CreateAgentInteraction{
Agent: interactions.AgentOption("antigravity-preview-09-2026"),
Input: interactions.NewInteractionsInput("Now download the file reports/q1.csv from the same bucket."),
Environment: genai.Ptr(interactions.NewCreateAgentInteractionEnvironment(refreshedEnv)),
}),
})
if err != nil {
log.Fatal(err)
}
if secondRes.Interaction.OutputText != nil {
fmt.Println(*secondRes.Interaction.OutputText)
}
}
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"
}
}
]
}
}
}'
Жизненный цикл среды
Жизненный цикл сред выглядит следующим образом:
| Штат | Поведение |
|---|---|
| Создано | Предоставляется, когда во взаимодействии указан объект environment: "remote" или объект конфигурации. |
| Активно | Выполняется во время взаимодействия. |
| Бездействие | Автоматический снимок экрана, который был остановлен после 15 минут бездействия. |
| Офлайн | Хранится в течение семи дней с момента последней активности. Можно возобновить, передав его идентификатор. |
| Удалено | Автоматически удаляются из системы после истечения срока хранения TTL (7 дней) или при удалении вручную. |
Environments API
Вы можете использовать Environments API для программного управления сеансами в изолированной среде. Перечисление сред позволяет обнаруживать активные идентификаторы сеансов и восстанавливать состояние, если подключение клиента завершается во время выполнения длительной задачи. Вы также можете проверять метаданные сеанса и удалять среды после завершения рабочих процессов, не дожидаясь автоматического истечения срока жизни.
Получение списка сред
Список активных сред, относящихся к вашему проекту. Используйте параметры разбивки на страницы, чтобы управлять размером пакета ответов.
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));
}
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
interactionssdk "google.golang.org/genai/interactions"
"google.golang.org/genai/interactions/models/components"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
sdk := interactionssdk.New(interactionssdk.WithSecurity(components.Security{
APIKey: genai.Ptr(os.Getenv("GEMINI_API_KEY")),
}))
res, err := sdk.Environments.ListEnvironments(ctx, operations.ListEnvironmentsRequest{
PageSize: genai.Ptr(10),
})
if err != nil {
log.Fatal(err)
}
if res.ListEnvironmentsResponse != nil {
for _, env := range res.ListEnvironmentsResponse.Environments {
fmt.Printf("Environment ID: %s, Status: %v\n", env.ID, env.Status)
}
}
}
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments?pageSize=10" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Ответ будет выглядеть примерно так:
{
"environments": [
{
"id": "140128b2a13c12c00a5a0d8cf7af9469",
"status": "active"
},
{
"id": "362b738275a1d74af6f1c62bc050da73",
"status": "active"
}
],
"next_page_token": "Cj...5aE="
}
Как получить среду
Получение метаданных и сведений о конфигурации для определенной среды по ее названию ресурса.
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));
Проложить маршрут
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
interactionssdk "google.golang.org/genai/interactions"
"google.golang.org/genai/interactions/models/components"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
sdk := interactionssdk.New(interactionssdk.WithSecurity(components.Security{
APIKey: genai.Ptr(os.Getenv("GEMINI_API_KEY")),
}))
res, err := sdk.Environments.GetEnvironment(ctx, operations.GetEnvironmentRequest{
ID: "YOUR_ENVIRONMENT_ID",
})
if err != nil {
log.Fatal(err)
}
env := res.Environment
fmt.Printf("Environment ID: %s, Status: %v\n", env.ID, env.Status)
}
REST
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Ответ будет выглядеть примерно так:
{
"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"
}
]
}
}
Удаление среды
Явно завершайте и удаляйте среду, чтобы очистить ресурсы песочницы, когда ваши задачи или конвейеры будут выполнены.
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");
Проложить маршрут
package main
import (
"context"
"log"
"os"
"google.golang.org/genai"
interactionssdk "google.golang.org/genai/interactions"
"google.golang.org/genai/interactions/models/components"
"google.golang.org/genai/interactions/models/operations"
)
func main() {
ctx := context.Background()
sdk := interactionssdk.New(interactionssdk.WithSecurity(components.Security{
APIKey: genai.Ptr(os.Getenv("GEMINI_API_KEY")),
}))
_, err := sdk.Environments.DeleteEnvironment(ctx, operations.DeleteEnvironmentRequest{
ID: "YOUR_ENVIRONMENT_ID",
})
if err != nil {
log.Fatal(err)
}
}
REST
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Как управлять файлами в среде
Во время выполнения агент создает и изменяет файлы в песочнице. Вы можете просматривать содержимое каталогов, получать метаданные файлов, скачивать отдельные файлы или целые каталоги в виде архивов TAR, а также загружать файлы или извлекать архивы непосредственно в среду. В тестовых средах действуют ограничения на использование хранилища.
Как посмотреть список файлов в каталоге
Перечислять содержимое каталога в среде. По умолчанию выводится список корневого каталога.
Параметры запроса
| Параметр | Тип | Описание |
|---|---|---|
recursive |
Логическое значение | Если указан параметр true, все файлы и каталоги будут перечислены рекурсивно. По умолчанию: 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"
В ответе возвращается массив files с метаданными для каждой записи:
{
"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"
}
]
}
Поля для ввода файлов
| Поле | Тип | Описание |
|---|---|---|
name |
string | Название файла или каталога. |
path |
string | Полный путь относительно корневого каталога среды. |
type |
string | FILE или DIRECTORY. |
size_bytes |
string | Размер файла в байтах (только для файлов). |
mime_type |
string | MIME-тип (только для файлов). |
created |
string | Временная метка создания в формате ISO 8601. |
modified |
string | Временная метка последнего изменения в формате ISO 8601. |
Как получить метаданные файла
Получение метаданных для определенного файла по пути.
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"
В ответе возвращаются метаданные файла, заключенные в массив 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"
}
]
}
Если такого файла не существует, API вернет ошибку 404:
{
"error": {
"message": "Path 'nonexistent.txt' not found in environment 'ENV_ID'.",
"code": "not_found"
}
}
Как скачать один файл
Скачать содержимое определенного файла. В SDK используйте метод download(). В запросах REST добавьте параметр запроса ?alt=media к пути к файлу. Сервер отвечает кодом 200 OK и передает необработанный контент файла.
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
Как скачать каталог в виде архива TAR
Чтобы скачать весь каталог в виде архива TAR, запросите путь к каталогу с помощью команды ?alt=media. Будет возвращен файл POSIX tar (не сжатый с помощью gzip). Используйте символ "больше" (recursive=true), чтобы включить вложенные подкаталоги.
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
Матрица поведения
В таблице ниже приведены ожидаемые ответы и поведение архива для конечных точек файлов и каталогов, методов HTTP и параметров запроса.
| Запрос | alt |
recursive |
extract |
overwrite |
Ответ |
|---|---|---|---|---|---|
GET /files |
(нет) | (нет) | - | - | Список корневого каталога в формате JSON |
GET /files/{path} (файл) |
(нет) | - | - | - | Метаданные файла в формате JSON |
GET /files/{path} (направление) |
(нет) | false |
- | - | Список дочерних элементов в формате JSON |
GET /files/{path} (направление) |
(нет) | true |
- | - | Список всех дочерних объектов в формате JSON |
GET /files/{path}?alt=media (файл) |
media |
- | - | - | Необработанное содержимое файла |
GET /files/{path}?alt=media (направление) |
media |
false |
- | - | Архив TAR с файлами в каталоге |
GET /files/{path}?alt=media (направление) |
media |
true |
- | - | Архив tar всех файлов рекурсивно |
GET /files?alt=media |
media |
false |
- | - | Архив tar только с файлами корневого уровня |
PUT /files/{path} (файл) |
- | - | false |
false |
Записывает файл по указанному пути. Возвращает значение 409 Conflict, если оно уже существует. |
PUT /files/{path}?overwrite=true |
- | - | false |
true |
Записывает или перезаписывает файл по указанному пути. |
PUT /files/{path}?extract=true |
- | - | true |
false |
Распаковывает архив в целевой каталог. Возвращает значение 409 Conflict, если существует какой-либо целевой файл. |
PUT /files/{path}?extract=true&overwrite=true |
- | - | true |
true |
Распаковывает архив, заменяя существующие файлы. |
Как загрузить файлы в среду
Загружайте отдельные файлы или архивы каталогов непосредственно в существующую песочницу среды с помощью HTTP PUT. Если родительских каталогов не существует, они будут созданы автоматически. Для хранилища в средах действуют ограничения на использование.
Как загрузить один файл
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
В ответе возвращаются метаданные загруженного файла, заключенные в массив files для единообразия с конечными точками list и get:
{
"files": [
{
"name": "file.txt",
"path": "workspace/data/file.txt",
"type": "FILE",
"size_bytes": "1024",
"mime_type": "text/plain"
}
]
}
Как загрузить и извлечь архив каталога
Чтобы передать в одном запросе весь код или структуру каталогов, загрузите архив .tar или .tar.gz с помощью 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
В ответе перечислены все файлы, записанные в архив:
{
"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"
}
]
}
Как загружать большие файлы с помощью сеанса с возможностью возобновления
При загрузке больших файлов или при нестабильном подключении используйте сеанс с возможностью возобновления вместо отправки всего тела запроса. При возобновляемой загрузке передача разбивается на фрагменты, которые можно повторить по отдельности, поэтому при сбое в середине процесса вам не придется начинать все заново.
Начните сеанс с помощью uploadType=resumable. Отправьте пустой запрос и используйте заголовки X-Upload-Content-Type и X-Upload-Content-Length, чтобы указать тип медиаконтента и общий размер полезной нагрузки, которую вы планируете загрузить:
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
URL сеанса передается в ответе в заголовке Location. В этом URL уже есть upload_id, поэтому ключ API не нужен:
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
Загрузите полезную нагрузку по этому URL частями. Каждый фрагмент объявляет диапазон байтов и общий размер с помощью заголовка 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>
Все фрагменты, кроме последнего, возвращают значение 308 Resume Incomplete. Заголовок Range сообщает, сколько байтов сервер уже передал. Если передача фрагмента не удалась, она возобновляется с этого места.
HTTP/1.1 308 Resume Incomplete
Range: bytes=0-10485759
Content-Length: 0
Отправьте оставшиеся фрагменты тем же способом:
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>
Последний фрагмент завершает загрузку и возвращает метаданные файла в том же конверте files, что и при однократной загрузке:
{
"files": [
{
"name": "large_dataset.bin",
"path": "workspace/data/large_dataset.bin",
"type": "FILE",
"size_bytes": "20971520",
"mime_type": "application/octet-stream"
}
]
}
Возобновляемые сеансы также работают с extract и overwrite. Укажите эти параметры запроса в исходном запросе, а не в отдельных фрагментах.
Защита от перезаписи
По умолчанию для overwrite задано значение false. Если целевой путь уже существует, запрос возвращает ошибку 409 Conflict и ничего не записывается:
{
"error": {
"message": "Requested entity already exists",
"code": "aborted"
}
}
Чтобы заменить существующий файл или каталог, задайте параметр overwrite=true (или добавьте ?overwrite=true в REST). При использовании extract=true проверка конфликтов применяется к каждому файлу в архиве, поэтому запрос завершается неудачно, если существует какой-либо целевой файл.
Скачать полный снимок (устаревший)
Чтобы перенести существующий код на API файлов среды:
Python: замените устаревшие запросы на скачивание файлов следующими:
archive = client.environments.files.download( environment="YOUR_ENVIRONMENT_ID", path="workspace", ) with open("snapshot.tar", "wb") as f: f.write(archive)JavaScript замените устаревшие запросы на скачивание файлов на:
const bytes = await client.environments.files.download({ environment: "YOUR_ENVIRONMENT_ID", path: "workspace", }); fs.writeFileSync("snapshot.tar", Buffer.from(bytes));REST: замените
GET /v1beta/files/environment-$ENV_ID:download?alt=mediaна: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
Цены и ресурсы
Каждая среда работает с фиксированным распределением ресурсов:
| Ресурс | Значение |
|---|---|
| ЦП | 4 ядра |
| Память | 16 ГБ |
Вычислительные ресурсы среды (процессор, память, выполнение в изолированной среде) не оплачиваются в период предварительной версии. Информацию о стоимости токенов агента можно найти на странице Цены.
Ограничения
- Статус предварительной версии. Среды и управляемые агенты находятся на этапе предварительной версии. Функции и схемы могут меняться.
- Размер встроенного источника. Размер встроенных источников ограничен 1 МБ на файл и 2 МБ на все файлы.
- Размер источника. Размер хранилищ Git ограничен 500 МБ, а хранилищ Cloud Storage – 2 ГБ.
- Запуск среды. Подготовка новой среды занимает до пяти секунд. Если исходный репозиторий большой, это время может увеличиться.
- Срок действия среды. Неактивные офлайн-среды хранятся в течение семи дней, после чего удаляются автоматически. Если передать идентификатор среды, у которого истек срок действия или который является недействительным, будет возвращена ошибка
404 Not Found. - Поддержка файлов. В настоящее время агент может читать только текстовые файлы и файлы изображений. Поддержка двоичных файлов пока недоступна.
- Нельзя монтировать из корневого каталога. При добавлении пользовательского источника нельзя задать в качестве целевого корневой каталог (
/). Необходимо указать подкаталог.
Дальнейшие действия
- Обзор агентов. Узнайте об основных понятиях, связанных с управляемыми агентами.
- Краткое руководство. Начните создавать многоходовые диалоги и потоковую передачу данных.
- Antigravity Agent. Изучите возможности, инструменты, выбор модели и цены для агента по умолчанию.
- Создание специальных агентов. Определите собственных агентов, используя
AGENTS.mdиSKILL.md. - Хуки. Обеспечивают соблюдение правил безопасности и выполняют проверки побочных эффектов в песочнице.