Skip to content

Chaining Multiple Agents

Create powerful workflows by connecting specialized agents in sequence.

Difficulty: Intermediate Time: 15 minutes

What You'll Build

Learn to:

  • Design multi-agent pipelines
  • Pass data between agents with input/output mapping
  • Use worktrees for code-modifying agents
  • Optimize for quality and speed

Agent ChainTBD: Replace with diagram of agent chain

Prerequisites

Why Chain Agents?

Single agents can become overloaded with complex tasks. Chaining allows:

BenefitDescription
SpecializationEach agent focuses on one task
QualityExperts produce better results
DebuggingEasier to identify issues
ReusabilityAgents can be mixed and matched
ScalabilityAdd stages without rewriting

Example 1: Content Pipeline

Create a blog post from a topic:

┌──────────┐    ┌───────────┐    ┌──────────┐    ┌──────────┐
│ Research  │───>│  Outline  │───>│  Writer  │───>│  Editor  │
│  Agent    │    │   Agent   │    │  Agent   │    │  Agent   │
└──────────┘    └───────────┘    └──────────┘    └──────────┘

Agent Definitions

Researcher:

yaml
name: Content Researcher
description: Researches topics and gathers sources

systemPrompt: |
  Research the given topic thoroughly:
  1. Find key facts and statistics
  2. Identify expert opinions
  3. Note recent developments
  4. List credible sources

  Output as structured JSON.

model: claude-sonnet-5-0
allowedTools:
  - tool: WebSearch
    allowed: true
  - tool: WebFetch
    allowed: true

outputSchema:
  type: object
  properties:
    keyFacts:
      type: array
      items:
        type: string
    sources:
      type: array
      items:
        type: object
        properties:
          title:
            type: string
          url:
            type: string

Outliner:

yaml
name: Content Outliner
description: Creates content structure

systemPrompt: |
  Create a detailed outline based on the research:
  1. Compelling headline
  2. Introduction hook
  3. Main sections with key points
  4. Conclusion

  Structure for reader engagement.

model: claude-sonnet-5-0
thinkingLevel: think

Writer:

yaml
name: Content Writer
description: Writes engaging content

systemPrompt: |
  Write the full article following the outline:
  - Engaging, conversational tone
  - Use research facts naturally
  - Include examples and analogies
  - Aim for 800-1200 words

model: claude-opus-4-6
thinkingLevel: think-hard

Editor:

yaml
name: Content Editor
description: Polishes and fact-checks

systemPrompt: |
  Edit the article for:
  - Grammar and clarity
  - Fact accuracy
  - Flow and readability
  - SEO optimization

  Return the polished version with a summary of changes.

model: claude-sonnet-5-0
thinkingLevel: think

Flow Configuration

json
{
  "nodes": [
    {
      "id": "trigger",
      "type": "trigger",
      "label": "Topic Input",
      "config": {},
      "position": { "x": 0, "y": 0 },
      "triggerType": "manual",
      "triggerConfig": {
        "inputSchema": {
          "type": "object",
          "properties": {
            "topic": { "type": "string", "description": "Topic to write about" }
          },
          "required": ["topic"]
        }
      }
    },
    {
      "id": "researcher",
      "type": "agent",
      "label": "Research",
      "config": {},
      "position": { "x": 250, "y": 0 },
      "agentId": "content-researcher",
      "inputMapping": { "topic": "trigger.input.topic" },
      "outputMapping": {}
    },
    {
      "id": "outliner",
      "type": "agent",
      "label": "Outline",
      "config": {},
      "position": { "x": 500, "y": 0 },
      "agentId": "content-outliner",
      "inputMapping": {
        "topic": "trigger.input.topic",
        "research": "nodes.researcher.output"
      },
      "outputMapping": {}
    },
    {
      "id": "writer",
      "type": "agent",
      "label": "Write",
      "config": {},
      "position": { "x": 750, "y": 0 },
      "agentId": "content-writer",
      "inputMapping": {
        "outline": "nodes.outliner.output",
        "research": "nodes.researcher.output"
      },
      "outputMapping": {}
    },
    {
      "id": "editor",
      "type": "agent",
      "label": "Edit",
      "config": {},
      "position": { "x": 1000, "y": 0 },
      "agentId": "content-editor",
      "inputMapping": { "article": "nodes.writer.output" },
      "outputMapping": {}
    },
    {
      "id": "end",
      "type": "end",
      "label": "Done",
      "config": {},
      "position": { "x": 1250, "y": 0 },
      "endType": "success"
    }
  ],
  "edges": [
    { "id": "e1", "source": "trigger", "target": "researcher" },
    { "id": "e2", "source": "researcher", "target": "outliner" },
    { "id": "e3", "source": "outliner", "target": "writer" },
    { "id": "e4", "source": "writer", "target": "editor" },
    { "id": "e5", "source": "editor", "target": "end" }
  ],
  "variables": {},
  "maxIterations": 5
}

Example 2: Code Quality Pipeline

Review and improve code:

┌──────────┐    ┌───────────┐    ┌──────────┐    ┌──────────┐
│ Security  │───>│Performance│───>│  Style   │───>│ Summary  │
│  Review   │    │  Review   │    │  Review  │    │  Report  │
└──────────┘    └───────────┘    └──────────┘    └──────────┘

TIP

For independent reviews like this, consider Parallel Execution instead of chaining — running security, performance, and style reviews simultaneously is much faster.

Agent Definitions

Security Reviewer:

yaml
name: Security Reviewer
systemPrompt: |
  Review code for security vulnerabilities:
  - Injection attacks (SQL, XSS, command)
  - Authentication/authorization issues
  - Sensitive data exposure
  - Insecure dependencies

  Rate severity: critical, high, medium, low

Performance Reviewer:

yaml
name: Performance Reviewer
systemPrompt: |
  Analyze code for performance issues:
  - Algorithm complexity
  - Memory usage
  - Database query efficiency
  - Caching opportunities

  Suggest specific optimizations.

Style Reviewer:

yaml
name: Style Reviewer
systemPrompt: |
  Review code style and maintainability:
  - Naming conventions
  - Code organization
  - Documentation
  - Best practices

  Be constructive and specific.

Summary Generator:

yaml
name: Review Summarizer
systemPrompt: |
  Compile all reviews into an actionable summary:
  1. Critical issues (must fix)
  2. Important improvements
  3. Nice-to-have suggestions
  4. Overall assessment

  Prioritize by impact.

Passing Data Between Agents

Using Input/Output Mapping

Agent nodes wire data through inputMapping and outputMapping:

yaml
# Outliner agent node
agentId: content-outliner
inputMapping:
  topic: "trigger.input.topic"
  research: "nodes.researcher.output"
outputMapping: {}

Each key in inputMapping becomes a field available to the agent. Each value is a context path pointing to data from triggers or earlier nodes.

Using Output Schemas

Define structured output to make downstream mapping predictable:

yaml
outputSchema:
  type: object
  properties:
    status:
      type: string
    data:
      type: object
    metadata:
      type: object

Access specific fields in the next agent:

yaml
inputMapping:
  data: "nodes.previousAgent.output.data"

Accumulating Context

Pass multiple previous outputs to a later agent:

yaml
inputMapping:
  originalRequest: "trigger.input"
  researchResults: "nodes.researcher.output"
  analysis: "nodes.analyzer.output"
  task: "'Based on the above, provide recommendations.'"

Worktree Support

For chains where agents modify code, use worktrees to isolate changes:

yaml
# Agent node config
agentId: feature-developer
worktreeMode: "new"
worktreeConfig:
  label: "feature-implementation"
  baseBranch: "main"
  autoMergeOnSuccess: true
  cleanupOnComplete: true
inputMapping:
  plan: "nodes.planner.output"

A downstream agent can inherit the worktree:

yaml
# Reviewer agent node
agentId: code-reviewer
worktreeMode: "inherit"
inheritWorktreeFromNodeId: "developer"
inputMapping:
  code: "nodes.developer.output"

Session Continuity

For iterative flows (loops), enable session reuse so the agent continues its previous conversation instead of starting fresh:

yaml
agentId: iterative-refiner
reuseSessionOnLoop: true
inputMapping:
  feedback: "nodes.reviewer.output"

You can also resume from a different node's CLI session:

yaml
agentId: follow-up-agent
resumeFromNodeId: "initial-agent"

Optimization Tips

Model Selection by Stage

StageModelReasoning
Data collectionHaikuFast, simple task
AnalysisSonnetBalanced
Final outputOpusQuality matters

Parallel Where Possible

Independent analyses can run simultaneously:

         ┌─── Security Review ──┐
Input ───┼─── Performance Review ───┤ Merge ──── Summary
         └─── Style Review ─────┘

See Parallel Execution for details.

Best Practices

  1. Single responsibility: Each agent does one thing well
  2. Clear interfaces: Define input/output schemas
  3. Use debug mode: Step through chains to verify data flow
  4. Test incrementally: Verify each agent before chaining
  5. Monitor costs: Chaining multiplies API usage
  6. Use worktrees: Isolate code changes per agent

Sciorex is proprietary software.