Kurzanleitung: Agent mit dem Agent Development Kit erstellen

In dieser Kurzanleitung erfahren Sie, wie Sie Ihr Google Cloud -Projekt einrichten, das Agent Development Kit (ADK) installieren, einen einfachen Agent einrichten und die Entwickler-Benutzeroberfläche ausführen.

In dieser Kurzanleitung wird davon ausgegangen, dass Sie eine lokale IDE (VS Code, PyCharm usw.) mit Python 3.10+ und Terminalzugriff verwenden. Der Agent wird vollständig auf Ihrem Computer ausgeführt, was für die lokale Anwendungsentwicklung empfohlen wird.

Hinweise

Gehen Sie folgendermaßen vor:

Google Cloud -Projekt einrichten

Richten Sie Ihr Google Cloud -Projekt ein und aktivieren Sie die Vertex AI API.

  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. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    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.

      Zu IAM
    2. Wählen Sie das Projekt aus.
    3. Klicken Sie auf Zugriff erlauben.
    4. Geben Sie im Feld Neue Hauptkonten Ihre Nutzer-ID ein. Dies ist in der Regel die E-Mail-Adresse eines Google-Kontos.

    5. Wählen Sie in der Liste Rolle auswählen eine Rolle aus.
    6. Wenn Sie weitere Rollen hinzufügen möchten, klicken Sie auf Weitere Rolle hinzufügen und fügen Sie weitere Rollen hinzu.
    7. Klicken Sie auf Speichern.
  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  8. Enable the Vertex AI API.

    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.

      Zu IAM
    2. Wählen Sie das Projekt aus.
    3. Klicken Sie auf Zugriff erlauben.
    4. Geben Sie im Feld Neue Hauptkonten Ihre Nutzer-ID ein. Dies ist in der Regel die E-Mail-Adresse eines Google-Kontos.

    5. Wählen Sie in der Liste Rolle auswählen eine Rolle aus.
    6. Wenn Sie weitere Rollen hinzufügen möchten, klicken Sie auf Weitere Rolle hinzufügen und fügen Sie weitere Rollen hinzu.
    7. Klicken Sie auf Speichern.
  10. Anmeldedaten einrichten

    Richten Sie die Google Cloud CLI in Ihrem lokalen Terminal ein und authentifizieren Sie sich damit. Wenn Sie mit der Gemini API in Google AI Studio vertraut sind, beachten Sie, dass die Gemini API in Vertex AI Identity and Access Management anstelle von API-Schlüsseln zur Verwaltung des Zugriffs verwendet.

    1. Installieren und initialisieren Sie Google Cloud CLI.

    2. Wenn Sie die gcloud CLI bereits installiert haben, aktualisieren Sie die gcloud-Komponenten mit diesem Befehl.

      gcloud components update
    3. Führen Sie den folgenden Befehl aus, um eine lokale ADC-Datei (Standardanmeldedaten für Anwendungen) zu generieren. Ihr Agent verwendet diese Anmeldedaten für den Zugriff auf Vertex AI während der lokalen Anwendungsentwicklung.

      gcloud auth application-default login

      Weitere Informationen finden Sie unter Standardanmeldedaten für Anwendungen einrichten.

    Virtuelle Umgebung einrichten und ADK installieren

    • Virtuelle Umgebung erstellen und aktivieren (empfohlen):

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

      pip install google-adk
      

    Agent erstellen

    Erstellen Sie die Ordnerstruktur über das Terminal:

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

    Ihre Struktur:

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

    Kopieren Sie den folgenden Code in die drei Dateien, die Sie erstellt haben:

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

    Der Agent ist mit zwei Funktionstools mit Mock-Implementierungen ausgestattet.

    Agent ausführen und testen

    1. Wechseln Sie im Terminal zum übergeordneten Verzeichnis des Agents (z. B. mit cd ..):

      parent_folder/      <-- navigate to this directory
          multi_tool_agent/
              __init__.py
              agent.py
              .env
      
    2. Führen Sie den folgenden Befehl aus, um die Web-UI für Entwickler zu starten.

      adk web
      

      Öffnen Sie die angegebene URL (normalerweise http://localhost:8000 oder http://127.0.0.1:8000) in Ihrem Browser. Diese Verbindung bleibt vollständig auf Ihrem lokalen Computer. Wählen Sie multi_tool_agent aus und interagieren Sie mit dem Agent.

    Beispiele für Prompts zum Ausprobieren

    Sie können die folgenden Prompts ausprobieren:

    • Wie ist das Wetter in New York?
    • Wie spät ist es in New York?
    • Wie ist das Wetter in Paris?
    • Wie spät ist es in Paris?

    Nächste Schritte