02-347-7730  |  Saeree ERP - Complete ERP Solution for Thai Businesses Contact Us

Multi-Agent Workflow with OpenClaw

Build Multi-Agent Workflows with OpenClaw Design and Implement AI Agent Orchestration
  • 3
  • April

OpenClaw Deep Dive Series EP.4 — From EP.3 where we wrote a Kernel Module step by step, it's now time to level up — making multiple AI Agents work together as a team! Multi-Agent Workflow is the practice of designing each Agent to specialize in a specific area, then coordinating them to handle tasks too complex for a single Agent. It's like the first Agent we built in EP.1, but this time we have an entire team!

In short — what you will learn in this article:

  • What is Multi-Agent — The concept of multiple AI Agents working together as a team
  • Agent Roles & Specialization — How to design roles for each Agent
  • Orchestration Patterns — Sequential, Parallel, Hierarchical, Feedback Loop
  • Message Passing — How Agents communicate (Direct, Shared Memory, Event Bus)
  • Error Handling & Fallback — What to do when an Agent fails
  • Real-world Workflow — Practical example: building a competitor analysis report

Why Multi-Agent?

A Single Agent can handle many tasks, but it has clear limitations: limited context window (the longer, the more it forgets), inability to work on multiple tasks simultaneously, and the more complex the task the more it hallucinates — Multi-Agent solves these problems by dividing work among specialized Agents, each responsible for what it does best, then coordinating together.

Comparison Single Agent Multi-Agent
Complexity Handles simple tasks well, gets confused with complex ones Breaks complex tasks into subtasks, each Agent focuses on one thing
Accuracy More tasks means more hallucination Specialized Agents + Reviewer verification = higher accuracy
Scalability Limited by context window, cannot scale Add more Agents as needed, easy to scale
Specialization Must be good at everything (jack of all trades) Each Agent excels at one thing (master of one)
Fault Tolerance If the Agent crashes = everything stops One Agent crashes, others continue + fallback

Agent Roles — Designing the AI Team

The core concept of Multi-Agent is: instead of having one Agent do everything, divide the work among multiple Agents, each specializing in one area — just like a real team in an organization with a manager, researcher, analyst, writer, and QA. Each person handles what they do best, producing better results than one person doing everything.

Agent Role Responsibility Example Task
Coordinator Agent Receives user commands, distributes tasks to other Agents, merges results Receives "analyze competitors" command, then assigns work to each team
Research Agent Searches for information, browses the web, summarizes news Searches competitor news from the last 3 months, summarizes as bullet points
Data Agent Pulls data from DB/API, analyzes numbers Pulls sales data from ERP, compares with industry averages
Writer Agent Writes reports, creates documents, formats output Combines data from Research + Data, writes a PDF report
Reviewer Agent Reviews results, performs QA before delivering to the user Checks accuracy of numbers and language before sending the final report

Dividing Agents into clear roles ensures each one has a focused prompt without carrying too much context — similar to designing specialized Skills, but elevated to full Agents.

Orchestration Patterns — Coordination Models

For multiple Agents to work together effectively, you need clear coordination patterns — OpenClaw supports 4 main patterns:

Pattern How It Works Best For Advantage
Sequential A → B → C (one step at a time) Tasks where the next step depends on the previous result Simple to implement, easy to debug, predictable results
Parallel A + B + C simultaneously → merge results Tasks where each part is independent and doesn't need to wait Fast, saves time
Hierarchical Boss Agent delegates to subordinates, subordinates report back Complex tasks requiring mid-process decision-making Flexible, can adjust plans based on the situation
Feedback Loop Do → Review → Fix → Review again Tasks requiring high quality, such as report writing High quality, verified through multiple review rounds
# Sequential Pattern
User → [Research Agent] → [Data Agent] → [Writer Agent] → [Reviewer Agent] → User

# Parallel Pattern
              → [Research Agent] →
User → Fork                          Merge → [Writer Agent] → User
              → [Data Agent]     →

# Hierarchical Pattern
User → [Coordinator Agent] →→ [Research Agent] → report back
                               →→ [Data Agent]     → report back
                               →→ [Writer Agent]   → report back
                               → Combine → User

# Feedback Loop Pattern
User → [Writer Agent] ↔ [Reviewer Agent] (loop until approved) → User

Building a Multi-Agent Workflow — Real Example

Let's build a real Workflow — Use Case: "Build a competitor analysis report" where the Coordinator Agent distributes work to 4 Agents collaborating together.

Workflow Overview

User: "Analyze 3 competitors in the Thai ERP market"
  |
  v
[Coordinator Agent] -- distributes tasks -->
  |
  |--> [Research Agent]  Search competitor news from the last 3 months
  |--> [Data Agent]      Pull market share + pricing data
  |
  v (wait for results from both)
  |
  |--> [Writer Agent]    Write a report from gathered data
  |
  v
  |--> [Reviewer Agent]  QA review
  |
  v (if not approved, send back to Writer for revision)
  |
  v
User: Receives the final report

Workflow Config (YAML)

# workflows/competitor-analysis.yaml

name: competitor-analysis
description: "Multi-Agent competitor analysis"

agents:
  coordinator:
    role: "Coordinator"
    model: "gpt-4"
    prompt: "You are a project manager. Receive user commands, distribute tasks to your team, merge results."

  researcher:
    role: "Research"
    model: "gpt-4"
    prompt: "You are a market researcher. Search for competitor information, summarize news, analyze trends."
    skills: ["web-search", "news-summary"]

  data_analyst:
    role: "Data Analysis"
    model: "gpt-4"
    prompt: "You are a data analyst. Pull numbers from DB/API, create charts, compare data."
    skills: ["db-query", "chart-generator"]

  writer:
    role: "Writer"
    model: "gpt-4"
    prompt: "You are a report writer. Combine data from research and analytics teams into an easy-to-read report."

  reviewer:
    role: "Reviewer"
    model: "gpt-4"
    prompt: "You are QA. Verify accuracy, language, and numbers before delivering the report to the user."

workflow:
  - step: "research"
    agent: ["researcher", "data_analyst"]
    mode: "parallel"

  - step: "write"
    agent: "writer"
    input_from: ["researcher", "data_analyst"]

  - step: "review"
    agent: "reviewer"
    input_from: "writer"
    retry_if_failed: true
    max_retries: 2

Coordinator Logic (JavaScript)

// coordinator.js — Receive commands, distribute tasks, merge results

const { AgentRunner, WorkflowEngine } = require('@openclaw/sdk');

async function runCompetitorAnalysis(userRequest) {
  const engine = new WorkflowEngine('workflows/competitor-analysis.yaml');

  // Step 1: Parallel — Research + Data Analysis
  console.log('[Coordinator] Dispatching to Research & Data agents...');
  const [researchResult, dataResult] = await Promise.all([
    engine.run('researcher', {
      task: `Search competitor news: ${userRequest}`,
      timeRange: '3 months'
    }),
    engine.run('data_analyst', {
      task: `Pull market and pricing data: ${userRequest}`,
      sources: ['market-db', 'pricing-api']
    })
  ]);

  // Step 2: Sequential — Writer merges results
  console.log('[Coordinator] Dispatching to Writer...');
  const report = await engine.run('writer', {
    task: 'Write a competitor analysis report',
    researchData: researchResult.output,
    analyticsData: dataResult.output,
    format: 'executive-summary'
  });

  // Step 3: Feedback Loop — Reviewer checks
  let finalReport = report;
  for (let attempt = 0; attempt < 3; attempt++) {
    console.log(`[Coordinator] Review attempt ${attempt + 1}...`);
    const review = await engine.run('reviewer', {
      task: 'Review the report',
      report: finalReport.output
    });

    if (review.output.approved) {
      console.log('[Coordinator] Report approved!');
      return review.output.finalReport;
    }

    // Send back to Writer for revision
    finalReport = await engine.run('writer', {
      task: 'Revise the report based on feedback',
      originalReport: finalReport.output,
      feedback: review.output.feedback
    });
  }

  return finalReport.output;
}

Message Passing — How Do Agents Communicate?

The heart of Multi-Agent is passing data between Agents — OpenClaw supports 3 main methods, each suited for different use cases:

Method Principle Best For Limitation
Direct Agent sends data directly to another Agent (agent-to-agent) Simple workflows with 2-3 Agents Agents must know each other, not flexible
Shared Memory All Agents read/write to a shared context object Workflows where Agents need to see the same data Must handle race conditions
Event Bus pub/sub — Agent publishes event, other Agents subscribe Complex workflows with many Agents More complex, harder to debug

Shared Context Object

// shared-context.js — All Agents read/write through this object

const sharedContext = {
  // Data from the User
  userRequest: "Analyze ERP competitors in Thailand",
  createdAt: "2026-04-03T09:00:00Z",

  // Research Agent writes results here
  research: {
    status: "completed",
    competitors: [
      { name: "Competitor A", marketShare: "25%", strengths: ["Low price"] },
      { name: "Competitor B", marketShare: "18%", strengths: ["Feature-rich"] },
      { name: "Competitor C", marketShare: "12%", strengths: ["Good service"] }
    ],
    lastUpdated: "2026-04-03T09:05:00Z"
  },

  // Data Agent writes results here
  analytics: {
    status: "completed",
    marketSize: "15 billion THB",
    growthRate: "12% YoY",
    lastUpdated: "2026-04-03T09:04:30Z"
  },

  // Writer Agent writes the report here
  report: { status: "pending", content: null },

  // Reviewer Agent writes feedback here
  review: { status: "pending", approved: false, feedback: null }
};

Event Bus Pattern

// event-bus.js — pub/sub for Agent-to-Agent communication

const { EventBus } = require('@openclaw/sdk');
const bus = new EventBus();

// Research Agent — publishes when search is complete
bus.on('task:research', async (task) => {
  const result = await researchAgent.run(task);
  bus.emit('research:completed', result);
});

// Data Agent — publishes when analysis is complete
bus.on('task:analyze', async (task) => {
  const result = await dataAgent.run(task);
  bus.emit('analysis:completed', result);
});

// Writer Agent — subscribes, waiting for results from Research + Data
let pendingResults = {};
bus.on('research:completed', (data) => {
  pendingResults.research = data;
  checkAndWrite();
});
bus.on('analysis:completed', (data) => {
  pendingResults.analysis = data;
  checkAndWrite();
});

function checkAndWrite() {
  if (pendingResults.research && pendingResults.analysis) {
    bus.emit('task:write', {
      research: pendingResults.research,
      analysis: pendingResults.analysis
    });
  }
}

// Start Workflow — emit tasks in parallel
bus.emit('task:research', { query: "ERP competitors Thailand" });
bus.emit('task:analyze', { query: "ERP market share" });

Error Handling & Fallback

Multi-Agent systems have a higher chance of failure compared to Single Agent because they have more moving parts — you need proper risk management and a solid disaster recovery plan:

Scenario Cause How to Handle
Agent Not Responding (Timeout) LLM slow, network error, Agent crash Set timeout + retry 2-3 times + fallback agent
Agent Wrong Response (Validation Failed) Hallucination, wrong format, missing fields Schema validation + send feedback for Agent to fix
API Error External API down, authentication expired Retry with exponential backoff + cache old data
LLM Rate Limit Too many simultaneous requests Queue system + stagger requests + fallback model
// error-handling.js — Retry Logic + Fallback Agent

async function runWithRetry(agent, task, options = {}) {
  const maxRetries = options.maxRetries || 3;
  const timeout = options.timeout || 30000; // 30 seconds
  const fallbackAgent = options.fallbackAgent || null;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`[Retry] Attempt ${attempt}/${maxRetries} for ${agent.name}`);

      const result = await Promise.race([
        agent.run(task),
        new Promise((_, reject) =>
          setTimeout(() => reject(new Error('Timeout')), timeout)
        )
      ]);

      // Validate output
      if (!result || !result.output) {
        throw new Error('Invalid output: missing required fields');
      }

      return result;
    } catch (error) {
      console.error(`[Retry] ${agent.name} failed: ${error.message}`);

      if (attempt === maxRetries && fallbackAgent) {
        console.log(`[Retry] Switching to fallback: ${fallbackAgent.name}`);
        return fallbackAgent.run(task);
      }

      // Exponential backoff
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
    }
  }

  throw new Error(`All retries failed for ${agent.name}`);
}

Important Considerations When Using Multi-Agent:

  • Multi-Agent uses many times more tokens than Single Agent — costs increase with the number of Agents. Plan your budget carefully.
  • More Agents means harder debugging — you need good logging across every Agent and every message passed between them.
  • Don't create more Agents than necessary — start with 2-3 first, add more only when truly needed.
  • Watch out for security — Agents communicating with each other may pass sensitive data. Access control is essential.

Saeree ERP + Multi-Agent Workflow:

Multi-Agent Workflow is ideal for ERP tasks that require coordination across multiple departments, such as checking budgets + approving documents + notifying executives simultaneously — Saeree ERP is developing an AI Assistant that will use Multi-Agent Workflow as the core mechanism for automated operations. Interested in an ERP system ready for AI in the future? Consult with our team for free

OpenClaw Deep Dive Series — Read More

"Multi-Agent Workflow transforms AI from a single assistant into an intelligent team that coordinates automatically — handling complex tasks more accurately, faster, and more reliably."

- Saeree ERP Team

References

Interested in ERP for Your Organization?

Consult with Grand Linux Solution experts — free of charge

Request Free Demo

Call 02-347-7730 | sale@grandlinux.com

Saeree ERP Author

About the Author

Paitoon Butri

Network & Server Security Specialist, Grand Linux Solution Co., Ltd.