使用 Gemini 和 Gemma 模型建構多代理系統

1. 簡介

在本實驗室,您將建構分散式多代理系統,不只是簡單的聊天機器人。

雖然單一 LLM 就能回答問題,但現實世界的問題往往很複雜,需要專門的角色來處理。您不會要求後端工程師設計 UI,也不會要求設計師最佳化資料庫查詢。同樣地,我們也可以建立專門的 AI 代理,專注於一項工作,並互相協調來解決複雜的問題。

您將建構課程建立系統,其中包含:

  • 研究代理:使用 google_search 尋找最新資訊。
  • 審查代理:審核研究的品質和完整性。
  • 內容建構代理:將研究結果轉為結構完整的課程。
  • 調度管理代理:管理這些專家之間的工作流程和通訊。

課程內容

  • 定義可使用工具 (搜尋網路) 的代理 (研究員)。
  • 使用 Pydantic 為評估工具實作結構化輸出。
  • 透過 Agent-to-Agent (A2A) 通訊協定,連線至遠端代理。
  • 建構 LoopAgent,在研究員和評審之間建立意見回饋循環。
  • 使用 ADK 在本機執行分散式系統。
  • 將多代理系統部署至 Google Cloud Run。
  • 在 Cloud Run GPU 上使用 Gemma 模型,建構內容建構代理。

軟硬體需求

  • 網路瀏覽器,例如 Chrome
  • 已啟用計費功能的 Google Cloud 專案

2. 架構和自動化調度管理原則

首先,我們來瞭解這些代理如何協同運作。我們要建構課程建立管道。

系統設計

架構圖

使用代理自動調度管理

標準代理 (例如研究員) 會執行工作。調度管理代理 (例如 LoopAgent 或 SequentialAgent) 負責管理其他代理。他們沒有自己的工具,而是透過委派來執行工作。

  1. LoopAgent:這就像程式碼中的 while 迴圈。這個方式會依序重複執行一組代理,直到符合條件或達到最高疊代次數為止。我們將這項功能用於研究循環:
    • 研究員負責尋找資訊。
    • Judge 則會評估。
    • 如果 Judge 輸出「Fail」,EscalationChecker 會讓迴圈繼續執行。
    • 如果 Judge 判定「通過」,EscalationChecker 就會中斷迴圈。
  2. SequentialAgent:這項操作與標準指令碼執行作業類似。會依序執行代理。我們將此用於高階管道:
    • 首先,執行研究迴圈 (直到完成並取得良好資料)。
    • 接著,執行 Content Builder (編寫課程)。

結合這些技術,我們就能建立強大的系統,在生成最終輸出內容前自我修正。

3. 設定

專案設定

建立 Google Cloud 專案

  1. 在 Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案。
  2. 確認雲端專案已啟用計費功能。瞭解如何確認專案是否已啟用計費功能。

啟動 Cloud Shell

Cloud Shell 是在 Google Cloud 中運作的指令列環境,已預先載入必要工具。

  1. 點選 Google Cloud 控制台頂端的「啟用 Cloud Shell」。
  2. 連至 Cloud Shell 後,請驗證您的驗證狀態:
    gcloud auth list
    
  3. 確認專案已設定:
    gcloud config get project
    
  4. 如果專案未如預期設定,請執行下列指令:
    export PROJECT_ID=<YOUR_PROJECT_ID>
    gcloud config set project $PROJECT_ID
    

環境設定

  1. 開啟 Cloud Shell:按一下 Google Cloud 控制台右上方的「啟用 Cloud Shell」圖示。

取得範例程式碼

  1. 將範例存放區複製到主目錄:
      cd ~
    
    從 Google Cloud DevRel Demos 資料夾複製本程式碼實驗室所需的程式碼。
    git clone --depth 1 --filter=blob:none --sparse https://github.com/GoogleCloudPlatform/devrel-demos.git temp-repo && cd temp-repo && git sparse-checkout set agents/multi-agent-system && cd .. && mv temp-repo/agents/multi-agent-system . && rm -rf temp-repo
    
    移至含有本程式碼實驗室程式碼的資料夾
    cd multi-agent-system
    
  2. 啟用 API:執行下列指令,啟用必要的 Google Cloud 服務:
    gcloud services enable \
        run.googleapis.com \
        artifactregistry.googleapis.com \
        cloudbuild.googleapis.com \
        aiplatform.googleapis.com \
        compute.googleapis.com
    
  3. 在編輯器中開啟這個資料夾。
    cloudshell edit .
    

設定環境

  1. 設定環境變數。我們會建立 .env 檔案來儲存這些變數,這樣一來,即使工作階段中斷連線,您也能輕鬆重新載入變數。
    cat <<EOF > .env
    export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
    export GOOGLE_CLOUD_LOCATION=europe-west4
    export GOOGLE_GENAI_USE_VERTEXAI=true
    EOF
    
  2. 提供環境變數來源:
    source .env
    

4. 🕵️ 研究員代理

研究員代理

Researcher 是專家,它的唯一工作是尋找資訊。為此,模型需要存取 Google 搜尋工具。

為什麼要區分研究員?

深度對談:為什麼不讓一個代理處理所有工作?

小型、專注的代理較容易評估和偵錯。如果研究結果不佳,請調整 Researcher 的提示。如果課程格式不佳,請反覆調整 Content Builder。在單一「全能型」提示中,修正某個問題往往會導致另一個問題。

  1. 如果您是在 Cloud Shell 中操作,請執行下列指令,開啟 Cloud Shell 編輯器:
    cloudshell workspace .
    
  2. 開啟 agents/researcher/agent.py。
  3. 查看下列定義 researcher 代理的程式碼:
    # ... existing imports ...
    
    # Define the Researcher Agent
    researcher = Agent(
        name="researcher",
        model=MODEL,
        description="Gathers information on a topic using Google Search.",
        instruction="""
        You are an expert researcher. Your goal is to find comprehensive and accurate information on the user's topic.
        Use the `google_search` tool to find relevant information.
        Summarize your findings clearly.
        If you receive feedback that your research is insufficient, use the feedback to refine your next search.
        """,
        tools=[google_search],
    )
    
    root_agent = researcher
    

重要概念:工具使用

請注意,我們傳遞了 tools=[google_search]。ADK 會處理向 LLM 描述這項工具的複雜作業。當模型判斷需要資訊時,會產生結構化工具呼叫,ADK 則會執行 Python 函式 google_search,並將結果回傳給模型。

5. ⚖️ 評審代理

Judge Agent

研究員會努力工作,但 LLM 可能會偷懶。我們需要評審來審查作品。審查代理接受研究資料,並傳回結構化的通過/未通過評估結果。

結構化輸出

深度對談:如要自動執行工作流程,我們需要可預測的輸出內容。冗長的文字評論難以透過程式剖析。透過強制執行 JSON 結構定義 (使用 Pydantic),我們可確保 Judge 傳回布林值 pass 或 fail,讓程式碼能可靠地執行。

  1. 開啟 agents/judge/agent.py。
  2. 請查看下列程式碼,瞭解如何定義 JudgeFeedback 結構定義和 judge 代理。
    # 1. Define the Schema
    class JudgeFeedback(BaseModel):
        """Structured feedback from the Judge agent."""
        status: Literal["pass", "fail"] = Field(
            description="Whether the research is sufficient ('pass') or needs more work ('fail')."
        )
        feedback: str = Field(
            description="Detailed feedback on what is missing. If 'pass', a brief confirmation."
        )
    
    # 2. Define the Agent
    judge = Agent(
        name="judge",
        model=MODEL,
        description="Evaluates research findings for completeness and accuracy.",
        instruction="""
        You are a strict editor.
        Evaluate the 'research_findings' against the user's original request.
        If the findings are missing key info, return status='fail'.
        If they are comprehensive, return status='pass'.
        """,
        output_schema=JudgeFeedback,
        # Disallow delegation because it should only output the schema
        disallow_transfer_to_parent=True,
        disallow_transfer_to_peers=True,
    )
    
    root_agent = judge
    

重要概念:限制代理行為

我們設定了 disallow_transfer_to_parent=True 和 disallow_transfer_to_peers=True。這會強制 Judge 僅傳回結構化 JudgeFeedback。無法決定要與使用者「對話」或委派給其他代理。因此在邏輯流程中,這屬於確定性元件。

6. ✍️ 內容建構代理

內容建立工具

內容建構工具是創意文案撰寫工具。負責將核准的研究內容轉為課程。這個應用程式使用 Cloud Run 提供的 Gemma 模型。

首先,來看看託管模型的 Cloud Run 服務

  1. 開啟「ollama_backend/Dockerfile」
  2. 您可以在這裡看到 Dockerfile 如何使用 Ollama 映像檔、監聽通訊埠 8080 的要求,並將要求的模型儲存在 /model 資料夾中。
FROM ollama/ollama:latest

# Listen on all interfaces, port 8080 (Cloud Run default)
ENV OLLAMA_HOST 0.0.0.0:8080

# Store model weight files in /models
ENV OLLAMA_MODELS /models

⚙️ 部署時,您將設定下列項目:

  • GPU:選擇 NVIDIA L4,因為這款 GPU 執行推論工作負載的性價比極高。L4 提供 24 GB GPU 記憶體和最佳化張量運算,非常適合 Gemma 等 2.7 億參數模型
  • 記憶體:16 GB 系統記憶體,用於處理模型載入、CUDA 作業和 Ollama 的記憶體管理
  • CPU:8 核心,可提供最佳 I/O 處理和預先處理工作
  • 並行:每個執行個體 4 個要求,可平衡處理量和 GPU 記憶體用量
  • 逾時:600 秒,可容納初始模型載入和容器啟動

現在來看看使用 Gemma 模型的 Content Builder 建構代理。

  1. 開啟 agents/content_builder/agent.py。
  2. 查看下列定義 content_builder 代理程式的程式碼。
# the `ollama-gemma-gpu` Cloud Run service URL which hosts the Gemma model
target_url = os.environ.get("OLLAMA_API_BASE")

# ... existing code ...

# (Note: We use 'ollama/gemma3:270m' to align with ADK's expected prefix)
gemma_model_name = os.environ.get("GEMMA_MODEL_NAME", "gemma3:270m")
model = LiteLlm(
    model=f"ollama_chat/{gemma_model_name}",
    api_base=target_url
)

# 5. Define the Agent
content_builder = Agent(
    name="content_builder",
    model=model,
    description="Transforms research findings into a structured course.",
    instruction="""
    You are an expert course creator.
    Take the approved 'research_findings' and transform them into a well-structured, engaging course module.

    **Formatting Rules:**
    1. Start with a main title using a single `#` (H1).
    2. Use `##` (H2) for main section headings. These will be used for the Table of Contents.
    3. Use `###` (H3) for sub-sections within main sections.
    4. Use bullet points and clear paragraphs.
    5. Maintain a professional but engaging tone.

    **Structure Requirements:**
    - Begin with a brief Introduction section explaining what the learner will gain.
    - Organize content into 3-5 main sections with clear headings.
    - Include Key Takeaways at the end as a bulleted summary.
    - Keep each section focused and concise.

    Ensure the content directly addresses the user's original request.
    Do not include any preamble or explanation outside the course content itself.
    """,
)

root_agent = content_builder

重要概念:Context 傳播

您可能會想:「內容建構工具怎麼知道研究員找到什麼?」在 ADK 中,管道中的代理會共用 session.state。稍後,我們會在 Orchestrator 中設定 Researcher 和 Judge,將輸出內容儲存至這個共用狀態。Content Builder 的提示可有效存取這項記錄。

7. 🎻 協調代理

調度管理代理

Orchestrator 是多代理團隊的管理員,與執行特定任務的專員代理 (研究員、評審、內容建構工具) 不同,自動調度管理工具的工作是協調工作流程,並確保資訊在代理之間正確流動。

🌐 架構:Agent2Agent (A2A)

A2A 架構

在本實驗室中,我們要建構分散式系統。我們不會在單一 Python 程序中執行所有代理,而是將其部署為獨立的微服務。這樣一來,每個代理都能獨立擴充,即使發生故障,也不會導致整個系統當機。

為此,我們會使用 Agent-to-Agent (A2A) 通訊協定。

A2A 通訊協定

深度對談:在正式環境系統中,代理程式會在不同的伺服器 (甚至是不同的雲端) 上執行。A2A 通訊協定提供標準方法,讓代理透過 HTTP 互相探索及通訊。RemoteA2aAgent 是這個通訊協定的 ADK 用戶端。

  1. 開啟 agents/orchestrator/agent.py。
  2. 查看下列定義連線的程式碼。
    # ... existing code ...
    
    # Connect to the Researcher (Localhost port 8001)
    researcher_url = os.environ.get("RESEARCHER_AGENT_CARD_URL", "http://localhost:8001/a2a/agent/.well-known/agent-card.json")
    researcher = RemoteA2aAgent(
        name="researcher",
        agent_card=researcher_url,
        description="Gathers information using Google Search.",
        # IMPORTANT: Save the output to state for the Judge to see
        after_agent_callback=create_save_output_callback("research_findings"),
        # IMPORTANT: Use authenticated client for communication
        httpx_client=create_authenticated_client(researcher_url)
    )
    
    # Connect to the Judge (Localhost port 8002)
    judge_url = os.environ.get("JUDGE_AGENT_CARD_URL", "http://localhost:8002/a2a/agent/.well-known/agent-card.json")
    judge = RemoteA2aAgent(
        name="judge",
        agent_card=judge_url,
        description="Evaluates research.",
        after_agent_callback=create_save_output_callback("judge_feedback"),
        httpx_client=create_authenticated_client(judge_url)
    )
    
    # Content Builder (Localhost port 8003)
    content_builder_url = os.environ.get("CONTENT_BUILDER_AGENT_CARD_URL", "http://localhost:8003/a2a/agent/.well-known/agent-card.json")
    content_builder = RemoteA2aAgent(
        name="content_builder",
        agent_card=content_builder_url,
        description="Builds the course.",
        httpx_client=create_authenticated_client(content_builder_url)
    )
    

8. 🛑 提報檢查工具

迴圈需要停止的方法。如果 Judge 說「Pass」,我們希望立即退出迴圈,並移至 Content Builder。

使用 BaseAgent 自訂邏輯

深度對談:並非所有代理都使用 LLM。有時您需要簡單的 Python 邏輯。BaseAgent 可讓您定義只執行程式碼的代理。在本例中,我們會檢查工作階段狀態,並使用 EventActions(escalate=True) 向 LoopAgent 發出停止信號。

  1. 仍在 agents/orchestrator/agent.py 中。
  2. 檢閱下列程式碼審查、評審的意見回饋,準備好後再繼續下一個步驟
    class EscalationChecker(BaseAgent):
        """Checks the judge's feedback and escalates (breaks the loop) if it passed."""
    
        async def _run_async_impl(
            self, ctx: InvocationContext
        ) -> AsyncGenerator[Event, None]:
            # Retrieve the feedback saved by the Judge
            feedback = ctx.session.state.get("judge_feedback")
            print(f"[EscalationChecker] Feedback: {feedback}")
    
            # Check for 'pass' status
            is_pass = False
            if isinstance(feedback, dict) and feedback.get("status") == "pass":
                is_pass = True
            # Handle string fallback if JSON parsing failed
            elif isinstance(feedback, str) and '"status": "pass"' in feedback:
                is_pass = True
    
            if is_pass:
                # 'escalate=True' tells the parent LoopAgent to stop looping
                yield Event(author=self.name, actions=EventActions(escalate=True))
            else:
                # Continue the loop
                yield Event(author=self.name)
    
    escalation_checker = EscalationChecker(name="escalation_checker")
    

重要概念:透過事件控制流程

代理不只會透過文字通訊,還會使用事件。這個代理會透過 escalate=True 產生事件,向上層 (LoopAgent) 傳送信號。LoopAgent 則會擷取這個信號並終止迴圈。

9. 🔁 研究循環

研究迴圈

我們需要意見回饋循環:研究 -> 判斷 -> (失敗) -> 研究 -> ...

  1. agents/orchestrator/agent.py。
  2. 請查看下列程式碼如何定義 research_loop。
    research_loop = LoopAgent(
        name="research_loop",
        description="Iteratively researches and judges until quality standards are met.",
        sub_agents=[researcher, judge, escalation_checker],
        max_iterations=3,
    )
    

重要概念:LoopAgent

LoopAgent 會依序循環播放 sub_agents。

  1. researcher:尋找資料。
  2. judge:評估資料。
  3. escalation_checker:決定是否要yield Event(escalate=True)。如果發生 escalate=True,迴圈會提早中斷。否則,系統會從研究員開始重新計算 (最多 max_iterations)。

10. 🔗 最終管道

最終管道

整合所有資訊

  1. agents/orchestrator/agent.py。
  2. 查看檔案底部如何定義 root_agent。
    root_agent = SequentialAgent(
        name="course_creation_pipeline",
        description="A pipeline that researches a topic and then builds a course from it.",
        sub_agents=[research_loop, content_builder],
    )
    

重要概念:階層式組合

請注意,research_loop 本身是代理 (LoopAgent),我們將其視為 SequentialAgent 中的其他子代理。這種可組合性可讓您透過巢狀結構簡單模式 (序列中的迴圈、路由器中的序列等),建構複雜的邏輯。

11. 🚀 部署至 Cloud Run

我們會將每個代理部署為 Cloud Run 上的獨立服務,包括用於課程建立工具 UI 的 Cloud Run 服務,以及使用 GPU 執行 Gemma 模型的 Cloud Run 服務。

瞭解部署設定

將代理部署至 Cloud Run 時,我們會傳遞多個環境變數,設定代理的行為和連線能力:

  • GOOGLE_CLOUD_PROJECT:確保代理使用正確的 Google Cloud 雲端專案,進行記錄和 Vertex AI 呼叫。
  • GOOGLE_GENAI_USE_VERTEXAI:指示代理架構 (ADK) 使用 Vertex AI 進行模型推論,而非直接呼叫 Gemini API。
  • [AGENT]_AGENT_CARD_URL:這對 Orchestrator 來說至關重要。這會指示 Orchestrator 在何處尋找遠端代理。將這個變數設為已部署的 Cloud Run 網址 (特別是代理卡片路徑),Orchestrator 就能透過網際網路探索研究、審查和內容建構代理,並與其通訊。

如要將所有代理部署至 Cloud Run 服務,請執行下列指令碼。

首先,請確認指令碼可執行。

chmod u+x ~/multi-agent-system/deploy.sh

注意:系統會依序部署各項服務,因此需要幾分鐘才能完成。

~/multi-agent-system/deploy.sh

12. 建立課程!

開啟 Course Creator 網站。Course Creator Cloud Run 服務是指令碼部署的最後一項服務。課程建立工具的網址為 https://course-creator-..run.app,這應該是部署指令碼的最後一行輸出內容。

然後輸入課程構想,例如「線性代數」。

代理會開始製作課程。

最終管道

13. 清除所用資源

為避免系統向您的 Google Cloud 帳戶收取本程式碼實驗室所用資源的費用,請按照下列步驟刪除服務和容器映像檔。

1. 刪除 Cloud Run 服務

最有效率的清理方式,是刪除部署至 Cloud Run 的服務。

# Delete the main agent and app services
gcloud run services delete researcher content-builder judge orchestrator course-creator \
    --region $REGION --quiet

# Delete the GPU backend (Ollama)
gcloud run services delete ollama-gemma-gpu \
    --region $OLLAMA_REGION --quiet

2. 刪除 Artifact Registry 映像檔

使用 --source 旗標部署時,Google Cloud 會在 Artifact Registry 建立存放區,用於儲存容器映像檔。如要移除這些項目並節省儲存空間費用,請刪除存放區:

gcloud artifacts repositories delete cloud-run-source-deploy --location us-east4 --quiet

3. 移除本機檔案和環境

為保持 Cloud Shell 殼層環境整潔,請移除專案資料夾和所有本機設定:

cd ~
rm -rf multi-agent-system

4. (選用) 刪除專案

如果您是為了這個程式碼實驗室建立專案,可以透過「管理資源」頁面關閉專案,確保不會產生其他費用。

14. 恭喜!

您已成功建構及部署可用於正式環境的分散式多代理系統。

學習成果

  • 拆解複雜工作:我們不使用單一大型提示,而是將工作拆分為專門角色 (研究員、評審、內容建構者)。
  • 實作品質驗證:我們使用 LoopAgent 和結構化 Judge,確保只有高品質的資訊能進入最後步驟。
  • 專為正式環境打造:我們使用 Agent-to-Agent (A2A) 通訊協定和 Cloud Run 建立系統,讓每個代理都成為獨立且可擴充的微服務。這比在單一 Python 指令碼中執行所有作業更為穩健。
  • 自動化調度管理:我們使用 SequentialAgent 和 LoopAgent 定義明確的控制流程模式。* Cloud Run GPU:將 Gemma 模型部署至 Cloud Run GPU