Guida di avvio rapido di Esegui il codice

Questa pagina mostra come effettuare chiamate API dirette all'esecuzione di codice di Agent Engine per eseguire codice non attendibile in un ambiente sandbox isolato. Le chiamate API dirette sono utili quando non vuoi che il framework dell'agente orchestri le chiamate per te o se vuoi integrare l'esecuzione di codice con altri framework dell'agente.

In questa guida rapida imparerai a:

  • Crea un'istanza di Agent Engine per accedere a Code Execution
  • Crea una sandbox di esecuzione del codice
  • Elencare e ottenere sandbox (facoltativo)
  • Eseguire il codice in un sandbox
  • Esegui più codice utilizzando lo stesso sandbox. Tieni presente che la sandbox mantiene automaticamente il proprio stato.
  • Esegui la pulizia

Prima di iniziare

Configura il progetto e l'ambiente.

Configura il progetto

  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. Ottenere i ruoli richiesti

    Per ottenere le autorizzazioni necessarie per utilizzare Vertex AI Agent Engine, chiedi all'amministratore di concederti il ruolo IAM Vertex AI User (roles/aiplatform.user) nel progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

    Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

    Configura l'ambiente

    Questa sezione presuppone che tu abbia configurato un ambiente di sviluppo Python o che tu stia utilizzando un runtime con un ambiente di sviluppo Python (come Colab).

    Installare le librerie

    Installa l'SDK Vertex AI:

      pip install google-cloud-aiplatform>=1.112.0

    Autenticarsi in Vertex AI

    Per autenticarti:

    shell locale

    gcloud init
    gcloud auth application-default login
    

    Colab

    from google.colab import auth
    
    auth.authenticate_user()
    

    Crea un'istanza Agent Engine

    Per utilizzare l'esecuzione del codice, crea prima un'istanza di Agent Engine. Non è necessario eseguire il deployment di un agente per utilizzare l'esecuzione di codice. Senza il deployment, la creazione di un'istanza di Agent Engine dovrebbe richiedere pochi secondi.

    import vertexai
    
    client = vertexai.Client(project=PROJECT_ID, location=LOCATION)
    
    agent_engine = client.agent_engines.create()
    agent_engine_name = agent_engine.api_resource.name
    

    Sostituisci quanto segue:

    • PROJECT_ID: il tuo ID progetto Google Cloud .
    • LOCATION: La Google Cloud regione del tuo motore agente.

    Creare un sandbox

    Crea una sandbox per l'esecuzione del codice.

    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
    

    Sostituisci quanto segue:

    • SANDBOX_DISPLAY_NAME: il nome leggibile dell'ambiente sandbox di esecuzione del codice.

    Puoi anche configurare le impostazioni della sandbox, come il linguaggio di programmazione e la configurazione della macchina:

    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
    

    Durante l'anteprima sono supportati solo LANGUAGE_PYTHON e LANGUAGE_JAVASCRIPT. Se machine_config non è specificato, la configurazione predefinita è 2 vCPU e 1,5 GB di RAM. Se specifichi MACHINE_CONFIG_VCPU4_RAM4GIB, la sandbox ha 4 vCPU e 4 GB di RAM.

    Elencare e ottenere sandbox (facoltativo)

    Elenca tutte le sandbox associate all'istanza di Agent Engine specificata:

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

    Ecco l'output di esempio:

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

    Per ottenere una sandbox esistente:

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

    Ecco l'output di esempio:

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

    Eseguire il codice in un sandbox

    Per eseguire il codice, chiama 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)
    

    Ecco l'output di esempio:

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

    Tieni presente quanto segue:

    • execute_code reimposta la durata (TTL) del sandbox.
    • I file devono essere incorporati nella richiesta e codificati in base64.
    • Ogni richiesta o risposta può contenere fino a 100 MB di file.

    Esegui più codice in un sandbox

    Per dimostrare che la sandbox mantiene il suo stato, esegui altro codice nella stessa sandbox:

    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)
    

    Ecco l'output di esempio:

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

    La risposta include un file che deve essere decodificato. Ecco un esempio di come decodificare l'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))
    

    Ecco l'output di esempio:

    b'HelloWorld\n'
    

    Esegui la pulizia

    Per eseguire la pulizia delle risorse create da questa guida rapida, elimina la sandbox e l'istanza Agent Engine.

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

    Passaggi successivi