Tworzenie i wdrażanie agentów ADK (Agent Deployment Kit) niewymagających pisania dużej ilości kodu za pomocą narzędzia ADK Visual Builder

1. Cel tego modułu

Z tego praktycznego modułu dowiesz się, jak tworzyć agentów za pomocą ADK (Agent Development Kit) Visual Builder. ADK (Agent Development Kit) Visual Builder umożliwia tworzenie agentów ADK (Agent Development Kit) przy użyciu niskokodowego podejścia. Dowiesz się, jak testować aplikację lokalnie i wdrażać ją w Cloud Run.

Czego się nauczysz

a7c151e463f26e19.jpeg

Ilustracja 1. Za pomocą wizualnego narzędzia ADK możesz tworzyć agentów przy użyciu interfejsu GUI, który nie wymaga pisania dużych ilości kodu.

2. Konfiguracja projektu

  • Jeśli nie masz jeszcze projektu, którego możesz użyć, musisz utworzyć nowy projekt w konsoli GCP. Wybierz projekt w selektorze projektów (w lewym górnym rogu konsoli Google Cloud) 6fce70b12b5fc94.png.

Ilustracja 2. Kliknięcie pola obok logo Google Cloud umożliwia wybranie projektu. Sprawdź, czy projekt jest wybrany.

  • W tym module do wykonania zadań użyjemy edytora Cloud Shell. Otwórz Cloud Shell i ustaw projekt za pomocą Cloud Shell.
  • Kliknij ten link, aby przejść bezpośrednio do edytora Cloud Shell.
  • Otwórz terminal, jeśli nie jest jeszcze otwarty, klikając Terminal>Nowy terminal w menu. Wszystkie polecenia z tego samouczka możesz uruchamiać w tym terminalu.
  • Aby sprawdzić, czy projekt jest już uwierzytelniony, użyj w terminalu Cloud Shell tego polecenia:
gcloud auth list
  • Aby potwierdzić projekt, uruchom w Cloud Shell to polecenie:
gcloud config list project
  • Skopiuj identyfikator projektu i użyj tego polecenia, aby go ustawić:
gcloud config set project <YOUR_PROJECT_ID>
  • Jeśli nie pamiętasz identyfikatora projektu, możesz wyświetlić listę wszystkich identyfikatorów projektów za pomocą polecenia
gcloud projects list

3. Włącz interfejsy API

Aby przeprowadzić to ćwiczenie, musimy włączyć niektóre usługi API. Uruchom w Cloud Shell to polecenie.

gcloud services enable aiplatform.googleapis.com
gcloud services enable cloudresourcemanager.googleapis.com

Przedstawiamy interfejsy API

  • Interfejs Vertex AI API (aiplatform.googleapis.com) umożliwia dostęp do platformy Vertex AI , dzięki czemu aplikacja może wchodzić w interakcje z modelami Gemini w celu generowania tekstu, prowadzenia sesji czatu i wywoływania funkcji.
  • Interfejs Cloud Resource Manager API (cloudresourcemanager.googleapis.com) umożliwia zautomatyzowane zarządzanie metadanymi projektów Google Cloud, takimi jak identyfikator i nazwa projektu, które są często wymagane przez inne narzędzia i pakiety SDK do weryfikacji tożsamości i uprawnień projektu.

4. Sprawdzanie, czy środki zostały zastosowane

Na etapie konfiguracji projektu zgłoszono prośbę o bezpłatne środki, które umożliwiają korzystanie z usług w Google Cloud. Gdy zastosujesz środki, utworzymy nowe bezpłatne konto rozliczeniowe o nazwie „Konto rozliczeniowe w okresie próbnym Google Cloud Platform”. Aby sprawdzić, czy środki zostały zastosowane, wykonaj te czynności w edytorze Cloud Shell:

curl -s https://raw.githubusercontent.com/haren-bh/gcpbillingactivate/main/activate.py | python3

Jeśli operacja się powiedzie, zobaczysz wynik podobny do tego poniżej. Jeśli zobaczysz komunikat „Successfully linked project” (Projekt połączony), oznacza to, że Twoje konto rozliczeniowe jest prawidłowo skonfigurowane. Wykonując powyższy krok, możesz sprawdzić, czy Twoje konto jest połączone. Jeśli nie jest, zostanie połączone. Jeśli nie masz wybranego projektu, pojawi się prośba o jego wybranie. Możesz też zrobić to wcześniej, wykonując czynności opisane w sekcji Konfigurowanie projektu. e0268411fd0691a2.png

Ilustracja 3. Potwierdzenie połączenia konta rozliczeniowego

5. Wprowadzenie do pakietu Agent Development Kit

Pakiet Agent Development Kit oferuje kilka kluczowych korzyści dla deweloperów tworzących aplikacje oparte na agentach:

  1. Systemy wieloagentowe: twórz modułowe i skalowalne aplikacje, łącząc w hierarchii wielu wyspecjalizowanych agentów. Umożliwia złożoną koordynację i delegowanie.
  2. Bogaty ekosystem narzędzi: wyposaż agentów w różne funkcje: korzystaj z gotowych narzędzi (wyszukiwanie, wykonywanie kodu itp.), twórz funkcje niestandardowe, integruj narzędzia z zewnętrznych platform agentów (LangChain, CrewAI) lub używaj innych agentów jako narzędzi.
  3. Elastyczna orkiestracja: definiuj przepływy pracy za pomocą agentów przepływu pracy (SequentialAgent, ParallelAgentLoopAgent) w przypadku przewidywalnych potoków lub korzystaj z dynamicznego kierowania opartego na LLM (LlmAgent przekazywanie) w celu dostosowywania zachowań.
  4. Zintegrowane środowisko programistyczne: lokalne tworzenie, testowanie i debugowanie za pomocą zaawansowanego interfejsu wiersza poleceń i interaktywnego interfejsu programistycznego. Sprawdzaj zdarzenia, stan i kroki wykonywania agenta.
  5. Wbudowana ocena: systematycznie oceniaj skuteczność agenta, sprawdzając zarówno jakość ostatecznej odpowiedzi, jak i trajektorię wykonania krok po kroku na podstawie predefiniowanych przypadków testowych.
  6. Gotowość do wdrożenia: konteneryzuj i wdrażaj agentów w dowolnym miejscu – uruchamiaj lokalnie, skaluj za pomocą Vertex AI Agent Engine lub integruj z infrastrukturą niestandardową za pomocą Cloud Run lub Dockera.

Inne pakiety SDK generatywnej AI lub platformy agentów również umożliwiają wysyłanie zapytań do modeli, a nawet udostępnianie im narzędzi, ale dynamiczna koordynacja między wieloma modelami wymaga znacznego nakładu pracy z Twojej strony.

Zestaw Agent Development Kit oferuje bardziej zaawansowane ramy niż te narzędzia, co pozwala łatwo łączyć ze sobą wiele agentów w celu tworzenia złożonych, ale łatwych w utrzymaniu procesów.

e97ad3e26ceb7a2f.png

Rysunek 4. Pozycjonowanie ADK (Agent Development Kit)

W najnowszych wersjach do ADK (Agent Development Kit) dodano narzędzie ADK Visual Builder, które umożliwia tworzenie agentów ADK (Agent Development Kit) przy użyciu niewielkiej ilości kodu. W tym module szczegółowo omówimy Narzędzie do tworzenia wizualnego ADK.

6. Instalowanie ADK i konfigurowanie środowiska

Najpierw musimy skonfigurować środowisko, aby można było uruchomić ADK (Agent Development Kit). W tym module uruchomimy ADK (Agent Development Kit) i wykonamy wszystkie zadania w Google Cloud w edytorze Cloud Shell .

Przygotowywanie edytora Cloud Shell

  1. Kliknij ten link, aby przejść bezpośrednio do edytora Cloud Shell.
  2. Kliknij Dalej.
  3. Gdy pojawi się prośba o autoryzację Cloud Shell, kliknij Autoryzuj.
  4. W dalszej części tego modułu możesz pracować w tym oknie jako środowisku IDE z edytorem Cloud Shell i terminalem Cloud Shell.
  5. Otwórz nowy terminal, klikając Terminal>New Terminal (Terminal>Nowy terminal) w edytorze Cloud Shell. Wszystkie polecenia poniżej będą uruchamiane w tym terminalu.

Uruchamianie edytora wizualnego ADK

  1. Wykonaj te polecenia, aby sklonować potrzebne źródło z GitHub i zainstalować niezbędne biblioteki. Uruchom polecenia w terminalu otwartym w edytorze Cloud Shell.
#create the project directory
mkdir ~/adkui
cd ~/adkui
  1. Do utworzenia środowiska Pythona użyjemy narzędzia uv (uruchom w terminalu edytora Cloud Shell):
#Install uv if you do not have installed yet
pip install uv

#go to the project directory
cd ~/adkui

#Create the virtual environment
uv venv


#use the newly created environment
source .venv/bin/activate

#install libraries
uv pip install google-adk==1.22.1
uv pip install python-dotenv

Uwaga: jeśli kiedykolwiek będziesz musiał(a) ponownie uruchomić terminal, pamiętaj, aby skonfigurować środowisko Pythona, wykonując polecenie „source .venv/bin/activate”.

  1. W edytorze kliknij kolejno View (Widok) –> Toggle hidden files (Przełącz ukryte pliki). W folderze adkui utwórz plik .env o tej treści:
#go to adkui folder
cd ~/adkui
cat <<EOF>> .env
GOOGLE_GENAI_USE_VERTEXAI=1
GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
GOOGLE_CLOUD_LOCATION=us-central1
IMAGEN_MODEL="imagen-3.0-generate-002"
GENAI_MODEL="gemini-2.5-flash"
EOF

7. Tworzenie prostego agenta za pomocą narzędzia ADK Visual Builder

W tej sekcji utworzymy prostego agenta za pomocą ADK Visual Builder.ADK Visual Builder to narzędzie internetowe, które zapewnia wizualne środowisko projektowania przepływu pracy do tworzenia agentów ADK (Agent Development Kit) i zarządzania nimi. Umożliwia projektowanie, tworzenie i testowanie agentów w przyjaznym dla początkujących interfejsie graficznym. Zawiera też asystenta opartego na AI, który pomaga w tworzeniu agentów.

a62f805e02759763.jpeg

Ilustracja 5. Wizualny kreator pakietu ADK

  1. Wróć do katalogu głównego adkui w terminalu i wykonaj to polecenie, aby uruchomić agenta lokalnie (uruchom w terminalu edytora Cloud Shell). Powinien się uruchomić serwer ADK, a w terminalu powinny być widoczne wyniki podobne do tych na rysunku 6.
#go to the directory adkui
cd ~/adkui
# Run the following command to run ADK locally
adk web

dfda0b40b44e9230.png

Ilustracja 6. Uruchamianie aplikacji ADK

  1. Naciśnij Ctrl+kliknięcie (CMD+kliknięcie w systemie macOS) adresu URL http:// wyświetlanego w terminalu, aby otworzyć w przeglądarce ADK (Agent Development Kit).

8b5b97c99563987e.png

Ilustracja 7. Interfejs internetowy ADK. ADK ma te komponenty: 1. Przełączanie trybu jasnego i ciemnego, 2. Zwijanie panelu, 3. Tworzenie agenta, 4. Edytowanie agenta

  1. Aby utworzyć nowego agenta, naciśnij przycisk „+”.

8be783739a4fa361.png

Rysunek 8. Okno dialogowe tworzenia nowej aplikacji

  1. Nadaj mu nazwę „Agent1” i kliknij Utwórz.

75b41854cf000b5a.png

Rysunek 9. Interfejs Kreatora agentów

  1. Panel jest podzielony na 3 główne sekcje: po lewej stronie znajdują się elementy sterujące do tworzenia agentów na podstawie interfejsu GUI, pośrodku jest wizualizacja postępów, a po prawej stronie znajduje się Asystent do tworzenia agentów za pomocą języka naturalnego.
  2. Agent został utworzony. Aby kontynuować, kliknij przycisk Zapisz. Uwaga: aby nie utracić zmian, musisz kliknąć Zapisz.
  3. Agent powinien być teraz gotowy do testowania. Aby rozpocząć, wpisz w polu czatu prompta, np.:
Hi, what can you do?

3fbcbca52ec22bb5.png

Ilustracja 10. Testowanie agenta.

7.Wróćmy do edytora i przyjrzyjmy się nowo wygenerowanym plikom. Eksplorator znajdziesz po lewej stronie. Przejdź do folderu adkgui i rozwiń go, aby wyświetlić katalog Agent 1. W folderze możesz sprawdzić plik YAML, który definiuje agenta, jak pokazano na ilustracji poniżej.

3af1515bad1387a4.png

Rysunek 11. Definicja agenta w pliku YAML

  1. Teraz wróćmy do edytora GUI i dodajmy kilka funkcji do agenta. Aby to zrobić, naciśnij przycisk edycji (patrz rysunek 7, element 4, ikona ołówka).
  2. Dodamy do agenta funkcję wyszukiwarki Google. W tym celu musimy dodać wyszukiwarkę Google jako narzędzie dostępne dla agenta, z którego może on korzystać. Aby to zrobić, kliknij znak „+” obok sekcji Narzędzia w lewym dolnym rogu ekranu, a następnie w menu kliknij Wbudowane narzędzie (patrz rysunek 12). 1c021cb0c9a2432a.png

Ilustracja 12. Dodawanie nowego narzędzia do agenta

  1. Z listy Wbudowane narzędzie wybierz google_search i kliknij Utwórz (patrz rysunek 12). Spowoduje to dodanie wyszukiwarki Google jako narzędzia w Twoim agencie.
  2. Kliknij przycisk Zapisz, aby zapisać zmiany.

43e4f68dbb048347.png

Ilustracja 13. Lista narzędzi dostępnych w interfejsie narzędzia ADK Visual Builder

  1. Możesz teraz przetestować agenta. Najpierw ponownie uruchom serwer ADK. Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. Na liście pracowników wybierz Agent1. Twój agent może teraz korzystać z wyszukiwarki Google. W polu czatu przetestuj ten prompt:
What is the weather today in Yokohama?

Odpowiedź z wyszukiwarki Google powinna wyglądać tak jak poniżej. 71d9377da4a0bd0c.png

Ilustracja 14. Wyszukiwarka Google z agentem

  1. Teraz wróćmy do edytora i sprawdźmy kod utworzony w tym kroku. W panelu bocznym Eksplorator w Edytorze kliknij root_agent.yaml, aby otworzyć plik. Sprawdź, czy jako narzędzie dodano google_search (rysunek 15).

2ac95d98921ec54d.png

Ilustracja 15. Potwierdzenie, że narzędzie google_search zostało dodane do Agent1

8. Wdrażanie agenta w Cloud Run

Teraz wdróżmy utworzonego agenta w Cloud Run. Dzięki Cloud Run możesz szybko tworzyć aplikacje i witryny na w pełni zarządzanej platformie.

Możesz uruchamiać usługi frontendu i backendu oraz zadania wsadowe, hostować duże modele językowe, a także tworzyć kolejki zadań przetwarzania bez konieczności zarządzania infrastrukturą.

Jeśli w terminalu edytora Cloud Shell nadal działa serwer ADK (Agent Development Kit), naciśnij Ctrl+C, aby go zatrzymać.

  1. Przejdź do katalogu głównego projektu.
cd ~/adkui
  1. Pobierz kod wdrożenia. Po uruchomieniu polecenia w panelu Eksplorator edytora Cloud Shell powinien pojawić się plik deploycloudrun.py.
curl -LO https://raw.githubusercontent.com/haren-bh/codelabs/main/adk_visual_builder/deploycloudrun.py
  1. Sprawdź opcje wdrażania w pliku deploycloudrun.py. Aby wdrożyć agenta w Cloud Run, użyjemy polecenia adk deploy. Pakiet ADK (Agent Development Kit) ma wbudowaną opcję wdrażania agenta w Cloud Run. Musimy określić parametry, takie jak identyfikator projektu Google Cloud, region itp. W przypadku ścieżki aplikacji ten skrypt zakłada, że agent_path=./Agent1. Utworzymy też nowe konto usługi z niezbędnymi uprawnieniami i dołączymy je do Cloud Run. Cloud Run potrzebuje dostępu do usług takich jak Vertex AI i Cloud Storage, aby uruchomić agenta.
   command = [
        "adk", "deploy", "cloud_run",
        f"--project={project_id}",
        f"--region={location}",
        f"--service_name={service_name}",
        f"--app_name={app_name}",
        f"--artifact_service_uri=memory://",
        f"--with_ui",
        agent_path,
        f"--",
        f"--service-account={sa_email}",
    ]
  1. Uruchom skrypt deploycloudrun.py**. Wdrożenie powinno się rozpocząć zgodnie z rysunkiem poniżej**.
python3 deploycloudrun.py

Jeśli pojawi się komunikat z potwierdzeniem, jak poniżej, naciśnij Y i Enter w przypadku wszystkich wiadomości. Skrypt depoycloudrun.py zakłada, że agent znajduje się w folderze Agent1, tak jak utworzono go powyżej.

a62b6b35bc5992db.png

Ilustracja 16. Wdrażanie agenta w Cloud Run. W odpowiedzi na wiadomości z potwierdzeniem naciśnij Y.

  1. Po zakończeniu wdrażania powinien się wyświetlić adres URL usługi, np. https://agent1service-78833623456.us-central1.run.app.
  2. Otwórz adres URL w przeglądarce, aby uruchomić aplikację.

baaf3bcb8117883.png

        Figure 17: Agent running in Cloud Run

9. Tworzenie agenta z subagentem i narzędziem niestandardowym

W poprzedniej sekcji utworzyliśmy pojedynczego agenta z wbudowanym narzędziem wyszukiwarki Google. W tej sekcji utworzysz system z wieloma agentami, w którym agenci mogą korzystać z narzędzi niestandardowych.

  1. Najpierw ponownie uruchom serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. Aby utworzyć nowego agenta, kliknij przycisk „+”. W oknie dialogowym agenta wpisz „Agent2” (rysunek 18) i kliknij „Utwórz”.

c657dfeb5185a42c.png

Ilustracja 18. Tworzenie nowej aplikacji agenta.

  1. W sekcji instrukcji narzędzia Agent2 wpisz te informacje:
You are an agent that takes image creation instruction from the user and passes it to your sub agent
  1. Teraz dodamy sub-agenta do agenta głównego. Aby to zrobić, kliknij przycisk „+” po lewej stronie menu Sub Agent u dołu panelu po lewej stronie (rysunek 19) i wybierz „LLM Agent” (Agent LLM). Spowoduje to utworzenie nowego agenta jako nowego subagenta agenta głównego.

c7e13dca96faa084.png

Ilustracja 19. Dodawanie nowego sub-agenta.

  1. W sekcji Instrukcje dla sub_agent_1 wpisz ten tekst:
You are an Agent that can take instructions about an image and create an image using the create_image tool.
  1. Teraz dodajmy do tego sub-agenta niestandardowe narzędzie. To narzędzie wywoła model Imagen, aby wygenerować obraz na podstawie instrukcji użytkownika. Aby to zrobić, najpierw kliknij podagenta utworzonego w poprzednim kroku, a następnie kliknij przycisk „+” obok menu Narzędzia. Na liście opcji narzędzia kliknij „Narzędzie funkcji”. To narzędzie umożliwi nam dodanie do niego własnego kodu.

dd4ed4726300a1b1.png

Ilustracja 20. Kliknij narzędzie Funkcja, aby utworzyć nowe narzędzie. 8. W oknie dialogowym nadaj narzędziu nazwę Agent2.image_creation_tool.create_image. feb5c69a876e8dda.png

Ilustracja 21. Dodawanie nazwy narzędzia

  1. Aby zapisać zmiany, kliknij przycisk Zapisz.
  2. W terminalu edytora Cloud Shell naciśnij Ctrl+S, aby zamknąć serwer ADK.
  3. W terminalu wpisz to polecenie, aby utworzyć plik image_creation_tool.py.
touch ~/adkui/Agent2/image_creation_tool.py
  1. Otwórz nowo utworzony plik image_creation_tool.py, klikając go w panelu Eksplorator w edytorze Cloud Shell. Zastąp zawartość pliku image_creation_tool.py poniższym kodem i zapisz go (Ctrl+S).
import os
import io
import vertexai
from vertexai.preview.vision_models import ImageGenerationModel
from dotenv import load_dotenv
import uuid
from typing import Union
from datetime import datetime
from google import genai
from google.genai import types
from google.adk.tools import ToolContext
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def create_image(prompt: str,tool_context: ToolContext) -> Union[bytes, str]:
  """
  Generates an image based on a text prompt using a Vertex AI Imagen model.
  Args:
      prompt: The text prompt to generate the image from.

  Returns:
      The binary image data (PNG format) on success, or an error message string on failure.
  """
  print(f"Attempting to generate image for prompt: '{prompt}'")

  try:
      # Load environment variables from .env file two levels up
      dotenv_path = os.path.join(os.path.dirname(__file__), '..', '..', '.env')
      load_dotenv(dotenv_path=dotenv_path)
      project_id = os.getenv("GOOGLE_CLOUD_PROJECT")
      location = os.getenv("GOOGLE_CLOUD_LOCATION")
      model_name = os.getenv("IMAGEN_MODEL")
      client = genai.Client(
          vertexai=True,
          project=project_id,
          location=location,
      )
      response = client.models.generate_images(
          model="imagen-3.0-generate-002",
          prompt=prompt,
          config=types.GenerateImagesConfig(
              number_of_images=1,
              aspect_ratio="9:16",
              safety_filter_level="block_low_and_above",
              person_generation="allow_adult",
          ),
      )
      if not all([project_id, location, model_name]):
          return "Error: Missing GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION, or IMAGEN_MODEL in .env file."
      vertexai.init(project=project_id, location=location)
      model = ImageGenerationModel.from_pretrained(model_name)
      images = model.generate_images(
          prompt=prompt,
          number_of_images=1
      )
      if response.generated_images is  None:
          return "Error: No image was generated."
      for generated_image in response.generated_images:
          # Get the image bytes
          image_bytes = generated_image.image.image_bytes
          counter = str(tool_context.state.get("loop_iteration", 0))
          artifact_name = f"generated_image_" + counter + ".png"
          # Save as ADK artifact (optional, if still needed by other ADK components)
          report_artifact = types.Part.from_bytes(
              data=image_bytes, mime_type="image/png"
          )
          await tool_context.save_artifact(artifact_name, report_artifact)
          logger.info(f"Image also saved as ADK artifact: {artifact_name}")
          return {
              "status": "success",
              "message": f"Image generated .  ADK artifact: {artifact_name}.",
              "artifact_name": artifact_name,
          }
  except Exception as e:
      error_message = f"An error occurred during image generation: {e}"
      print(error_message)
      return error_message
  1. Najpierw ponownie uruchom serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  1. Na karcie interfejsu ADK (Agent Development Kit) wybierz Agent2 na liście agentów i kliknij przycisk edycji (ikonę ołówka). W Edytorze wizualnym ADK (Agent Development Kit) kliknij przycisk Zapisz, aby zachować zmiany.
  2. Teraz możemy przetestować nowego agenta.
  3. W interfejsie czatu ADK (Agent Development Kit) wpisz ten prompt: Możesz też wypróbować inne prompty. Powinny się wyświetlić wyniki widoczne na rysunku 22.
Create an image of a cat

5ef38727b5af2c88.png

Ilustracja 22. Interfejs czatu ADK

10. Tworzenie agenta przepływu pracy

Poprzedni krok polegał na utworzeniu agenta z podagentem i specjalistycznymi narzędziami do tworzenia obrazów, a ten etap koncentruje się na udoskonaleniu możliwości agenta. Ulepszymy ten proces, dbając o to, aby początkowy prompt użytkownika był zoptymalizowany przed wygenerowaniem obrazu. W tym celu w agencie głównym zostanie zintegrowany agent sekwencyjny, który będzie obsługiwać ten dwuetapowy proces:

  1. Otrzymuje prompt od agenta głównego i ulepsza go.
  2. Przekaż dopracowany prompt do agenta tworzącego obrazy, aby wygenerować ostateczny obraz za pomocą IMAGEN.
  3. Najpierw ponownie uruchom serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. Wybierz Agent2 w selektorze agentów i kliknij przycisk Edytuj (ikonę ołówka).
  3. Kliknij Agent2 (Agent główny), a następnie kliknij przycisk „+” obok menu Podagenci. Na liście opcji kliknij Sequential Agent (Agent sekwencyjny).
  4. Struktura agenta powinna wyglądać jak na rysunku 2368ad7cee0619895f.png

Ilustracja 23. Struktura agenta sekwencyjnego

  1. Teraz dodamy pierwszego agenta do Sequential Agent, który będzie działać jako wzmacniacz promptów. Aby to zrobić, kliknij przycisk Dodaj subagenta w polu SequentialAgent i kliknij LLM Agent.
  2. Musimy dodać do sekwencji kolejnego agenta, więc powtórz krok 6, aby dodać kolejnego agenta LLM (kliknij przycisk + i wybierz LLMAgent).
  3. Kliknij sub_agent_4 i dodaj nowe narzędzie, klikając ikonę „+” obok Narzędzi w panelu po lewej stronie. Wybierz „Narzędzie funkcji”. W oknie dialogowym nazwij narzędzie Agent2.image_creation_tool.create_image i kliknij „Utwórz”.
  4. Teraz możemy usunąć agenta sub_agent_1, ponieważ został on zastąpiony bardziej zaawansowanym agentem sub_agent_2. Aby to zrobić, kliknij przycisk Usuń po prawej stronie sub_agent_1 na diagramie.

d859376fd77299a.png

Ilustracja 24. Usuwanie sub_agent_1 10. Struktura naszego agenta wygląda jak na rysunku 25.

f2f9dae3183d2b6.png

Ilustracja 25. Struktura końcowa ulepszonego agenta

  1. Kliknij sub_agent_3 i w instrukcjach wpisz te informacje:
     Act as a professional AI Image Prompt Engineer. I will provide you 
    with a basic idea for an image. Your job is to expand my idea into 
    a detailed, high-quality prompt for models like Imagen. 
    
    For every input, output the following structure:
    1. **Optimized Prompt**: A vivid, descriptive paragraph including 
    subject, background, lighting, and textures.
    2. **Style & Medium**: Specify if it is photorealistic, digital art, 
    oil painting, etc.
    3. **Camera & Lighting**: Define the lens (e.g., 85mm), angle, 
    and light quality (e.g., volumetric, golden hour).
    
    Guidelines: Use sensory language, avoid buzzwords like 'photorealistic' 
    unless necessary, and focus on specific artistic descriptors.
    Once the prompt is created send the prompt to the 
  1. Kliknij sub_agent_4. Zmień instrukcję na taką:
You are an agent that takes instructions about an image and can generate the image using the create_image tool.
  1. Kliknij przycisk Zapisz.
  2. Otwórz panel Eksplorator edytora Cloud Shell i otwórz pliki YAML agenta. Pliki agenta powinny wyglądać tak jak poniżej.
root_agent.yaml

name: Agent2
model: gemini-2.5-flash
agent_class: LlmAgent
instruction: You are an agent that takes image creation instruction from the
  user and passes it to your sub agent
sub_agents:
  - config_path: ./sub_agent_2.yaml
tools: []
sub_agent_2.yaml

name: sub_agent_2
agent_class: SequentialAgent
sub_agents:
  - config_path: ./sub_agent_3.yaml
  - config_path: ./sub_agent_4.yaml
sub_agent_3.yaml

name: sub_agent_3
model: gemini-2.5-flash
agent_class: LlmAgent
instruction: |
  Act as a professional AI Image Prompt Engineer. I will provide you  with a
  basic idea for an image. Your job is to expand my idea into  a detailed,
  high-quality prompt for models like Imagen. 

  For every input, output the following structure: 1. **Optimized Prompt**: A
  vivid, descriptive paragraph including  subject, background, lighting, and
  textures. 2. **Style & Medium**: Specify if it is photorealistic, digital
  art,  oil painting, etc. 3. **Camera & Lighting**: Define the lens (e.g.,
  85mm), angle,  and light quality (e.g., volumetric, golden hour).

  Guidelines: Use sensory language, avoid buzzwords like
  'photorealistic'  unless necessary, and focus on specific artistic
  descriptors. Once the prompt is created send the prompt to the 
sub_agents: []
tools: []
sub_agent_4.yaml

name: sub_agent_4
model: gemini-2.5-flash
agent_class: LlmAgent
instruction: You are an agent that takes instructions about an image and
  generate the image using the create_image tool.
sub_agents: []
tools:
  - name: Agent2.image_creation_tool.create_image
  1. Teraz przetestujmy go.
  2. Najpierw ponownie uruchom serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. Na liście pracowników wybierz Pracownik2. Wpisz ten prompt:
Create an image of a Cat
  1. Podczas pracy agenta możesz sprawdzić terminal w edytorze Cloud Shell, aby zobaczyć, co dzieje się w tle. Ostateczny wynik powinien wyglądać jak na rysunku 26.

dfbd8a88cf7f86a.png

Ilustracja 26. Testowanie agenta

11. Tworzenie agenta za pomocą Asystenta kreatora agentów

Asystent narzędzia do tworzenia agentów jest częścią wizualnego narzędzia do tworzenia pakietu ADK, które umożliwia interaktywne tworzenie agentów za pomocą promptów w prostym interfejsie czatu, co pozwala na tworzenie agentów o różnym stopniu złożoności. Korzystając z wizualnego narzędzia ADK, możesz od razu otrzymywać wizualne informacje zwrotne o opracowywanych agentach. W tym module utworzymy agenta, który na podstawie prośby użytkownika będzie generować komiks w formacie HTML. Użytkownicy mogą podać prosty prompt, np. „Utwórz komiks o Jasiu i Małgosi”, lub wpisać całą historię. Następnie przeanalizuje narrację, podzieli ją na kilka paneli i użyje Nanobanany do wygenerowania wizualizacji komiksu, a na koniec spakuje wynik w formacie HTML.

d02de8d649d7c8aa.png

Ilustracja 27. Interfejs asystenta Kreatora agentów

Zaczynajmy!

  1. Najpierw ponownie uruchom serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. W interfejsie ADK (Agent Development Kit) kliknij przycisk „+”, aby utworzyć nowego agenta.
  3. W oknie dialogowym wpisz „Agent3” i kliknij przycisk „Utwórz”. 7300603c2dbfcbbd.png

Ilustracja 28. Tworzenie nowego agenta Agent3

  1. W panelu Asystenta po prawej stronie wpisz ten prompt: Poniższy prompt zawiera wszystkie instrukcje potrzebne do utworzenia systemu agentów, który utworzy agenta opartego na HTML-u.
System Goal: You are the Studio Director (Root Agent). Your objective is to manage a linear pipeline of four ADK Sequential Agents to transform a user's seed idea into a fully rendered, responsive HTML5 comic book. 

0. Root Agent: The Studio Director
Role: Orchestrator and State Manager.

Logic: Receives the user's initial request. It initializes the workflow and ensures the output of each Sub-Agent is passed as the context for the next. It monitors the sequence to ensure no steps are skipped. Make sure the query explicitly mentions "Create me a comic of ..." if it's just a general question or prompt just answer the question.

1. Sub-Agent: The Scripting Agent (Sequential Step 1)
Role: Narrative & Character Architect.

Input: Seed idea from Root Agent.

Logic: 1. Create a Character Manifest: Define 3 specific, unchangeable visual identifiers 
          for every character (e.g., "Gretel: Blue neon hair ribbons, silver apron, 
          glowing boots"). 
       2. Expand the seed idea into a coherent narrative arc.

Output: A narrative script and a mandatory character visual guide.

2. Sub-Agent: The Panelization Agent (Sequential Step 2)
Role: Cinematographer & Storyboarder.

Input: Script and Character Manifest from Step 1.

Logic: 
     1. Divide the script into exactly X panels (User-defined or default to 8). 
     2. For each panel, define a specific composition (e.g., "Panel 1: 
        Wide shot of the gingerbread house").


Output: A structured list of exactly X panel descriptions.

3. Sub-Agent: The Image Synthesis Agent (Sequential Step 3)
Role: Technical Artist & Asset Generator.

Input: The structured list of panel descriptions from Step 2.

Logic: 
     1. Iterative Generation: You must execute the "generate_image" tool in 
     "image_generation.py" file 
     (Nano Banana) individually for each panel defined in Step 2. 
     2. Prompt Engineering: For every panel, translate the description into a 
     Nano Banana prompt, strictly enforcing the character identifiers 
     (e.g., the "blue neon ribbons") and the global style: "vibrant comic book style, 
     heavy ink lines, cel-shaded, 4k." . Make sure that the necessary speech bubbles
     are present in the image representing the dialogue.
     3. Mapping: Associate each generated image URL with its corresponding panel 
     number and dialogue.

Output: A complete gallery of X images mapped to their respective panel data.

4. Sub-Agent: The Assembly Agent (Sequential Step 4)
Role: Frontend Developer.

Input: The mapped images and panel text from Step 3.

Logic: 
     1. Write a clean, responsive HTML5/CSS3 file that shows the comic. The comic should be
        Scrollable with image on the top and the description below the image.   
     2. Use "write_comic_html" tool in file_writer.py to write the created html file in 
        the "output" folder.      
     4. In the "write_comic_html" tool add logic to copy the images folder to the 
        output folder so that the images in the html file are actually visible when 
        the user opens the html file.

Output: A final, production-ready HTML code block.
  1. Agent może poprosić Cię o wpisanie modelu, którego chcesz użyć. W takim przypadku wybierz gemini-2.5-pro z dostępnych opcji.

f2773d0bf9a861e1.png Rysunek 29. Wpisz gemini-2.5-pro, jeśli pojawi się prośba o podanie modelu, którego chcesz użyć

  1. Asystent może zaproponować Ci plan i poprosić o potwierdzenie, czy możesz go zaakceptować. Sprawdź plan, wpisz „OK” i naciśnij „Enter”.

7bc52b1e4ec468a4.png Rysunek 30. Wpisz OK, jeśli plan wygląda dobrze. Po zakończeniu pracy przez Asystenta powinna być widoczna struktura agenta, jak pokazano na rysunku 31.

7f6ed3d590253cf2.png Ilustracja 31. Agent utworzony przez Asystenta kreatora agentów 9. W sekcji image_synthesis_agent (nazwa może być inna) kliknij narzędzie „Agent3.tools.image_generation.gene...”. Jeśli ostatnia część nazwy narzędzia nie jest image_generation.generate_image change, zmień ją na image_generation.generate_image. Jeśli nazwa jest już ustawiona, nie musisz jej zmieniać. Aby zapisać, naciśnij przycisk „Zapisz”.

e48d3e712ba79a57.png Ilustracja 32. Zmień nazwę narzędzia na image_generation.generate_image i kliknij Zapisz.

  1. W sekcji assembly_agent (nazwa agenta może być inna) kliknij narzędzie **Agent3.tools.file_writer.write_comic_...**. Jeśli ostatnia sekcja nazwy narzędzia nie jest równa **file_writer.write_comic_html**, zmień ją na **file_writer.write_comic_html**.

cfff7ecb78a95246.png Rysunek 33. Zmiana nazwy narzędzia na file_writer.write_comic_html 11. Aby zapisać nowo utworzonego agenta, kliknij przycisk Zapisz w lewym dolnym rogu panelu po lewej stronie. 12. W panelu Eksplorator edytora Cloud Shell rozwiń folder Agent3. W folderze Agent3/ powinien znajdować się folder tools. Kliknij Agent3/tools/file_writer.py, aby otworzyć ten plik, i zastąp jego zawartość poniższym kodem. Aby zapisać zmiany, naciśnij Ctrl+S. Uwaga: asystent agenta mógł już utworzyć prawidłowy kod, ale w tym module użyjemy przetestowanego kodu.

import os
import shutil

def write_comic_html(html_content: str, image_directory: str = "images") -> str:
   """
   Writes the final HTML content to a file and copies the image assets.

   Args:
       html_content: A string containing the full HTML of the comic.
       image_directory: The source directory where generated images are stored.

   Returns:
       A confirmation message indicating success or failure.
   """
   output_dir = "output"
   images_output_dir = os.path.join(output_dir, image_directory)

   try:
       # Create the main output directory
       if not os.path.exists(output_dir):
           os.makedirs(output_dir)

       # Copy the entire image directory to the output folder
       if os.path.exists(image_directory):
           if os.path.exists(images_output_dir):
               shutil.rmtree(images_output_dir)  # Remove old images
           shutil.copytree(image_directory, images_output_dir)
       else:
           return f"Error: Image directory '{image_directory}' not found."

       # Write the HTML file
       html_file_path = os.path.join(output_dir, "comic.html")
       with open(html_file_path, "w") as f:
           f.write(html_content)

       return f"Successfully created comic at '{html_file_path}'"

   except Exception as e:
       return f"An error occurred: {e}"
  1. W panelu Eksplorator edytora Cloud Shell rozwiń folder Agent3. W folderze **Agent3/**powinien znajdować się folder tools. Kliknij Agent3/tools/image_generation.py, aby otworzyć ten plik, i zastąp jego zawartość poniższym kodem. Aby zapisać, naciśnij Ctrl+S. Uwaga: asystent agenta mógł już utworzyć prawidłowy kod, ale w tym module użyjemy przetestowanego kodu.
import time
import os
import io
import vertexai
from vertexai.preview.vision_models import ImageGenerationModel
from dotenv import load_dotenv
import uuid
from typing import Union
from datetime import datetime
from google import genai
from google.genai import types
from google.adk.tools import ToolContext

import logging
import asyncio

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# It's better to initialize the client once and reuse it.
# IMPORTANT: Your Google Cloud Project ID must be set as an environment variable
# for the client to authenticate correctly.


def edit_image(client, prompt: str, previous_image: str, model_id: str) -> Union[bytes, None]:
   """
   Calls the model to edit an image based on a prompt.

   Args:
       prompt: The text prompt for image editing.
       previous_image: The path to the image to be edited.
       model_id: The model to use for the edit.

   Returns:
       The raw image data as bytes, or None if an error occurred.
   """

   try:
       with open(previous_image, "rb") as f:
           image_bytes = f.read()

       response = client.models.generate_content(
           model=model_id,
           contents=[
               types.Part.from_bytes(
                   data=image_bytes,
                   mime_type="image/png",  # Assuming PNG, adjust if necessary
               ),
               prompt,
           ],
           config=types.GenerateContentConfig(
               response_modalities=['IMAGE'],
           )
       )

       # Extract image data
       for part in response.candidates[0].content.parts:
           if part.inline_data:
               return part.inline_data.data

       logger.warning("Warning: No image data was generated for the edit.")
       return None

   except FileNotFoundError:
       logger.error(f"Error: The file {previous_image} was not found.")
       return None
   except Exception as e:
       logger.error(f"An error occurred during image editing: {e}")
       return None

async def generate_image(tool_context: ToolContext, prompt: str, image_name: str, previous_image: str = None) -> dict:
   """
   Generates or edits an image and saves it to the 'images/' directory.

   If 'previous_image' is provided, it edits that image. Otherwise, it generates a new one.

   Args:
       prompt: The text prompt for the operation.
       image_name: The desired name for the output image file (without extension).
       previous_image: Optional path to an image to be edited.

   Returns:
       A confirmation message with the path to the saved image or an error message.
   """
   load_dotenv()
   project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
   if not project_id:
       return "Error: GOOGLE_CLOUD_PROJECT environment variable is not set."
  
   try:
       client = genai.Client(vertexai=True, project=project_id, location="global")
   except Exception as e:
       return f"Error: Failed to initialize genai.Client: {e}"

   image_data = None
   model_id = "gemini-3-pro-image-preview"

   try:
       if previous_image:
           logger.info(f"Editing image: {previous_image}")
           image_data = edit_image(
               client=client,
               prompt=prompt,
               previous_image=previous_image,
               model_id=model_id
           )
       else:
           logger.info("Generating new image")
           # Generate the image
           response = client.models.generate_content(
               model=model_id,
               contents=prompt,
               config=types.GenerateContentConfig(
                   response_modalities=['IMAGE'],
                   image_config=types.ImageConfig(aspect_ratio="16:9"),
               ),
           )

           # Check for errors
           if response.candidates[0].finish_reason != types.FinishReason.STOP:
               return f"Error: Image generation failed. Reason: {response.candidates[0].finish_reason}"

           # Extract image data
           for part in response.candidates[0].content.parts:
               if part.inline_data:
                   image_data = part.inline_data.data
                   break

       if not image_data:
           return {"status": "error", "message": "No image data was generated.", "artifact_name": None}

       # Create the images directory if it doesn't exist
       output_dir = "images"
       os.makedirs(output_dir, exist_ok=True)

       # Save the image to file system
       file_path = os.path.join(output_dir, f"{image_name}.png")
       with open(file_path, "wb") as f:
           f.write(image_data)

       # Save as ADK artifact
       counter = str(tool_context.state.get("loop_iteration", 0))
       artifact_name = f"{image_name}_" + counter + ".png"
       report_artifact = types.Part.from_bytes(data=image_data, mime_type="image/png")
       await tool_context.save_artifact(artifact_name, report_artifact)
       logger.info(f"Image also saved as ADK artifact: {artifact_name}")

       return {
           "status": "success",
           "message": f"Image generated and saved to {file_path}. ADK artifact: {artifact_name}.",
           "artifact_name": artifact_name,
       }

   except Exception as e:
       return f"An error occurred: {e}"
  1. Poniżej znajdziesz ostateczne pliki YAML utworzone w środowisku autora (pamiętaj, że pliki w Twoim środowisku mogą się nieco różnić). Upewnij się, że struktura pliku YAML agenta odpowiada układowi wyświetlanemu w wizualnym kreatorze ADK.
root_agent.yamlname: studio_director
model: gemini-2.5-pro
agent_class: LlmAgent
description: The Studio Director who manages the comic creation pipeline.
instruction: >
 You are the Studio Director. Your objective is to manage a linear pipeline of
 four sequential agents to transform a user's seed idea into a fully rendered,
 responsive HTML5 comic book.


 Your role is to be the primary orchestrator and state manager. You will
 receive the user's initial request.


 **Workflow:**

 1.  If the user's prompt starts with "Create me a comic of ...", you must
 delegate the task to your sub-agent to begin the comic creation pipeline.

 2.  If the user asks a general question or provides a prompt that does not
 explicitly ask to create a comic, you must answer the question directly
 without triggering the comic creation pipeline.

 3.  Monitor the sequence to ensure no steps are skipped. Ensure the output of
 each Sub-Agent is passed as the context for the next.
sub_agents:
 - config_path: ./comic_pipeline.yaml
tools: []
comic_pipline.yaml
name: comic_pipeline
agent_class: SequentialAgent
description: A sequential pipeline of agents to create a comic book.
sub_agents:
 - config_path: ./scripting_agent.yaml
 - config_path: ./panelization_agent.yaml
 - config_path: ./image_synthesis_agent.yaml
 - config_path: ./assembly_agent.yaml
scripting_agent.yamlname: scripting_agent
model: gemini-2.5-pro
agent_class: LlmAgent
description: Narrative & Character Architect.
instruction: >
 You are the Scripting Agent, a Narrative & Character Architect.

 Your input is a seed idea for a comic.


 **Your Logic:**

 1.  **Create a Character Manifest:** You must define exactly 3 specific,
 unchangeable visual identifiers for every character. For example: "Gretel:
 Blue neon hair ribbons, silver apron, glowing boots". This is mandatory.

 2.  **Expand the Narrative:** Expand the seed idea into a coherent narrative
 arc with dialogue.


 **Output:**

 You must output a JSON object containing:

 - "narrative_script": A detailed script with scenes and dialogue.

 - "character_manifest": The mandatory character visual guide.
sub_agents: []
tools: []
panelization_agent.yamlname: panelization_agent
model: gemini-2.5-pro
agent_class: LlmAgent
description: Cinematographer & Storyboarder.
instruction: >
 You are the Panelization Agent, a Cinematographer & Storyboarder.

 Your input is a narrative script and a character manifest.


 **Your Logic:**

 1.  **Divide the Script:** Divide the script into a specific number of panels.
 The user may define this number, or you should default to 8 panels.

 2.  **Define Composition:** For each panel, you must define a specific
 composition, camera shot (e.g., "Wide shot", "Close-up"), and the dialogue for
 that panel.


 **Output:**

 You must output a JSON object containing a structured list of exactly X panel
 descriptions, where X is the number of panels. Each item in the list should
 have "panel_number", "composition_description", and "dialogue".
sub_agents: []
tools: []
image_synthesis_agent.yaml
name: image_synthesis_agent
model: gemini-2.5-pro
agent_class: LlmAgent
description: Technical Artist & Asset Generator.
instruction: >
 You are the Image Synthesis Agent, a Technical Artist & Asset Generator.

 Your input is a structured list of panel descriptions.


 **Your Logic:**

 1.  **Iterate and Generate:** You must iterate through each panel description
 provided in the input. For each panel, you will execute the `generate_image`
 tool.

 2.  **Construct Prompts:** For each panel, you will construct a detailed
 prompt for the image generation tool. This prompt must strictly enforce the
 character visual identifiers from the manifest and include the global style:
 "vibrant comic book style, heavy ink lines, cel-shaded, 4k". The prompt must
 also describe the composition and include a request for speech bubbles to
 contain the dialogue.

 3.  **Map Output:** You must associate each generated image URL with its
 corresponding panel number and dialogue.


 **Output:**

 You must output a JSON object containing a complete gallery of all generated
 images, mapped to their respective panel data (panel_number, dialogue,
 image_url).
sub_agents: []
tools:
 - name: Agent3.tools.image_generation.generate_image
assembly_agent.yamlname: assembly_agent
model: gemini-2.5-pro
agent_class: LlmAgent
description: Frontend Developer for comic book assembly.
instruction: >
 You are the Assembly Agent, a Frontend Developer.

 Your input is the mapped gallery of images and panel data.


 **Your Logic:**

 1.  **Generate HTML:** You will write a clean, responsive HTML5/CSS3 file to
 display the comic. The comic must be vertically scrollable, with each panel
 displaying its image on top and the corresponding dialogue or description
 below it.

 2.  **Write File:** You must use the `write_comic_html` tool to save the
 generated HTML to a file named `comic.html` in the `output/` folder.

 3.  Pass the list of image URLs to the tool so it can handle the image assets
 correctly.


 **Output:**

 You will output a confirmation message indicating the path to the final HTML
 file.
sub_agents: []
tools:
 - name: Agent3.tools.file_writer.write_comic_html
  1. Otwórz kartę interfejsu ADK (Agent Development Kit) , wybierz „Agent3” i kliknij przycisk edycji („ikona pióra”).
  2. W lewym dolnym rogu ekranu kliknij przycisk Zapisz. Spowoduje to zachowanie wszystkich zmian kodu wprowadzonych w głównym agencie.
  3. Teraz możemy rozpocząć testowanie agenta.
  4. Zamknij bieżącą kartę interfejsu ADK (Agent Development Kit) i wróć do karty edytora Cloud Shell.
  5. W terminalu na karcie Edytor Cloud Shell najpierw uruchom ponownie serwer ADK (Agent Development Kit). Otwórz terminal, w którym został uruchomiony serwer ADK (Agent Development Kit), i naciśnij CTRL+C, aby go zamknąć, jeśli nadal działa. Aby ponownie uruchomić serwer, wykonaj te czynności:
#make sure you are in the right folder.
cd ~/adkui

#start the server
adk web
  1. Kliknij adres URL z naciśniętym klawiszem Ctrl (np. http://localhost:8000) wyświetlany na ekranie. W karcie przeglądarki powinien wyświetlić się interfejs ADK (Agent Development Kit).
  2. Na liście pracowników wybierz Agent3.
  3. Wpisz ten prompt:
Create a Comic Book based on the following story,

Title: The Story of Momotaro

The story of Momotaro (Peach Boy) is one of Japan's most famous and beloved folktales. It is a classic "hero's journey" that emphasizes the virtues of courage, filial piety, and teamwork.

The Miraculous Birth
Long, long ago, in a small village in rural Japan, lived an elderly couple. They were hardworking and kind, but they were sad because they had never been blessed with children.

One morning, while the old woman was washing clothes by the river, she saw a magnificent, giant peach floating downstream. It was larger than any peach she had ever seen. With great effort, she pulled it from the water and brought it home to her husband for their dinner.

As they prepared to cut the fruit open, the peach suddenly split in half on its own. To their astonishment, a healthy, beautiful baby boy stepped out from the pit.

"Don't be afraid," the child said. "The Heavens have sent me to be your son."

Overjoyed, the couple named him Momotaro (Momo meaning peach, and Taro being a common name for an eldest son).

The Call to Adventure
Momotaro grew up to be stronger and kinder than any other boy in the village. During this time, the village lived in fear of the Oniogres and demons who lived on a distant island called Onigashima. These Oni would often raid the mainland, stealing treasures and kidnapping villagers.

When Momotaro reached young adulthood, he approached his parents with a request. "I must go to Onigashima," he declared. "I will defeat the Oni and bring back the stolen treasures to help our people."

Though they were worried, his parents were proud. As a parting gift, the old woman prepared Kibi-dango (special millet dumplings), which were said to provide the strength of a hundred men.

Gathering Allies
Momotaro set off on his journey toward the sea. Along the way, he met three distinct animals:

The Spotted Dog: The dog growled at first, but Momotaro offered him one of his Kibi-dango. The dog, tasting the magical dumpling, immediately swore his loyalty.

The Monkey: Further down the road, a monkey joined the group in exchange for a dumpling, though he and the dog bickered constantly.

The Pheasant: Finally, a pheasant flew down from the sky. After receiving a piece of the Kibi-dango, the bird joined the team as their aerial scout.

Momotaro used his leadership to ensure the three animals worked together despite their differences, teaching them that unity was their greatest strength.

The Battle of Onigashima
The group reached the coast, built a boat, and sailed to the dark, craggy shores of Onigashima. The island was guarded by a massive iron gate.

The Pheasant flew over the walls to distract the Oni and peck at their eyes.

The Monkey climbed the walls and unbolted the Great Gate from the inside.

The Dog and Momotaro charged in, using their immense strength to overpower the demons.

The Oni were caught off guard by the coordinated attack. After a fierce battle, the King of the Oni fell to his knees before Momotaro, begging for mercy. He promised to never trouble the villagers again and surrendered all the stolen gold, jewels, and precious silks.

The Triumphant Return
Momotaro and his three companions loaded the treasure onto their boat and returned to the village. The entire town celebrated their homecoming.

Momotaro used the wealth to ensure his elderly parents lived the rest of their lives in comfort and peace. He remained in the village as a legendary protector, and his story was passed down for generations as a reminder that bravery and cooperation can overcome even the greatest evils.
  1. Podczas pracy agenta możesz wyświetlać zdarzenia w terminalu edytora Cloud Shell.
  2. Wygenerowanie wszystkich obrazów może trochę potrwać, więc uzbrój się w cierpliwość lub idź na kawę. Gdy rozpocznie się generowanie obrazu, powinny pojawić się obrazy związane z artykułem, jak poniżej.

2dbdfb6916b75ef0.jpeg

Ilustracja 34. Historia Momotaro w formie komiksu. Jeśli wszystko przebiegnie pomyślnie, wygenerowany plik HTML zostanie zapisany w folderze HTML. Jeśli chcesz ulepszyć agenta, możesz wrócić do Asystenta agenta i poprosić go o wprowadzenie kolejnych zmian.

a4840cb8a82ec55.jpeg

Ilustracja 35. Zawartość folderu wyjściowego

  1. Jeśli krok 25 zostanie wykonany prawidłowo, w folderze output pojawi się plik comic.html. Aby to sprawdzić, wykonaj te czynności. Najpierw otwórz nowy terminal, klikając Terminal>New Terminal (Terminal>Nowy terminal) w menu głównym edytora Cloud Shell. Powinien otworzyć się nowy terminal.
#go to the project folder
cd ~/adkui

#activate python virtual environment
source .venv/bin/activate

#Go to the output folder
cd ~/adkui/output

#start local web server
python -m http.server 8080
  1. Kliknij z naciśniętym klawiszem Ctrl http://0.0.0.0:8080.

16e0108a9f27e44e.png

Ilustracja 36. Uruchamianie lokalnego serwera WWW

  1. Zawartość folderu powinna być wyświetlana na karcie przeglądarki. Kliknij plik HTML (np. comic.html). Komiks powinien być wyświetlany w sposób pokazany poniżej (dane wyjściowe mogą się nieco różnić). 4fb869f885cb938b.jpeg

Ilustracja 37. Działanie na hoście lokalnym

12. Czyszczenie danych

Teraz usuńmy to, co właśnie utworzyliśmy.

  1. Usuń utworzoną właśnie aplikację Cloud Run. Otwórz Cloud Run, klikając Cloud Run . Powinna być widoczna aplikacja utworzona w poprzednim kroku. Zaznacz pole obok aplikacji i kliknij przycisk Usuń.

db630152398108cb.png Ilustracja 38. Usuwanie aplikacji Cloud Run 2. Usuwanie plików w Cloud Shell

#Execute the following to delete the files
cd ~
rm -R ~/adkui

13. Podsumowanie

Gratulacje! Udało Ci się utworzyć agentów ADK (Agent Development Kit) za pomocą wbudowanego wizualnego narzędzia do tworzenia ADK. Dowiedzieliśmy się też, jak wdrożyć aplikację w Cloud Run. To ważne osiągnięcie, które obejmuje podstawowy cykl życia nowoczesnej aplikacji natywnej dla chmury i zapewnia solidną podstawę do wdrażania własnych złożonych systemów opartych na agentach.

Podsumowanie

W tym module nauczyliśmy się:

Przydatne materiały