コード実行のクイックスタート

このページでは、Agent Engine Code Execution に直接 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: Agent Engine の 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 が指定されていない場合、デフォルトの構成は 2 個の vCPU と 1.5 GB の RAM です。MACHINE_CONFIG_VCPU4_RAM4GIB を指定すると、サンドボックスには 4 個の vCPU と 4 GB の RAM が割り当てられます。

    サンドボックスを一覧表示して取得する(省略可)

    指定された 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 でエンコードする必要があります。
    • 各リクエストまたはレスポンスには、最大 100 MB のファイルを含めることができます。

    サンドボックスでより多くのコードを実行する

    サンドボックスが状態を維持していることを確認するには、同じサンドボックスでさらにコードを実行します。

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

    次のステップ