셸 샌드박스 빠른 시작

셸 샌드박스 는 Agent Platform 인스턴스에 연결된 관리형의 격리된 Linux 컨테이너입니다. 샌드박스는 에이전트가 보낸 셸 명령어를 실행하고 stdout, stderr, 종료 코드를 반환합니다. 사용자 자체 인프라에서 실행되는 것은 없으며 샌드박스가 삭제되면 컨테이너가 소멸됩니다.

에이전트가 신뢰할 수 없거나 생성된 셸 명령어를 실행하거나, 패키지를 설치하거나, 파일을 조작하거나, 환경을 노출하지 않고 명령줄 도구를 실행해야 하는 경우 셸 샌드박스를 사용합니다.

제한사항

  • send_command()execute_code()는 셸 샌드박스에서 작동하지 않습니다. 이러한 메서드는 코드 실행 샌드박스를 타겟팅하고 셸 컨테이너에서 허용하지 않는 Python 페이로드를 전송합니다. 셸 샌드박스에서 /exec를 사용합니다.

시작하기 전에

프로젝트 및 환경 설정

프로젝트 설정

  1. 계정에 로그인합니다. Google Cloud 를 처음 사용하는 경우 Google Cloud, 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. 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

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

  4. 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

  5. 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

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

  7. 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 사용자 (roles/aiplatform.user).

라이브러리 설치

Agent Platform 모듈로 SDK를 설치합니다.

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

인증

애플리케이션 기본 사용자 인증 정보로 인증하려면 다음 단계를 따르세요.

gcloud auth application-default login

Agent Platform 인스턴스 만들기

셸 샌드박스를 사용하려면 먼저 Agent Platform 인스턴스를 만듭니다. 셸 샌드박스를 사용하기 위해 에이전트를 배포할 필요는 없습니다. 배포 없이도 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 리전입니다. 지원되는 리전을 참조하세요.

셸 샌드박스 만들기

샌드박스를 만들 때 다음 중 하나 이상을 제공해야 합니다.

  • 환경이 설정된 spec (shell_environment)
  • 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에 도달합니다.

명령어 실행

샌드박스에서 셸 명령어를 실행하려면 명령어를 컨테이너로 전송하는 도우미 함수 execute_bash()를 사용합니다.

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

명령어는 stdout, stderr, returncode, duration_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는 없습니다.
  • 각 명령어는 새 셸에서 실행되므로 cd 및 셸 변수는 호출 간에 전달되지 않습니다. 하나의 명령어에서 연결하거나 /workspace 아래의 파일에 상태를 씁니다.
  • 템플릿에서 아웃바운드 인터넷 액세스를 사용 설정하지 않는 한 사용 중지됩니다.

정리

샌드박스를 삭제하고 요금이 발생하지 않도록 하려면 다음을 실행합니다.

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

다음 단계