eddiebe147

Chain Builder

8
2
# Install this skill:
npx skills add eddiebe147/claude-settings --skill "Chain Builder"

Install specific skill from multi-skill repository

# Description

Build and execute multi-step prompt chains for complex tasks

# SKILL.md


name: Chain Builder
slug: chain-builder
description: Build and execute multi-step prompt chains for complex tasks
category: meta
complexity: complex
version: "1.0.0"
author: "ID8Labs"
triggers:
- "build a chain"
- "create prompt chain"
- "chain these prompts"
- "sequence these tasks"
- "chain builder"
tags:
- prompt-chaining
- automation
- workflow


Chain Builder

The Chain Builder skill helps you design and execute multi-step prompt chains where the output of one prompt becomes the input to the next. This enables complex, multi-stage processing that would be difficult to accomplish in a single prompt, while maintaining clarity, modularity, and debuggability.

This skill guides you through chain design, identifying optimal breakpoints, managing data flow between steps, handling errors, and validating outputs at each stage. It's particularly valuable for tasks that involve multiple distinct phases like research β†’ analysis β†’ synthesis β†’ formatting, or ideation β†’ planning β†’ implementation β†’ review.

Use this skill when you have complex tasks that benefit from sequential processing, when you need intermediate validation between steps, or when different parts of a task require different specialized prompts or tools.

Core Workflows

Workflow 1: Design Prompt Chain from Goal

  1. Clarify the end goal:
  2. What's the final output?
  3. What quality standards apply?
  4. What constraints exist?
  5. Decompose into logical stages:
  6. Identify distinct phases
  7. Determine stage boundaries
  8. Order by dependencies
  9. Design individual prompts:
  10. Purpose of each stage
  11. Input requirements
  12. Output specifications
  13. Success criteria
  14. Define data flow:
  15. What passes between stages?
  16. What format for intermediate outputs?
  17. What state is maintained?
  18. Add validation:
  19. Checkpoints after each stage
  20. Quality gates
  21. Error handling
  22. Document the chain:
  23. Chain purpose
  24. Stage descriptions
  25. Data flow diagram
  26. Usage examples
  27. Test end-to-end

Workflow 2: Execute Existing Chain

  1. Load chain definition:
  2. Read chain specification
  3. Understand stages
  4. Prepare inputs
  5. Initialize chain state:
  6. Set initial inputs
  7. Prepare storage for outputs
  8. Initialize tracking
  9. Execute each stage sequentially:
  10. Run stage prompt
  11. Validate output
  12. If validation fails: Handle error
  13. If validation passes: Continue
  14. Store intermediate result
  15. Pass output to next stage
  16. Monitor progress:
  17. Track current stage
  18. Log outputs
  19. Report status
  20. Validate final output
  21. Report results and any issues

Workflow 3: Debug Chain Failure

  1. Identify failure point:
  2. Which stage failed?
  3. What was the input to that stage?
  4. What error occurred?
  5. Analyze root cause:
  6. Was input malformed?
  7. Was prompt unclear?
  8. Was validation too strict?
  9. Was context insufficient?
  10. Test stage in isolation:
  11. Run stage with known good input
  12. Verify prompt works correctly
  13. Check output format
  14. Fix the issue:
  15. Update prompt if unclear
  16. Adjust validation if too strict
  17. Add error handling if needed
  18. Improve data passing if malformed
  19. Retest from failure point
  20. Document the fix

Workflow 4: Optimize Chain Performance

  1. Analyze current chain:
  2. Execution time per stage
  3. Token usage per stage
  4. Success rate per stage
  5. Bottlenecks
  6. Identify optimization opportunities:
  7. Stages that could be parallelized
  8. Redundant processing
  9. Overly complex prompts
  10. Unnecessary validation
  11. Refactor for efficiency:
  12. Combine related stages
  13. Parallelize independent stages
  14. Simplify prompts
  15. Optimize data passing
  16. Maintain quality:
  17. Don't sacrifice accuracy for speed
  18. Keep validation comprehensive
  19. Preserve error handling
  20. Test optimized chain
  21. Measure improvements

Quick Reference

Action Command/Trigger
Design new chain "Design a prompt chain for [goal]"
Execute chain "Run this chain: [chain spec]"
Debug chain failure "Debug this chain: [error details]"
Optimize chain "Optimize this chain: [chain spec]"
Validate chain design "Review this chain design: [spec]"
Add stage to chain "Add stage for [purpose] to this chain"
Parallelize stages "Which stages can run in parallel?"

Best Practices

  • Keep Stages Focused: Each stage should have one clear purpose
  • Don't mix research and analysis in one prompt
  • Don't combine formatting with content generation
  • Each stage = one transformation

  • Make Outputs Explicit: Define exactly what each stage produces

  • Specify format (JSON, markdown, etc.)
  • Define required fields
  • Set quality criteria
  • Provide examples

  • Validate Between Stages: Catch errors early

  • Check output format
  • Verify required fields exist
  • Validate against criteria
  • Fail fast if something's wrong

  • Handle Errors Gracefully: Plan for failures

  • Define retry logic
  • Provide fallback options
  • Log failures for debugging
  • Don't cascade bad data

  • Maintain State Carefully: Track what you need, discard what you don't

  • Pass only necessary data forward
  • Keep intermediate outputs for debugging
  • Clear state between independent chains
  • Version chain state if long-running

  • Optimize Data Passing: Minimize token usage

  • Extract only needed information
  • Summarize when possible
  • Use references instead of duplication
  • Compress verbose outputs

  • Document Thoroughly: Make chains maintainable

  • Purpose of each stage
  • Expected inputs/outputs
  • Validation rules
  • Error handling
  • Example executions

  • Test Incrementally: Build confidence stage by stage

  • Test each stage in isolation
  • Test pairs of stages
  • Test full chain
  • Test with edge cases

Chain Design Patterns

Sequential Processing

Stage 1: Collect β†’ Stage 2: Process β†’ Stage 3: Format β†’ Output

Use when: Each stage depends on previous stage's complete output
Example: Web scraping β†’ Data cleaning β†’ Analysis β†’ Report generation

Branching Chain

Stage 1: Analyze β†’
  If condition A: Stage 2a β†’ Merge
  If condition B: Stage 2b β†’ Merge
β†’ Stage 3: Synthesize

Use when: Different processing paths based on criteria
Example: File type detection β†’ [JSON parser | CSV parser | XML parser] β†’ Normalize

Parallel Aggregation

Input β†’
  [Stage 1a, Stage 1b, Stage 1c] (parallel) β†’
  Stage 2: Combine β†’
  Output

Use when: Independent analyses that merge later
Example: [Syntax check, Type check, Lint] β†’ Aggregate results β†’ Report

Iterative Refinement

Stage 1: Generate β†’
Stage 2: Critique β†’
  If quality met: Output
  If not: Refine β†’ back to Stage 1 (max N iterations)

Use when: Output quality improves through iteration
Example: Write β†’ Review β†’ [Good? β†’ Done | Revise β†’ Write]

Fan-Out/Fan-In

Stage 1: Split β†’
  [Process chunk 1, Process chunk 2, ..., Process chunk N] β†’
  Stage 2: Merge β†’
  Output

Use when: Large input needs parallel processing
Example: Split document β†’ [Analyze sections] β†’ Synthesize findings

Pipeline with Validation

Stage 1 β†’ Validate β†’ Stage 2 β†’ Validate β†’ Stage 3 β†’ Validate β†’ Output

Use when: Quality gates needed between stages
Example: Generate β†’ Check syntax β†’ Transform β†’ Check schema β†’ Deploy β†’ Verify

Chain Specification Format

chain:
  name: "Chain Name"
  description: "What this chain accomplishes"
  version: "1.0.0"

  stages:
    - id: "stage_1"
      name: "Stage Name"
      prompt: "Prompt template with {{placeholders}}"
      inputs:
        - name: "input_name"
          source: "user_input | previous_stage | context"
          required: true
      outputs:
        - name: "output_name"
          format: "json | markdown | text"
          schema: "Optional JSON schema"
      validation:
        - type: "format | content | schema"
          rule: "Validation rule"
          on_fail: "retry | skip | abort"
      on_error:
        action: "retry | fallback | abort"
        max_retries: 3

    - id: "stage_2"
      name: "Next Stage"
      prompt: "Use {{stage_1.output_name}} to..."
      # ... rest of stage definition

  execution:
    mode: "sequential | parallel | conditional"
    timeout_per_stage: 300
    max_total_time: 1800

Example Chains

Research β†’ Analysis β†’ Report Chain

**Chain**: Research Report Generator

**Stage 1**: Web Research
- Prompt: "Research [topic] using web search. Find 5-10 authoritative sources."
- Output: List of sources with summaries
- Validation: At least 5 sources, each with URL and summary

**Stage 2**: Content Analysis
- Input: Sources from Stage 1
- Prompt: "Analyze these sources and extract key themes, findings, and insights."
- Output: Structured analysis (JSON)
- Validation: JSON schema with required fields

**Stage 3**: Report Writing
- Input: Analysis from Stage 2
- Prompt: "Write executive report based on analysis. Include summary, findings, recommendations."
- Output: Markdown report
- Validation: Contains required sections

**Stage 4**: Formatting
- Input: Report from Stage 3
- Prompt: "Format report for [platform] with proper structure and styling."
- Output: Platform-ready document

Code Generation β†’ Review β†’ Test Chain

**Chain**: Tested Code Generator

**Stage 1**: Generate Code
- Prompt: "Generate [component] with [requirements]"
- Output: Code file(s)
- Validation: Valid syntax, includes all required functions

**Stage 2**: Code Review
- Input: Code from Stage 1
- Prompt: "Review code for bugs, performance issues, best practices"
- Output: Review findings (JSON)
- Validation: Categorized by severity

**Stage 3**: Apply Fixes
- Input: Code and Review findings
- Prompt: "Fix high and medium severity issues"
- Output: Revised code
- Validation: Addresses all high-severity issues

**Stage 4**: Generate Tests
- Input: Final code
- Prompt: "Generate unit tests with >80% coverage"
- Output: Test file(s)
- Validation: Tests run and pass

**Stage 5**: Verify
- Input: Code and tests
- Action: Run tests
- Output: Test results
- Validation: All tests pass

Content Creation Chain

**Chain**: Blog Post Creator

**Stage 1**: Research & Ideation
- Prompt: "Research [topic] and generate 5 article angles"
- Output: List of angles with brief descriptions

**Stage 2**: Select & Outline
- Input: Angles from Stage 1
- Prompt: "Select best angle and create detailed outline"
- Output: Article outline

**Stage 3**: Draft Content
- Input: Outline from Stage 2
- Prompt: "Write full article following outline"
- Output: Article draft (markdown)

**Stage 4**: Edit & Polish
- Input: Draft from Stage 3
- Prompt: "Edit for clarity, flow, grammar, and engagement"
- Output: Polished article

**Stage 5**: Generate Metadata
- Input: Article from Stage 4
- Prompt: "Generate title variations, meta description, tags"
- Output: SEO metadata

**Stage 6**: Format for Platform
- Input: Article and metadata
- Prompt: "Format for [CMS] with proper structure"
- Output: Platform-ready post

Debugging Chains

When a chain fails:

  1. Isolate the stage: Run failed stage independently
  2. Check inputs: Verify data passed to stage is valid
  3. Inspect output: See what stage actually produced
  4. Review prompt: Is it clear and achievable?
  5. Test validation: Is validation rule appropriate?
  6. Check context: Does stage have needed information?
  7. Review logs: What happened during execution?

Monitoring Chain Health

Track these metrics:

  • Success rate: % of chains completing successfully
  • Stage failure rate: Which stages fail most often?
  • Execution time: How long does chain take?
  • Token usage: Cost per chain execution
  • Retry rate: How often do stages need retries?
  • Quality scores: How good are final outputs?

# Supported AI Coding Agents

This skill is compatible with the SKILL.md standard and works with all major AI coding agents:

Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.