Gemini 中文指南
获取 API 密钥 ↗

托管智能体的运行环境

↓ 下载 MarkdownInteractions API

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

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

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

该 environment 参数 #

该 environment 参数接受三种形式:

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

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

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)

配置环境 #

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

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)

从源安装 #

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

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

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

钩子 #

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

私人来源 #

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

一种选择是存储 凭证 由 ID 引用,因此您只需存储一次秘密,并且每个需要该源的环境都可以引用它:

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

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

对于 私有 Git 存储库, 使用 Basic 与您的身份验证 GitHub 个人访问token (PAT)。使用编码 token x-oauth-basic 作为用户名:

shell
echo -n "x-oauth-basic:ghp_YourPATHere" | base64
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": "*"
                }
            ]
        }
    }
)

对于 私有云存储桶,使用标准 OAuth 2.0 承载 token:

shell
gcloud auth print-access-token
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": "*"
                }
            ]
        }
    },
)

预装软件 #

该沙箱在 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.12numpy, pandas, requests, google-genai, beautifulsoup4, pyyaml, ast-grep-cli
Node.js 22create-next-app, create-vite, typescript

环境变量 #

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

领域类型说明
envobject变量名称到值的映射。值可以是文字 string 或表格的凭证参考 {"credential": "credential-id"}.
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)

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

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

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

网络配置 #

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

领域类型说明
domainstring要匹配的域。使用准确的主机名或 * 对于所有域。
credentialstring已存储的ID 凭证。出口代理解析它并在请求时注入 auth 标头。
transformobject包含平面键值对的对象,表示要注入匹配请求的标头,例如 {"Authorization": "Bearer ..."}.
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)

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

凭证 #

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

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

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)

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

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

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)

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

禁用网络访问 #

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

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)

刷新凭据 #

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

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

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)

环境生命周期 #

环境遵循以下生命周期:

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

环境 API #

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

列出环境 #

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

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

响应类似于以下内容:

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

获取环境 #

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

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

响应类似于以下内容:

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

删除环境 #

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

py
from google import genai

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

client.environments.delete(id="YOUR_ENVIRONMENT_ID")

管理环境中的文件 #

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

列出目录中的文件 #

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

查询参数#

参数类型说明
recursive布尔值当 true,递归列出所有文件和目录。默认值: false.
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}")

响应返回一个 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 最后修改时间戳。

获取文件元数据 #

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

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

响应返回包装在 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"
  }
}

下载单个文件 #

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

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)

下载目录作为 tar 存档 #

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

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

行为矩阵#

以下行为矩阵总结了跨文件和目录端点、HTTP 方法和查询参数的预期响应和存档行为:

请求altrecursiveextractoverwrite回应
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 (目录)mediafalse--目录中直接文件的 Tar 归档
GET /files/{path}?alt=media (目录)mediatrue--递归地对所有文件进行 tar 归档
GET /files?alt=mediamediafalse--仅根级文件的 Tar 存档
PUT /files/{path} (文件)--falsefalse将文件写入路径。退货 409 Conflict 如果它已经存在
PUT /files/{path}?overwrite=true--falsetrue写入或覆盖路径中的文件
PUT /files/{path}?extract=true--truefalse将存档解压到目标目录中。退货 409 Conflict 如果目标文件存在
PUT /files/{path}?extract=true&overwrite=true--truetrue解压存档,替换任何现有文件

上传文件到环境 #

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

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

上传单个文件#

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

响应返回上传文件的元数据,包装在 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.

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

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

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,冲突检查适用于存档中的每个文件,因此如果存在任何目标文件,请求将失败。

下载完整快照(已弃用) #

注意:遗产 /files/environment-{id}:download 端点已弃用。使用 环境文件端点 下载目录或单个文件。

要将现有代码迁移到环境文件 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
    

自托管环境 #

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

要连接自托管环境:

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

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

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

您还可以在以下位置运行运行时 Docker 或无根 Podman。为了进行测试,您可以运行它 本地。本地模式运行 execute_bash 直接在你的主机上,除非你通过 --disable-bash。请参阅 自托管环境指南 有关设置说明。该指南还包括参考架构和部署清单。

定价和资源 #

每个 Google 托管的环境都以固定的 CPU 和内存分配运行。在预览期间,Google 不会为托管环境计算计费。参见 价格 智能体 token 成本。

限制 #

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

后续步骤 #

搜索标题、API 名称或正文内容