# 托管智能体的运行环境

环境是 Linux 沙箱，为智能体提供一个执行代码和保存文件的隔离位置。它们与交互上下文分离，因此您可以在多个交互中重用相同的环境或随时重新开始。默认情况下，Google 托管沙箱，或者您可以连接 [自托管环境](/docs/agent-environment#self-hosted-environments) 在您自己的基础设施中运行工具。

以下示例演示了如何创建与新远程环境的交互并检索其 ID：

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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}`);
```
{% /tab %}

{% tab label="REST" %}
```shell
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"
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

## 该 `environment` 参数  {% #the-environment-parameter %}

该 `environment` 参数接受三种形式：

| 形式         | 示例                         | 何时使用                   |
| ---------- | -------------------------- | ---------------------- |
| `"remote"` | `environment="remote"`     | 提供一个新的沙箱。              |
| 环境ID       | `environment="env_abc123"` | 重用现有沙箱及其所有文件和包。        |
| 配置对象       | `environment={...}`        | 使用源、网络规则、环境变量或组合配置新沙箱。 |

下面的例子演示了三种使用方法 `environment`
参数。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# 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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

// 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);
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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"
            }
        ]
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

// 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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

## 配置环境  {% #configure-an-environment %}

设置环境的一种方法是告诉智能体您需要安装什么。它处理依赖性解析和故障排除。环境准备好后，保存 `environment_id` 并重复使用它。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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"
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

### 从源安装  {% #mount-from-a-source %}

如果您确切知道智能体需要哪些文件，请在一次调用中挂载它们，而不是迭代。的 `environment` 配置对象接受一个 `sources` 数组具有三种类型：

| 来源类型    | `type` 值     | 说明                                      | 限制                |
| ------- | ------------ | --------------------------------------- | ----------------- |
| Git 存储库 | `repository` | 将存储库从 URL 克隆到沙箱中 `target`.              | 500 MB            |
| 云存储     | `gcs`        | 将文件或目录从 Cloud Storage 复制到沙盒中： `target`. | 2国标               |
| 内联内容    | `inline`     | 将原始文本内容写入沙箱中的文件 `target`.               | 每个文件 1 MB，2 总计 MB |

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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"
            }
        ]
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

您可以结合使用这两种方法：以声明方式挂载已知源，然后通过后续交互进行迭代以安装包或运行安装脚本。您无法设置 root (`/`) 作为添加自定义源时的目标，您必须始终指定一个子目录。

### 钩子  {% #hooks %}

您还可以安装一个 `.agents/hooks.json` 将配置文件和自定义拦截脚本放入沙箱中，以强制执行安全防护措施或在工具执行时运行自动验证。有关架构定义和代码示例，请参阅 [钩子](/docs/agent-hooks).

### 私人来源  {% #private-sources %}

您还可以通过在网络配置中验证源域来从私有 GitHub 存储库或私有 Cloud Storage 存储桶下载。

一种选择是存储 [凭证](/docs/agent-credentials) 由 ID 引用，因此您只需存储一次秘密，并且每个需要该源的环境都可以引用它：

```json
"network": {
    "allowlist": [
        { "domain": "github.com", "credential": "github-production" },
        { "domain": "*" }
    ]
}
```

您还可以将标题设置为内联 `transform`，如以下示例所示。出口代理以相同的方式应用这两种形式，并且在这两种情况下，秘密都不会落在沙箱内。

对于 **私有 Git 存储库**, 使用 `Basic` 与您的身份验证 [GitHub 个人访问token (PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)。使用编码 token `x-oauth-basic` 作为用户名：

```shell
echo -n "x-oauth-basic:ghp_YourPATHere" | base64
```

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
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": "*"
                }
            ]
        }
    }
)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```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: "*"
                }
            ]
        }
    },
});
```
{% /tab %}

{% tab label="REST" %}
```shell
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": "*"
                }
            ]
        }
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

对于 **私有云存储桶**，使用标准 OAuth 2.0 承载 token：

```shell
gcloud auth print-access-token
```

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
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": "*"
                }
            ]
        }
    },
)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```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: "*"
                }
            ]
        }
    },
});
```
{% /tab %}

{% tab label="REST" %}
```shell
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": "*"
                }
            ]
        }
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

## 预装软件  {% #pre-installed-software %}

该沙箱在 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`                                                                                                         |

## 环境变量  {% #environment-variables %}

使用 `env` 字段用于设置沙箱内的环境变量。每个条目将变量名称映射到用于配置的文字字符串或对存储的引用 [凭证](/docs/agent-credentials) 为了一个秘密。 智能体以在任何 shell 中的方式查看它们，因此从进程环境读取的工具和脚本无需额外接线即可获取它们。

| 领域    | 类型       | 说明                                                                    |
| ----- | -------- | --------------------------------------------------------------------- |
| `env` | `object` | 变量名称到值的映射。值可以是文字 `string` 或表格的凭证参考 `{"credential": "credential-id"}`. |

{% tabs %}
{% tab filename="env_vars.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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)
```
{% /tab %}

{% tab filename="env_vars.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
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"}
        }
    }
}'
```
{% /tab %}
{% /tabs %}

变量适用于智能体在该交互中运行的每个命令，包括 shell 命令、构建步骤以及它启动的任何进程。

这两种值类型的行为不同。文字字符串以纯文本形式写入容器中。凭证引用则不然：变量接收占位符，并且出口代理仅在对该凭证的受信任域的出站请求中替换真正的秘密。参见 [使用凭据作为环境变量](/docs/agent-credentials#environment-variables)
了解它是如何运作的。

注意：沙箱中运行的任何东西都可以读取文字值，包括智能体本身。使用它们进行配置，例如 `NODE_ENV`，不是为了秘密。每个秘密都属于凭证。

## 网络配置  {% #network-configuration %}

默认情况下，环境具有不受限制的出站网络访问。使用 `network` 字段来限制出站流量到特定域。每条规则指定一个 `domain`，加上一个可选的 `credential` 注入存储的秘密和可选的 `transform` 对象将标头注入到匹配的请求中。这些标头对于每次交互都可以是唯一的，您可以针对同一环境更新它们。

| 领域           | 类型       | 说明                                                            |
| ------------ | -------- | ------------------------------------------------------------- |
| `domain`     | `string` | 要匹配的域。使用准确的主机名或 `*` 对于所有域。                                    |
| `credential` | `string` | 已存储的ID [凭证](/docs/agent-credentials)。出口代理解析它并在请求时注入 auth 标头。  |
| `transform`  | `object` | 包含平面键值对的对象，表示要注入匹配请求的标头，例如 `{"Authorization": "Bearer ..."}`. |

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
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": "*"}
            ]
        }
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

设置允许列表后，仅允许对明确列出的域的请求。您可以使用通配符来匹配子域（例如， `{"domain": "*.example.com"}`），但请注意，这与根域不匹配 `example.com`，必须单独添加。要允许所有其他流量，例如在没有注入标头的情况下路由未列出的域，请添加 `{"domain": "*"}` 作为一个包罗万象的条目。

### 凭证  {% #credentials %}

有两种方法可以验证出站流量，一种是通过 ID 引用的存储凭证，另一种是内联 `transform` 关于允许名单规则。出口代理同时应用于网络上，因此在这两种情况下，秘密都不会进入沙箱，也不会出现在交互负载中。

A [托管凭证](/docs/agent-credentials) 当您想要存储一次秘密并重复使用它时，可以使用它。项目中的每个环境、智能体和触发器都可以引用相同的 ID，并且您可以将其轮换到一个位置。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# 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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

// 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);
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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": "*" }
            ]
        }
    }
}'
```
{% /tab %}
{% /tabs %}

安 `oauth2` 凭据还会自行刷新其访问权限 token，因此当 token 过期时，长时间运行的交互不会中断。参见 [凭证](/docs/agent-credentials) 查看凭证类型和管理操作的完整列表。

您还可以设置内联标题 `transform`。这适用于该值属于单个调用的情况，例如您在创建交互之前生成的 token。以这种方式设置的标头由相同的出口代理注入，它们永远不会作为环境变量或文件暴露在沙箱内。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
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(http_options={"api_version": "v1beta"})

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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```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({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
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>"
                    }
                }
            ]
        }
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

`credential` 和 `transform` 可以出现在同一条规则上。首先应用凭证，然后 `transform` 合并在顶部，因此显式 `transform` 如果两者设置相同的密钥，则 header 获胜。常见的模式是身份验证标头的凭据加上 `transform` 对于服务期望的额外标头。

### 禁用网络访问  {% #disable-network-access %}

要阻止所有出站网络访问，请设置 `network` 到 `disabled`:

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Analyze the local files only.",
    environment={
        "type": "remote",
        "network": "disabled",
    },
)

print(interaction.output_text)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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);
```
{% /tab %}

{% tab label="REST" %}
```shell
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"
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

### 刷新凭据  {% #refresh-credentials %}

内联token如访问token和短暂的API 密钥会过期。您可以通过传递现有的来刷新它们 `environment_id` 与新的一起 `network` 下一次交互时的配置。新的网络规则完全取代了以前的规则，同时保留了环境的文件系统状态（已安装的包、文件、存储库）。

如果您使用存储的 [凭证](/docs/agent-credentials) 相反，你不需要这个。一个 `oauth2` 凭证会自行刷新，轮换任何凭证都是 `PATCH` 在凭证上，引用它的每条许可名单规则都保持不变。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# 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)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

// 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);
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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"
                    }
                }
            ]
        }
    }
}'
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
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 = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

// 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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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, &genai.ClientConfig{HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta"}})
    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)
    }
}
```
{% /tab %}
{% /tabs %}

## 环境生命周期  {% #environment-lifecycle %}

环境遵循以下生命周期：

| 状态      | 行为                                        |
| ------- | ----------------------------------------- |
| **已创建** | 当交互指定时进行配置 `environment: "remote"` 或配置对象。 |
| **活跃**  | 在交互正在进行时运行。                               |
| **空闲**  | 自动快照并在 15 分钟不活动后停止。                       |
| **离线**  | 自上次活动以来保留 7 天。可以通过传递其 ID 来恢复。             |
| **已删除** | 7 天 TTL 保留到期后或手动删除时自动从系统中删除。              |

## 环境 API  {% #environments-api %}

您可以使用环境 API 以编程方式管理沙箱会话。通过枚举环境，您可以发现活动会话 ID，并在客户端连接在长时间运行的任务期间终止时恢复状态。您还可以在工作流结束时检查会话元数据并显式删除环境，而不是等待自动 TTL 过期。

### 列出环境  {% #list-environments %}

列出属于您的项目的活动环境。使用分页参数来控制响应批量大小。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

response = client.environments.list(page_size=10)
for env in response.environments:
    print(f"Environment ID: {env.id}, Status: {env.status}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const response = await client.environments.list({ page_size: 10 });
for (const env of response.environments || []) {
    console.log(`Environment ID: ${env.id}, Status: ${env.status}`);
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments?pageSize=10" \
-H "x-goog-api-key: $GEMINI_API_KEY"
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
import com.google.genai.gaos.models.environments.Environment;
import com.google.genai.gaos.models.environments.ListEnvironmentsResponse;
import java.util.List;

Client client = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

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));
}
```
{% /tab %}

{% tab label="Go" %}
```go
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)
        }
    }
}
```
{% /tab %}
{% /tabs %}

响应类似于以下内容：

```json
{
  "environments": [
    {
      "id": "140128b2a13c12c00a5a0d8cf7af9469",
      "status": "active"
    },
    {
      "id": "362b738275a1d74af6f1c62bc050da73",
      "status": "active"
    }
  ],
  "next_page_token": "Cj...5aE="
}
```

### 获取环境  {% #get-an-environment %}

按资源名称检索特定环境的元数据和配置详细信息。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

env = client.environments.get(id="YOUR_ENVIRONMENT_ID")
print(f"Environment ID: {env.id}, Status: {env.status}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const env = await client.environments.get("YOUR_ENVIRONMENT_ID");
console.log(`Environment ID: ${env.id}, Status: ${env.status}`);
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;
import com.google.genai.gaos.models.environments.Environment;

Client client = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

Environment env = client.environments.getEnvironment("YOUR_ENVIRONMENT_ID").environment().get();
System.out.println("Environment ID: " + env.id().orElse("") + ", Status: " + env.status().orElse(null));
```
{% /tab %}

{% tab label="Go" %}
```go
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)
}
```
{% /tab %}
{% /tabs %}

响应类似于以下内容：

```json
{
  "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"
      }
    ]
  }
}
```

### 删除环境  {% #delete-an-environment %}

当任务或管道完成时，显式终止并删除环境以清理沙箱资源。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

client.environments.delete(id="YOUR_ENVIRONMENT_ID")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

await client.environments.delete("YOUR_ENVIRONMENT_ID");
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \
-H "x-goog-api-key: $GEMINI_API_KEY"
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.HttpOptions;

Client client = Client.builder().httpOptions(HttpOptions.builder().apiVersion("v1beta").build()).build();

client.environments.deleteEnvironment("YOUR_ENVIRONMENT_ID");
```
{% /tab %}

{% tab label="Go" %}
```go
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)
    }
}
```
{% /tab %}
{% /tabs %}

## 管理环境中的文件  {% #download-files-from-the-environment %}

智能体在执行期间创建和修改沙箱内的文件。您可以浏览目录内容、获取文件元数据、将单个文件或整个目录下载为 tar 存档，以及将文件上传或将存档直接提取到环境中。沙盒环境中的存储受到公平使用限制。

### 列出目录中的文件  {% #list-files-in-a-directory %}

列出环境中目录的内容。默认情况下，列出根目录。

#### 查询参数

| 参数          | 类型  | 说明                                 |
| ----------- | --- | ---------------------------------- |
| `recursive` | 布尔值 | 当 `true`，递归列出所有文件和目录。默认值： `false`. |

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# 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}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

// 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}`);
}
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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"
```
{% /tab %}
{% /tabs %}

响应返回一个 `files` 包含每个条目元数据的数组：

```json
{
  "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`       | 字符串 | 文件或目录名称。                 |
| `path`       | 字符串 | 相对于环境根目录的完整路径。           |
| `type`       | 字符串 | 要么 `FILE` 或 `DIRECTORY`. |
| `size_bytes` | 字符串 | 文件大小以字节为单位（仅限文件）。        |
| `mime_type`  | 字符串 | MIME 类型（仅限文件）。           |
| `created`    | 字符串 | ISO 8601 创建时间戳。          |
| `modified`   | 字符串 | ISO 8601 最后修改时间戳。        |

### 获取文件元数据  {% #get-file-metadata %}

按路径获取特定文件的元数据。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const response = await client.environments.files.list({
    environment: "YOUR_ENVIRONMENT_ID",
    path: "src/main.py",
});
const file = response.files?.[0];
if (file) {
    console.log(`Name: ${file.name}, Size: ${file.size_bytes} bytes, Type: ${file.mime_type}`);
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src/main.py" \
  -H "x-goog-api-key: $GEMINI_API_KEY"
```
{% /tab %}
{% /tabs %}

响应返回包装在 `files` 数组：

```json
{
  "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` 错误：

```json
{
  "error": {
    "message": "Path 'nonexistent.txt' not found in environment 'ENV_ID'.",
    "code": "not_found"
  }
}
```

### 下载单个文件  {% #download-a-single-file %}

下载特定文件的内容。在 SDK 中，使用 `download()`
方法。在 REST 请求中，附加 `?alt=media` 查询参数为文件路径。服务器响应 `200 OK` 并流式传输原始文件内容。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

content = client.environments.files.download(
    environment="YOUR_ENVIRONMENT_ID",
    path="src/main.py",
)

with open("main.py", "wb") as f:
    f.write(content)
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

const bytes = await client.environments.files.download({
    environment: "YOUR_ENVIRONMENT_ID",
    path: "src/main.py",
});

fs.writeFileSync("main.py", Buffer.from(bytes));
```
{% /tab %}

{% tab label="REST" %}
```shell
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
```
{% /tab %}
{% /tabs %}

### 下载目录作为 tar 存档  {% #download-a-directory-as-a-tar-archive %}

通过请求目录路径将整个目录下载为 tar 存档 `?alt=media`。这将返回一个 POSIX tar 文件（未压缩）。使用 `recursive=true` 包括嵌套子目录。

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
import tarfile
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# 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")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import { execSync } from "child_process";
import * as fs from "fs";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

// 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");
```
{% /tab %}

{% tab label="REST" %}
```shell
# 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
```
{% /tab %}
{% /tabs %}

#### 行为矩阵

以下行为矩阵总结了跨文件和目录端点、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`      | 解压存档，替换任何现有文件                          |

### 上传文件到环境  {% #upload-a-file %}

使用 HTTP 将单个文件或目录存档直接上传到现有环境沙箱 `PUT`。如果父目录不存在，则会自动创建。环境中的存储受到公平使用限制。

注意：REST 上传使用 `/upload/` 路径前缀，例如 `https://generativelanguage.googleapis.com/upload/v1beta/environments/{environment_id}/files/{path}`. A `PUT` 发送时不带前缀返回一个 `400` 错误。 Python 和 JavaScript 客户端会为您添加前缀。

#### 上传单个文件

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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)")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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)`);
```
{% /tab %}

{% tab label="REST" %}
```shell
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
```
{% /tab %}
{% /tabs %}

响应返回上传文件的元数据，包装在 `files` 数组与列表保持一致并获取端点：

```json
{
  "files": [
    {
      "name": "file.txt",
      "path": "workspace/data/file.txt",
      "type": "FILE",
      "size_bytes": "1024",
      "mime_type": "text/plain"
    }
  ]
}
```

#### 上传并解压目录存档

要在单个请求中播种整个代码库或目录结构，请上传 `.tar` 或 `.tar.gz` 存档与 `extract=true`.

{% tabs %}
{% tab filename="env_setup.py" label="Python" %}
```py
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

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}")
```
{% /tab %}

{% tab filename="env_setup.js" label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";
import * as fs from "fs";

const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });

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}`);
}
```
{% /tab %}

{% tab label="REST" %}
```shell
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
```
{% /tab %}
{% /tabs %}

响应列出了存档写入的每个文件：

```json
{
  "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"
    }
  ]
}
```

注意：存档格式是从有效负载本身检测到的，因此 `.tar` 和 `.tar.gz` 两者都可以工作，无论 `Content-Type` 你发送。

#### 通过可恢复会话上传大文件

对于较大的有效负载，或者通过不可靠的连接上传时，请使用可恢复会话，而不是在一个请求中发送整个正文。可恢复上传将传输分成可以单独重试的块，因此中途失败不会迫使您重新开始。

首先启动会话 `uploadType=resumable`。发送一个空的正文并使用 `X-Upload-Content-Type` 和 `X-Upload-Content-Length` 用于声明媒体类型和您要上传的有效负载的总大小的标头：

```http
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
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` 标头：

```http
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` header 告诉您服务器已提交多少字节，如果块失败，您可以从这里恢复：

```http
HTTP/1.1 308 Resume Incomplete
Range: bytes=0-10485759
Content-Length: 0
```

以同样的方式发送剩余的块：

```http
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>
```

最后的 chunk 完成上传并返回文件元数据，同样 `files` 信封作为单次上传：

```json
{
  "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` 错误并且没有写入任何内容：

```json
{
  "error": {
    "message": "Requested entity already exists",
    "code": "aborted"
  }
}
```

要替换现有文件或目录，请设置 `overwrite=true` （或附加 `?overwrite=true` 休息时）。与 `extract=true`，冲突检查适用于存档中的每个文件，因此如果存在任何目标文件，请求将失败。

### 下载完整快照（已弃用）  {% #download-full-snapshot-deprecated %}

注意：遗产 `/files/environment-{id}:download` 端点已弃用。使用 [环境文件端点](/docs/agent-environment#download-a-directory-as-a-tar-archive) 下载目录或单个文件。

要将现有代码迁移到环境文件 API：

* **Python**：将旧文件下载请求替换为：

  ```py
  archive = client.environments.files.download(
      environment="YOUR_ENVIRONMENT_ID",
      path="workspace",
  )
  with open("snapshot.tar", "wb") as f:
      f.write(archive)
  ```

* **JavaScript**：将旧文件下载请求替换为：

  ```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` 与：

  ```shell
  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
  ```

## 自托管环境  {% #self-hosted-environments %}

您可以连接自托管环境，而不是使用 Google 管理的沙箱。这使得托管智能体在您控制的计算基础设施内执行工具。您的沙箱使用开源协议通过出站 HTTPS 连接 [Gemini API CLI](/docs/cli)，并且不需要入站防火墙端口。

要连接自托管环境：

1. 致电 `POST /v1beta/environments` 使用 `{"mode": "self_hosted"}` 获得一个环境 `id` 以及一次性的 `environment_key`.
1. 运行 `gemini-api environments connect` （来自 [`google-gemini/gemini-api-cli`](https://github.com/google-gemini/gemini-api-cli)）在你的沙箱里 `environment_key`.
1. 通过环境 `id` 在 `environment` 打电话时 `interactions.create`.

**注意：** 托管沙箱选项（`sources`, `network`, `env`, 和 `/files`
快照）仅适用于 Google 托管的环境。自托管环境拒绝它们 `400 INVALID_ARGUMENT`.

以下示例展示了如何连接沙箱提供程序：

* [Google Cloud 运行](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/cloud-run)
* [智能体基板](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/agent-substrate)
* [Cloudflare 沙盒](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/cloudflare)
* [代托纳](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/daytona)
* [E2B](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/e2b)
* [Fly.io（精灵和机器）](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/fly-machines)
* [莫代尔](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/modal)
* [维塞尔沙盒](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/providers/vercel)

您还可以在以下位置运行运行时 [Docker 或无根 Podman](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/containers)。为了进行测试，您可以运行它 [本地](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted/local)。本地模式运行 `execute_bash` 直接在你的主机上，除非你通过 `--disable-bash`。请参阅 [自托管环境指南](https://github.com/google-gemini/gemini-api-cli/tree/main/docs/self-hosted)
有关设置说明。该指南还包括参考架构和部署清单。

## 定价和资源  {% #pricing-resources %}

每个 Google 托管的环境都以固定的 CPU 和内存分配运行。在预览期间，Google 不会为托管环境计算计费。参见 [价格](/docs/pricing#pricing-for-agents) 智能体 token 成本。

## 限制  {% #limitations %}

- **预览状态：** 环境和托管智能体处于预览状态。功能和架构可能会发生变化。
- **内联源大小：** 内联源每个文件限制为 1 MB，所有文件的总计限制为 2 MB。
- **源尺寸**：Git 存储库仅限于 500 MB，Cloud Storage 存储库仅限于 2 GB。
- **环境启动：** 配置新环境最多需要 ~5 秒。这次大型源存储库可能会增加。
- **环境过期：** 使用自动 TTL 清理功能，非活动离线环境将保留 7 天，然后过期。传递过期或无效的环境 ID 将返回 `404 Not Found` 错误。
- **文件支持：** 智能体目前仅限于读取文本和图像文件。二进制文件支持尚不可用。
- **没有从根目录安装：** 您无法设置 root (`/`) 作为添加自定义源时的目标，您必须始终指定一个子目录。

## 后续步骤  {% #whats-next %}

* [智能体概述](/docs/agents)：了解托管智能体的核心概念。
* [快速入门](/docs/managed-agents-quickstart)：开始通过多轮对话和流媒体进行构建。
* [Antigravity 智能体](/docs/antigravity-agent)：探索默认智能体的功能、工具、型号选择和定价。
* [建筑定制智能体](/docs/custom-agents)：使用定义您自己的智能体 `AGENTS.md` 和 `SKILL.md`.
* [钩子](/docs/agent-hooks)：加强安全防护并在沙箱内运行副作用验证。
