Desarrolla e implementa agentes en Vertex AI Agent Engine con el Kit de desarrollo de agentes

En esta página, se muestra cómo crear e implementar un agente en el entorno de ejecución de Vertex AI Agent Engine con el Kit de desarrollo de agentes (ADK). En esta guía de inicio rápido, se te guiará por 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.

  • Implementa el agente en el entorno 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 supone que usas un IDE local y acceso a la terminal.

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

Para la guía de inicio rápido que usa frameworks compatibles que no sean el Kit de desarrollo de agentes, consulta Desarrolla e implementa agentes en Vertex AI Agent Engine.

Antes de comenzar

  1. Accede a tu Google Cloud cuenta de. Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  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

Para obtener los permisos que necesitas para usar Vertex AI Agent Engine, pídele a tu administrador que te otorgue los siguientes roles de IAM en tu proyecto:

Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.

También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.

Instala e inicializa 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 se requiere ninguna acción.

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

    Proyecto de Google Cloud

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

    Aquí:

Desarrolla 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. Crea una instancia de 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 localmente:

    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)
    

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

Implementa un agente

Para implementar el agente, crea 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",
    }
)

en el que STAGING_BUCKET es un bucket de Cloud Storage con el prefijo gs://.

Usa un agente

Para probar el agente implementado, envía 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)

Limpia

Sigue estos pasos para evitar que se apliquen cargos a tu Google Cloud cuenta de por los recursos que usaste en esta página.

remote_agent.delete(force=True)

¿Qué sigue?