open-multi-agent-orchestration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Open Multi-Agent Orchestration

开放式多Agent编排框架

Skill by ara.so — AI Agent Skills collection.
Open Multi-Agent is a TypeScript-native multi-agent orchestration framework that automatically decomposes goals into task DAGs, parallelizes independent tasks, and synthesizes results. It supports 10+ LLM providers, built-in tools, MCP server integration, and has only three runtime dependencies.
ara.so提供的Skill——AI Agent技能合集。
Open Multi-Agent是一款基于TypeScript的多Agent编排框架,可自动将目标分解为任务DAG、并行执行独立任务并合成结果。它支持10+大语言模型提供商、内置工具、MCP服务器集成,且仅需三个运行时依赖。

Installation

安装

bash
npm install @open-multi-agent/core
Requirements: Node.js >= 18
bash
npm install @open-multi-agent/core
要求: Node.js >= 18

Core Concepts

核心概念

Three Execution Modes

三种执行模式

  1. Single Agent - One agent, one prompt
  2. Auto-orchestrated Team - Coordinator decomposes goal into tasks automatically
  3. Explicit Pipeline - You define the task graph and assignments
  1. 单Agent - 一个Agent,一个提示词
  2. 自动编排团队 - 协调Agent自动将目标分解为任务
  3. 显式流水线 - 您定义任务图和分配规则

Basic Single Agent

基础单Agent示例

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

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

const result = await orchestrator.runAgent({
  name: 'coder',
  systemPrompt: 'You are an expert TypeScript developer.',
  tools: ['bash', 'file_write', 'file_read'],
}, 'Create a simple Express server in /tmp/api')

console.log(result.success) // true
console.log(result.content) // agent's final response
console.log(result.totalTokenUsage) // { input_tokens: 1234, output_tokens: 567 }
typescript
import { OpenMultiAgent } from '@open-multi-agent/core'

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

const result = await orchestrator.runAgent({
  name: 'coder',
  systemPrompt: 'You are an expert TypeScript developer.',
  tools: ['bash', 'file_write', 'file_read'],
}, 'Create a simple Express server in /tmp/api')

console.log(result.success) // true
console.log(result.content) // agent's final response
console.log(result.totalTokenUsage) // { input_tokens: 1234, output_tokens: 567 }

Auto-Orchestrated Team (Recommended)

自动编排团队(推荐)

The coordinator agent decomposes your goal into a task DAG and executes it:
typescript
import { OpenMultiAgent, type AgentConfig } from '@open-multi-agent/core'

const agents: AgentConfig[] = [
  {
    name: 'architect',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Design clean API contracts and data models.',
    tools: ['file_write'],
  },
  {
    name: 'developer',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Implement runnable TypeScript code.',
    tools: ['bash', 'file_read', 'file_write', 'file_edit'],
  },
  {
    name: 'reviewer',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Review code for correctness and security.',
    tools: ['file_read', 'grep'],
  },
]

const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => {
    console.log(event.type, event.task ?? event.agent ?? '')
  },
})

const team = orchestrator.createTeam('api-team', {
  name: 'api-team',
  agents,
  sharedMemory: true, // agents can share context
})

const result = await orchestrator.runTeam(
  team,
  'Create a REST API for a todo list in /tmp/todo-api/'
)

console.log(result.success)
console.log(result.content) // synthesized final result
console.log(result.totalTokenUsage.output_tokens)
协调Agent会将您的目标分解为任务DAG并执行:
typescript
import { OpenMultiAgent, type AgentConfig } from '@open-multi-agent/core'

const agents: AgentConfig[] = [
  {
    name: 'architect',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Design clean API contracts and data models.',
    tools: ['file_write'],
  },
  {
    name: 'developer',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Implement runnable TypeScript code.',
    tools: ['bash', 'file_read', 'file_write', 'file_edit'],
  },
  {
    name: 'reviewer',
    model: 'claude-sonnet-4-6',
    systemPrompt: 'Review code for correctness and security.',
    tools: ['file_read', 'grep'],
  },
]

const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => {
    console.log(event.type, event.task ?? event.agent ?? '')
  },
})

const team = orchestrator.createTeam('api-team', {
  name: 'api-team',
  agents,
  sharedMemory: true, // agents can share context
})

const result = await orchestrator.runTeam(
  team,
  'Create a REST API for a todo list in /tmp/todo-api/'
)

console.log(result.success)
console.log(result.content) // synthesized final result
console.log(result.totalTokenUsage.output_tokens)

Explicit Task Pipeline

显式任务流水线

When you know the exact workflow:
typescript
import { OpenMultiAgent, type TaskConfig } from '@open-multi-agent/core'

const tasks: TaskConfig[] = [
  {
    id: 'design',
    description: 'Design the API schema',
    assignedTo: 'architect',
    dependencies: [],
  },
  {
    id: 'implement',
    description: 'Implement the endpoints',
    assignedTo: 'developer',
    dependencies: ['design'],
  },
  {
    id: 'test',
    description: 'Write integration tests',
    assignedTo: 'developer',
    dependencies: ['implement'],
  },
  {
    id: 'review',
    description: 'Security and code review',
    assignedTo: 'reviewer',
    dependencies: ['implement', 'test'],
  },
]

const result = await orchestrator.runTasks(team, tasks)
当您明确知晓工作流时:
typescript
import { OpenMultiAgent, type TaskConfig } from '@open-multi-agent/core'

const tasks: TaskConfig[] = [
  {
    id: 'design',
    description: 'Design the API schema',
    assignedTo: 'architect',
    dependencies: [],
  },
  {
    id: 'implement',
    description: 'Implement the endpoints',
    assignedTo: 'developer',
    dependencies: ['design'],
  },
  {
    id: 'test',
    description: 'Write integration tests',
    assignedTo: 'developer',
    dependencies: ['implement'],
  },
  {
    id: 'review',
    description: 'Security and code review',
    assignedTo: 'reviewer',
    dependencies: ['implement', 'test'],
  },
]

const result = await orchestrator.runTasks(team, tasks)

Provider Configuration

提供商配置

Environment Variables

环境变量

bash
undefined
bash
undefined

Anthropic

Anthropic

export ANTHROPIC_API_KEY=sk-ant-...
export ANTHROPIC_API_KEY=sk-ant-...

OpenAI

OpenAI

export OPENAI_API_KEY=sk-...
export OPENAI_API_KEY=sk-...

Google Gemini

Google Gemini

export GEMINI_API_KEY=...
export GEMINI_API_KEY=...

DeepSeek

DeepSeek

export DEEPSEEK_API_KEY=sk-...
export DEEPSEEK_API_KEY=sk-...

Azure OpenAI

Azure OpenAI

export AZURE_OPENAI_API_KEY=... export AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com export AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4 export AZURE_OPENAI_API_VERSION=2024-02-15-preview
export AZURE_OPENAI_API_KEY=... export AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com export AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4 export AZURE_OPENAI_API_VERSION=2024-02-15-preview

Ollama (local)

Ollama (local)

No API key needed, runs on localhost:11434 by default

No API key needed, runs on localhost:11434 by default

undefined
undefined

Using Multiple Providers in One Team

在单个团队中使用多个提供商

typescript
const agents: AgentConfig[] = [
  {
    name: 'planner',
    model: 'claude-sonnet-4-6', // Anthropic
    systemPrompt: 'Create detailed plans.',
  },
  {
    name: 'coder',
    model: 'gpt-4o', // OpenAI
    systemPrompt: 'Write production-grade code.',
    tools: ['bash', 'file_write'],
  },
  {
    name: 'local-reviewer',
    model: 'ollama:qwen2.5-coder:32b', // Local Ollama
    systemPrompt: 'Review code for bugs.',
    tools: ['file_read', 'grep'],
  },
]
typescript
const agents: AgentConfig[] = [
  {
    name: 'planner',
    model: 'claude-sonnet-4-6', // Anthropic
    systemPrompt: 'Create detailed plans.',
  },
  {
    name: 'coder',
    model: 'gpt-4o', // OpenAI
    systemPrompt: 'Write production-grade code.',
    tools: ['bash', 'file_write'],
  },
  {
    name: 'local-reviewer',
    model: 'ollama:qwen2.5-coder:32b', // Local Ollama
    systemPrompt: 'Review code for bugs.',
    tools: ['file_read', 'grep'],
  },
]

Ollama (Local Models)

Ollama(本地模型)

typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'ollama:qwen2.5-coder:7b',
})

const result = await orchestrator.runAgent({
  name: 'local-coder',
  model: 'ollama:deepseek-coder-v2:16b',
  systemPrompt: 'You write Python code.',
  tools: ['bash', 'file_write'],
}, 'Create a FastAPI hello world in /tmp/api.py')
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'ollama:qwen2.5-coder:7b',
})

const result = await orchestrator.runAgent({
  name: 'local-coder',
  model: 'ollama:deepseek-coder-v2:16b',
  systemPrompt: 'You write Python code.',
  tools: ['bash', 'file_write'],
}, 'Create a FastAPI hello world in /tmp/api.py')

Tools

工具

Built-in Tools

内置工具

Available out of the box:
  • bash
    - Execute shell commands
  • file_read
    - Read file contents
  • file_write
    - Write files
  • file_edit
    - Edit files using search/replace
  • grep
    - Search file contents
  • glob
    - List files matching patterns
typescript
const agent: AgentConfig = {
  name: 'dev',
  systemPrompt: 'You are a developer.',
  tools: ['bash', 'file_read', 'file_write', 'file_edit', 'grep'],
}
开箱即用的工具:
  • bash
    - 执行Shell命令
  • file_read
    - 读取文件内容
  • file_write
    - 写入文件
  • file_edit
    - 通过搜索/替换编辑文件
  • grep
    - 搜索文件内容
  • glob
    - 列出匹配模式的文件
typescript
const agent: AgentConfig = {
  name: 'dev',
  systemPrompt: 'You are a developer.',
  tools: ['bash', 'file_read', 'file_write', 'file_edit', 'grep'],
}

Custom Tools with Zod

使用Zod定义自定义工具

typescript
import { defineTool } from '@open-multi-agent/core'
import { z } from 'zod'

const weatherTool = defineTool({
  name: 'get_weather',
  description: 'Get current weather for a city',
  parameters: z.object({
    city: z.string().describe('City name'),
    units: z.enum(['celsius', 'fahrenheit']).default('celsius'),
  }),
  execute: async ({ city, units }) => {
    // Your implementation
    const temp = units === 'celsius' ? 22 : 72
    return `Weather in ${city}: ${temp}°${units === 'celsius' ? 'C' : 'F'}`
  },
})

const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  customTools: [weatherTool],
})

const result = await orchestrator.runAgent({
  name: 'assistant',
  tools: ['get_weather'],
}, 'What is the weather in London?')
typescript
import { defineTool } from '@open-multi-agent/core'
import { z } from 'zod'

const weatherTool = defineTool({
  name: 'get_weather',
  description: 'Get current weather for a city',
  parameters: z.object({
    city: z.string().describe('City name'),
    units: z.enum(['celsius', 'fahrenheit']).default('celsius'),
  }),
  execute: async ({ city, units }) => {
    // Your implementation
    const temp = units === 'celsius' ? 22 : 72
    return `Weather in ${city}: ${temp}°${units === 'celsius' ? 'C' : 'F'}`
  },
})

const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  customTools: [weatherTool],
})

const result = await orchestrator.runAgent({
  name: 'assistant',
  tools: ['get_weather'],
}, 'What is the weather in London?')

MCP Server Integration

MCP服务器集成

Connect Model Context Protocol servers:
typescript
import { connectMCPTools } from '@open-multi-agent/core'

const mcpTools = await connectMCPTools({
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  env: {
    GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN,
  },
})

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

const result = await orchestrator.runAgent({
  name: 'github-agent',
  tools: ['create_or_update_file', 'search_repositories'], // MCP tools
}, 'Search for TypeScript agent frameworks and create a comparison in repo.md')
连接Model Context Protocol服务器:
typescript
import { connectMCPTools } from '@open-multi-agent/core'

const mcpTools = await connectMCPTools({
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  env: {
    GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN,
  },
})

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

const result = await orchestrator.runAgent({
  name: 'github-agent',
  tools: ['create_or_update_file', 'search_repositories'], // MCP tools
}, 'Search for TypeScript agent frameworks and create a comparison in repo.md')

Agent Delegation Tool

Agent委托工具

Allow agents to delegate to other agents:
typescript
const team = orchestrator.createTeam('dev-team', {
  name: 'dev-team',
  agents: [
    {
      name: 'lead',
      systemPrompt: 'You coordinate work.',
      tools: ['delegate_to_agent'],
    },
    {
      name: 'specialist',
      systemPrompt: 'You implement features.',
      tools: ['bash', 'file_write'],
    },
  ],
})

// The 'lead' agent can now call delegate_to_agent to hand off tasks
允许Agent将任务委托给其他Agent:
typescript
const team = orchestrator.createTeam('dev-team', {
  name: 'dev-team',
  agents: [
    {
      name: 'lead',
      systemPrompt: 'You coordinate work.',
      tools: ['delegate_to_agent'],
    },
    {
      name: 'specialist',
      systemPrompt: 'You implement features.',
      tools: ['bash', 'file_write'],
    },
  ],
})

// The 'lead' agent can now call delegate_to_agent to hand off tasks

Structured Output

结构化输出

Get Zod-validated responses:
typescript
import { z } from 'zod'

const resultSchema = z.object({
  files: z.array(z.object({
    path: z.string(),
    purpose: z.string(),
  })),
  commands: z.array(z.string()),
  summary: z.string(),
})

const result = await orchestrator.runAgent({
  name: 'architect',
  systemPrompt: 'You design project structures.',
}, 'Design a TypeScript library structure', {
  resultSchema,
})

// result.parsedContent is now typed and validated
console.log(result.parsedContent.files) // TypeScript knows the shape
console.log(result.parsedContent.commands)
获取经过Zod验证的响应:
typescript
import { z } from 'zod'

const resultSchema = z.object({
  files: z.array(z.object({
    path: z.string(),
    purpose: z.string(),
  })),
  commands: z.array(z.string()),
  summary: z.string(),
})

const result = await orchestrator.runAgent({
  name: 'architect',
  systemPrompt: 'You design project structures.',
}, 'Design a TypeScript library structure', {
  resultSchema,
})

// result.parsedContent is now typed and validated
console.log(result.parsedContent.files) // TypeScript knows the shape
console.log(result.parsedContent.commands)

Shared Memory

共享内存

In-Memory (Default)

内存存储(默认)

typescript
const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true, // default in-memory store
})
typescript
const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true, // default in-memory store
})

Custom Memory Store (Redis)

自定义内存存储(Redis)

typescript
import { MemoryStore } from '@open-multi-agent/core'
import Redis from 'ioredis'

class RedisMemoryStore implements MemoryStore {
  private redis: Redis

  constructor() {
    this.redis = new Redis(process.env.REDIS_URL)
  }

  async get(key: string): Promise<string | null> {
    return this.redis.get(key)
  }

  async set(key: string, value: string): Promise<void> {
    await this.redis.set(key, value)
  }

  async delete(key: string): Promise<void> {
    await this.redis.del(key)
  }

  async clear(): Promise<void> {
    await this.redis.flushdb()
  }
}

const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true,
  memoryStore: new RedisMemoryStore(),
})
typescript
import { MemoryStore } from '@open-multi-agent/core'
import Redis from 'ioredis'

class RedisMemoryStore implements MemoryStore {
  private redis: Redis

  constructor() {
    this.redis = new Redis(process.env.REDIS_URL)
  }

  async get(key: string): Promise<string | null> {
    return this.redis.get(key)
  }

  async set(key: string, value: string): Promise<void> {
    await this.redis.set(key, value)
  }

  async delete(key: string): Promise<void> {
    await this.redis.del(key)
  }

  async clear(): Promise<void> {
    await this.redis.flushdb()
  }
}

const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true,
  memoryStore: new RedisMemoryStore(),
})

Observability

可观测性

Progress Events

进度事件

typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => {
    switch (event.type) {
      case 'agent_start':
        console.log(`Starting agent: ${event.agent}`)
        break
      case 'task_start':
        console.log(`Task started: ${event.task}`)
        break
      case 'task_complete':
        console.log(`Task complete: ${event.task}`)
        break
      case 'agent_complete':
        console.log(`Agent finished: ${event.agent}`)
        break
    }
  },
})
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => {
    switch (event.type) {
      case 'agent_start':
        console.log(`Starting agent: ${event.agent}`)
        break
      case 'task_start':
        console.log(`Task started: ${event.task}`)
        break
      case 'task_complete':
        console.log(`Task complete: ${event.task}`)
        break
      case 'agent_complete':
        console.log(`Agent finished: ${event.agent}`)
        break
    }
  },
})

Trace Observability

追踪可观测性

typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onTrace: (span) => {
    console.log('Span:', span.type, span.name)
    console.log('Duration:', span.endTime - span.startTime, 'ms')
    if (span.metadata?.tokens) {
      console.log('Tokens:', span.metadata.tokens)
    }
  },
})
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onTrace: (span) => {
    console.log('Span:', span.type, span.name)
    console.log('Duration:', span.endTime - span.startTime, 'ms')
    if (span.metadata?.tokens) {
      console.log('Tokens:', span.metadata.tokens)
    }
  },
})

Post-Run Dashboard

运行后仪表盘

Generate HTML report of executed task DAG:
typescript
const result = await orchestrator.runTeam(team, goal)

// result.trace contains all execution data
// Render to HTML (implementation in docs/observability.md)
生成已执行任务DAG的HTML报告:
typescript
const result = await orchestrator.runTeam(team, goal)

// result.trace contains all execution data
// Render to HTML (implementation in docs/observability.md)

Plan-Only Mode

仅规划模式

Preview the task DAG without executing:
typescript
const plan = await orchestrator.runTeam(team, goal, { planOnly: true })

console.log('Tasks:', plan.tasks.map(t => ({
  id: t.id,
  description: t.description,
  assignedTo: t.assignedTo,
  dependencies: t.dependencies,
})))
预览任务DAG而不执行:
typescript
const plan = await orchestrator.runTeam(team, goal, { planOnly: true })

console.log('Tasks:', plan.tasks.map(t => ({
  id: t.id,
  description: t.description,
  assignedTo: t.assignedTo,
  dependencies: t.dependencies,
})))

Fan-Out / MapReduce Pattern

扇出/MapReduce模式

Parallel execution without dependencies:
typescript
import { AgentPool } from '@open-multi-agent/core'

const pool = new AgentPool({
  defaultModel: 'claude-sonnet-4-6',
  agents: [
    { name: 'analyzer-1', systemPrompt: 'Analyze data source 1.' },
    { name: 'analyzer-2', systemPrompt: 'Analyze data source 2.' },
    { name: 'analyzer-3', systemPrompt: 'Analyze data source 3.' },
  ],
})

const results = await pool.runParallel([
  { agent: 'analyzer-1', prompt: 'Analyze feed A' },
  { agent: 'analyzer-2', prompt: 'Analyze feed B' },
  { agent: 'analyzer-3', prompt: 'Analyze feed C' },
])

// Aggregate results
const aggregator = new OpenMultiAgent({ defaultModel: 'claude-sonnet-4-6' })
const summary = await aggregator.runAgent({
  name: 'aggregator',
  systemPrompt: 'Merge analysis results.',
}, `Merge these findings:\n${results.map(r => r.content).join('\n\n')}`)
无依赖的并行执行:
typescript
import { AgentPool } from '@open-multi-agent/core'

const pool = new AgentPool({
  defaultModel: 'claude-sonnet-4-6',
  agents: [
    { name: 'analyzer-1', systemPrompt: 'Analyze data source 1.' },
    { name: 'analyzer-2', systemPrompt: 'Analyze data source 2.' },
    { name: 'analyzer-3', systemPrompt: 'Analyze data source 3.' },
  ],
})

const results = await pool.runParallel([
  { agent: 'analyzer-1', prompt: 'Analyze feed A' },
  { agent: 'analyzer-2', prompt: 'Analyze feed B' },
  { agent: 'analyzer-3', prompt: 'Analyze feed C' },
])

// Aggregate results
const aggregator = new OpenMultiAgent({ defaultModel: 'claude-sonnet-4-6' })
const summary = await aggregator.runAgent({
  name: 'aggregator',
  systemPrompt: 'Merge analysis results.',
}, `Merge these findings:\n${results.map(r => r.content).join('\n\n')}`)

Production Checklist

生产环境检查清单

Context Management

上下文管理

typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  maxContextTokens: 100000, // prevent context overflow
  contextStrategy: 'truncate', // or 'summarize'
})
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  maxContextTokens: 100000, // prevent context overflow
  contextStrategy: 'truncate', // or 'summarize'
})

Task Retry with Backoff

带退避的任务重试

typescript
const tasks: TaskConfig[] = [
  {
    id: 'api-call',
    description: 'Fetch external data',
    assignedTo: 'fetcher',
    dependencies: [],
    retry: {
      maxAttempts: 3,
      backoffMs: 1000, // exponential backoff
    },
  },
]
typescript
const tasks: TaskConfig[] = [
  {
    id: 'api-call',
    description: 'Fetch external data',
    assignedTo: 'fetcher',
    dependencies: [],
    retry: {
      maxAttempts: 3,
      backoffMs: 1000, // exponential backoff
    },
  },
]

Loop Detection

循环检测

typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  maxIterations: 20, // prevent infinite loops
})
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  maxIterations: 20, // prevent infinite loops
})

Tool Output Truncation

工具输出截断

typescript
import { defineTool } from '@open-multi-agent/core'
import { z } from 'zod'

const largeTool = defineTool({
  name: 'fetch_logs',
  description: 'Fetch system logs',
  parameters: z.object({ lines: z.number() }),
  execute: async ({ lines }) => {
    const logs = getLogs(lines) // potentially huge
    return logs.slice(0, 10000) // truncate to 10k chars
  },
})
typescript
import { defineTool } from '@open-multi-agent/core'
import { z } from 'zod'

const largeTool = defineTool({
  name: 'fetch_logs',
  description: 'Fetch system logs',
  parameters: z.object({ lines: z.number() }),
  execute: async ({ lines }) => {
    const logs = getLogs(lines) // potentially huge
    return logs.slice(0, 10000) // truncate to 10k chars
  },
})

Common Patterns

常见模式

Contract Review Workflow

合同审查工作流

Four-task DAG with parallel branches:
typescript
const tasks: TaskConfig[] = [
  {
    id: 'extract',
    description: 'Extract key terms from contract',
    assignedTo: 'extractor',
    dependencies: [],
  },
  {
    id: 'risk-check',
    description: 'Identify legal risks',
    assignedTo: 'legal-expert',
    dependencies: ['extract'],
  },
  {
    id: 'compliance-check',
    description: 'Check regulatory compliance',
    assignedTo: 'compliance-expert',
    dependencies: ['extract'],
  },
  {
    id: 'report',
    description: 'Generate final report',
    assignedTo: 'reporter',
    dependencies: ['risk-check', 'compliance-check'],
  },
]

const result = await orchestrator.runTasks(team, tasks)
带有并行分支的四任务DAG:
typescript
const tasks: TaskConfig[] = [
  {
    id: 'extract',
    description: 'Extract key terms from contract',
    assignedTo: 'extractor',
    dependencies: [],
  },
  {
    id: 'risk-check',
    description: 'Identify legal risks',
    assignedTo: 'legal-expert',
    dependencies: ['extract'],
  },
  {
    id: 'compliance-check',
    description: 'Check regulatory compliance',
    assignedTo: 'compliance-expert',
    dependencies: ['extract'],
  },
  {
    id: 'report',
    description: 'Generate final report',
    assignedTo: 'reporter',
    dependencies: ['risk-check', 'compliance-check'],
  },
]

const result = await orchestrator.runTasks(team, tasks)

Translation with Back-Translation

带回译的翻译工作流

typescript
const team = orchestrator.createTeam('translation', {
  name: 'translation',
  agents: [
    {
      name: 'translator',
      model: 'claude-sonnet-4-6',
      systemPrompt: 'Translate English to target language.',
    },
    {
      name: 'back-translator',
      model: 'gpt-4o',
      systemPrompt: 'Translate back to English.',
    },
    {
      name: 'validator',
      model: 'claude-sonnet-4-6',
      systemPrompt: 'Compare original and back-translation, flag drift.',
    },
  ],
  sharedMemory: true,
})

const tasks: TaskConfig[] = [
  { id: 'translate', description: 'Translate to Spanish', assignedTo: 'translator', dependencies: [] },
  { id: 'back-translate', description: 'Translate back to English', assignedTo: 'back-translator', dependencies: ['translate'] },
  { id: 'validate', description: 'Compare and flag drift', assignedTo: 'validator', dependencies: ['translate', 'back-translate'] },
]

const result = await orchestrator.runTasks(team, tasks)
typescript
const team = orchestrator.createTeam('translation', {
  name: 'translation',
  agents: [
    {
      name: 'translator',
      model: 'claude-sonnet-4-6',
      systemPrompt: 'Translate English to target language.',
    },
    {
      name: 'back-translator',
      model: 'gpt-4o',
      systemPrompt: 'Translate back to English.',
    },
    {
      name: 'validator',
      model: 'claude-sonnet-4-6',
      systemPrompt: 'Compare original and back-translation, flag drift.',
    },
  ],
  sharedMemory: true,
})

const tasks: TaskConfig[] = [
  { id: 'translate', description: 'Translate to Spanish', assignedTo: 'translator', dependencies: [] },
  { id: 'back-translate', description: 'Translate back to English', assignedTo: 'back-translator', dependencies: ['translate'] },
  { id: 'validate', description: 'Compare and flag drift', assignedTo: 'validator', dependencies: ['translate', 'back-translate'] },
]

const result = await orchestrator.runTasks(team, tasks)

Troubleshooting

故障排除

"Model not found" Error

"Model not found"错误

Make sure the correct API key is set:
bash
undefined
确保已设置正确的API密钥:
bash
undefined

Check which provider your model uses

Check which provider your model uses

export ANTHROPIC_API_KEY=sk-ant-... # for claude-* export OPENAI_API_KEY=sk-... # for gpt-* export GEMINI_API_KEY=... # for gemini-*
undefined
export ANTHROPIC_API_KEY=sk-ant-... # for claude-* export OPENAI_API_KEY=sk-... # for gpt-* export GEMINI_API_KEY=... # for gemini-*
undefined

Ollama Connection Refused

Ollama连接被拒绝

bash
undefined
bash
undefined

Start Ollama daemon

Start Ollama daemon

ollama serve
ollama serve

Pull the model

Pull the model

ollama pull qwen2.5-coder:7b
ollama pull qwen2.5-coder:7b

Verify it's running

Verify it's running

Task Hangs / Times Out

任务挂起/超时

Enable progress logging to see where it's stuck:
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => console.log(event), // debug all events
  timeout: 300000, // 5 minutes per task
})
启用进度日志查看卡住的位置:
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6',
  onProgress: (event) => console.log(event), // debug all events
  timeout: 300000, // 5 minutes per task
})

"Too many tokens" Error

"Too many tokens"错误

Reduce context or use a larger context window model:
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6', // 200k context
  maxContextTokens: 100000,
  contextStrategy: 'truncate', // keep recent messages only
})
减少上下文或使用更大上下文窗口的模型:
typescript
const orchestrator = new OpenMultiAgent({
  defaultModel: 'claude-sonnet-4-6', // 200k context
  maxContextTokens: 100000,
  contextStrategy: 'truncate', // keep recent messages only
})

MCP Server Won't Connect

MCP服务器无法连接

Check stderr from the MCP process:
typescript
const mcpTools = await connectMCPTools({
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN },
  onStderr: (data) => console.error('MCP stderr:', data),
})
检查MCP进程的stderr:
typescript
const mcpTools = await connectMCPTools({
  command: 'npx',
  args: ['-y', '@modelcontextprotocol/server-github'],
  env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN },
  onStderr: (data) => console.error('MCP stderr:', data),
})

Agents Not Sharing Context

Agent不共享上下文

Ensure
sharedMemory: true
is set:
typescript
const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true, // required for context sharing
})
确保已设置
sharedMemory: true
typescript
const team = orchestrator.createTeam('team', {
  name: 'team',
  agents: [...],
  sharedMemory: true, // required for context sharing
})

CLI Usage

CLI使用

For shell and CI workflows:
bash
undefined
适用于Shell和CI工作流:
bash
undefined

Install globally

Install globally

npm install -g @open-multi-agent/core
npm install -g @open-multi-agent/core

Run a team

Run a team

oma run --team api-team --goal "Create REST API" --config team.json
oma run --team api-team --goal "Create REST API" --config team.json

Plan only

Plan only

oma plan --team api-team --goal "Create REST API" --config team.json
oma plan --team api-team --goal "Create REST API" --config team.json

Output JSON for parsing

Output JSON for parsing

oma run --team api-team --goal "..." --json > result.json

See [docs/cli.md](https://github.com/open-multi-agent/open-multi-agent/blob/main/docs/cli.md) for full CLI reference.
oma run --team api-team --goal "..." --json > result.json

完整CLI参考请查看[docs/cli.md](https://github.com/open-multi-agent/open-multi-agent/blob/main/docs/cli.md)。

Resources

资源