이 페이지에서는 Agent Engine 코드 실행에 직접 API를 호출하여 신뢰할 수 없는 코드를 격리된 샌드박스 환경에서 실행하는 방법을 보여줍니다. 직접 API 호출은 에이전트 프레임워크가 호출을 대신 조정하지 않기를 원하거나 코드 실행을 다른 에이전트 프레임워크와 통합하고자 할 때 유용합니다.
이 빠른 시작에서는 다음 작업을 수행합니다.
- 코드 실행에 액세스할 수 있도록 Agent Engine 인스턴스 만들기
- 코드 실행 샌드박스 만들기
- 샌드박스 나열 및 가져오기(선택사항)
- 샌드박스에서 코드 실행
- 동일한 샌드박스를 사용하여 추가 코드를 실행합니다. 샌드박스가 자동으로 상태를 유지하는지 확인합니다.
- 삭제
시작하기 전에
프로젝트 및 환경 설정
프로젝트 설정
- 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.
-
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. -
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. PROJECT_ID
: Google Cloud 프로젝트 ID입니다.LOCATION
: 에이전트 엔진의 Google Cloud 리전입니다.SANDBOX_DISPLAY_NAME
: 코드 실행 샌드박스 환경에 대한 인간이 읽을 수 있는 이름입니다.execute_code
는 샌드박스의 TTL(수명)을 재설정합니다.- 파일은 요청에 인라인으로 포함되어야 하며 base64로 인코딩되어야 합니다.
- 각 요청 또는 응답에는 최대 100MB의 파일을 포함할 수 있습니다.
필요한 역할 가져오기
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
다음을 바꿉니다.
샌드박스 만들기
코드 실행을 위한 샌드박스를 만듭니다.
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
다음을 바꿉니다.
샌드박스 설정은 코딩 언어 및 머신 구성을 포함해 추가로 구성할 수도 있습니다.
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_PYTHON
및 LANGUAGE_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'),
]
)
다음에 유의하세요.
샌드박스에서 추가 코드 실행
샌드박스가 상태를 유지한다는 것을 보여주기 위해 동일한 샌드박스에서 코드를 추가로 실행합니다.
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()