코드 실행 빠른 시작

이 페이지에서는 에이전트 엔진 코드 실행에 직접 API를 호출하여 격리된 샌드박스 환경에서 신뢰할 수 없는 코드를 실행하는 방법을 보여줍니다. 직접 API 호출은 에이전트 프레임워크가 호출을 조정하지 않도록 하거나 코드 실행을 다른 에이전트 프레임워크와 통합하려는 경우에 유용합니다.

이 빠른 시작에서는 다음 작업을 수행합니다.

  • Code Execution에 액세스하기 위한 Agent Engine 인스턴스 만들기
  • 코드 실행 샌드박스 만들기
  • 샌드박스 나열 및 가져오기 (선택사항)
  • 샌드박스에서 코드 실행
  • 동일한 샌드박스를 사용하여 더 많은 코드를 실행합니다. 샌드박스는 상태를 자동으로 유지합니다.
  • 삭제

시작하기 전에

프로젝트 및 환경 설정

프로젝트 설정

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  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 (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 Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. 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 (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 Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. 필요한 역할 가져오기

    Vertex AI Agent Engine을 사용하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 Vertex AI 사용자 (roles/aiplatform.user) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

    환경 설정

    이 섹션에서는 Python 개발 환경을 설정했거나 Python 개발 환경이 포함된 런타임 (예: Colab)을 사용하고 있다고 가정합니다.

    라이브러리 설치

    Vertex AI SDK를 설치합니다.

      pip install google-cloud-aiplatform>=1.112.0

    Vertex AI에 인증

    인증하려면 다음 단계를 따르세요.

    로컬 셸

    gcloud init
    gcloud auth application-default login
    

    Colab

    from google.colab import auth
    
    auth.authenticate_user()
    

    Agent Engine 인스턴스 만들기

    코드 실행을 사용하려면 먼저 Agent Engine 인스턴스를 만드세요. 코드 실행을 사용하기 위해 에이전트를 배포할 필요는 없습니다. 배포가 없으므로 Agent Engine 인스턴스를 만드는 데는 몇 초면 됩니다.

    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: 에이전트 엔진의 Google Cloud 리전입니다.

    샌드박스 만들기

    코드 실행을 위한 샌드박스를 만듭니다.

    operation = client.agent_engines.sandboxes.create(
        spec={"code_execution_environment": {}},
        name=agent_engine_name,
        config=types.CreateAgentEngineSandboxConfig(display_name=SANDBOX_DISPLAY_NAME)
    )
    
    sandbox_name = operation.response.name
    

    다음을 바꿉니다.

    • SANDBOX_DISPLAY_NAME: 코드 실행 샌드박스 환경의 사람이 읽을 수 있는 이름입니다.

    코딩 언어 및 머신 구성과 같은 샌드박스 설정을 구성할 수도 있습니다.

    operation = client.agent_engines.sandboxes.create(
        spec={
            "code_execution_environment": {
                "code_language": "LANGUAGE_JAVASCRIPT",
                "machine_config": "MACHINE_CONFIG_VCPU4_RAM4GIB"
            }
        },
        name=agent_engine_name,
        config=types.CreateAgentEngineSandboxConfig(display_name=sandbox_display_name),
    )
    
    sandbox_name = operation.response.name
    

    미리보기 중에는 LANGUAGE_PYTHONLANGUAGE_JAVASCRIPT만 지원됩니다. machine_config을 지정하지 않으면 기본 구성은 vCPU 2개와 RAM 1.5GB입니다. MACHINE_CONFIG_VCPU4_RAM4GIB을 지정하면 샌드박스에 vCPU 4개와 RAM 4GB가 있습니다.

    샌드박스 나열 및 가져오기 (선택사항)

    지정된 Agent Engine 인스턴스와 연결된 모든 샌드박스를 나열합니다.

    sandboxes = client.agent_engines.sandboxes.list(name=agent_engine_name)
    
    for sandbox in sandboxes:
        pprint.pprint(sandbox)
    

    샘플 출력은 다음과 같습니다.

    SandboxEnvironment(
      create_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC)),
      display_name='test_sandbox',
      name=SANDBOX_NAME,
      spec=SandboxEnvironmentSpec(
        code_execution_environment=SandboxEnvironmentSpecCodeExecutionEnvironment()
      ),
      state=<State.STATE_RUNNING: 'STATE_RUNNING'>,
      update_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC))
    )
    

    기존 샌드박스를 가져오려면 다음을 실행합니다.

    sandbox = client.agent_engines.sandboxes.get(name=sandbox_name)
    
    pprint.pprint(sandbox)
    

    샘플 출력은 다음과 같습니다.

    SandboxEnvironment(
      create_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC)),
      display_name='test_sandbox',
      name=SANDBOX_NAME,
      spec=SandboxEnvironmentSpec(
        code_execution_environment=SandboxEnvironmentSpecCodeExecutionEnvironment()
      ),
      state=<State.STATE_RUNNING: 'STATE_RUNNING'>,
      update_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC))
    )
    

    샌드박스에서 코드 실행

    코드를 실행하려면 execute_code를 호출하세요.

    python_code = """
    lines = []
    with open("input.txt", "r") as input:
        for line in input:
            lines.append(line)
    """
    input_data = {
        "code": python_code,
        "files": [{
            "name": "input.txt",
            "content": "aGVsbG8="
        }]
    }
    
    response = client.agent_engines.sandboxes.execute_code(
        name = sandbox_name,
        input_data = input_data
    )
    pprint.pprint(response)
    

    샘플 출력은 다음과 같습니다.

    ExecuteSandboxEnvironmentResponse(
      outputs=[
        Chunk(
          data=b'{"msg_err":"","msg_out":"","output_files":[]}',
          mime_type='application/json'),
      ]
    )
    

    다음에 유의하세요.

    • execute_code는 샌드박스의 TTL (수명)을 재설정합니다.
    • 파일은 요청에 인라인으로 포함되어야 하며 base64로 인코딩되어야 합니다.
    • 각 요청 또는 응답에는 최대 100MB의 파일이 포함될 수 있습니다.

    샌드박스에서 더 많은 코드 실행

    샌드박스가 상태를 유지하는지 확인하려면 동일한 샌드박스에서 코드를 추가로 실행하세요.

    python_code = """
    with open("output.txt", "w") as output:
        for line in lines:
            output.write(line + "World\n")
    """
    input_data = {"code": python_code}
    
    response = client.agent_engines.sandboxes.execute_code(
        name = sandbox_name,
        input_data = input_data
    )
    
    pprint.pprint(response)
    

    샘플 출력은 다음과 같습니다.

    ExecuteSandboxEnvironmentResponse(
      outputs=[
        Chunk(
          data=b'{
            "msg_err":"",
            "msg_out":"",
            "output_files":[{"content":"SGVsbG9Xb3JsZAo=", "name":"output.txt"}],
          }',
          mime_type='application/json',
        ),
      ]
    )
    

    응답에 디코딩해야 하는 파일이 포함되어 있습니다. 다음은 출력을 디코딩하는 방법의 예입니다.

    import base64
    import json
    
    if response.outputs[0].mime_type=="application/json":
        json_output = json.loads(response.outputs[0].data.decode("utf-8"))
        output_file_content = json_output.get("output_files")[0].get("content")
        print(output_file_content.b64decode(output_file_content))
    

    샘플 출력은 다음과 같습니다.

    b'HelloWorld\n'
    

    삭제

    이 빠른 시작에서 만든 리소스를 정리하려면 샌드박스와 Agent Engine 인스턴스를 삭제하세요.

    client.agent_engines.sandboxes.delete(name=sandbox_name)
    agent_engine.delete()
    

    다음 단계