A
返回 發現
發現2026/06/26 君澤智庫研究員 Bryan Chan43 分鐘閱讀

Open Multi-Agent (OMA) 完整教學:從目標到 Task DAG 的 TypeScript 多 Agent 編排框架

深入解析 OMA(open-multi-agent)v1.8.0:TypeScript 原生多 Agent 編排框架,Goal-Driven Task DAG、Checkpoint 斷點續傳、Consensus 共識驗證、10+ LLM Provider 支持。附完整代碼示例與實戰教學。

Open Multi-Agent (OMA) 完整教學

TL;DR: OMA 是一個 TypeScript 原生多 Agent 編排框架,核心賣點是 Goal-First — 你給一個目標,Coordinator Agent 自動分解為 Task DAG,並行執行獨立任務,最後合成結果。v1.8.0 新增 Checkpoint 斷點續傳和 Consensus 共識驗證。

為什麼 OMA 值得關注?

2026 年的 Agent 框架市場已經高度成熟:

框架 語言 Stars 核心定位
LangGraph Python + JS 120K+ 圖優先(Graph-First),精確控制
CrewAI Python 52.8K 角色驅動(Role-Based),快速原型
Mastra TypeScript 24.8K TS 原生,Vercel 部署
OMA TypeScript 6.4K 目標驅動(Goal-First),自動 DAG

OMA 的差異化在於 Goal-First 設計:你不需要預先定義節點和邊,只需要描述目標,框架自動生成任務圖。


核心概念

Goal-First vs Graph-First

Graph-FirstLangGraph 方式):
  你定義 Node ANode BNode C → 編譯 → 執行
  優點:精確控制、可預測
  缺點:需要預先知道所有步驟

Goal-FirstOMA 方式):
  你描述目標 → Coordinator 自動生成 DAG → 並行執行 → 合成結果
  優點:靈活、適應性強
  缺點:非確定性(每次分解可能不同)

架構全景

┌─────────────────────────────────────────────────────────┐
│                    OpenMultiAgent                        │
│                                                          │
│  ┌──────────────┐     ┌──────────────────────────────┐  │
│  │  Coordinator │────▶│        TaskQueue              │  │
│  │  (臨時 Agent) │     │  - dependency graph           │  │
│  │  - 分解目標   │     │  - auto unblock               │  │
│  │  - 生成 DAG  │     │  - maxConcurrency (default: 5) │  │
│  └──────────────┘     └──────────────────────────────┘  │
│         │                        │                       │
│         ▼                        ▼                       │
│  ┌──────────────┐     ┌──────────────────────────────┐  │
│  │  AgentPool   │     │      SharedMemory             │  │
│  │  - Semaphore │     │  - 跨 Agent 數據共享          │  │
│  │  - 並行執行  │     │  - MemoryStore interface      │  │
│  └──────────────┘     └──────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

快速開始

安裝

npm install @open-multi-agent/core

# 或用 npx 直接運行
npx oma run --goal "Build a REST API" --team team.json

運行依賴僅 3 個anthropic-ai/sdkopenaizod。整個代碼庫 27 個源文件,一個下午可以讀完。

第一個單 Agent

import { OpenMultiAgent } from '@open-multi-agent/core'

const orchestrator = new OpenMultiAgent({
  defaultModel: 'deepseek-v4-flash',
  defaultProvider: 'deepseek',
})

const result = await orchestrator.runAgent(
  {
    name: 'assistant',
    systemPrompt: 'You are a helpful TypeScript expert.',
  },
  'Explain TypeScript generics in 3 sentences'
)

console.log(result.output)
// TypeScript generics allow you to write reusable code by parameterizing types,
// enabling functions and classes to work with any data type while maintaining
// type safety. They use angle bracket syntax (<T>) to declare type variables...

第一個多 Agent 團隊

import { OpenMultiAgent, type AgentConfig } from '@open-multi-agent/core'

const orchestrator = new OpenMultiAgent({
  defaultModel: 'deepseek-v4-flash',
  defaultProvider: 'deepseek',
})

// 定義團隊成員
const researcher: AgentConfig = {
  name: 'researcher',
  provider: 'deepseek',
  model: 'deepseek-v4-pro',
  systemPrompt: 'You research topics and gather concrete facts with sources.',
}

const writer: AgentConfig = {
  name: 'writer',
  provider: 'anthropic',
  model: 'claude-sonnet-4-6',
  systemPrompt: 'You turn research notes into clear, engaging prose.',
}

// 創建團隊(啟用共享內存)
const team = orchestrator.createTeam('content-team', {
  name: 'content-team',
  agents: [researcher, writer],
  sharedMemory: true,  // 關鍵!讓 writer 能看到 researcher 的發現
})

// 一調用搞定
const result = await orchestrator.runTeam(team, 'Write a guide on TypeScript decorators')

console.log(result.success)        // true
console.log(result.totalTokenUsage) // { input_tokens: 2847, output_tokens: 1203 }

發生了什麼?

  1. Coordinator 收到目標,分解為 3 個研究任務 + 1 個寫作任務
  2. 3 個研究任務並行執行(無依賴關係)
  3. 寫作任務等待所有研究完成後才開始
  4. Coordinator 最後合成最終答案

三種運行模式

模式 1:runAgent() — 單 Agent

最簡單的入口。一個 Agent,一個 Prompt。

const result = await orchestrator.runAgent(agent, 'Your prompt here')

模式 2:runTeam() — 自動編排

給一個目標,框架自動規劃。

const result = await orchestrator.runTeam(team, 'Build a REST API with auth')

注意:Coordinator 是 LLM,分解結果每次可能不同。如果需要確定性,用 runTasks()

模式 3:runTasks() — 顯式管線

你自己定義任務圖,完全可控。

const result = await orchestrator.runTasks(team, [
  {
    title: 'Design schema',
    description: 'Design the database schema for a blog.',
    assignee: 'architect',
  },
  {
    title: 'Implement API',
    description: 'Build REST endpoints based on the schema.',
    assignee: 'developer',
    dependsOn: ['Design schema'],  // 等待 schema 完成
  },
  {
    title: 'Write tests',
    description: 'Write unit tests for all endpoints.',
    assignee: 'tester',
    dependsOn: ['Implement API'],
  },
])

Provider 支持(10+ 內建)

OMA 支持在同一個團隊中混合使用不同 Provider:

const team = orchestrator.createTeam('mixed-team', {
  name: 'mixed-team',
  agents: [
    // Anthropic Claude
    { name: 'architect', provider: 'anthropic', model: 'claude-opus-4-7',
      systemPrompt: 'You design systems.' },
    // OpenAI GPT
    { name: 'developer', provider: 'openai', model: 'gpt-4o',
      systemPrompt: 'You write code.' },
    // DeepSeek(便宜好用)
    { name: 'reviewer', provider: 'deepseek', model: 'deepseek-v4-flash',
      systemPrompt: 'You review code.' },
    // MiniMax(國產之光)
    { name: 'documenter', provider: 'minimax', model: 'MiniMax-M3',
      systemPrompt: 'You write docs.' },
    // 本地模型(Ollama)
    { name: 'helper', provider: 'openai', model: 'llama3',
      baseURL: 'http://localhost:11434/v1',
      apiKey: 'ollama',
      systemPrompt: 'You help with tasks.' },
  ],
  sharedMemory: true,
})

完整 Provider 列表

Provider Config 默認模型 備註
Anthropic provider: 'anthropic' claude-sonnet-4-6 最強推理
OpenAI provider: 'openai' gpt-4o 通用
DeepSeek provider: 'deepseek' deepseek-v4-flash 性價比之王
MiniMax provider: 'minimax' MiniMax-M3 國產首選
Gemini provider: 'gemini' gemini-2.5-pro Google 生態
Grok provider: 'grok' grok-3 xAI
Bedrock provider: 'bedrock' - AWS 企業級
Azure provider: 'azure-openai' - 微軟雲
Copilot provider: 'copilot' - GitHub
Ollama provider: 'openai' + baseURL 自定義 本地免費

v1.8.0 新功能深度解析

1. Checkpoint & Resume(斷點續傳)

長時間運行的任務可以崩潰後恢復:

import { OpenMultiAgent, InMemoryStore } from '@open-multi-agent/core'

// 方式 1:簡寫(使用 team 的 sharedMemoryStore)
const result = await orchestrator.runTeam(team, goal, {
  checkpoint: true,
})

// 方式 2:指定獨立存儲
const result = await orchestrator.runTeam(team, goal, {
  checkpoint: {
    enabled: true,
    runId: 'production-run-001',  // 必須提供
    store: new RedisStore(),       // Redis / Postgres / 自定義
  },
})

// 崩潰後恢復
const restored = await orchestrator.restore({
  team,
  runId: 'production-run-001',
})
// 已完成的 task 會跳過,只執行剩餘部分

技術細節

  • 基於 MemoryStore 接口,與 SharedMemory 共用同一存儲層
  • 每個完成的 task 寫入 snapshot(JSON 格式)
  • Resume 時重新執行 Coordinator synthesis
  • Task 粒度恢復(中斷的 task 從頭重跑,不是 mid-task)

限制

  • Snapshot-based,不是 event-sourced(每次覆蓋前一次)
  • 如果 checkpoint store 和 sharedMemory store 相同,不會重複序列化(避免 O(N²) 寫入)

2. Consensus Verification(共識驗證)

多 Judge 共識驗證機制,防止單個 Agent 的錯誤:

const result = await orchestrator.runTeam(team, goal, {
  verifyJudges: [
    {
      name: 'critic-1',
      provider: 'anthropic',
      model: 'claude-opus-4-7',
      systemPrompt: 'You are a strict code reviewer. Find bugs and security issues.',
    },
    {
      name: 'critic-2',
      provider: 'openai',
      model: 'gpt-4o',
      systemPrompt: 'You verify factual accuracy and completeness.',
    },
  ],
})

工作流程

  1. Proposer Agent 生成答案
  2. Judge Agents 嘗試反駁
  3. 達到 quorum(多數同意)→ 通過
  4. 未達到 → 要求修改後重新驗證

3. CLI Dashboard

npx oma run --goal "Build a REST API" --team team.json --dashboard

生成靜態 HTML 顯示:

  • Task DAG 可視化
  • 每個 task 的執行時間
  • Token 使用量
  • Agent 分配情況

CLI 使用(oma binary)

OMA 的 CLI 是 JSON-first 設計,適合 CI/CD 集成:

# 安裝
npm install -g @open-multi-agent/core

# 運行
npx oma run --goal "Your goal" --team team.json

# 輸出到文件
npx oma run --goal "..." --team team.json > result.json

# 美觀輸出
npx oma run --goal "..." --team team.json --pretty

# 包含完整消息歷史
npx oma run --goal "..." --team team.json --include-messages

Team JSON 格式

{
  "name": "my-team",
  "agents": [
    {
      "name": "researcher",
      "provider": "deepseek",
      "model": "deepseek-v4-pro",
      "systemPrompt": "You research topics thoroughly."
    },
    {
      "name": "writer",
      "provider": "anthropic",
      "model": "claude-sonnet-4-6",
      "systemPrompt": "You write clear, engaging content."
    }
  ],
  "sharedMemory": true
}

Exit Codes

Code 意義 CI/CD 處理
0 成功 繼續
1 運行完成但失敗 檢查 result.json
2 輸入/文件錯誤 修復配置
3 崩潰或 API 錯誤 重試或報警

GitHub Actions 集成

name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm install @open-multi-agent/core
      - run: |
          npx oma run \
            --goal "Review the code changes in this PR for bugs, security issues, and style violations" \
            --team review-team.json \
            --pretty > review-result.json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
      - run: |
          cat review-result.json | jq '.agentResults.coordinator.output'

實戰示例

示例 1:合同審查 DAG

import { OpenMultiAgent, type TaskConfig } from '@open-multi-agent/core'

const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  defaultProvider: 'anthropic',
})

const team = orchestrator.createTeam('contract-review', {
  name: 'contract-review',
  agents: [
    { name: 'extractor', systemPrompt: 'Extract clauses from contracts.' },
    { name: 'compliance', systemPrompt: 'Check regulatory compliance.' },
    { name: 'summarizer', systemPrompt: 'Generate executive summaries.' },
    { name: 'notifier', systemPrompt: 'Generate final reports.' },
  ],
  sharedMemory: true,
})

const tasks: TaskConfig[] = [
  {
    title: 'extract-clauses',
    description: 'Extract all clauses from the contract into structured JSON.',
    assignee: 'extractor',
  },
  {
    title: 'compliance-check',
    description: 'Check each clause for regulatory compliance.',
    assignee: 'compliance',
    dependsOn: ['extract-clauses'],
    maxRetries: 2,
    retryDelayMs: 500,
    retryBackoff: 2,  // 指數退避
  },
  {
    title: 'summary',
    description: 'Generate executive summary.',
    assignee: 'summarizer',
    dependsOn: ['extract-clauses'],
  },
  {
    title: 'final-report',
    description: 'Compile all analysis into a Markdown report.',
    assignee: 'notifier',
    dependsOn: ['compliance-check', 'summary'],
  },
]

const result = await orchestrator.runTasks(team, tasks)
// Task 2 (compliance) 和 Task 3 (summary) 會並行執行!

示例 2:事故事後分析(Incident Postmortem)

const team = orchestrator.createTeam('sre-team', {
  name: 'sre-team',
  agents: [
    { name: 'log-analyzer', systemPrompt: 'Analyze log patterns.' },
    { name: 'deploy-checker', systemPrompt: 'Check recent deployments.' },
    { name: 'impact-assessor', systemPrompt: 'Assess user impact.' },
    { name: 'hypothesizer', systemPrompt: 'Form root cause hypotheses.' },
    { name: 'writer', systemPrompt: 'Write postmortem documents.' },
  ],
  sharedMemory: true,
})

const result = await orchestrator.runTeam(team, `
  Analyze the incident logs from 2026-06-25 14:00-14:30 UTC.
  Correlate with recent deployments and produce a postmortem.
`)
// Coordinator 自動生成 5 個任務的 DAG
// 前 3 個並行執行 → hypothesizer 等待 → writer 最後

示例 3:成本分層管線

// 便宜的模型做分類,貴的模型做創作
const team = orchestrator.createTeam('cost-optimized', {
  name: 'cost-optimized',
  agents: [
    { name: 'classifier', provider: 'openai', model: 'gpt-4o-mini',
      systemPrompt: 'Classify support tickets by urgency.' },
    { name: 'responder', provider: 'anthropic', model: 'claude-opus-4-7',
      systemPrompt: 'Draft detailed responses for urgent tickets.' },
    { name: 'qa', provider: 'deepseek', model: 'deepseek-v4-flash',
      systemPrompt: 'Review responses for accuracy.' },
  ],
})
// 每 100 次運行成本從 $450(全 Opus)降到 ~$57

SharedMemory 深入解析

SharedMemory 是 Agent 之間通信的核心機制:

// 方式 1:內存存儲(默認)
const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [agent1, agent2],
  sharedMemory: true,  // 使用 InMemoryStore
})

// 方式 2:持久化存儲(Redis)
class RedisStore implements MemoryStore {
  async get(key: string): Promise<string | null> { /* ... */ }
  async set(key: string, value: string): Promise<void> { /* ... */ }
  async list(prefix: string): Promise<string[]> { /* ... */ }
  async delete(key: string): Promise<void> { /* ... */ }
  async clear(): Promise<void> { /* ... */ }
}

const team = orchestrator.createTeam('durable-team', {
  name: 'durable-team',
  agents: [agent1, agent2],
  sharedMemoryStore: new RedisStore(),  // 優先於 sharedMemory: true
})

工作原理

  1. 每個 task 完成後,結果寫入 SharedMemory
  2. 下游 task 的 prompt 會自動包含上游結果
  3. Key 格式:<teamId>/<key>,命名空間隔離

Production Checklist

在生產環境部署 OMA 前,確認以下配置:

關注點 配置項 位置
限制對話長度 maxTurns + contextStrategy AgentConfig
限制工具輸出 maxToolOutputChars AgentConfig
失敗重試 maxRetries, retryDelayMs, retryBackoff TaskConfig
預算控制 maxTokenBudget OrchestratorConfig
循環檢測 loopDetection + onLoopDetected OrchestratorConfig
追蹤審計 onTrace OrchestratorConfig
斷點續傳 checkpoint: true RunTeamOptions

與 Loop Engineering 的對比

作為 OpenClaw 用戶,我們自建了 Loop Engineering 系統。以下是兩者對比:

維度 OMA Loop Engineering
任務拆分 自動 DAG(LLM 驅動) 七階段強制引擎
驗證機制 Consensus(LLM Judge) External Supervisor
權限控制 Permission Matrix
崩潰恢復 ✅ Checkpoint ❌ 無
共享內存 ✅ MemoryStore ❌ Agent 隔離
CLI oma binary loop_engine.py
語言 TypeScript Python
生態 npm OpenClaw

結論:OMA 的 Checkpoint 和 Consensus 設計值得借鑑,但 Loop Engineering 的 External Supervisor 在驗證可靠性上更強。


總結

特性 評分
設計理念 ⭐⭐⭐⭐⭐ Goal-First 非常優雅
代碼質量 ⭐⭐⭐⭐⭐ 27 文件,可讀性極高
Provider 支持 ⭐⭐⭐⭐⭐ 10+ 內建,混合使用
生產就緒 ⭐⭐⭐⭐ Checkpoint + Retry + Loop Detection
社區生態 ⭐⭐⭐ 6.4K stars,增長中
文檔質量 ⭐⭐⭐⭐ 完整示例 + 官方文檔

適合誰?

  • TypeScript 後端需要多 Agent 編排
  • 不想預先定義所有步驟
  • 需要混合使用多個 LLM Provider
  • 需要 CLI/CI 集成

不適合誰?

  • 需要精確控制每一步(用 LangGraph)
  • Python 生態(用 CrewAI)
  • 需要完整企業級治理(用 LangGraph + LangSmith)

參考鏈接