Shell 沙盒快速入门

Shell 沙盒是一种托管式隔离 Linux 容器,它与 Agent Platform 实例相关联。 沙盒会运行代理发送的 shell 命令,并返回 stdout、stderr 和退出代码。您的基础架构上不会运行任何内容,并且在删除沙盒时,容器也会被销毁。

当代理需要运行不受信任或生成的 shell 命令、安装软件包、操纵文件或驱动命令行工具而不暴露您的环境时,请使用 shell 沙盒。

限制

  • send_command()execute_code() 不适用于 shell 沙盒。这些方法面向 代码执行沙盒 并发送 Python 载荷,而 shell 容器不接受这些载荷。请将 /exec 与 shell 沙盒搭配使用。

准备工作

设置您的项目和环境。

设置项目

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Gemini Enterprise Agent Platform API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

获取所需的角色

如需使用沙盒,您需要以下角色:

  • 项目的 Agent Platform User (roles/aiplatform.user)。

安装库

安装包含 Agent Platform 模块的 SDK:

pip install "google-cloud-aiplatform[agent_engines]"

身份验证

如需使用应用默认凭据进行身份验证,请执行以下操作:

gcloud auth application-default login

创建 Agent Platform 实例

如需使用 shell 沙盒,请先创建 Agent Platform 实例。 您无需部署代理即可使用 shell 沙盒。 创建 Agent Platform 实例只需几秒钟,无需进行部署。

import vertexai

client = vertexai.Client(project='PROJECT_ID', location='LOCATION')

agent_engine = client.agent_engines.create()
agent_engine_name = agent_engine.api_resource.name

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID。

  • LOCATION:您的 Agent Platform 实例的 Google Cloud 区域。 请参阅支持的区域

创建 shell 沙盒

创建沙盒时,您需要提供以下至少一项:

  • 包含环境集 (shell_environment) 的 spec
  • config.sandbox_environment_template(如果未指定,系统会创建默认模板。如需了解详情,请参阅跨沙盒重复使用模板
  • config.sandbox_environment_snapshot

以下示例在沙盒规范中传递 shell_environment

engine = (
    "projects/PROJECT_ID/locations/LOCATION"
    "/reasoningEngines/INSTANCE_ID"
)

operation = client.agent_engines.sandboxes.create(
    name=engine,
    spec={"shell_environment": {}},
    config={
        "display_name": "my-shell-sandbox",
        "wait_for_completion": True,
        "ttl": "3600s",
    },
)
sandbox = operation.response
print(sandbox.name, sandbox.state)

沙盒准备就绪后,会输出类似于以下内容的响应:

projects/.../sandboxEnvironments/1035360621853409280 SandboxState.STATE_RUNNING

沙盒通常会在大约 20 秒内达到 STATE_RUNNING 状态。

运行命令

如需在沙盒中运行 shell 命令,请使用辅助函数 execute_bash(),该函数会将命令发送到容器:

result = client.sandboxes.execute_bash(
    name=sandbox.name,
    command="echo hello && whoami && pwd",
)
print(result)

该命令会返回 stdoutstderrreturncodeduration_ms

{'stdout': 'hello\nappuser\n/workspace\n', 'stderr': '', 'returncode': 0, 'duration_ms': 8}

execute_bash() 会使用您自己的凭据进行身份验证,因此您无需服务帐号或已签名的 JWT。

可选:您可以明确设置 cwd 以选择工作目录,并设置 timeout 以限制命令的运行时间。否则,沙盒会使用自己的默认值(/workspace 和沙盒的时间限制):

result = client.sandboxes.execute_bash(
    name=sandbox.name,
    command="pytest -q",
    cwd="/workspace/app",
    timeout=120,
)

如需了解命令是否失败,请检查 returncodestderr

result = client.sandboxes.execute_bash(
    name=sandbox.name,
    command="ls /nope",
)
print(result)
{'stdout': '', 'stderr': "ls: cannot access '/nope': No such file or directory\n", 'returncode': 2, 'duration_ms': 5}

使用容器环境时,请注意以下事项:

  • 命令以无特权用户 appuser 身份运行;没有 sudo
  • 每个命令都在新的 shell 中运行,因此 cd 和 shell 变量不会在调用之间传递。将它们链接到一个命令中,或将状态写入 /workspace 下的文件。
  • 除非模板启用出站互联网访问权限,否则该权限处于关闭状态。

清理

如需删除沙盒并停止产生费用,请运行以下命令:

client.agent_engines.sandboxes.delete(name=sandbox.name)
print("Sandbox deleted.")

后续步骤