이 페이지에서는 Vertex AI Agent Engine 코드 실행에 직접 API를 호출하여 신뢰할 수 없는 코드를 격리된 샌드박스 환경에서 실행하는 방법을 보여줍니다. 직접 API 호출은 에이전트 프레임워크가 호출을 대신 조정하지 않기를 원하거나 코드 실행을 다른 에이전트 프레임워크와 통합하고자 할 때 유용합니다.
이 빠른 시작에서는 다음 작업을 수행합니다.
- 코드 실행에 액세스할 수 있도록 Vertex AI Agent Engine 인스턴스 만들기
- 코드 실행 샌드박스 만들기
- (선택사항) 샌드박스 나열 및 가져오기
- 샌드박스에서 코드 실행
- 동일한 샌드박스를 사용하여 추가 코드를 실행합니다. 샌드박스가 자동으로 상태를 유지하는지 확인합니다.
- 삭제
에이전트 개발 키트(ADK)에서 코드 실행을 사용하는 방법에 대한 자세한 내용은 Vertex AI Agent Engine의 코드 실행 도구를 참고하세요.
시작하기 전에
프로젝트 및 환경 설정
프로젝트 설정
- Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
-
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 theresourcemanager.projects.createpermission. 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.enablepermission. 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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. 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.enablepermission. Learn how to grant roles.
필요한 역할 가져오기
Vertex AI Agent Engine을 사용하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 Vertex AI 사용자(roles/aiplatform.user) IAM 역할을 부여해 달라고 요청하세요.
역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.
커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.
환경 설정
이 섹션에서는 Python 개발 환경을 설정했거나 Python 개발 환경이 포함된 런타임(예: Colab)을 사용하고 있다고 가정합니다.
라이브러리 설치
Vertex AI SDK를 설치합니다.
pip install google-cloud-aiplatform>=1.112.0Vertex AI에 인증
인증하려면 다음 안내를 따르세요.
로컬 셸
gcloud init
gcloud auth application-default login
Colab
from google.colab import auth
auth.authenticate_user()
Vertex AI Agent Engine 인스턴스 만들기
코드 실행을 사용하려면 먼저 Vertex AI Agent Engine 인스턴스를 만들어야 합니다. 코드 실행을 사용하기 위해 에이전트를 배포할 필요는 없습니다. 배포가 없으므로 Vertex AI 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: Vertex AI Agent Engine 인스턴스의 Google Cloud 리전입니다. Vertex AI Agent Engine 지원 리전을 참고하세요.
샌드박스 만들기
코드 실행을 위한 샌드박스를 만듭니다.
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='projects/PROJECT_ID/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID',
config=types.CreateAgentEngineSandboxConfig(
display_name=sandbox_display_name, ttl="3600s"),
)
다음을 바꿉니다.
PROJECT_ID: Google Cloud 프로젝트 ID입니다.
LOCATION: Vertex AI Agent Engine 인스턴스의 Google Cloud 리전입니다. Vertex AI Agent Engine 지원 리전을 참고하세요.
AGENT_ENGINE_ID: Vertex AI Agent Engine 인스턴스의 ID입니다.
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를 호출합니다.
my_code = """
with open("input.txt", "r") as input:
with open("output.txt", "w") as output:
for line in input:
print(line)
output.write(line)
"""
input_data = {
"code": my_code,
"files": [{
"name": "input.txt",
"content": b"Hello, world!"
}]
}
response = client.agent_engines.sandboxes.execute_code(
name = sandbox_name,
input_data = input_data
)
샘플 출력은 다음과 같습니다.
ExecuteSandboxEnvironmentResponse(
outputs=[
Chunk(
data=b'{
"msg_err":"",
"msg_out":"",
}',
mime_type='application/json',
),
chunk(
data=b"hello world!",
mime_type="text/plain"
attributes={
"file_name":"output.txt"
}
)
]
)
다음에 유의하세요.
execute_code는 샌드박스의 TTL(수명)을 재설정합니다.- 출력은 원시 바이트입니다.
- 각 요청 또는 응답에는 최대 100MB의 파일을 포함할 수 있습니다.
샌드박스에서 추가 코드 실행
샌드박스가 상태를 유지한다는 것을 보여주기 위해 동일한 샌드박스에서 코드를 추가로 실행합니다.
python_code = """
with open("output2.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":"",
}',
mime_type='application/json',
),
chunk(
data=b"hello world!",
mime_type="text/plain"
attributes={
"file_name":"output2.txt"
}
)
]
)
응답에는 디코딩해야 하는 파일이 포함됩니다. 다음은 출력을 디코딩하는 방법의 예시입니다.
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'
삭제
이 빠른 시작에서 만든 리소스를 삭제하려면 샌드박스와 Vertex AI Agent Engine 인스턴스를 삭제하세요.
client.agent_engines.sandboxes.delete(name=sandbox_name)
agent_engine.delete()