管理沙盒模板

每个沙盒都由一个沙盒环境模板提供支持,该模板描述了要运行的容器映像。沙盒模板可作为自定义容器沙盒的蓝图。此页面演示了如何使用 Agent Platform SDK 管理沙盒模板的生命周期。您可以列出现有模板、查看其详细信息,或在不再需要时将其删除。

如需修改模板的配置(例如更改容器映像),请删除现有模板,然后使用更新后的配置创建新模板。

准备工作

如需管理沙盒模板,您需要拥有项目的以下角色:

  • Agent Platform User (roles/aiplatform.user)

在沙盒之间重复使用模板

对于计算机使用和 shell 沙盒,如果您未指定模板,系统会为沙盒创建默认模板(DEFAULT_CONTAINER_CATEGORY_COMPUTER_USE 或 DEFAULT_CONTAINER_CATEGORY_SHELL_SANDBOX)。

每次不指定模板名称的 create() 调用都会创建一个新模板。删除沙盒不会删除模板,因此您需要单独删除模板。如果您创建了许多沙盒,建议您重复使用模板以节省资源。

创建模板:

from agentplatform._genai import types

template_op = client.agent_engines.sandboxes.templates.create(
    name=instance_name,
    display_name="shell-sandbox-template",
    config=types.CreateSandboxEnvironmentTemplateConfig(
        default_container_environment=types.SandboxEnvironmentTemplateDefaultContainerEnvironment(
            default_container_category=types.DefaultContainerCategory.DEFAULT_CONTAINER_CATEGORY_SHELL_SANDBOX,
        ),
    ),
)
template = template_op.response.name

通过设置 sandbox_environment_template 将每个沙盒与模板相关联:

operation = client.sandboxes.create(
    name=instance_name,
    spec={"shell_environment": {}},
    config={
        "sandbox_environment_template": template,
        "wait_for_completion": True,
    },
)

列出模板

如需列出与 Agent Platform 实例关联的所有沙盒模板,请执行以下操作:

import agentplatform

client = agentplatform.Client(project='PROJECT_ID', location='LOCATION')
instance_name = 'projects/PROJECT_ID/locations/LOCATION/reasoningEngines/INSTANCE_ID'

templates_response = client.sandboxes.templates.list(name=instance_name)

for template in templates_response.sandbox_environment_templates:
    print(template.name)

替换以下内容:

  • PROJECT_ID:您的 Cloud de Confiance 项目 ID。
  • LOCATION:Agent Platform 实例的 Cloud de Confiance 区域。 请参阅支持的地区。
  • INSTANCE_ID:Agent Platform 实例 ID。

查看模板详细信息

如需查看特定沙盒模板的配置,请执行以下操作:

template_name = 'projects/PROJECT_ID/locations/LOCATION/reasoningEngines/INSTANCE_ID/SandboxEnvironmentTemplate/TEMPLATE_ID'

template = client.sandboxes.templates.get(name=template_name)
print(template)

替换以下内容:

  • PROJECT_ID:您的 Cloud de Confiance 项目 ID。
  • LOCATION:Agent Platform 实例的 Cloud de Confiance 区域。 请参阅支持的地区。
  • INSTANCE_ID:包含沙盒模板的 Agent Platform 实例 ID。
  • TEMPLATE_ID:沙盒模板 ID。

查看沙盒的模板

如需查看与沙盒关联的沙盒模板,请运行以下命令:

print(sandbox.sandbox_environment_template)

删除模板

如需删除沙盒模板,请执行以下操作:

client.sandboxes.templates.delete(name=template_name)
print("Template deleted.")