Skip to content

Multi-Agent System Example

A multi-agent system where specialized agents work together to accomplish complex tasks.

Overview

The Multi-Agent pattern:

  1. Supervisor - Routes tasks to appropriate workers
  2. Specialized Workers - Each handles specific tasks
  3. Routing Strategy - Determines task assignment
  4. Aggregation - Combines results

Complete Example

typescript
import { MultiAgentSystemBuilder } from '@agentforge/patterns';
import { ChatOpenAI } from '@langchain/openai';
import { webScraper, calculator, fileWriter } from '@agentforge/tools';

const model = new ChatOpenAI({ model: 'gpt-4' });

// Create builder
const builder = new MultiAgentSystemBuilder({
  supervisor: {
    model,
    strategy: 'skill-based',
  },
  aggregator: {
    model,
    systemPrompt: 'Combine results into a comprehensive report',
  },
  maxIterations: 10,
});

// Register specialized workers
builder.registerWorkers([
  {
    name: 'researcher',
    description: 'Conducts research and gathers information',
    capabilities: ['research', 'web-scraping', 'data-collection'],
    tools: [webScraper],
    systemPrompt: 'You are a research specialist. Find accurate information.',
    model,
  },
  {
    name: 'analyst',
    description: 'Analyzes data and identifies patterns',
    capabilities: ['analysis', 'statistics', 'calculations'],
    tools: [calculator],
    systemPrompt: 'You are a data analyst. Analyze and interpret data.',
    model,
  },
  {
    name: 'writer',
    description: 'Creates professional reports and documents',
    capabilities: ['writing', 'documentation', 'reporting'],
    tools: [fileWriter],
    systemPrompt: 'You are a professional writer. Create clear, engaging content.',
    model,
  },
]);

// Build and use the system
const system = builder.build();

const result = await system.invoke({
  input: 'Create a market analysis report for AI startups in 2024',
});

console.log('Final Report:', result.response);

Output Example

[Supervisor] Routing iteration 1/10
[Supervisor] Routing to researcher: Best skill match with score 3 (skills: research, web_search, data_collection)

[Worker: researcher] Executing task...
[Worker: researcher] Task completed

[Supervisor] Routing iteration 2/10
[Supervisor] Routing to analyst: Best skill match with score 2 (skills: analysis, statistics, calculations)

[Worker: analyst] Executing task...
[Worker: analyst] Task completed

[Supervisor] Routing iteration 3/10
[Supervisor] Routing to writer: Best skill match with score 2 (skills: writing, documentation, reporting)

[Worker: writer] Executing task...
[Worker: writer] Task completed

[Supervisor] All tasks completed, moving to aggregation
[Aggregator] Combining results from 3 workers

📄 Final Report: [Comprehensive market analysis with data and insights]

Routing Strategies

Skill-Based Routing

Routes tasks based on matching worker skills:

typescript
const builder = new MultiAgentSystemBuilder({
  supervisor: {
    model,
    strategy: 'skill-based', // Routes by matching skills
  },
  aggregator: { model },
});

Round-Robin Routing

Distributes tasks evenly across workers:

typescript
const builder = new MultiAgentSystemBuilder({
  supervisor: {
    model,
    strategy: 'round-robin', // Distributes evenly
  },
  aggregator: { model },
});

LLM-Based Routing

Let the LLM decide which worker to route to:

typescript
const builder = new MultiAgentSystemBuilder({
  supervisor: {
    model,
    strategy: 'llm-based', // LLM decides routing
    systemPrompt: 'Route tasks based on worker expertise and current workload',
  },
  aggregator: { model },
});

When to Use Multi-Agent

Best for:

  • Complex workflows
  • Specialized tasks
  • Parallel processing
  • Large-scale projects
  • Team collaboration simulation

Key Features

  • Specialization - Each agent has expertise
  • Coordination - Smart task routing
  • Scalability - Add more agents easily
  • Flexibility - Sequential, parallel, or custom workflows
  • Efficiency - Parallel execution when possible

Agent Communication

typescript
import { createMultiAgentSystem, createReActAgent } from '@agentforge/patterns';
import { ChatOpenAI } from '@langchain/openai';

const model = new ChatOpenAI({ model: 'gpt-4' });

// Create specialized worker agents
const researcher = createReActAgent({
  model,
  tools: [webScraper],
  systemPrompt: 'You are a research specialist.'
});

const analyst = createReActAgent({
  model,
  tools: [calculator],
  systemPrompt: 'You are a data analyst.'
});

const writer = createReActAgent({
  model,
  tools: [fileWriter],
  systemPrompt: 'You are a professional writer.'
});

// Create multi-agent system with supervisor and workers
const system = createMultiAgentSystem({
  supervisor: {
    strategy: 'skill-based',
    model,
    maxIterations: 10
  },

  workers: [
    {
      id: 'researcher',
      capabilities: {
        skills: ['research', 'data-gathering'],
        tools: ['web-scraper'],  // Real tool from @agentforge/tools
        available: true,
        currentWorkload: 0
      },
      agent: researcher
    },
    {
      id: 'analyst',
      capabilities: {
        skills: ['analysis', 'evaluation'],
        tools: ['calculator'],
        available: true,
        currentWorkload: 0
      },
      agent: analyst
    },
    {
      id: 'writer',
      capabilities: {
        skills: ['writing', 'summarization'],
        tools: ['file-writer'],  // Real tool from @agentforge/tools
        available: true,
        currentWorkload: 0
      },
      agent: writer
    }
  ],

  aggregator: {
    model,
    systemPrompt: 'Combine the results from all agents into a coherent response.'
  }
});

Monitoring

typescript
// Use an external metrics library like prom-client
import { Histogram, Counter } from 'prom-client';

const agentDuration = new Histogram({
  name: 'agent_duration_seconds',
  help: 'Agent execution duration',
  labelNames: ['agent_name']
});

const agentInvocations = new Counter({
  name: 'agent_invocations_total',
  help: 'Total agent invocations',
  labelNames: ['agent_name']
});

// Track metrics by wrapping agent invocations
const result = await system.invoke({ input: 'Your task' });

// Record metrics after execution
agentDuration.observe({ agent_name: 'researcher' }, 1.5);
agentInvocations.inc({ agent_name: 'researcher' });

Next Steps

Released under the MIT License.