Panduan memulai Eksekusi Kode

Halaman ini menunjukkan cara melakukan panggilan API langsung ke Vertex AI Agent Engine Code Execution untuk menjalankan kode yang tidak tepercaya di lingkungan sandbox yang terisolasi. Panggilan API langsung berguna jika Anda tidak ingin framework agen mengatur panggilan untuk Anda atau jika Anda ingin mengintegrasikan Eksekusi Kode dengan framework agen lain.

Dalam panduan memulai ini, Anda akan melakukan tugas berikut:

  • Membuat instance Vertex AI Agent Engine untuk mengakses Eksekusi Kode
  • Membuat sandbox Eksekusi Kode
  • (Opsional) Mencantumkan dan mendapatkan sandbox
  • Menjalankan kode di sandbox
  • Jalankan lebih banyak kode menggunakan sandbox yang sama. Perhatikan bahwa sandbox secara otomatis mempertahankan statusnya.
  • Pembersihan

Untuk mengetahui informasi selengkapnya tentang penggunaan Eksekusi Kode dengan Agent Development Kit (ADK), lihat Alat Eksekusi Kode dengan Vertex AI Agent Engine.

Sebelum memulai

Menyiapkan project dan lingkungan Anda.

Menyiapkan project

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  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 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 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 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

Mendapatkan peran yang diperlukan

Untuk mendapatkan izin yang diperlukan guna menggunakan Vertex AI Agent Engine, minta administrator Anda untuk memberi Anda peran IAM Vertex AI User (roles/aiplatform.user) di project Anda. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Menyiapkan lingkungan Anda

Bagian ini mengasumsikan bahwa Anda telah menyiapkan lingkungan pengembangan Python, atau menggunakan runtime dengan lingkungan pengembangan Python (seperti Colab).

Menginstal library

Instal Vertex AI SDK:

  pip install google-cloud-aiplatform>=1.112.0

Melakukan autentikasi ke Vertex AI

Untuk melakukan autentikasi:

Shell lokal

gcloud init
gcloud auth application-default login

Colab

from google.colab import auth

auth.authenticate_user()

Membuat instance Vertex AI Agent Engine

Untuk menggunakan Eksekusi Kode, buat instance Vertex AI Agent Engine terlebih dahulu. Anda tidak perlu men-deploy agen untuk menggunakan Eksekusi Kode. Tanpa deployment, pembuatan instance Vertex AI Agent Engine akan memerlukan waktu beberapa detik.

import vertexai

client = vertexai.Client(project=PROJECT_ID, location=LOCATION)

agent_engine = client.agent_engines.create()
agent_engine_name = agent_engine.api_resource.name

Ganti kode berikut:

Membuat sandbox

Buat sandbox untuk eksekusi kode.

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

Ganti kode berikut:

  • SANDBOX_DISPLAY_NAME: nama lingkungan sandbox eksekusi kode yang mudah dibaca manusia.

Anda juga dapat mengonfigurasi setelan sandbox seperti bahasa coding dan konfigurasi mesin:

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"),
)

Ganti kode berikut:

Hanya LANGUAGE_PYTHON dan LANGUAGE_JAVASCRIPT yang didukung. Jika machine_config tidak ditentukan, konfigurasi defaultnya adalah 2 vCPU dan RAM 1,5 GB. Jika Anda menentukan MACHINE_CONFIG_VCPU4_RAM4GIB, sandbox memiliki 4 vCPU dan RAM 4 GB.

(Opsional) Mencantumkan dan mendapatkan sandbox

Mencantumkan semua sandbox yang terkait dengan instance Agent Engine yang ditentukan:

sandboxes = client.agent_engines.sandboxes.list(name=agent_engine_name)

for sandbox in sandboxes:
    pprint.pprint(sandbox)

Berikut contoh output-nya:

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))
)

Untuk mendapatkan sandbox yang ada:

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

pprint.pprint(sandbox)

Berikut contoh output-nya:

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))
)

Menjalankan kode di sandbox

Untuk mengeksekusi kode, panggil 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
)

Berikut contoh output-nya:

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"
        }
    )
  ]
)

Perhatikan hal berikut:

  • execute_code mereset time to live (TTL) sandbox.
  • Outputnya dalam byte mentah.
  • Setiap permintaan atau respons dapat berisi file hingga 100 MB.

Menjalankan lebih banyak kode di sandbox

Untuk mendemonstrasikan bahwa sandbox mempertahankan statusnya, jalankan lebih banyak kode di sandbox yang sama:

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)

Berikut contoh output-nya:

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"
        }
    )

  ]
)

Respons menyertakan file yang perlu didekode. Berikut contoh cara mendekode output:

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))

Berikut contoh output-nya:

b'HelloWorld\n'

Pembersihan

Untuk membersihkan resource yang dibuat oleh panduan memulai ini, hapus sandbox dan instance Vertex AI Agent Engine Anda.

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

Langkah berikutnya