Desarrollar y desplegar agentes en Vertex AI Agent Engine con Agent Development Kit

En esta página se muestra cómo crear y desplegar un agente en el tiempo de ejecución de Vertex AI Agent Engine con Agent Development Kit (ADK). En esta guía de inicio rápido se explican los siguientes pasos:

  • Configura tu Google Cloud proyecto.

  • Instala el SDK de Vertex AI para Python y el ADK.

  • Desarrolla un agente de cambio de divisas.

  • Despliega el agente en el tiempo de ejecución de Vertex AI Agent Engine.

  • Prueba el agente implementado.

También puedes usar las siguientes guías de inicio rápido alternativas para el ADK:

  • Guía de inicio rápido del ADK: La guía de inicio rápido del ADK se ejecuta por completo en tu máquina y presupone que usas un IDE local y acceso a la terminal.

  • Paquete Agent Starter: una colección de plantillas de agentes de IA generativa listas para la producción creadas para Vertex AI Agent Engine.

Para consultar la guía de inicio rápido sobre frameworks compatibles que no sean Agent Development Kit, consulta Desarrollar y desplegar agentes en Vertex AI Agent Engine.

Antes de empezar

  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 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 and Cloud Storage APIs.

    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 APIs

  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 and Cloud Storage APIs.

    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 APIs

  8. Para obtener los permisos que necesitas para usar Vertex AI Agent Engine, pide a tu administrador que te conceda los siguientes roles de gestión de identidades y accesos en tu proyecto:

    Para obtener más información sobre cómo conceder roles, consulta el artículo Gestionar acceso a proyectos, carpetas y organizaciones.

    También puedes conseguir los permisos necesarios a través de roles personalizados u otros roles predefinidos.

    Instalar e inicializar el SDK de Vertex AI para Python

    1. Ejecuta el siguiente comando para instalar el SDK de Vertex AI para Python y otros paquetes necesarios:

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,adk]>=1.112
    2. Autenticarse como usuario

      Shell local

      Ejecuta el siguiente comando:

      gcloud auth application-default login

      Colab

      Ejecuta el siguiente código:

      from google.colab import auth
      
      auth.authenticate_user(project_id="PROJECT_ID")
      

      Cloud Shell

      No tienes que hacer nada.

      Modo Exprés

      Si usas Vertex AI en modo exprés, no tienes que hacer nada.

    3. Ejecuta el siguiente código para importar Vertex AI Agent Engine e inicializar el SDK:

      Proyecto de Google Cloud

      import vertexai
      
      client = vertexai.Client(
          project="PROJECT_ID",               # Your project ID.
          location="LOCATION",                # Your cloud region.
      )
      

      Donde:

      Modo Exprés

      Si usas Vertex AI en modo exprés, ejecuta el siguiente código:

      import vertexai
      from vertexai import agent_engines
      
      vertexai.init(
          key="API_KEY"
      )
      

      donde API_KEY es la clave de API que usas para autenticar el agente.

    Desarrollar un agente

    1. Desarrolla una herramienta de cambio de divisas para tu agente:

      def get_exchange_rate(
          currency_from: str = "USD",
          currency_to: str = "EUR",
          currency_date: str = "latest",
      ):
          """Retrieves the exchange rate between two currencies on a specified date."""
          import requests
      
          response = requests.get(
              f"https://api.frankfurter.app/{currency_date}",
              params={"from": currency_from, "to": currency_to},
          )
          return response.json()
      
    2. Instancia un agente:

      from google.adk.agents import Agent
      from vertexai import agent_engines
      
      agent = Agent(
          model="gemini-2.0-flash",
          name='currency_exchange_agent',
          tools=[get_exchange_rate],
      )
      
      app = agent_engines.AdkApp(agent=agent)
      
    3. Prueba el agente de forma local:

      async for event in app.async_stream_query(
          user_id="USER_ID",
          message="What is the exchange rate from US dollars to SEK today?",
      ):
          print(event)
      

      donde USER_ID es un ID definido por el usuario con un límite de 128 caracteres.

    Desplegar un agente

    Despliega el agente creando un recurso reasoningEngine en Vertex AI:

    remote_agent = client.agent_engines.create(
        agent=app,
        config={
            "requirements": ["google-cloud-aiplatform[agent_engines,adk]"],
            "staging_bucket": "STAGING_BUCKET",
        }
    )
    

    donde STAGING_BUCKET es un segmento de Cloud Storage con el prefijo gs://.

    Usar un agente

    Prueba el agente implementado enviando una consulta:

    async for event in remote_agent.async_stream_query(
        user_id="USER_ID",
        message="What is the exchange rate from US dollars to SEK today?",
    ):
        print(event)
    

    Limpieza

    Para evitar que se apliquen cargos en tu cuenta de Google Cloud por los recursos utilizados en esta página, sigue estos pasos.

    remote_agent.delete(force=True)
    

    Siguientes pasos