Guide de démarrage rapide: Créer un agent avec le kit de développement d'agent

Ce guide de démarrage rapide vous explique comment configurer votre projet Google Cloud , installer l'Agent Development Kit (ADK), configurer un agent de base et exécuter son interface utilisateur pour les développeurs.

Ce guide de démarrage rapide suppose que vous utilisez un IDE local (VS Code, PyCharm, etc.) avec Python 3.10 ou version ultérieure et un accès au terminal. L'agent s'exécute entièrement sur votre machine, ce qui est recommandé pour le développement d'applications locales.

Avant de commencer

Procédez comme suit :

Configurer un projet Google Cloud

Configurez votre projet Google Cloud et activez l'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.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. Configurer les identifiants

    Sur votre terminal local, configurez la Google Cloud CLI et authentifiez-vous avec. Si vous connaissez l'API Gemini dans Google AI Studio, notez que l'API Gemini dans Vertex AI utilise Identity and Access Management au lieu de clés API pour gérer l'accès.

    1. Installez et initialisez la Google Cloud CLI.

    2. Si vous avez déjà installé la gcloud CLI, exécutez la commande suivante pour vous assurer que vos composants gcloud sont à jour.

      gcloud components update
    3. Exécutez la commande suivante pour générer un fichier local d'Identifiants par défaut de l'application (ADC). Votre agent utilisera ces identifiants pour accéder à Vertex AI lors du développement d'applications locales.

      gcloud auth application-default login

      Pour en savoir plus, consultez Configurer les identifiants par défaut de l'application.

    Configurer un environnement virtuel et installer ADK

    • Créez et activez un environnement virtuel (recommandé) :

      # 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
      
    • Installez l'ADK :

      pip install google-adk
      

    Créer un agent

    Dans le terminal, créez la structure de dossiers :

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

    Votre structure :

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

    Copiez et collez le code suivant dans les trois fichiers que vous avez créés :

    • \_\_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]
      )
      

    L'agent est équipé de deux outils de fonction avec des implémentations fictives.

    Exécuter et tester votre agent

    1. Dans le terminal, accédez au répertoire parent de l'agent (par exemple, à l'aide de cd ..) :

      parent_folder/      <-- navigate to this directory
          multi_tool_agent/
              __init__.py
              agent.py
              .env
      
    2. Exécutez la commande suivante pour lancer l'interface utilisateur Web du développeur.

      adk web
      

      Ouvrez l'URL fournie (généralement http://localhost:8000 ou http://127.0.0.1:8000) dans votre navigateur. Cette connexion reste entièrement sur votre ordinateur local. Sélectionnez multi_tool_agent et interagissez avec l'agent.

    Exemples de requêtes à essayer

    Vous pouvez essayer les requêtes suivantes :

    • Quel temps fait-il à New York ?
    • Quelle heure est-il à New York ?
    • Quel temps fait-il à Paris ?
    • Quelle heure est-il à Paris ?

    Étapes suivantes