Skip to main content

Overview

This example demonstrates coordinating multiple specialized AI agents that work together on complex tasks. Each agent has specific expertise, and their outputs combine to produce comprehensive results. Perfect for research, analysis, content creation, and any task benefiting from multiple perspectives.

Architecture

Research Agent  \
Analysis Agent   → Synthesis Agent → Review Agent → Output
Writing Agent   /

Complete Example

name: multi-agent-research
description: Coordinate research, analysis, and writing agents

state:
  schema:
    researchFindings: object
    analysisResults: object
    draftContent: string
    finalContent: string

flow:
  # Phase 1: Parallel Research by Specialized Agents
  parallel:
    - member: research-technical
      type: Think
      config:
        provider: openai
        model: gpt-4o
        systemPrompt: |
          You are a technical research specialist.
          Focus on technical details, specifications, and implementation.
      input:
        prompt: |
          Research technical aspects of: ${input.topic}
          Provide detailed technical information and specifications.
      state:
        set: [researchFindings]

    - member: research-market
      type: Think
      config:
        provider: anthropic
        model: claude-3-5-sonnet-20241022
        systemPrompt: |
          You are a market research specialist.
          Focus on market trends, adoption, and business impact.
      input:
        prompt: |
          Research market aspects of: ${input.topic}
          Analyze trends, adoption rates, and business implications.
      state:
        set: [researchFindings]

    - member: research-competitive
      type: Think
      config:
        provider: openai
        model: gpt-4o
        systemPrompt: |
          You are a competitive analysis specialist.
          Focus on competitors, alternatives, and comparisons.
      input:
        prompt: |
          Research competitive landscape for: ${input.topic}
          Identify competitors and comparative advantages.
      state:
        set: [researchFindings]

  # Phase 2: Synthesis Agent Combines Research
  - member: synthesize-research
    type: Think
    config:
      provider: anthropic
      model: claude-3-5-sonnet-20241022
      systemPrompt: |
        You are a research synthesis specialist.
        Combine multiple research perspectives into cohesive insights.
    state:
      use: [researchFindings]
    input:
      prompt: |
        Synthesize these research findings into key insights:

        Technical Research:
        ${research-technical.output.text}

        Market Research:
        ${research-market.output.text}

        Competitive Research:
        ${research-competitive.output.text}

        Provide 5-7 key insights that integrate all perspectives.

  # Phase 3: Parallel Analysis by Domain Experts
  parallel:
    - member: analyze-opportunities
      type: Think
      config:
        provider: openai
        model: gpt-4o
        systemPrompt: |
          You are a strategic opportunity analyst.
          Identify growth opportunities and potential.
      input:
        prompt: |
          Based on these insights, identify opportunities:
          ${synthesize-research.output.text}
      state:
        set: [analysisResults]

    - member: analyze-risks
      type: Think
      config:
        provider: anthropic
        model: claude-3-5-sonnet-20241022
        systemPrompt: |
          You are a risk assessment specialist.
          Identify potential risks and mitigation strategies.
      input:
        prompt: |
          Based on these insights, analyze risks:
          ${synthesize-research.output.text}
      state:
        set: [analysisResults]

    - member: analyze-recommendations
      type: Think
      config:
        provider: openai
        model: gpt-4o
        systemPrompt: |
          You are a strategic advisor.
          Provide actionable recommendations.
      input:
        prompt: |
          Based on these insights, provide recommendations:
          ${synthesize-research.output.text}
      state:
        set: [analysisResults]

  # Phase 4: Writing Agent Creates Content
  - member: write-draft
    type: Think
    config:
      provider: anthropic
      model: claude-3-5-sonnet-20241022
      systemPrompt: |
        You are an expert content writer.
        Create clear, engaging, well-structured content.
    state:
      use: [researchFindings, analysisResults]
      set: [draftContent]
    input:
      prompt: |
        Write a comprehensive analysis on ${input.topic}.

        Use these research findings:
        ${synthesize-research.output.text}

        Incorporate this analysis:
        • Opportunities: ${analyze-opportunities.output.text}
        • Risks: ${analyze-risks.output.text}
        • Recommendations: ${analyze-recommendations.output.text}

        Structure:
        1. Executive Summary
        2. Key Insights
        3. Opportunities
        4. Risks
        5. Recommendations
        6. Conclusion

  # Phase 5: Quality Validation
  - member: validate-content
    type: Validate
    state:
      use: [draftContent]
    scoring:
      evaluator: validate
      evaluatorConfig:
        type: judge
        model: gpt-4o-mini
        systemPrompt: |
          Evaluate content quality on:
          - Completeness
          - Clarity
          - Accuracy
          - Structure
      criteria:
        completeness: "All required sections present"
        clarity: "Clear and easy to understand"
        accuracy: "Factually accurate based on research"
        structure: "Well-organized and logical flow"
      thresholds:
        minimum: 0.85
      onFailure: retry
      retryLimit: 3
      requireImprovement: true

  # Phase 6: Review and Polish
  - member: review-agent
    type: Think
    config:
      provider: anthropic
      model: claude-3-5-sonnet-20241022
      systemPrompt: |
        You are an expert editor and reviewer.
        Polish content for excellence.
    state:
      use: [draftContent]
      set: [finalContent]
    input:
      prompt: |
        Review and polish this content:

        ${write-draft.output.text}

        Validation feedback:
        ${validate-content.output.feedback}

        Improve clarity, fix any issues, and ensure excellence.

output:
  content: ${review-agent.output.text}
  metadata:
    topic: ${input.topic}
    agents:
      research: 3
      analysis: 3
      writing: 1
      review: 1
    quality:
      score: ${validate-content.output.score}
      attempts: ${validate-content.output.attempts}
    researchSummary:
      technical: ${research-technical.output.text[0..200]}
      market: ${research-market.output.text[0..200]}
      competitive: ${research-competitive.output.text[0..200]}

Agent Specialization Patterns

Different Models for Different Tasks

# Complex reasoning: GPT-4o
- member: complex-analysis
  config:
    provider: openai
    model: gpt-4o

# Long-form writing: Claude 3.5 Sonnet
- member: write-content
  config:
    provider: anthropic
    model: claude-3-5-sonnet-20241022

# Quick validation: GPT-4o Mini
- member: validate
  config:
    provider: openai
    model: gpt-4o-mini

Temperature Tuning by Agent

# Creative agent: Higher temperature
- member: creative-agent
  config:
    temperature: 0.9

# Analytical agent: Lower temperature
- member: analytical-agent
  config:
    temperature: 0.3

# Factual agent: Very low temperature
- member: factual-agent
  config:
    temperature: 0.1

Coordination Patterns

Sequential Handoff

flow:
  - member: agent-1
  - member: agent-2
    input:
      previousWork: ${agent-1.output}
  - member: agent-3
    input:
      previousWork: ${agent-2.output}

Parallel + Synthesis

flow:
  parallel:
    - member: agent-1
    - member: agent-2
    - member: agent-3

  - member: synthesize
    input:
      inputs:
        - ${agent-1.output}
        - ${agent-2.output}
        - ${agent-3.output}

Iterative Refinement

flow:
  - member: draft
  - member: critique
  - member: revise
    input:
      draft: ${draft.output}
      critique: ${critique.output}
  - member: final-review

Advanced Patterns

Debate Between Agents

flow:
  - member: position-a
    input:
      stance: "advocate"

  - member: position-b
    input:
      stance: "skeptic"

  - member: moderator
    input:
      positionA: ${position-a.output}
      positionB: ${position-b.output}
      task: "synthesize balanced view"

Agent Voting

flow:
  parallel:
    - member: agent-1
    - member: agent-2
    - member: agent-3

  - member: aggregate-votes
    type: Transform
    input:
      votes:
        - ${agent-1.output.recommendation}
        - ${agent-2.output.recommendation}
        - ${agent-3.output.recommendation}
      expression: |
        {
          "consensus": $count(votes[$ = "approve"]) >= 2 ? "approve" : "reject"
        }

Hierarchical Agents

flow:
  # Worker agents
  parallel:
    - member: worker-1
    - member: worker-2
    - member: worker-3

  # Manager agent
  - member: manager
    input:
      workerOutputs:
        - ${worker-1.output}
        - ${worker-2.output}
        - ${worker-3.output}
      task: "coordinate and decide next steps"

  # Executive agent
  - member: executive
    input:
      managerReport: ${manager.output}
      task: "final decision"

Testing

import { describe, it, expect } from 'vitest';
import { TestConductor } from '@ensemble-edge/conductor/testing';

describe('multi-agent-research', () => {
  it('should coordinate multiple agents', async () => {
    const conductor = await TestConductor.create({
      mocks: {
        ai: {
          responses: {
            'research-technical': { text: 'Technical findings...' },
            'research-market': { text: 'Market findings...' },
            'research-competitive': { text: 'Competitive findings...' },
            'synthesize-research': { text: 'Key insights...' },
            'analyze-opportunities': { text: 'Opportunities...' },
            'analyze-risks': { text: 'Risks...' },
            'analyze-recommendations': { text: 'Recommendations...' },
            'write-draft': { text: 'Draft content...' },
            'review-agent': { text: 'Final content...' }
          }
        }
      }
    });

    const result = await conductor.executeEnsemble('multi-agent-research', {
      topic: 'AI in Healthcare'
    });

    expect(result).toBeSuccessful();
    expect(result.output.metadata.agents.research).toBe(3);
    expect(result.output.content).toBeDefined();
  });

  it('should validate content quality', async () => {
    const conductor = await TestConductor.create();

    const result = await conductor.executeEnsemble('multi-agent-research', {
      topic: 'Test Topic'
    });

    expect(result.output.metadata.quality.score).toBeGreaterThan(0.85);
  });
});

Best Practices

  1. Specialize agents - Each agent has clear expertise
  2. Use appropriate models - Match model to task complexity
  3. Tune temperature - Creative vs analytical tasks
  4. Parallel when possible - Independent agents run concurrently
  5. Synthesize results - Combine perspectives coherently
  6. Validate quality - Check output meets standards
  7. State management - Track agent outputs
  8. Clear instructions - Specific system prompts