# 策展 · X (Twitter) 🔥🔥🔥

> 作者：Google Cloud Tech (@GoogleCloudTech) · 平台：X (Twitter) · 日期：2026-04-24

> 原始來源：https://x.com/GoogleCloudTech/status/2047367046070161674

## 中文摘要

# 從技能到系統：ADK 2.0 中的 5 種 Multi-Agent 編排模式

幾週前，我們關於 5 種 Agent 技能設計模式的文章在網路上爆紅。這些模式（Tool Wrapper、Generator、Reviewer、Inversion、Pipeline）為開發者設計 Agent 技能提供了一套結構化的詞彙。但無論單一技能設計得多好，它也只能解決問題的一部分。

更困難的問題是：如何在生產系統中編排跨越多個 Agent 的多項技能？你該如何確保 Agent A 的輸出格式正確，能作為 Agent B 的輸入？如何在允許 AI 在每個步驟中保持靈活性的同時，強制執行某些步驟必須按特定順序進行？又該如何協調由不同團隊使用不同語言編寫的 Agent？

在 Google Cloud Next 26 大會上，我們推出了 Agent Development Kit (ADK) 2.0，透過三個核心新增功能來回答這些問題：基於圖的工作流 (graph-based workflows)、協作式 Agent (collaborative agents) 以及標準化的技能框架。以下是 5 種能將你的 Agent 架構提升到新層次的編排模式。

作者：@addyosmani 與 @Saboo_Shubham_

## 模式 1：混合圖 (The Hybrid Graph)

Agent 系統中最常見的生產環境故障就是編排失敗。Agent 對每個單獨步驟的推理正確，但執行順序錯誤、跳過了強制性步驟，或是走了一條沒有人類審核員預期到的路徑。

這之所以發生，是因為大多數 Agent 架構將工作流邏輯編碼在系統 Prompt 中。LLM 在前幾輪對話中會忠實地遵循指令，但到了第七輪，它開始走捷徑；到了第十二輪，它甚至完全跳過步驟。這是使用自然語言指令來定義程序化工作流的根本限制。LLM 是優化器，它們受過訓練，旨在高效地產生有幫助的輸出。當模型看到一個五步驟的工作流時，它通常會認為透過合併步驟或重新排序，可以產生更有幫助的回應。

ADK 2.0 的基於圖的工作流從結構上解決了這個問題。你將 Agent 邏輯定義為一個有向圖，其中節點是動作，邊是帶有條件邏輯的轉換。關鍵創新在於，你可以在同一個圖中混合確定性節點（硬編碼的業務規則）與 AI 驅動節點（LLM 推理）。

![](https://pub-75d4fe1e4e80421b9ecb1245a7ae0d1a.r2.dev/curated/1776994555342-iaHGmzYl8aIAAuOkAjpg.jpg)

這是一個具體的例子：貸款申請處理 Agent。有些步驟必須是確定性的（法規遵循檢查、信用評分門檻、文件要求），而其他步驟則受益於 AI 的靈活性（評估文件品質、總結財務狀況、產生建議）。

```python
from google.adk import Agent, Graph, Node, Edge

loan_processor = Graph(name="loan-processor")

# 確定性節點：驗證所需文件
@loan_processor.node("validate_docs")
def validate_documents(application):
    required = ["id_proof", "income_proof", "address_proof", "bank_statements"]
    missing = [doc for doc in required if doc not in application.documents]
    if missing:
        return {"status": "incomplete", "missing": missing}
    return {"status": "complete"}

# AI 驅動節點：評估文件品質
@loan_processor.node("assess_quality")
async def assess_document_quality(application, llm):
    return await llm.analyze(
        prompt="Evaluate the quality and authenticity of these documents. "
               "Flag any concerns about readability, completeness, or "
               "potential inconsistencies.",
        documents=application.documents
    )

# 確定性節點：信用評分檢查
@loan_processor.node("credit_check")
def check_credit_score(application):
    score = application.credit_score
    if score >= 750:
        return {"tier": "prime", "auto_approve": True}
    elif score >= 650:
        return {"tier": "standard", "auto_approve": False}
    else:
        return {"tier": "subprime", "auto_approve": False, "flag": True}

# AI 驅動節點：產生建議
@loan_processor.node("recommendation")
async def generate_recommendation(application, assessment, credit, llm):
    return await llm.analyze(
        prompt="Based on the document assessment and credit check, "
               "generate a loan recommendation with risk factors "
               "and suggested terms.",
        context={"assessment": assessment, "credit": credit}
    )

# 確定性節點：合規檢查
@loan_processor.node("compliance")
def compliance_check(recommendation):
    # 硬編碼的監管規則，不能由 AI 驅動
    violations = []
    if recommendation.apr > MAX_LEGAL_APR:
        violations.append("APR exceeds regulatory maximum")
    if recommendation.term_months > MAX_TERM:
        violations.append("Term exceeds maximum allowed")
    return {"compliant": len(violations) == 0, "violations": violations}

# 定義帶有條件的圖邊
loan_processor.add_edge("validate_docs", "assess_quality",
                        condition=lambda r: r["status"] == "complete")
loan_processor.add_edge("validate_docs", "request_missing_docs",
                        condition=lambda r: r["status"] == "incomplete")
loan_processor.add_edge("assess_quality", "credit_check")
loan_processor.add_edge("credit_check", "recommendation")
loan_processor.add_edge("recommendation", "compliance")
loan_processor.add_edge("compliance", "human_review",
                        condition=lambda r: not r["compliant"])
loan_processor.add_edge("compliance", "auto_approve",
                        condition=lambda r: r["compliant"])
```

與基於 Prompt 的編排相比，關鍵差異在於強制性的結構是由框架執行的。LLM 在每個節點內擁有靈活性，但不能跳過節點或重新排序圖。確定性節點可以使用標準測試框架進行單元測試；AI 驅動節點可以使用 Agent Simulation 分別進行評估；而圖結構本身是可檢查的，因此合規官員可以審查工作流，並驗證每個必要步驟都已包含且順序正確，而無需閱讀任何 LLM Prompt。

## 模式 2：協調者-專家 (The Coordinator-Specialist)

「上帝 Agent (God agent)」是生產 Agent 系統中最常見的反模式。一個 Agent 試圖做所有事情：客戶支援、資料分析、文件產生、API 整合。它的系統 Prompt 有數千個 token 長，工具集龐大，且行為不可預測，因為 LLM 不斷在數十種可能的動作之間進行決策。

隨著你增加功能，問題會變得更嚴重。大約在增加第五個主要功能時，系統就會變得不可靠。Agent 會對任務使用錯誤的工具，在進行資料分析時套用客戶支援的語氣，或者在回答關於專案時間表的簡單問題時遵循財務合規規則。指令會爭奪模型的注意力，模型開始做出你未預料到的權衡。

ADK 2.0 的協作式 Agent 為「協調者-專家」模式提供了原生支援。協調者 Agent 負責任務路由和工作流管理，而專家 Agent 則透過專注的上下文和工具處理特定領域的工作。

```python
from google.adk import Agent, CoordinatorAgent, TransferProtocol

# 具有專注職責的專家 Agent
data_analyst = Agent(
    name="data-analyst",
    instructions="""You are a data analysis specialist. You have access
    to BigQuery and can run SQL queries, generate visualizations, and
    produce statistical summaries. Focus exclusively on data tasks.
    If asked about anything outside data analysis, transfer back
    to the coordinator.""",
    tools=[bigquery_tool, visualization_tool, statistics_tool]
)

document_writer = Agent(
    name="document-writer",
    instructions="""You are a technical document specialist. You produce
    reports, summaries, and documentation in structured formats.
    You do not access databases or run queries. If the user needs
    data analysis, transfer to the coordinator for routing.""",
    tools=[markdown_tool, template_tool, format_tool],
    skills=["report-generator", "executive-summary"]  # ADK 技能
)

customer_expert = Agent(
    name="customer-expert",
    instructions="""You are a customer context specialist. You have
    access to CRM data, support ticket history, and customer
    communication logs. Provide customer insights but do not
    generate reports - transfer to the coordinator for that.""",
    tools=[salesforce_tool, zendesk_tool, email_search_tool]
)

# 負責路由任務的協調者 Agent
coordinator = CoordinatorAgent(
    name="project-coordinator",
    specialists=[data_analyst, document_writer, customer_expert],
    transfer_protocol=TransferProtocol.CONTEXTUAL,
    instructions="""You are a project coordinator. When a user makes
    a request, determine which specialist(s) need to be involved.
    For complex requests that span multiple domains, orchestrate
    the specialists in sequence: gather data first, then generate
    the report.

    Example routing:
    - "Analyze Q3 sales data" → data-analyst
    - "Write the quarterly report" → document-writer
    - "What's the history with Acme Corp?" → customer-expert
    - "Create a report on Acme Corp's Q3 performance" →
      customer-expert (context) → data-analyst (numbers) →
      document-writer (final report)"""
)
```

傳輸協議定義了 Agent 在交接過程中上下文如何流動。`TransferProtocol.CONTEXTUAL` 意味著協調者在轉移到下一個專家時，會包含來自前一個專家輸出的相關上下文。文件撰寫者不需要重新查詢資料庫，它會直接接收資料分析師的輸出作為上下文。

每個專家都有自己的身份（透過 Agent Identity）、自己的工具權限（由 Agent Gateway 管理）以及自己的記憶。資料分析師無法存取 CRM 資料，客戶專家無法執行 SQL 查詢。任何單一 Agent 故障的影響範圍都被限制在其領域內。

這種模式也簡化了測試和迭代。當資料分析師的輸出品質下降時，你只需評估並修復該專家，而無需重新訓練或重新 Prompt 一個龐大的單體 Agent。當你增加新功能（例如競爭情報專家）時，只需將其註冊到協調者，它就能立即使用。

## 模式 3：技能組合 (Skill Composition)

在我們之前的文章中，我們介紹了五種技能設計模式：Tool Wrapper、Generator、Reviewer、Inversion 和 Pipeline。ADK 2.0 透過宣告式的技能框架將這些模式標準化，使技能成為多 Agent 工作流中的一等公民。

關鍵的新增功能是 `SkillToolset`，它讓 Agent 可以將技能作為工具來載入和使用。Agent 不需要知道技能的內部實作，它只需要知道技能的名稱、描述及其介面。這實現了組合——以原始技能作者未預料到的方式，跨 Agent 串聯技能。

![](https://pub-75d4fe1e4e80421b9ecb1245a7ae0d1a.r2.dev/curated/1776994554891-iaHGmziATaQAAjWHRjpg.jpg)

以下是其實際運作方式。想像你有三個由不同團隊構建的現有技能：

```
skills/
├── data-extractor/
│   └── SKILL.md          # 模式：Tool Wrapper (從 API 提取資料)
├── trend-analyzer/
│   └── SKILL.md          # 模式：Pipeline (多步驟趨勢分析)
└── executive-summary/
    └── SKILL.md          # 模式：Generator (產生格式化摘要)
```

協調者 Agent 可以將這些技能組合成一個工作流，而這些技能最初並非為此而設計：

```python
from google.adk import Agent, SkillToolset

market_intelligence = Agent(
    name="market-intelligence",
    skills=SkillToolset([
        "data-extractor",       # 從市場 API 拉取資料
        "trend-analyzer",       # 執行統計趨勢分析
        "executive-summary"     # 產生格式化報告
    ]),
    instructions="""You are a market intelligence agent. When asked
    for a market analysis:
    1. Use data-extractor to pull relevant market data
    2. Pass the data to trend-analyzer for pattern identification
    3. Use executive-summary to format findings for leadership

    Each skill handles its own domain. Your job is orchestration
    - ensuring the output of each skill is properly formatted
    as input for the next skill in the chain."""
)
```

得益於漸進式揭露 (progressive disclosure)，Agent 只有在實際呼叫該技能時才會載入其完整上下文。如果使用者詢問一個不需要趨勢分析的簡單問題，trend-analyzer 技能的指令、參考資料和 asset 永遠不會被載入到 context window 中。即使 Agent 可以存取數十種技能，這也能保持 context token 使用的高效性。

這與 npm、pip 和 Maven 成功的洞見相同：小型、專注、可組合的套件，且具有清晰的介面，比大型的單體函式庫更有價值。各個團隊為其領域構建技能（資料工程團隊構建提取技能，分析團隊構建分析技能，通訊團隊構建格式化技能）。由平台團隊組裝的協調者 Agent 可以將這些技能組合成跨越組織邊界的工作流，而無需這些團隊直接進行協調。

## 模式 4：跨語言管道 (The Cross-Language Pipeline)

ADK 現在支援四種語言：Python、TypeScript、Go 和 Java。每個 SDK 都原生支援 A2A (Agent-to-Agent) 協議。這意味著用 Python 編寫的 Agent 可以無縫委託給用 Go 編寫的 Agent，後者又可以委託給用 Java 編寫的 Agent。

這對於不同團隊使用不同語言的組織來說非常重要。ML 團隊使用 Python，平台團隊使用 Go，企業整合團隊使用 Java，前端團隊使用 TypeScript。過去，跨這些團隊構建多 Agent 工作流需要自定義 API 整合、協議協商和資料格式轉換。A2A 將這一切標準化了。

以下是跨語言管道在實踐中的樣子：

![](https://pub-75d4fe1e4e80421b9ecb1245a7ae0d1a.r2.dev/curated/1776994554912-diaHGmzsnPbQAAY6Tjpg.jpg)

每個 Agent 都會透過 `/.well-known/agent-card.json` 發布其能力。其他 Agent 會自動發現這些能力。A2A 協議處理任務管理、狀態更新和結果串流。從每個 Agent 的角度來看，委託給不同語言的遠端 Agent 就像呼叫本地函式一樣。

每個 SDK 也為管道帶來了特定語言的優勢。ADK Go 1.0 增加了用於多 Agent 管道分散式追蹤的 OpenTelemetry 整合、透過 plugin 實現的自我修復邏輯，以及基於 YAML 的 Agent 定義，讓你能夠以宣告式方式管理 Agent（就像你管理 Kubernetes 清單或 Terraform 資源一樣）。Java SDK 增加了用於管理長對話歷史的事件壓縮 (event compaction)，以及對於企業治理至關重要的人類審核工作流 ToolConfirmation。

## 模式 5：沙盒執行器 (The Sandboxed Executor)

最後一種模式解決了一個常見需求：Agent 需要在工作流中執行程式碼。資料分析 Agent 需要執行 pandas 操作，程式碼審核 Agent 需要執行測試，文件處理 Agent 需要執行轉換腳本。

如果執行環境未經隔離，在 Agent 內部執行任意程式碼會帶來安全風險。ADK 2.0 提供了安全 workspace：強化的沙盒環境，Agent 可以在其中執行 bash 指令、管理檔案並執行程式碼，所有這些都與你的核心系統隔離。

![](https://pub-75d4fe1e4e80421b9ecb1245a7ae0d1a.r2.dev/curated/1776994554898-iaHGmzyN3aAAALVj7jpg.jpg)

以下是 Python 中的程式碼實作：

```python
from google.adk import Agent, SecureWorkspace

code_analyst = Agent(
    name="code-analyst",
    workspace=SecureWorkspace(
        allowed_commands=["python", "pip", "pytest", "git"],
        filesystem_access="read-write",  # 僅限沙盒內
        network_access="restricted",      # 僅限允許列表中的網域
        max_execution_time=300,           # 每個指令 5 分鐘超時
        resource_limits={"memory": "2G", "cpu": "2"}
    ),
    instructions="""You are a code analysis specialist. When reviewing
    code, you can:
    1. Clone the repository into your workspace
    2. Install dependencies
    3. Run the test suite
    4. Execute static analysis tools
    5. Report findings with evidence from actual test results

    Your workspace is sandboxed. You cannot access systems outside
    your allowed network domains. All file operations are confined
    to your workspace directory."""
)
```

沙盒邊界是關鍵的安全屬性。Agent 可以在其 workspace 內執行任意 Python 程式碼，但該程式碼無法存取主機檔案系統、無法與未經批准的網域建立網路連線，也無法提升權限。如果 Agent 的程式碼執行出現異常——例如無限迴圈、過度記憶體分配、嘗試存取受限資源——沙盒會強制執行嚴格限制。

這種模式與我們上一篇文章中的 Pipeline 技能模式結合使用時特別強大。一個需要解析原始碼、產生 docstrings 並組裝最終文件的文件管道技能，可以在沙盒中執行每個步驟，使用實際的程式碼執行而不是 LLM 推理來進行解析步驟。結果更可靠——使用實際的 Python 解析 Python AST 比要求 LLM 推理程式碼結構更準確。

## 選擇正確的編排模式

這些模式可以像我們上一篇文章中的技能模式一樣進行組合：

- 混合圖可以在單個節點使用「協調者-專家」模式——圖定義整體工作流，而專家 Agent 處理特定領域的節點。

- 「協調者-專家」設定可以在每個專家內部使用「技能組合」——每個專家只載入與其領域相關的技能。

- 跨語言管道可以在任何階段使用「沙盒執行器」——Python Agent 在沙盒中執行 ML 模型，Go Agent 使用沙盒測試資料執行合規檢查。

- 任何模式都可以在單個技能層級整合我們上一篇文章中的五種技能模式（Tool Wrapper、Generator、Reviewer、Inversion、Pipeline）。

![](https://pub-75d4fe1e4e80421b9ecb1245a7ae0d1a.r2.dev/curated/1776994555350-diaHGmz6BaMAA7t60jpg.jpg)

## 開始使用

ADK 2.0 現已推出。請使用 `pip install google-adk --pre` (Python 3.11+) 進行安裝。你現有的 ADK 1.x Agent 是向後相容的，儘管進階實作可能需要進行遷移測試。

ADK 範例儲存庫 (github.com/google/adk-samples) 包含了超過 30 個跨 Python、TypeScript、Go 和 Java 的範例 Agent，涵蓋了從簡單的 Tool Wrapper 到複雜的多 Agent 工作流等各種模式。

文件：adk.dev
GitHub 儲存庫：ADK Python | ADK Java | ADK Go | ADK TypeScript

## 🚢 從 Agent 技能到系統：Google for Startups AI Agents 挑戰賽

加入我們為期 6 週的全球挑戰賽，超越演示階段，讓新創公司在 Gemini Enterprise Agent Platform 上構建、優化或重構自主 Agent。

你將獲得 500 美元的雲端額度、完整的平台存取權，並有機會贏取 90,000 美元的獎金池。將這些 ADK 2.0 編排模式付諸實踐，構建生產就緒的 Agent 系統。

立即報名，開始構建！

## 標籤

Skills, Agent, 教學資源, ADK
