跳至主要內容
精選 Architecture Performance Agents Task Tool

Multi-Agent 架構:平行執行模式

如何運用專門化 agents 同時工作,達成 5-10 倍的效率提升。學習官方 Task tool 語法、agent 類型,以及讓平行執行真正發揮效果的模式。

2026年1月10日 14 分鐘閱讀 作者:ClaudeWorld

Claude Code 最強大的功能之一是 multi-agent 執行——能夠產生專門化的 agents 平行工作。正確使用時,可以在複雜任務上達成 5-10 倍的效率提升。

本指南涵蓋官方 Task tool 語法、內建 agent 類型,以及平行執行的實際模式。

理解 Task Tool

Task tool 是 Claude Code 產生 subagents 的機制。根據官方文件

官方語法

Task({
  subagent_type: "Explore",     // Required: "Explore" or "general-purpose"
  model: "haiku",               // Optional: "haiku", "sonnet", or "opus"
  prompt: `                     // Required: Task description
    Explore authentication module (thoroughness: medium).
    Find all JWT-related functions and their usage.
  `,
  run_in_background: false      // Optional: Run asynchronously
})

可用的 subagent_type 值

來自 Claude Code GitHub

subagent_type用途最佳使用場景
Explore由 Haiku 4.5 驅動的快速程式碼庫導覽檔案搜尋、模式匹配、結構分析
general-purpose複雜的多步驟推理實作、重構、程式碼審查

模型選擇

// Haiku 4.5 - Fast & cheap (default for Explore)
Task({ subagent_type: "Explore", model: "haiku", ... })

// Sonnet 4.5 - Balanced (default for general-purpose)
Task({ subagent_type: "general-purpose", model: "sonnet", ... })

// Opus 4.5 - Most capable (critical tasks)
Task({ subagent_type: "general-purpose", model: "opus", ... })

成本/速度權衡:

  • Haiku 4.5:比 Sonnet 快 2 倍,成本僅 1/3
  • Sonnet 4.5:最佳程式碼撰寫效能,支援 Extended Thinking
  • Opus 4.5:最高智力,預設啟用 Thinking Mode(v2.0.67+)

Explore Agent 深入解析

Explore agent(v2.1.0 引入)專為快速程式碼庫探索設計。

徹底程度等級

// Quick - 10-30 seconds
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Explore auth module (thoroughness: quick). Find login handler."
})

// Medium - 30-60 seconds (recommended)
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Explore auth module (thoroughness: medium). Map JWT flow and middleware."
})

// Very Thorough - 60-120 seconds
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Explore auth module (thoroughness: very thorough). Complete security analysis."
})

為什麼 Explore 更有效率

舊方法(5 個依序步驟):

1. Glob: find *auth*.ts         → 15 seconds
2. Grep: search "JWT"           → 15 seconds
3. Read: auth/index.ts          → 10 seconds
4. Grep: find authenticate()    → 15 seconds
5. Read: test files             → 10 seconds
Total: 65 seconds

新方法(1 個 Explore agent):

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Explore authentication (thoroughness: medium). Focus on JWT, middleware, tests."
})
// Total: 30-45 seconds, same or better results

內建專門化 Agents

Claude Code 提供這些專門化的 agent 類型:

Agent角色使用時機建議模型
code-reviewer程式碼品質分析實作完成後Sonnet
security-auditor漏洞偵測認證/支付變更時Sonnet/Opus
test-runner測試執行與分析程式碼變更後Haiku
debugger根本原因分析錯誤調查時Sonnet
refactor-assistant程式碼改善降低複雜度時Sonnet
doc-writer文件撰寫API 變更時Haiku/Sonnet

依序 vs 平行執行

依序(慢):

Task 1 (30s) → Task 2 (30s) → Task 3 (30s) → Task 4 (30s)
Total: 120 seconds

平行(快):

Task 1 (30s) ┐
Task 2 (30s) ├→ All complete in 30 seconds
Task 3 (30s) │
Task 4 (30s) ┘
Total: 30 seconds

計算公式: 平行執行時間 = max(個別時間),而非總和。

核心模式

模式 1:分析群集

同時啟動多個 Explore agents 從不同角度分析。

Prompt: "I need to understand how user authentication works in this project."

Claude spawns 5 parallel agents:
→ Task 1 (Explore quick): Map auth-related file structure
→ Task 2 (Explore quick): Find all JWT/session references
→ Task 3 (Explore medium): Analyze middleware chain
→ Task 4 (Explore quick): Identify auth configuration
→ Task 5 (Explore quick): Review existing auth tests

Results synthesized into comprehensive overview.

實作:

// All 5 agents launch simultaneously
Task({ subagent_type: "Explore", model: "haiku",
  prompt: "Map auth-related file structure (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
  prompt: "Find all JWT and session references (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
  prompt: "Analyze authentication middleware chain (thoroughness: medium)" })
Task({ subagent_type: "Explore", model: "haiku",
  prompt: "Find auth configuration files (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
  prompt: "Review authentication test files (thoroughness: quick)" })

使用場景:

  • 探索不熟悉的程式碼庫
  • 理解複雜功能
  • 變更前的影響分析
  • 技術債評估

模式 2:分而治之

將大型任務拆分為平行執行的獨立子任務。

Prompt: "Refactor the payment module to use the new API client."

Claude spawns agents per file:
→ Agent 1: Refactor payment/checkout.ts
→ Agent 2: Refactor payment/subscription.ts
→ Agent 3: Refactor payment/refund.ts
→ Agent 4: Update payment/types.ts
→ Agent 5: Update tests in payment/__tests__/

Each agent has context about the new API client pattern.

實作:

// Shared context provided to all agents
const sharedContext = `
  Migration context:
  - Replace RestClient with new ApiClient from src/lib/api.ts
  - Use new error handling pattern from src/lib/errors.ts
  - Maintain backward compatibility for exported functions
`;

Task({ subagent_type: "general-purpose", model: "sonnet",
  prompt: `${sharedContext}\n\nRefactor payment/checkout.ts` })
Task({ subagent_type: "general-purpose", model: "sonnet",
  prompt: `${sharedContext}\n\nRefactor payment/subscription.ts` })
// ... etc

使用場景:

  • 多檔案重構
  • 批次更新(重新命名、模式變更)
  • 大規模遷移
  • 跨檔案文件更新

模式 3:實作與審查並行

同時建構和審查,及早發現問題。

Prompt: "Implement user profile editing with proper validation."

Phase 1 - Implementation (parallel):
→ Agent 1: Implement API endpoint
→ Agent 2: Create form component
→ Agent 3: Write validation logic

Phase 2 - Review (parallel, starts after Phase 1):
→ Agent 4 (security-auditor): Security review
→ Agent 5 (code-reviewer): Quality check
→ Agent 6 (test-runner): Verify coverage

使用場景:

  • 新功能開發
  • 關鍵程式碼變更
  • 安全敏感的實作
  • 高複雜度功能

模式 4:多視角審查

對同一段程式碼取得不同專家的觀點。

Prompt: "Review PR #123 comprehensively."

Claude spawns specialized reviewers:
→ Agent 1 (code-reviewer): Code quality and patterns
→ Agent 2 (security-auditor): Security vulnerabilities
→ Agent 3 (Explore): Performance implications
→ Agent 4 (test-runner): Test coverage analysis
→ Agent 5 (general-purpose): Backward compatibility

Synthesized review with categorized findings.

使用場景:

  • 程式碼審查
  • 架構決策
  • 技術提案
  • 相依套件更新

模式 5:Bug 調查

當你不知道從何找起時,平行搜尋。

Prompt: "Users report 'undefined is not a function' on dashboard."

Claude spawns search agents:
→ Agent 1 (Explore): Search for error message in codebase
→ Agent 2 (Explore): Find recent dashboard changes
→ Agent 3 (Explore): Analyze dashboard dependencies
→ Agent 4 (Explore): Check for TypeScript errors
→ Agent 5 (Explore): Review related test failures

First agent to find strong lead guides investigation.

使用場景:

  • Bug 獵殺
  • 理解錯誤來源
  • 找出已棄用的用法
  • 追蹤資料流向

最佳實踐

1. 選擇正確的模型

探索/搜尋 → Haiku 4.5
- 檔案結構映射
- 模式搜尋
- 簡單分析
- 成本:每任務約 $0.001

複雜推理 → Sonnet 4.5
- 程式碼審查
- 架構規劃
- 實作
- 成本:每任務約 $0.003

關鍵決策 → Opus 4.5
- 安全分析
- 複雜重構
- 架構決策
- 成本:每任務約 $0.015

2. 保持 Agents 專注

每個 agent 應該有單一、明確的目標

太寬泛(不好):

"Analyze the entire codebase and find all issues"

專注(好):

Task({ prompt: "Find all usages of deprecated API v1" })
Task({ prompt: "Check for missing error handling in API routes" })
Task({ prompt: "Identify components without prop validation" })

3. 提供共享上下文

確保所有 agents 都有所需的上下文:

const sharedContext = `
  Context for all agents:
  - We're migrating from REST to GraphQL
  - Target files are in src/api/
  - Use the new ApiClient from src/lib/api.ts
  - Follow error handling patterns in src/lib/errors.ts
`;

Task({ prompt: `${sharedContext}\n\nTask 1: ...` })
Task({ prompt: `${sharedContext}\n\nTask 2: ...` })

4. 處理背景任務

對於長時間執行的任務,使用 run_in_background

Task({
  subagent_type: "general-purpose",
  model: "sonnet",
  prompt: "Comprehensive security audit of entire codebase",
  run_in_background: true  // Returns immediately, runs async
})

// Check on it later
TaskOutput({ task_id: "...", block: false })

5. 規劃綜合結果

多個 agents 產生多個輸出。規劃如何整合它們:

After parallel analysis:
1. Collect findings from all agents
2. Deduplicate overlapping discoveries
3. Prioritize by severity/impact
4. Create actionable summary

實際範例

功能開發工作流程

User: "Implement a notification system for order updates."

Phase 1 - Discovery (5 parallel Explore agents):
→ Map existing notification patterns
→ Find email/push notification code
→ Analyze order state machine
→ Review notification templates
→ Check existing event handlers

Phase 2 - Design (sequential, needs Phase 1 results):
→ Plan agent: Design notification architecture

Phase 3 - Implementation (4 parallel agents):
→ Create notification service
→ Add order event listeners
→ Build email templates
→ Write unit tests

Phase 4 - Review (3 parallel agents):
→ security-auditor: Check for data leaks
→ code-reviewer: Review patterns
→ test-runner: Verify coverage

Bug 調查

User: "Production error: 'Payment failed' but money was charged."

Parallel investigation (5 Explore agents):
→ Search payment logs for error pattern
→ Analyze payment service error handling
→ Check Stripe webhook handlers
→ Review recent payment changes
→ Find similar issues in error tracking

Results:
- Agent 3 finds: Webhook handler doesn't retry on timeout
- Agent 4 confirms: Recent change added new timeout logic
- Agent 1 shows: Pattern started after deploy on Jan 5

Root cause identified in ~1 minute vs 10+ sequential.

程式碼庫稽核

User: "Audit for security issues and tech debt."

Parallel audit (8 agents):

Security team:
→ security-auditor: SQL injection patterns
→ security-auditor: XSS vulnerabilities
→ security-auditor: Authentication issues
→ security-auditor: Sensitive data exposure

Quality team:
→ code-reviewer: Code duplication
→ code-reviewer: Complexity hotspots
→ test-runner: Coverage gaps
→ Explore: Outdated dependencies

All 8 agents work simultaneously.
Results categorized and prioritized.

效能考量

平行執行最有幫助的情況

  • 任務真正獨立
  • 操作是 I/O bound(檔案讀取、API 呼叫)
  • 分析受益於多重視角
  • 涵蓋面廣(多檔案、多模式)

平行執行幫助較小的情況

  • 任務有強相依性(A 必須在 B 之前完成)
  • 非常快速的任務(額外開銷超過效益)
  • 需要深度依序推理的任務
  • 範圍有限(只有一個檔案或函數)

額外開銷意識

平行執行有額外開銷:

  • Agent 初始化:每個約 1-2 秒
  • 上下文共享成本
  • 結果綜合時間

對於 5 秒以下的任務,依序執行可能更快。

開始使用

今天:

  1. 嘗試一個平行 Explore 群集:“Find all usages of X in the codebase”
  2. 注意與依序探索的速度差異

本週:

  1. 使用分析群集來理解複雜功能
  2. 實驗分而治之模式

本月:

  1. 發展適合你工作流程的專屬模式
  2. 識別哪些任務最受益於平行化
  3. 為不同 agent 類型優化模型選擇

快速參考

Task Tool 模板

Task({
  subagent_type: "Explore" | "general-purpose",
  model: "haiku" | "sonnet" | "opus",
  prompt: "Clear, focused task description",
  run_in_background: true | false
})

模型選擇指南

任務類型模型原因
檔案搜尋haiku快速、便宜
模式匹配haiku快速、便宜
程式碼審查sonnet平衡
實作sonnet平衡
安全稽核sonnet/opus徹底
架構opus能力最強

平行執行規則

獨立任務 → 同時啟動
相依任務 → 依序執行
混合情況 → 分階段方式(階段內平行,階段間依序)

Multi-agent 架構改變你與 Claude Code 互動的方式。不再是依序的提示,而是編排平行工作流程,在極短時間內完成。

來源:Claude Code DocumentationClaude Code GitHubCHANGELOG