Agent skill

Dspy Advanced Module Composition

by OmidZamani in OmidZamani/dspy-skills

A skill your agent uses for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.

MITAuto-check passed

Install Dspy Advanced Module Composition

skills CLI
$ npx skills add OmidZamani/dspy-skills --skill dspy-advanced-module-composition -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install OmidZamani/dspy-skills dspy-advanced-module-composition --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/OmidZamani/dspy-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/dspy-advanced-module-composition .claude/skills/dspy-advanced-module-composition && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
dspy-advanced-module-composition
GitHub stars
124
Token cost
~2.2k tokens
SKILL.md length
219 words
Files
2
Skills in repo
17
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.

  • Works in 4 steps: Ensemble Voting → MultiChainComparison → Sequential Composition → …
  • Composing DSPy modules with Ensemble
  • SKILL.md covers Goal, When to Use, Related Skills and Inputs, plus 6 more sections
  • Runs Python scripts from its folder

What it does

Dspy Advanced Module Composition is an agent skill from OmidZamani/dspy-skills. Use for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.

Its SKILL.md is about 2.2k tokens, which your agent loads only when the skill is triggered. The skill folder holds 1 other file (for example `example.py`).

The repository describes itself as: Collection of Claude Skills for DSPy framework - program language models, optimize prompts, and build RAG pipelines systematically. The licence is MIT.

When your agent uses it

  • Composing DSPy modules with Ensemble
  • MultiChainComparison
  • Ensemble voting
  • Sequential pipelines

Example prompts

  • “/dspy-advanced-module-composition”

Requirements

  • Python 3
  • Pre-approved tools (allowed-tools): Read, Write, Glob, Grep

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. Ensemble Voting
  2. MultiChainComparison
  3. Sequential Composition
  4. Fallback Strategies

What it can do on your machine

Read from SKILL.md and the folder at commit f5db3b7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Glob
    • Grep

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • dspy.ai
    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Dspy Advanced Module Composition loads about 2.2k tokens when it runs. Until then it costs about 42 tokens; SKILL.md has 219 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~42
When it runs · the whole SKILL.md, loaded when a task matches
~2.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from OmidZamani/dspy-skills at commit f5db3b7, republished under its MIT licence (© OmidZamani). 219 words, ~2,159 tokens.

Download SKILL.mdSave it as .claude/skills/dspy-advanced-module-composition/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
dspy-advanced-module-composition
description
Use for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.
allowed-tools
Read, Write, Glob, Grep
version
1.0.0
dspy-compatibility
3.2.1
tags
reasoning, optimizer

DSPy Advanced Module Composition

Goal

Compose complex DSPy programs using the Ensemble optimizer, MultiChainComparison for reasoning synthesis, and sequential module patterns.

When to Use

  • Need consensus from multiple approaches
  • Comparing different reasoning strategies
  • Building robust pipelines with fallbacks
  • Complex multi-step workflows with branching
  • Ensemble methods for improved accuracy

Inputs

InputTypeDescription
moduleslist[dspy.Module]Modules to compose
composition_typestr"ensemble", "sequential", "comparison"

Outputs

OutputTypeDescription
composed_programdspy.ModuleComposed multi-module program

Workflow

Phase 1: Ensemble Voting

Combine multiple programs using the Ensemble optimizer:

python
import dspy
from dspy.teleprompt import Ensemble

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))

# Define a signature for the task
class BasicQA(dspy.Signature):
    """Answer questions with short factoid answers."""
    question = dspy.InputField()
    answer = dspy.OutputField()

# Create multiple program instances (should be optimized/compiled programs)
# For simple demonstration, we'll use different predictors
program1 = dspy.Predict(BasicQA)
program2 = dspy.ChainOfThought(BasicQA)
program3 = dspy.Predict(BasicQA)

# Ensemble is an optimizer that compiles programs together
ensemble = Ensemble(reduce_fn=dspy.majority)
ensembled_program = ensemble.compile([program1, program2, program3])

# Use the ensembled program
result = ensembled_program(question="What is 2 + 2?")
print(result.answer)  # Voted answer
Phase 2: MultiChainComparison

Compare multiple reasoning attempts:

python
import dspy

class BasicQA(dspy.Signature):
    """Answer questions with short factoid answers."""
    question = dspy.InputField()
    answer = dspy.OutputField(desc="often between 1 and 5 words")

class ComparisonPipeline(dspy.Module):
    def __init__(self):
        # Generate multiple reasoning attempts
        self.cot = dspy.ChainOfThought(BasicQA)

        # Compare M attempts and select best
        # Must pass a Signature class, not a string
        self.compare = dspy.MultiChainComparison(
            BasicQA,
            M=3,  # Number of attempts to compare
            temperature=0.7
        )

    def forward(self, question):
        # Generate multiple completions to compare
        # Each completion must have rationale/reasoning field
        completions = [
            self.cot(question=question)
            for _ in range(3)
        ]

        # MultiChainComparison synthesizes them into best answer
        # Pass completions as positional arg, not keyword arg
        return self.compare(completions, question=question)

# Usage
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
pipeline = ComparisonPipeline()
result = pipeline(question="Explain quantum computing")
print(f"Best answer: {result.answer}")
print(f"Rationale: {result.rationale}")
Phase 3: Sequential Composition

Chain modules for multi-step workflows:

python
import dspy

# Define signatures for each step
class QueryRewrite(dspy.Signature):
    """Rewrite a question for better retrieval."""
    question = dspy.InputField()
    refined_query: str = dspy.OutputField()

class GenerateAnswer(dspy.Signature):
    """Generate answer from context and question."""
    context = dspy.InputField()
    question = dspy.InputField()
    answer = dspy.OutputField()

class ValidateAnswer(dspy.Signature):
    """Validate answer quality."""
    answer = dspy.InputField()
    question = dspy.InputField()
    is_valid: bool = dspy.OutputField()
    confidence: float = dspy.OutputField()

class SequentialRAG(dspy.Module):
    """Multi-step RAG pipeline."""

    def __init__(self):
        # Step 1: Query rewriting
        self.rewrite = dspy.Predict(QueryRewrite)

        # Step 2: Retrieval
        self.retrieve = dspy.Retrieve(k=5)

        # Step 3: Answer generation
        self.generate = dspy.ChainOfThought(GenerateAnswer)

        # Step 4: Validation
        self.validate = dspy.Predict(ValidateAnswer)

    def forward(self, question):
        # Sequential execution
        refined = self.rewrite(question=question)
        passages = self.retrieve(refined.refined_query).passages

        answer_pred = self.generate(
            context=passages,
            question=question
        )

        validation = self.validate(
            answer=answer_pred.answer,
            question=question
        )

        return dspy.Prediction(
            answer=answer_pred.answer,
            is_valid=validation.is_valid,
            confidence=validation.confidence
        )

# Usage
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
rag = SequentialRAG()
result = rag(question="What causes lightning?")
print(f"Answer: {result.answer} (valid: {result.is_valid})")
Phase 4: Fallback Strategies

Handle failures with fallback modules:

python
import dspy
import logging

logger = logging.getLogger(__name__)

class BasicQA(dspy.Signature):
    """Answer questions with short factoid answers."""
    question = dspy.InputField()
    answer = dspy.OutputField()

class RobustQA(dspy.Module):
    """Fallback strategy for errors."""

    def __init__(self):
        self.primary = dspy.ChainOfThought(BasicQA)
        self.fallback = dspy.Predict(BasicQA)

    def forward(self, question):
        try:
            result = self.primary(question=question)
            if result.answer and len(result.answer) > 10:
                return result
        except Exception as e:
            logger.error(f"Primary failed: {e}")

        return self.fallback(question=question)

Production Example

python
import dspy
from dspy.teleprompt import BootstrapFewShot, Ensemble

class GenerateAnswer(dspy.Signature):
    """Generate answer from context and question."""
    context = dspy.InputField()
    question = dspy.InputField()
    answer = dspy.OutputField()

class MultiStrategyQA(dspy.Module):
    """Production QA with retrieval."""

    def __init__(self):
        self.retrieve = dspy.Retrieve(k=3)
        self.generate = dspy.ChainOfThought(GenerateAnswer)

    def forward(self, question: str):
        context = self.retrieve(question).passages
        return self.generate(context=context, question=question)

# Usage with optimization
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
qa = MultiStrategyQA()

# First, optimize the base program
optimizer = BootstrapFewShot(
    metric=lambda ex, pred, trace: ex.answer in pred.answer,
    max_bootstrapped_demos=3
)

compiled_qa = optimizer.compile(qa, trainset=trainset)

# Then create ensemble from multiple optimized programs
# (train with different seeds or optimizers to get diversity)
program1 = optimizer.compile(qa, trainset=trainset)
program2 = optimizer.compile(qa, trainset=trainset)
program3 = optimizer.compile(qa, trainset=trainset)

ensemble = Ensemble(reduce_fn=dspy.majority)
final_program = ensemble.compile([program1, program2, program3])

Best Practices

  1. Test modules independently - Validate each module before composition
  2. Handle failures gracefully - Use try/except in parallel composition
  3. Balance cost vs accuracy - Ensembles are expensive (N × cost)
  4. Optimize composed programs - Use BootstrapFewShot or MIPROv2 on final composition
  5. Module reusability - Design modules to work in multiple compositions

Limitations

  • Ensemble increases cost linearly with module count
  • Voting strategies may not work for all output types
  • Sequential composition amplifies latency
  • Error propagation in chains can be hard to debug
  • Parallel composition requires careful state management

Official Documentation

© OmidZamani, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in skills/dspy-advanced-module-composition of OmidZamani/dspy-skills.

  • SKILL.md
  • example.py

Open the folder on GitHubat commit f5db3b7

Compare with similar skills

Dspy Advanced Module Composition next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Dspy Advanced Module Composition compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Dspy Advanced Module Composition this skillOmidZamani/dspy-skills124—~2.2kAutomated safety check: PassMIT
Cursor Advanced Composerjeremylongshore/tons-of-skills-marketplace2.8k—~2.3kAutomated safety check: PassMIT
Motion Advancedaffaan-m/ECC276k1 repos~4.7kAutomated safety check: PassMIT
DSPy Language Model ProgrammingOrchestra-Research/AI-Research-SKILLs13k9 repos~3.8kAutomated safety check: PassMIT
Es Modulesthedaviddias/Front-End-Checklist74k—~482Automated safety check: PassMIT
Composition Patternssickn33/agentic-awesome-skills47k1 repos~742Automated safety check: PassMIT

Similar skills

  • Cursor Advanced Composer

    jeremylongshore/tons-of-skills-marketplace

    Advanced Cursor Composer techniques: agent mode, parallel agents, complex refactoring, and multi-step orchestration.

    2.8k GitHub stars~2.3k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Motion Advanced

    affaan-m/ECC

    Advanced motion patterns for React / Next.js — drag & drop, gestures, text animations, SVG path drawing, custom hooks, imperative sequences (useAnimate), loaders, and the full API decision tree.

    276k GitHub starsUsed in 1 repo~4.7k tokens
    Auto-check passed
  • DSPy Language Model Programming

    Orchestra-Research/AI-Research-SKILLs

    Teaches an agent to build LM pipelines, RAG systems and agents in DSPy using signatures, modules and optimizers instead of hand-tuned prompts.

    13k GitHub starsUsed in 9 repos~3.8k tokens
    AI & LLM EngineeringAuto-check passed
  • Es Modules

    thedaviddias/Front-End-Checklist

    A skill your agent uses when reviewing scripts, client components, bundles, or runtime behavior related to Use ES modules (import/export).

    74k GitHub stars~482 tokensUpdated 3 days ago
    Auto-check passed
  • Composition Patterns

    sickn33/agentic-awesome-skills

    A skill your agent uses when working with composition-patterns tasks or workflows

    47k GitHub starsUsed in 1 repo~742 tokens
    DevelopmentAuto-check passed
  • Docker Compose

    sickn33/agentic-awesome-skills

    Define and run multi-container Docker applications using Docker Compose.

    47k GitHub starsUsed in 1 repo~2.2k tokens
    DevOps & CloudAuto-check: notes

More from OmidZamani/dspy-skills

All 17 skills in this repo
  • Skill Perfection

    OmidZamani/dspy-skills

    A skill your agent uses when you need to QA audit and fix a plugin skill file.

    124 GitHub stars~1.6k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Haystack Integration

    OmidZamani/dspy-skills

    A skill your agent uses for integrating DSPy with Haystack, optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts.

    124 GitHub stars~1.4k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Adapters Multimodal

    OmidZamani/dspy-skills

    A skill your agent uses for DSPy adapter selection, JSONAdapter, XMLAdapter, ChatAdapter, native function calling, structured outputs, and multimodal inputs like dspy.Image or dspy.Audio.

    124 GitHub stars~864 tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Better Together

    OmidZamani/dspy-skills

    A skill your agent uses for BetterTogether, prompt plus weight optimization, fine-tuning sequences, and strategy chains like p - w - p.

    124 GitHub stars~756 tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Bootstrap Fewshot

    OmidZamani/dspy-skills

    A skill your agent uses for BootstrapFewShot, bootstrapped demonstrations, teacher-model demos, and low-data DSPy prompt optimization.

    124 GitHub stars~1.3k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Custom Module Design

    OmidZamani/dspy-skills

    A skill your agent uses for creating custom DSPy modules, extending dspy.Module, reusable components, stateful modules, serialization, and module testing.

    124 GitHub stars~1.9k tokensUpdated 3 mo ago
    Auto-check passed

Questions about Dspy Advanced Module Composition

What does Dspy Advanced Module Composition do?

A skill your agent uses for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows. Dspy Advanced Module Composition is an agent skill from OmidZamani/dspy-skills. Use for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.

When should I use Dspy Advanced Module Composition?

Dspy Advanced Module Composition fits situations like: composing DSPy modules with Ensemble; multiChainComparison; ensemble voting; sequential pipelines.

How do I install Dspy Advanced Module Composition in Claude Code?

Run `npx skills add OmidZamani/dspy-skills --skill dspy-advanced-module-composition -a claude-code`. Or copy the skill folder (skills/dspy-advanced-module-composition in OmidZamani/dspy-skills) into .claude/skills/dspy-advanced-module-composition in your project. Claude Code loads it when a task matches its description.

How do I install Dspy Advanced Module Composition in Codex?

Run `npx skills add OmidZamani/dspy-skills --skill dspy-advanced-module-composition -a codex`. Or copy the skill folder (skills/dspy-advanced-module-composition in OmidZamani/dspy-skills) into .agents/skills/dspy-advanced-module-composition in your project. Codex loads it when a task matches its description.

Can I use Dspy Advanced Module Composition in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add OmidZamani/dspy-skills --skill dspy-advanced-module-composition -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/dspy-advanced-module-composition, .gemini/skills/dspy-advanced-module-composition, .github/skills/dspy-advanced-module-composition and .opencode/skills/dspy-advanced-module-composition in your project.

What does Dspy Advanced Module Composition need to run?

Going by SKILL.md and its folder, Dspy Advanced Module Composition needs Python for the scripts in its folder. Our summary lists: Python 3. Its frontmatter pre-approves these tools: Read, Write, Glob, Grep.

Does Dspy Advanced Module Composition access the network?

SKILL.md names 2 domains. As links in the text: dspy.ai and github.com. This is read from the text; nothing was executed.

Is Dspy Advanced Module Composition safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Dspy Advanced Module Composition use?

Dspy Advanced Module Composition is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Dspy Advanced Module Composition use?

About 2.2k tokens (SKILL.md is roughly 8.6k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Dspy Advanced Module Composition?

Skills that share tags, products or a category with Dspy Advanced Module Composition: Cursor Advanced Composer (jeremylongshore/tons-of-skills-marketplace, 2.8k stars), Motion Advanced (affaan-m/ECC, 276k stars), DSPy Language Model Programming (Orchestra-Research/AI-Research-SKILLs, 13k stars) and Es Modules (thedaviddias/Front-End-Checklist, 74k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Dspy Advanced Module Composition?

OmidZamani (a GitHub user) maintains it in OmidZamani/dspy-skills, which has 124 GitHub stars. The repository holds 17 skills in this directory. The repository was last updated on June 23, 2026.

Source: OmidZamani/dspy-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.