Guía de inicio rápido: crea un agente con Agent Development Kit

En esta guía de inicio rápido se explica cómo configurar tu Google Cloud proyecto, instalar el kit de desarrollo de agentes (ADK), configurar un agente básico y ejecutar su interfaz de usuario para desarrolladores.

En esta guía de inicio rápido se da por hecho que usas un IDE local (VS Code, PyCharm, etc.) con Python 3.10 o una versión posterior y acceso a la terminal. El agente se ejecuta por completo en tu máquina, lo que se recomienda para el desarrollo de aplicaciones locales.

Antes de empezar

Este agente debe seguir estos pasos:

Configurar un Google Cloud proyecto

Configura tu Google Cloud proyecto y habilita la API Vertex AI.

  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. Make sure that you have the following role or roles on the project: Vertex AI User

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Ir a IAM
    2. Selecciona el proyecto.
    3. Haz clic en Conceder acceso.
    4. En el campo Nuevos principales, introduce tu identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.

    5. En la lista Selecciona un rol, elige un rol.
    6. Para conceder más roles, haz clic en Añadir otro rol y añade cada rol adicional.
    7. Haz clic en Guardar.
  6. 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

  7. Verify that billing is enabled for your Google Cloud project.

  8. 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

  9. Make sure that you have the following role or roles on the project: Vertex AI User

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Ir a IAM
    2. Selecciona el proyecto.
    3. Haz clic en Conceder acceso.
    4. En el campo Nuevos principales, introduce tu identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.

    5. En la lista Selecciona un rol, elige un rol.
    6. Para conceder más roles, haz clic en Añadir otro rol y añade cada rol adicional.
    7. Haz clic en Guardar.
  10. Configurar credenciales

    En tu terminal local, configura la CLI de Google Cloud y autentícate con ella. Si ya conoces la API de Gemini en Google AI Studio, ten en cuenta que la API de Gemini en Vertex AI usa Gestión de Identidades y Accesos en lugar de claves de API para gestionar el acceso.

    1. Instala e inicializa la CLI de Google Cloud.

    2. Si ya has instalado la CLI de gcloud, asegúrate de que tus componentes de gcloud estén actualizados ejecutando este comando.

      gcloud components update
    3. Ejecuta el siguiente comando para generar un archivo local de credenciales predeterminadas de la aplicación (ADC). Tu agente usará estas credenciales para acceder a Vertex AI durante el desarrollo de la aplicación local.

      gcloud auth application-default login

      Para obtener más información, consulta Configurar credenciales predeterminadas de la aplicación.

    Configurar un entorno virtual e instalar el ADK

    • Crea y activa un entorno virtual (recomendado):

      # Create
      python -m venv .venv
      # Activate (uncomment the line relevant to your environment)
      # macOS/Linux: source .venv/bin/activate
      # Windows CMD: .venv\Scripts\activate.bat
      # Windows PowerShell: .venv\Scripts\Activate.ps1
      
    • Instala el ADK:

      pip install google-adk
      

    Crear un agente

    En el terminal, crea la estructura de carpetas:

    mkdir multi_tool_agent/
    touch \
    multi_tool_agent/__init__.py \
    multi_tool_agent/agent.py \
    multi_tool_agent/.env
    

    Tu estructura:

    parent_folder/
        multi_tool_agent/
            __init__.py
            agent.py
            .env
    

    Copia y pega el siguiente código en los tres archivos que has creado:

    • \_\_init\_\_.py

      from . import agent
      
    • .env

      # If using Gemini via Vertex AI on Google CLoud
      GOOGLE_CLOUD_PROJECT="your-project-id"
      GOOGLE_CLOUD_LOCATION="your-location" #e.g. us-central1
      GOOGLE_GENAI_USE_VERTEXAI="True"
      
    • agent.py

      from google.adk.agents import Agent
      
      def get_weather(city: str) -> dict:
          """Retrieves the current weather report for a specified city.
      
          Returns:
              dict: A dictionary containing the weather information with a 'status' key ('success' or 'error') and a 'report' key with the weather details if successful, or an 'error_message' if an error occurred.
          """
          if city.lower() == "new york":
              return {"status": "success",
                      "report": "The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit)."}
          else:
              return {"status": "error",
                      "error_message": f"Weather information for '{city}' is not available."}
      
      def get_current_time(city:str) -> dict:
          """Returns the current time in a specified city.
      
          Args:
              dict: A dictionary containing the current time for a specified city information with a 'status' key ('success' or 'error') and a 'report' key with the current time details in a city if successful, or an 'error_message' if an error occurred.
          """
          import datetime
          from zoneinfo import ZoneInfo
      
          if city.lower() == "new york":
              tz_identifier = "America/New_York"
          else:
              return {"status": "error",
                      "error_message": f"Sorry, I don't have timezone information for {city}."}
      
          tz = ZoneInfo(tz_identifier)
          now = datetime.datetime.now(tz)
          return {"status": "success",
                  "report": f"""The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}"""}
      
      root_agent = Agent(
          name="weather_time_agent",
          model="gemini-2.0-flash",
          description="Agent to answer questions about the time and weather in a city.",
          instruction="I can answer your questions about the time and weather in a city.",
          tools=[get_weather, get_current_time]
      )
      

    El agente está equipado con dos herramientas de función con implementaciones simuladas.

    Ejecutar y probar el agente

    1. En el terminal, ve al directorio principal del agente (por ejemplo, con cd ..):

      parent_folder/      <-- navigate to this directory
          multi_tool_agent/
              __init__.py
              agent.py
              .env
      
    2. Ejecuta el siguiente comando para iniciar la interfaz web para desarrolladores.

      adk web
      

      Abre la URL proporcionada (normalmente http://localhost:8000 o http://127.0.0.1:8000) en tu navegador. Esta conexión se mantiene por completo en tu máquina local. Selecciona multi_tool_agent e interactúa con el agente.

    Ejemplos de peticiones que puedes probar

    Puedes probar con las siguientes peticiones:

    • ¿Qué tiempo hace en Nueva York?
    • ¿Qué hora es en Nueva York?
    • ¿Qué tiempo hace en París?
    • ¿Qué hora es en París?

    Siguientes pasos