GENAI106
總覽
本實驗室說明如何在 Google Agent Development Kit (Google ADK) 中,自動調度管理多代理系統。
此外,本實驗室假設您熟悉下列實驗室涵蓋的 ADK 基本知識和工具使用方式:
- 開始使用 Google Agent Development Kit (ADK)
- 為 ADK 代理提供工具
目標
本實驗室的學習內容如下:
- 建立多個代理並按照上下層關係相互連結。
- 寫入工作階段狀態字典,在多輪對話與多個代理間建構內容。
- 指示代理讀取工作階段狀態值,做為回覆時參考的脈絡資訊。
- 使用工作流程代理,直接在代理間傳遞對話。
設定和需求
實驗室活動啟動須知
請詳閱以下操作說明。實驗室活動會計時,且中途無法暫停。點選「Start Lab」後就會開始計時,顯示可使用 Google Cloud 資源的時間。
您將在真正的雲端環境完成實作實驗室活動,而不是模擬或示範環境。為此,我們會提供新的臨時憑證,供您在實驗室活動期間登入及存取 Google Cloud。
為了順利完成這個實驗室,請先確認:
- 可以使用標準的網際網路瀏覽器 (Chrome 瀏覽器為佳)。
注意事項:請使用無痕模式 (建議選項) 或私密瀏覽視窗執行此實驗室,這可以防止個人帳戶和學員帳戶之間的衝突,避免個人帳戶產生額外費用。
- 是時候完成實驗室活動了!別忘了,活動一旦開始將無法暫停。
注意事項:務必使用實驗室專用的學員帳戶。如果使用其他 Google Cloud 帳戶,可能會產生額外費用。
如何開始實驗室及登入 Google Cloud 控制台
-
按一下「Start Lab」按鈕。如果實驗室會產生費用,畫面上會出現選擇付款方式的對話方塊。左側的「Lab Details」窗格會顯示下列項目:
- 「Open Google Cloud console」按鈕
- 剩餘時間
- 必須在這個實驗室使用的臨時憑證
- 完成這個實驗室所需的其他資訊 (如有)
-
按一下「Open Google Cloud console」;如果使用 Chrome 瀏覽器,也可以按一下滑鼠右鍵,選取「在無痕視窗中開啟連結」。
接著,實驗室會啟動相關資源,並開啟另一個分頁,顯示「登入」頁面。
提示:您可以在不同的視窗並排開啟分頁。
注意:頁面顯示「選擇帳戶」對話方塊時,請點選「使用其他帳戶」。
-
如有必要,請將下方的 Username 貼到「登入」對話方塊。
{{{user_0.username | "Username"}}}
您也可以在「Lab Details」窗格找到 Username。
-
點按「下一步」。
-
複製下方的 Password,並貼到「歡迎使用」對話方塊。
{{{user_0.password | "Password"}}}
您也可以在「Lab Details」窗格找到 Password。
-
點按「下一步」。
重要事項:請務必使用實驗室提供的憑證,而非自己的 Google Cloud 帳戶憑證。
注意:如果使用自己的 Google Cloud 帳戶來進行這個實驗室,可能會產生額外費用。
-
繼續點按後續頁面:
- 接受條款及細則。
- 由於這是臨時帳戶,請勿新增救援選項或雙重驗證機制。
- 請勿申請免費試用。
Google Cloud 控制台稍後會在這個分頁開啟。
注意:如要使用 Google Cloud 產品和服務,請按一下「導覽選單」,或在「搜尋」欄位輸入服務或產品名稱。
多代理系統
開發人員可以使用 Agent Development Kit,讓生成式模型的多步驟行為更可靠精細。您不必編寫冗長、複雜且不一定能穩定提供結果的提示詞,只要建構多個簡單的代理,再劃分工作和責任來組成一套流程,代理就會合作解決複雜問題。
採取這種架構有幾個主要優點,例如:
-
設計更簡單:您可以想成代理會各司其職,而且各有所長。
-
以更穩定的效能發揮專門作用:專用代理可從明確的樣本中學習,執行特定工作更可靠。
-
梳理工作流程:將工作流程劃分為不同代理,處理方式更有條理,更有助於思考。
-
容易改良及維護:直接變更複雜代理來導正某項行為,可能會影響其他生成結果。相比之下,調整或修正專用元件更簡單。
-
模組化:工作流程中的各個代理皆可輕鬆複製,並套用至其他類似流程。
階層式代理樹狀結構

您可以使用 Agent Development Kit,將代理整理成樹狀結構,限制每個代理的轉移選項,以便控管及預測對話在結構中可能採取的路徑。階層式結構的優點包括:
- 從現實世界的協作團隊汲取靈感,更容易設計及推論多代理系統的行為。
- 與一般軟體開發模式相呼應,對開發人員來說相當符合直覺。
- 開發人員能進一步控管系統內的資訊流向和工作委派流程,方便掌握可能的路徑並為系統偵錯。舉例來說,在系統流程的不同環節中,如果有兩個報告生成代理的說明類似,您可以透過樹狀結構,更輕鬆確保叫用的代理正確無誤。
這類結構的開頭一律為 root_agent 變數中定義的代理,但也可能以其他面向使用者的名稱來做區別。root_agent 為父代理,底下有一或多個子代理,每個子代理可以再有自己的子代理。
工作 1:安裝 ADK 並設定環境
這個實驗室環境已預先啟用 Agent Platform API。如要在自己的專案執行這些步驟,請前往 Agent Platform 並按照提示啟用。
準備 Cloud Shell 編輯器分頁
- 選取 Google Cloud 控制台視窗,然後依序按下鍵盤上的 G 和 S 鍵,開啟 Cloud Shell。或者,您也能點選 Cloud 控制台右上方的「啟用 Cloud Shell」按鈕
。
- 點選「繼續」。
- 系統提示您授權 Cloud Shell 時,按一下「授權」。
- 在 Cloud Shell 終端機面板右上角,點選「在新視窗中開啟」按鈕
。
- 點選窗格頂端的「開啟編輯器」鉛筆圖示
,即可查看檔案。
- 點選左側導覽選單頂端的「Explorer」圖示
,開啟檔案探索工具。
- 點選「Open Folder」按鈕。
- 「Open Folder」對話方塊出現後,點選「OK」,選取 Qwiklab 學員帳戶的主資料夾。
- 關閉畫面右側的其他教學課程或 Gemini 面板,為程式碼編輯器騰出更多空間。
- 操作本實驗室其餘步驟時,可全程用這個視窗做為 IDE,並搭配 Cloud Shell 編輯器和 Cloud Shell 終端機。
下載並安裝本實驗室的 ADK 和程式碼範例
-
將下列指令貼入 Cloud Shell 終端機,從 Cloud Storage bucket 複製這個實驗室要使用的程式碼檔案:
gcloud storage cp -r gs://{{{project_0.project_id| YOUR_GCP_PROJECT_ID}}}-bucket/* .
-
在 Cloud Shell 終端機執行下列指令,更新 PATH 環境變數,並安裝 ADK 和其他實驗室所需項目。
export PATH=$PATH:"/home/${USER}/.local/bin"
python3 -m pip install google-adk[otel-gcp]==1.30.0 -r adk_multiagent_systems/requirements.txt
工作 2:瞭解父代理、子代理和同層代理間的轉移方向
對話一律會從 root_agent 變數中定義的代理開始。
上層代理預設會隨時解讀各個子代理的說明,並判斷是否應將對話掌控權轉移給子代理。
您可以在父代理的 instruction 中,參照子代理的 name 參數值 (而非變數名稱) 來引導轉移方向。試試這個範例:
-
在 Cloud Shell 終端機執行下列指令,建立 .env 檔案來驗證 parent_and_subagents 目錄中的代理。
cd ~/adk_multiagent_systems
cat << EOF > parent_and_subagents/.env
GOOGLE_GENAI_USE_VERTEXAI=TRUE
GOOGLE_CLOUD_PROJECT={{{project_0.project_id| YOUR_GCP_PROJECT_ID}}}
GOOGLE_CLOUD_LOCATION=global
MODEL={{{project_0.startup_script.gemini_flash_model_id | gemini_flash_model_id}}}
EOF
這些變數的作用如下:
-
GOOGLE_GENAI_USE_VERTEXAI=TRUE:表示您使用 Agent Platform 來驗證身分,而非使用 Gemini API 金鑰。
-
GOOGLE_CLOUD_PROJECT 和 GOOGLE_CLOUD_LOCATION:提供要與模型呼叫建立關聯的專案和位置。
-
MODEL:存放在這裡的用途是做為環境變數供系統載入。
-
執行下列指令,將 .env 檔案複製到這個實驗室後續部分會用到的 workflow_agents 目錄:
cp parent_and_subagents/.env workflow_agents/.env
-
在 Cloud Shell 編輯器檔案總管窗格,前往 adk_multiagent_systems/parent_and_subagents 目錄。
-
點選「agent.py」來開啟這個檔案。
提示:Python 程式碼必須先定義子代理,才能新增至代理。如要依對話流程順序讀取 agent.py 檔案,建議從最下方的代理往回讀。
-
請注意,這裡有三個代理:
-
root_agent:在 ADK 開發 UI 和指令列介面中顯示的名稱為
steering。這個代理會詢問使用者是否已有目的地,或需要幫忙決定,並根據回覆將對話導向合適的子代理。請注意,這個代理的 instruction 雖然簡單且未提及子代理,但能讀取子代理的說明。
-
travel_brainstormer:如果使用者不知道要去哪裡旅遊,這個代理會協助發想目的地。
-
attractions_planner:使用者決定好旅遊國家/地區後,這個代理會列出觀光景點清單。
-
在建立的 root_agent 加入下列程式碼,將 travel_brainstormer 和 attractions_planner 設為 root_agent 的子代理:
sub_agents=[travel_brainstormer, attractions_planner]
-
儲存檔案。
-
請不要將對應的「parent」參數加入子代理,必須在建立父代理時指定 sub_agents,才能定義出階層式樹狀結構。
-
在 Cloud Shell 終端機執行下列指令,使用 ADK 指令列介面與代理對話:
cd ~/adk_multiagent_systems
adk run parent_and_subagents
-
看到 [user]: 提示詞時,請輸入下列內容向代理打招呼:
hello
輸出內容範例 (可能會與實際內容稍有不同):
[user]: hello
[steering]: Hello! Welcome to your travel adventure. Do you already know where you'd like to travel, or would you like some help deciding?
-
告訴代理:
I could use some help deciding.
輸出內容範例 (可能會與實際內容稍有不同):
[user]: I could use some help deciding.
[travel_brainstormer]: Hello! I'd love to help you decide on the perfect destination for your next trip.
To start, here are a few highly popular countries that travelers love:
* **Italy:** Famous for food, history, art, and beautiful landscapes.
* **Japan:** A unique blend of ultra-modern cities, ancient temples, stunning nature, and incredible cuisine.
* **Costa Rica:** A paradise for nature lovers, wildlife, and outdoor adventures.
* **France:** Renowned for world-class art, fashion, gastronomy, and romantic cities.
To help narrow things down to the perfect match for you, what are your primary goals for this trip? Are you looking for:
1. **Adventure** (hiking, wildlife, outdoor activities)
2. **Leisure** (relaxing on beaches, spas, slow-paced exploring)
3. **Learning** (history, museums, exploring different cultures)
4. **Shopping** (fashion, local markets, unique finds)
5. **Viewing Art** (galleries, architecture, world-famous masterpieces)
Let me know what sounds most exciting to you, or if you have a mix of these in mind!
-
您會發現回覆中括號內的名稱為 travel_brainstormer,代表 root_agent (名稱為 steering) 僅依據子代理的 description 就能將對話轉給適當的子代理。
-
在 user: 提示詞中輸入 exit,即可結束對話。
-
您也能在代理的 instructions 提供更詳細的指令,說明何時要將對話轉給子代理。在 agent.py 檔案,將下列幾行指令加入 root_agent 的 instruction:
If they need help deciding, send them to
'travel_brainstormer'.
If they know what country they'd like to visit,
send them to the 'attractions_planner'.
-
儲存檔案。
-
在 Cloud Shell 終端機執行下列指令,再次啟動指令列介面:
adk run parent_and_subagents
-
輸入下列內容,向代理打招呼:
hello
-
輸入下列內容來回覆代理:
I would like to go to Japan.
輸出內容範例 (可能會與實際內容稍有不同):
[user]: I would like to go to Japan.
[attractions_planner]: Japan is an incredible destination with a perfect blend of ancient traditions and futuristic cities!
Here are some of the top attractions and regions to consider for your trip, categorized by the type of experience:
### 1. **The Modern & Futuristic (Tokyo)**
* **Shibuya Crossing & Harajuku:** Experience the bustling energy of the world's busiest pedestrian crossing and the quirky fashion of Takeshita Street.
* **teamLab Planets:** An immersive, digital-art museum where you walk through water and interact with stunning light projections.
* **Senso-ji Temple:** Tokyo's oldest and most iconic Buddhist temple, located in the historic Asakusa district.
### 2. **History & Tradition (Kyoto & Nara)**
* **Fushimi Inari Shrine (Kyoto):** Famous for its path of thousands of vibrant red torii gates winding up the mountain.
* **Kinkaku-ji (The Golden Pavilion, Kyoto):** A breathtaking Zen temple covered in gold leaf, reflecting over a serene pond.
* **Nara Park (Nara):** Home to hundreds of freely roaming, bowing deer and the massive Great Buddha statue at Todai-ji Temple.
### 3. **Nature & Scenic Views**
* **Mount Fuji & Lake Kawaguchiko:** Enjoy stunning views of Japan's iconic volcano, especially beautiful during cherry blossom or autumn foliage seasons.
* **Arashiyama Bamboo Grove (Kyoto):** Walk through a towering forest of green bamboo that feels like another world.
### 4. **Food & Entertainment (Osaka)**
* **Dotonbori:** Osaka's neon-lit food street, famous for street foods like *takoyaki* (octopus balls) and *okonomiyaki* (savory pancakes).
* **Osaka Castle:** A magnificent historic landmark surrounded by a massive park and moat.
---
To help me tailor the perfect itinerary for you, **what kinds of things are you most interested in?**
* Historic temples and shrines?
* Modern city life and pop culture (anime, gaming, shopping)?
* Nature, hiking, and scenic landscapes?
* Incredible food and culinary experiences?
Let me know, and we can start building your custom list of stops!
-
您會發現對話已轉給另一個子代理 attractions_planner。
-
這時請回覆:
Actually I don't know what country to visit.
輸出內容範例 (可能會與實際內容稍有不同):
user: actually I don't know what country to visit
[travel_brainstormer]: Okay! I can help you brainstorm some countries for travel...
-
您會發現對話已轉給 travel_brainstormer 代理,也就是 attractions_planner 的同層代理。這項功能預設為允許。如果不希望對話轉給同層代理,可以將 attractions_planner 代理的 disallow_transfer_to_peers 參數設為 True。
-
在使用者提示詞中輸入 exit,結束工作階段。
逐步模式:如要讓代理逐步引導使用者完成程序,建議將第一步的代理設為 root_agent,然後將第二步的代理設為 root_agent 的唯一子代理,之後每個步驟的代理都是前一步代理的唯一子代理。
點選「Check my progress」,確認目標已達成。
瞭解父代理、子代理和同層代理間的轉移方向
工作 3:使用工作階段狀態來儲存及擷取特定資訊
ADK 中的每段對話都存放於 Session,所有參與對話的代理都能存取。工作階段包含對話記錄,代理會讀取這些內容並據此生成回覆。此外,工作階段還包含工作階段狀態字典,可供您進一步控管要強調的重要資訊,以及這些資訊的存取方式。
這項功能非常實用,有助於代理互相傳遞資訊,或在對話過程中,維持簡單的資料結構 (例如工作清單)。
請按照下列步驟新增和讀取狀態:
-
返回 adk_multiagent_systems/parent_and_subagents/agent.py 檔案。
-
將下列函式定義貼到 # Tools 標頭後方:
def save_attractions_to_state(
tool_context: ToolContext,
attractions: List[str]
) -> dict[str, str]:
"""Saves the list of attractions to state["attractions"].
Args:
attractions [str]: a list of strings to add to the list of attractions
Returns:
None
"""
# Load existing attractions from state. If none exist, start an empty list
existing_attractions = tool_context.state.get("attractions", [])
# Update the 'attractions' key with a combo of old and new lists.
# When the tool is run, ADK will create an event and make
# corresponding updates in the session's state.
tool_context.state["attractions"] = existing_attractions + attractions
# A best practice for tools is to return a status message in a return dict
return {"status": "success"}
-
這段程式碼有幾點需要留意:
- 工作階段會以
ToolContext 的形式傳遞至工具函式,您只需要指派參數接收即可,如上方所示的 tool_context 參數。接著就能使用 tool_context 存取工作階段資訊,例如對話記錄 (透過 tool_context.events),以及工作階段狀態字典 (透過 tool_context.state)。如果工具函式修改了 tool_context.state 字典,必須等到工具執行完畢,變更才會反映在工作階段狀態中。
- docstring 會明確說明引數區段和傳回值。
- 函式程式碼註解會說明如何輕鬆更新狀態字典。
-
建立 attractions_planner 代理時,加入 tools 參數來新增工具:
tools=[save_attractions_to_state]
-
在 attractions_planner 代理的現有 instruction,新增下列條列式內容:
- When they reply, use your tool to save their selected attraction
and then provide more possible attractions.
- If they ask to view the list, provide a bulleted list of
{ attractions? } and then suggest some more.
-
注意以大括號括住的區段 { attractions? }。這是 ADK 的索引鍵範本功能,會從狀態字典載入 attractions 索引鍵的值。在 attractions 索引鍵後方加上問號,可避免欄位尚未出現時發生錯誤。
-
接下來,您將在網頁介面執行代理,並前往分頁查看對工作階段狀態所做的變更。使用下列指令,啟動 Agent Development Kit 網頁版 UI:
adk web --allow_origins "regex:https://.*\.cloudshell\.dev"
輸出內容
INFO: Started server process [2434]
INFO: Waiting for application startup.
+-------------------------------------------------------+
| ADK Web Server started |
| |
| For local testing, access at http://localhost:8000. |
+-------------------------------------------------------+
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
-
點選終端機輸出內容中的 http://127.0.0.1:8000 連結,在新分頁開啟網頁介面。
-
系統會開啟新的瀏覽器分頁,顯示 ADK 開發 UI。
-
在左側的「Select an agent」下拉式選單,選取「parent_and_subagents」代理。
-
輸入 hello 開始對話。
-
代理向您打招呼之後,請回覆:
I'd like to go to Egypt.
對話應會轉給 attractions_planner,並顯示景點清單。
-
選取景點,例如:
I'll go to the Sphinx
-
代理應會透過回覆確認要求,例如「好,我已將人面獅身像存入清單。以下是其他景點...」。
-
點選標有勾號的回覆工具方塊,查看根據工具回覆建立的事件。您會發現其中的「actions」欄位包含 state_delta,作用是說明狀態變更。
-
代理應會提示您選取其他景點。請從列出的景點中擇一,然後回覆給代理。
-
在左側導覽選單點選「X」,退出先前查看的事件視窗。
-
現在側欄應會顯示事件清單和數個分頁選項。請選取「State」分頁標籤,即可查看目前的狀態,包括 attractions 陣列,當中有您要求的兩個值。

-
向代理傳送下列訊息:
What is on my list?
-
代理應會依據 instruction,傳回條列式清單。
-
測試完代理後,請關閉網路瀏覽器分頁,接著在 Cloud Shell 終端機按下 CTRL + C 鍵來停止伺服器。
在本實驗室的後續部分,您將示範如何使用狀態在代理間通訊。
點選「Check my progress」,確認目標已達成。
使用工作階段狀態來儲存及擷取特定資訊
如要將代理的完整文字回覆儲存於狀態字典,而非只儲存一小部分,可以在定義代理時設定 output_key 參數,代理的完整輸出內容就會儲存於狀態字典,並以該欄位名稱命名。
工作流程代理
如果想讓使用者與多個專用子代理逐一互動,在代理間建立上下層轉移關係,是非常合適的做法。
不過,如果想讓代理接連採取行動,而不必等使用者回覆,則可考慮使用工作流程代理。以下列舉幾個適用的範例情境:
-
規劃及執行:由某個代理準備項目清單,再由其他代理根據該清單執行後續工作,例如編寫文件。
-
研究及撰寫內容:由某個代理呼叫函式,從 Google 搜尋或其他資料來源收集脈絡資訊,然後由其他代理根據這些資訊輸出內容。
-
草擬及修訂:由某個代理草擬文件,然後由其他代理檢查並反覆修改。
為完成這類工作,工作流程代理設有多個子代理,而且會確保每個都會採取行動。Agent Development Kit 提供三種內建的工作流程代理,您也能自行定義:
SequentialAgent
LoopAgent
ParallelAgent
在本實驗室的後續部分,您將建構多代理系統,並使用多個 LLM 代理、工作流程代理和工具來控管代理流程。
具體來說,您將建構代理程式,為新的熱門電影編寫提案文件。這是根據某個歷史人物生平改編的傳記電影。您的子代理將負責研究,並與 screenwriter 和 critic 代理來回撰寫及修改。最後,其他子代理會協助構思選角方案,並根據歷史票房數據預測結果。
這個多代理系統最終將如下所示 (點選圖片可放大檢視):

不過,您會先從簡單的版本著手。
工作 4:開始使用 SequentialAgent 建構多代理系統
SequentialAgent 會以線性序列執行子代理。也就是說,sub_agents 清單中的各個子代理會依定義的順序逐一運作。
如果工作流程中的工作必須依特定順序執行,且前一項工作的輸出內容會做為後一項工作的輸入內容,就非常適合使用 SequentialAgent。
在這項工作,您將執行 SequentialAgent,建構電影提案製作多代理系統的第一個版本。代理結構的初稿大致如下:

-
在 Cloud Shell 編輯器,前往 adk_multiagent_systems/workflow_agents 目錄。
-
點選 workflow_agents 目錄中的「agent.py」檔案。
-
詳閱這個代理的定義檔。由於必須先定義子代理,才能指派至父代理,如要依對話流程順序讀取檔案,建議從最下方的代理往回讀。
-
您也能使用 append_to_state 函式工具,允許代理在狀態字典值中新增內容。如果代理可能會多次呼叫工具,或在 LoopAgent 的多個迴圈中執行動作,這項功能就特別實用,因為代理每次執行動作時的輸出內容都會儲存。
-
從 Cloud Shell 終端機啟動網頁介面,試用目前的代理版本。請使用 --reload_agents 引數,依據代理變更即時重新載入代理:
cd ~/adk_multiagent_systems
adk web --allow_origins "regex:https://.*\.cloudshell\.dev" --reload_agents
注意事項:如未關閉先前的 adk web 工作階段,預設通訊埠 8000 會遭到封鎖。只要使用有如 adk web --port 8001 的指令,即可透過新的通訊埠啟動開發 UI。
-
點選終端機輸出內容中的 http://127.0.0.1:8000 連結,在新分頁開啟網頁介面。
-
系統會開啟新的瀏覽器分頁,顯示 ADK 開發 UI。
-
在左側的「Select an agent」下拉式選單,選取「workflow_agents」。
-
輸入 hello 開始對話。代理可能要過一下子才會回覆,但應該會請您輸入歷史人物,開始生成電影劇情。
-
代理提示您輸入歷史人物時,可任選一位,或使用下列人物範例:
-
Zhang Zhongjing (張仲景):西元 2 世紀的著名中醫師。
-
Ada Lovelace (愛達·勒芙蕾絲):英國數學家兼作家,以研究早期電腦而聞名。
-
Marcus Aurelius (馬可·奧理略):羅馬皇帝,以哲學著作而聞名。
-
代理現在應會相互依序呼叫其他代理,開始執行工作流程,將劇情大綱檔案寫入 ~/adk_multiagent_systems/movie_pitches 目錄。檔案寫入磁碟時,您應會收到通知。
如果代理未回報檔案生成完畢,或詢問您是否想嘗試其他人物,可點選右上方的「+ New Session」,然後再試一次。
-
在 Cloud Shell 編輯器查看代理的輸出內容。只要在 Cloud Shell 編輯器選單依序啟用「View」>「Word Wrap」,即可查看完整文字,不必頻繁水平捲動。
-
在 ADK 開發 UI,點選表示一輪對話的任一代理圖示
,開啟事件檢視畫面。
-
事件檢視畫面會以樹狀結構呈現此工作階段使用的代理和工具。您可能需要捲動事件面板,才能查看完整內容。

- 除了圖表檢視畫面,您還能點選事件的「Request」分頁標籤,查看這個代理在要求中收到的資訊,包括對話記錄。
- 您也能點選事件的「Response」分頁標籤,查看代理傳回的內容。
注意:雖然系統能生成有趣的結果,但不代表指令可以很簡短或省略樣本。為每個代理額外加入更嚴謹的指令和樣本,才能大幅提升系統的可靠性。
點選「Check my progress」,確認目標已達成。
開始使用 SequentialAgent 建構多代理系統
工作 5:新增 LoopAgent 來執行疊代作業
LoopAgent 會依定義的序列執行子代理,然後再次從頭開始,過程中不會停下來等待使用者輸入。這個迴圈會一再重複,直到達到指定疊代次數,或其中一個子代理呼叫結束迴圈為止 (通常是呼叫內建的 exit_loop 工具)。
LoopAgent 非常適合需要持續修正、監控或反覆執行的工作流程。以下列舉幾個範例:
-
反覆修正:透過重複的代理循環,持續改良文件或計畫。
-
持續監控:使用一系列代理,定期檢查資料來源或條件。
-
討論或協商:代理互相反覆模擬討論,以便獲得更理想的結果。
您將新增 LoopAgent,在構思故事時,讓電影提案代理執行多輪研究和疊代作業。LoopAgent 不僅可協助修正腳本,還能讓使用者先輸入較籠統的內容。簡單來說,使用者可能不會提出具體的歷史人物,只知道自己想要一段關於古代醫師的故事。在這種情況下,代理可反覆進行「研究 > 寫作」循環,找出合適的人物,然後編寫故事。

修改後的代理運作流程大致如下:
-
root_agent greeter:維持不變。
- 現在
SequentialAgent film_concept_team 會由下列代理組成:
-
LoopAgent:名稱為 writers_room,位於序列開頭,包含下列代理:
-
researcher:作用與先前相同。
-
screenwriter:作用與先前類似。
-
critic:在迴圈中,對目前的草稿提出重要意見,進而啟動下一輪研究和改進。
- 迴圈終止時,對話掌控權將回到
SequentialAgent film_concept_team,再傳遞至序列中的下一個代理 file_writer。該代理會設定片名,並將序列結果寫入檔案,與先前一樣。
現在,請按照下列步驟進行變更:
-
在 adk_multiagent_systems/workflow_agents/agent.py 檔案,新增下列工具匯入語句,代理就能視需求結束迴圈:
from google.adk.tools import exit_loop
from google.adk.models import Gemini
-
新增 critic 代理來判斷劇情大綱是否完成,進而決定是否結束迴圈。請將下列新代理貼到 agent.py 檔案的 # Agents 區段標頭下方,不必覆寫現有代理。您會發現這個代理內含 exit_loop 工具,以及使用時間點的指令:
critic = Agent(
name="critic",
model=Gemini(model=model_name, retry_options=RETRY_OPTIONS),
description="Reviews the outline so that it can be improved.",
instruction="""
INSTRUCTIONS:
Consider these questions about the PLOT_OUTLINE:
- Does it meet a satisfying three-act cinematic structure?
- Do the characters' struggles seem engaging?
- Does it feel grounded in a real time period in history?
- Does it sufficiently incorporate historical details from the RESEARCH?
If the PLOT_OUTLINE does a good job with these questions, exit the writing loop with your 'exit_loop' tool.
If significant improvements can be made, use the 'append_to_state' tool to add your feedback to the field 'CRITICAL_FEEDBACK'.
Explain your decision and briefly summarize the feedback you have provided.
PLOT_OUTLINE:
{ PLOT_OUTLINE? }
RESEARCH:
{ research? }
""",
before_model_callback=log_query_to_model,
after_model_callback=log_model_response,
tools=[append_to_state, exit_loop]
)
-
建立新的 LoopAgent 並命名為 writers_room,以 researcher、screenwriter 和 critic 組成疊代迴圈。每次迴圈結束時,代理都會嚴格審查當前工作,促成下一輪的改良。請將下列內容貼到現有 SequentialAgent film_concept_team 區段之前。
writers_room = LoopAgent(
name="writers_room",
description="Iterates through research and writing to improve a movie plot outline.",
sub_agents=[
researcher,
screenwriter,
critic
],
max_iterations=5,
)
-
您會發現建立的 LoopAgent 內含 max_iterations 參數。這個參數會定義迴圈結束前的執行次數。無論您是否想以其他方法中斷迴圈,都建議限制疊代總次數。
-
更新 SequentialAgent film_concept_team,將 researcher 和 screenwriter 換成您剛才建立的 LoopAgent writers_room。file_writer 代理則應留在序列結尾。現在 film_concept_team 應如下所示:
film_concept_team = SequentialAgent(
name="film_concept_team",
description="Write a film plot outline and save it as a text file.",
sub_agents=[
writers_room,
file_writer
],
)
-
返回 ADK 開發 UI 分頁,點選右上方的「+ 新增工作階段」按鈕,啟動新的工作階段。
-
輸入 hello 開始新的對話。
-
代理提示您選擇歷史人物類型時,請選擇有興趣的人物,例如:
an industrial designer who made products for the masses
a cartographer (a map maker)
that guy who made crops yield more food
-
選擇人物類型後,代理應會反覆循環運作,最後設定片名,並將大綱寫入檔案。
-
使用 Cloud Shell 編輯器查看生成的檔案。該檔案應儲存於 adk_multiagent_systems/movie_pitches 目錄。與先前一樣,在編輯器選單依序啟用「View」>「Word Wrap」,即可查看完整文字,不必頻繁水平捲動。
點選「Check my progress」,確認目標已達成。
新增 LoopAgent 來執行疊代作業
工作 6:以「擴散收集」模式,使用 ParallelAgent 生成報告
ParallelAgent 可同時執行多個子代理。每個子代理都會各自運作,而且預設不會在同步執行時,直接共用對話記錄或狀態。
如果工作可劃分為獨立的子工作並同時處理,就很適合採用這種代理。使用 ParallelAgent 後,這類工作的整體執行時間將大幅縮短。
在本實驗室,您將加入補充報告,內容包含潛在票房表現研究和選角初步構想,藉此提升新電影提案的說服力。

修改後的代理運作流程大致如下:
-
greeter:維持不變。
- 現在
SequentialAgent film_concept_team 會由下列代理組成:
-
LoopAgent writers_room 同樣包含下列代理:
- researcher
- screenwriter
- critic
- 新的
ParallelAgent preproduction_team 會隨即運作。這個代理涵蓋:
-
box_office_researcher 代理:根據歷來票房資料,生成這部電影的潛在票房表現報告。
-
casting_agent 代理:找出曾主演類似電影的演員,據此提供選角初步構想。
-
file_writer 代理:將序列結果寫入檔案,與先前一樣。
儘管本例中的許多創意工作通常由人類團隊完成,但這項工作流程旨在說明如何將複雜的任務鏈拆分給多個子代理,藉以生成複雜文件的草稿,供人類團隊成員編輯和改進。
-
將下方的新代理和 ParallelAgent 貼到 workflow_agents/agent.py 檔案的 # Agents 標頭下方:
box_office_researcher = Agent(
name="box_office_researcher",
model=Gemini(model=model_name, retry_options=RETRY_OPTIONS),
description="Considers the box office potential of this film",
instruction="""
PLOT_OUTLINE:
{ PLOT_OUTLINE? }
INSTRUCTIONS:
Write a report on the box office potential of a movie like that described in PLOT_OUTLINE based on the reported box office performance of other recent films.
""",
output_key="box_office_report"
)
casting_agent = Agent(
name="casting_agent",
model=Gemini(model=model_name, retry_options=RETRY_OPTIONS),
description="Generates casting ideas for this film",
instruction="""
PLOT_OUTLINE:
{ PLOT_OUTLINE? }
INSTRUCTIONS:
Generate ideas for casting for the characters described in PLOT_OUTLINE
by suggesting actors who have received positive feedback from critics and/or
fans when they have played similar roles.
""",
output_key="casting_report"
)
preproduction_team = ParallelAgent(
name="preproduction_team",
sub_agents=[
box_office_researcher,
casting_agent
]
)
-
更新現有 film_concept_team 代理的 sub_agents 清單,在 writers_room 與 file_writer 之間加入 preproduction_team:
film_concept_team = SequentialAgent(
name="film_concept_team",
description="Write a film plot outline and save it as a text file.",
sub_agents=[
writers_room,
preproduction_team,
file_writer
],
)
-
將 file_writer 的 instruction 改為:
INSTRUCTIONS:
- Create a marketable, contemporary movie title suggestion for the movie described in the PLOT_OUTLINE. If a title has been suggested in PLOT_OUTLINE, you can use it, or replace it with a better one.
- Use your 'write_file' tool to create a new txt file with the following arguments:
- for a filename, use the movie title
- Write to the 'movie_pitches' directory.
- For the 'content' to write, include:
- The PLOT_OUTLINE
- The BOX_OFFICE_REPORT
- The CASTING_REPORT
PLOT_OUTLINE:
{ PLOT_OUTLINE? }
BOX_OFFICE_REPORT:
{ box_office_report? }
CASTING_REPORT:
{ casting_report? }
-
儲存檔案。
-
點選 ADK 開發 UI 右上方的「+ New Session」。
-
輸入 hello 開始對話。
-
代理提示時,輸入您有興趣的新人物構想,例如:
that actress who invented the technology for wifi
an exciting chef
key players in the worlds fair exhibitions
-
代理完成編寫並生成報告後,請前往 adk_multiagent_systems/movie_pitches 目錄查看生成的檔案。如果部分程序失敗,請點選右上方的「+ New session」,然後再試一次。
自訂工作流程代理
如果預先定義的工作流程代理 SequentialAgent、LoopAgent 和 ParallelAgent 無法滿足需求,不妨使用 CustomAgent 彈性導入新的工作流程邏輯。您可以定義子代理間的流程控制、條件式執行或狀態管理模式。這個代理適用於複雜的工作流程、有狀態的自動化調度管理作業,或將自訂商業邏輯整合至框架的自動化調度管理層。
本實驗室不會說明如何建立 CustomAgent,但您可以先認識這個代理,需要時就能使用!
恭喜!
在這個實驗室,您學會了如何建立多個代理,並按照上下層關係相互連結;將資料新增至工作階段狀態,並在代理指令讀取;以及使用工作流程代理,直接在代理之間傳遞對話。
Google Cloud 教育訓練與認證
協助您瞭解如何充分運用 Google Cloud 的技術。我們的課程會介紹專業技能和最佳做法,讓您快速掌握要領並持續進修。課程包含基本到進階等級,您可自行安排時間,選擇以隨選、線上或虛擬方式參加。認證可協助您驗證及證明自己在 Google Cloud 技術方面的技能和專業知識。
使用手冊上次更新日期:2026 年 7 月 26 日
實驗室上次測試日期:2026 年 7 月 26 日
著作權所有 2026 Google LLC。保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,所有其他公司和產品名稱可能是其關聯公司的商標。