Guida rapida: crea un agente con l'Agent Development Kit

Questa guida rapida ti illustra la configurazione del tuo progetto Google Cloud , l'installazione di Agent Development Kit (ADK), la configurazione di un agente di base e l'esecuzione della sua interfaccia utente per sviluppatori.

Questa guida rapida presuppone che tu stia utilizzando un IDE locale (VS Code, PyCharm e così via) con Python 3.10+ e accesso al terminale. L'agente viene eseguito interamente sulla tua macchina, il che è consigliato per lo sviluppo di applicazioni locali.

Prima di iniziare

Completa i seguenti passaggi:

Configurare un progetto Google Cloud

Configura il progetto Google Cloud e abilita 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. Configurare le credenziali

    Nel terminale locale, configura ed esegui l'autenticazione con Google Cloud CLI. Se hai familiarità con l'API Gemini in Google AI Studio, tieni presente che l'API Gemini in Vertex AI utilizza Identity and Access Management anziché le chiavi API per gestire l'accesso.

    1. Installa e inizializza Google Cloud CLI.

    2. Se hai già installato gcloud CLI, assicurati che i componenti gcloud siano aggiornati eseguendo questo comando.

      gcloud components update
    3. Esegui questo comando per generare un file Credenziali predefinite dell'applicazionee (ADC) locali. L'agente utilizzerà queste credenziali per accedere a Vertex AI durante lo sviluppo di applicazioni locali.

      gcloud auth application-default login

      Per ulteriori informazioni, vedi Configurare le credenziali predefinite dell'applicazione.

    Configura un ambiente virtuale e installa ADK

    • Crea e attiva un ambiente virtuale (consigliato):

      # 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
      
    • Installa ADK:

      pip install google-adk
      

    Crea un agente

    Utilizzando il terminale, crea la struttura delle cartelle:

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

    La tua struttura:

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

    Copia e incolla il seguente codice nei tre file che hai creato:

    • \_\_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'agente è dotato di due strumenti di funzione con implementazioni simulate.

    Esegui e testa l'agente

    1. Nel terminale, vai alla directory principale dell'agente (ad esempio, utilizzando cd ..):

      parent_folder/      <-- navigate to this directory
          multi_tool_agent/
              __init__.py
              agent.py
              .env
      
    2. Esegui questo comando per avviare la UI web per sviluppatori.

      adk web
      

      Apri l'URL fornito (di solito http://localhost:8000 o http://127.0.0.1:8000) nel browser. Questa connessione rimane interamente sulla tua macchina locale. Seleziona multi_tool_agent e interagisci con l'agente.

    Prompt di esempio da provare

    Puoi provare i seguenti prompt:

    • Che tempo fa a New York?
    • Che ore sono a New York?
    • Che tempo fa a Parigi?
    • Che ore sono a Parigi?

    Passaggi successivi