Agent skill

Dspy Custom Module Design

by OmidZamani in OmidZamani/dspy-skills

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

MITAuto-check passed

Install Dspy Custom Module Design

skills CLI
$ npx skills add OmidZamani/dspy-skills --skill dspy-custom-module-design -a claude-code

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

GitHub CLI
$ gh skill install OmidZamani/dspy-skills dspy-custom-module-design --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-custom-module-design .claude/skills/dspy-custom-module-design && 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-custom-module-design
GitHub stars
123
Token cost
~1.9k tokens
SKILL.md length
221 words
Files
2
Skills in repo
17
Repo updated
First seen
Licence
MIT

At a glance

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

  • Works in 4 steps: Basic Module Structure → Stateful Modules → Error Handling and Validation → …
  • Creating custom DSPy modules
  • 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 Custom Module Design is an agent skill from OmidZamani/dspy-skills. Use for creating custom DSPy modules, extending dspy.Module, reusable components, stateful modules, serialization, and module testing.

Its SKILL.md is about 1.9k 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

  • Creating custom DSPy modules
  • Extending dspy.Module
  • Reusable components
  • Stateful modules

Example prompts

  • “/dspy-custom-module-design”

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. Basic Module Structure
  2. Stateful Modules
  3. Error Handling and Validation
  4. Serialization

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 Custom Module Design loads about 1.9k tokens when it runs. Until then it costs about 40 tokens; SKILL.md has 221 words of instructions outside code blocks.

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

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). 221 words, ~1,937 tokens.

Download SKILL.mdSave it as .claude/skills/dspy-custom-module-design/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
dspy-custom-module-design
description
Use for creating custom DSPy modules, extending dspy.Module, reusable components, stateful modules, serialization, and module testing.
allowed-tools
Read, Write, Glob, Grep
version
1.0.0
dspy-compatibility
3.2.1
tags
production, reasoning

DSPy Custom Module Design

Goal

Design production-quality custom DSPy modules with proper architecture, state management, serialization, and testing patterns.

When to Use

  • Building reusable DSPy components
  • Complex logic beyond built-in modules
  • Need custom state management
  • Sharing modules across projects
  • Production deployment requirements

Inputs

InputTypeDescription
task_descriptionstrWhat the module should do
componentslistSub-modules or predictors
statedictStateful attributes

Outputs

OutputTypeDescription
custom_moduledspy.ModuleProduction-ready module

Workflow

Phase 1: Basic Module Structure

All custom modules inherit from dspy.Module:

python
import dspy

class BasicQA(dspy.Module):
    """Simple question answering module."""

    def __init__(self):
        super().__init__()
        self.predictor = dspy.Predict("question -> answer")

    def forward(self, question):
        """Entry point for module execution."""
        return self.predictor(question=question)

# Usage
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
qa = BasicQA()
result = qa(question="What is Python?")
print(result.answer)
Phase 2: Stateful Modules

Modules can maintain state across calls:

python
import dspy
import logging

logger = logging.getLogger(__name__)

class StatefulRAG(dspy.Module):
    """RAG with query caching."""

    def __init__(self, cache_size=100):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=3)
        self.generate = dspy.ChainOfThought("context, question -> answer")
        self.cache = {}
        self.cache_size = cache_size

    def forward(self, question):
        # Check cache
        if question in self.cache:
            return self.cache[question]

        # Retrieve and generate
        passages = self.retrieve(question).passages
        result = self.generate(context=passages, question=question)

        # Update cache with size limit
        if len(self.cache) >= self.cache_size:
            self.cache.pop(next(iter(self.cache)))
        self.cache[question] = result

        return result
Phase 3: Error Handling and Validation

Production modules need robust error handling:

python
import dspy
from typing import Optional
import logging

logger = logging.getLogger(__name__)

class RobustClassifier(dspy.Module):
    """Classifier with validation."""

    def __init__(self, valid_labels: list[str]):
        super().__init__()
        self.valid_labels = set(valid_labels)
        self.classify = dspy.Predict("text -> label: str, confidence: float")

    def forward(self, text: str) -> dspy.Prediction:
        if not text or not text.strip():
            return dspy.Prediction(label="unknown", confidence=0.0, error="Empty input")

        try:
            result = self.classify(text=text)

            # Validate label
            if result.label not in self.valid_labels:
                result.label = "unknown"
                result.confidence = 0.0

            return result

        except Exception as e:
            logger.error(f"Classification failed: {e}")
            return dspy.Prediction(label="unknown", confidence=0.0, error=str(e))
Phase 4: Serialization

Modules support save/load:

python
import dspy

# Save module state
module = MyCustomModule()
module.save("my_module.json")

# Load requires creating instance first, then loading state
loaded = MyCustomModule()
loaded.load("my_module.json")

# For loading entire programs (dspy>=2.6.0)
module.save("./my_module/", save_program=True)
loaded = dspy.load("./my_module/")

Production Example

python
import dspy
from typing import List, Optional
import logging

logger = logging.getLogger(__name__)

class ProductionRAG(dspy.Module):
    """Production-ready RAG with all best practices."""

    def __init__(
        self,
        retriever_k: int = 5,
        cache_enabled: bool = True,
        cache_size: int = 1000
    ):
        super().__init__()

        # Configuration
        self.retriever_k = retriever_k
        self.cache_enabled = cache_enabled
        self.cache_size = cache_size

        # Components
        self.retrieve = dspy.Retrieve(k=retriever_k)
        self.generate = dspy.ChainOfThought("context, question -> answer")

        # State
        self.cache = {} if cache_enabled else None
        self.call_count = 0

    def forward(self, question: str) -> dspy.Prediction:
        """Execute RAG pipeline with caching."""
        self.call_count += 1

        # Validation
        if not question or not question.strip():
            return dspy.Prediction(
                answer="Please provide a valid question.",
                error="Invalid input"
            )

        # Cache check
        if self.cache_enabled and question in self.cache:
            logger.info(f"Cache hit (call #{self.call_count})")
            return self.cache[question]

        # Execute pipeline
        try:
            passages = self.retrieve(question).passages

            if not passages:
                logger.warning("No passages retrieved")
                return dspy.Prediction(
                    answer="No relevant information found.",
                    passages=[]
                )

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

            # Update cache
            if self.cache_enabled:
                self._update_cache(question, result)

            return result

        except Exception as e:
            logger.error(f"RAG execution failed: {e}")
            return dspy.Prediction(
                answer="An error occurred while processing your question.",
                error=str(e)
            )

    def _update_cache(self, key: str, value: dspy.Prediction):
        """Manage cache with size limit."""
        if len(self.cache) >= self.cache_size:
            self.cache.pop(next(iter(self.cache)))
        self.cache[key] = value

    def clear_cache(self):
        """Clear cache."""
        if self.cache_enabled:
            self.cache.clear()

Best Practices

  1. Single responsibility - Each module does one thing well
  2. Validate inputs - Check for None, empty strings, invalid types
  3. Handle errors - Return Predictions with error fields, never raise
  4. Log important events - Cache hits, errors, validation failures
  5. Test independently - Unit test modules before composition

Limitations

  • State increases memory usage (careful with large caches)
  • Serialization doesn't automatically save custom state
  • Module testing requires mocking LM calls
  • Deep module hierarchies can be hard to debug
  • Performance overhead from validation in hot paths

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-custom-module-design of OmidZamani/dspy-skills.

  • SKILL.md
  • example.py

Open the folder on GitHubat commit f5db3b7

Compare with similar skills

Dspy Custom Module Design 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 Custom Module Design compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Dspy Custom Module Design this skillOmidZamani/dspy-skills123—~1.9kAutomated safety check: PassMIT
Abp Moduleabpframework/abp14k—~1.6kAutomated safety check: PassLGPL-3.0
DSPy Language Model ProgrammingOrchestra-Research/AI-Research-SKILLs13k9 repos~3.8kAutomated safety check: PassMIT
Es Modulesthedaviddias/Front-End-Checklist74k—~482Automated safety check: PassMIT
Terraform Module Librarywshobson/agents40k11 repos~1.3kAutomated safety check: PassMIT
Splitting Oversized ModulesPostHog/posthog40k—~2.2kAutomated safety check: PassCustom licence

Similar skills

  • Abp Module

    abpframework/abp

    ABP reusable Module solution template - EF Core + MongoDB dual support, virtual methods for extensibility, DbTablePrefix, module options pattern, entity extension, separate connection string.

    14k GitHub stars~1.6k tokensUpdated today
    DatabasesAuto-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 4 days ago
    Auto-check passed
  • Build reusable, tested Terraform modules for AWS, Azure, GCP and OCI, with a standard file layout, an AWS VPC example, versioning rules and Terratest checks.

    40k GitHub starsUsed in 11 repos~1.3k tokens
    DevOps & CloudAuto-check passed
  • Official

    Split an oversized Python module (a thousand-plus-line logic.py, models.py, api.py, or its test file) into a package of one module per concern, mechanically and provably without changing behavior.

    40k GitHub stars~2.2k tokensUpdated today
    Frontend & DesignAuto-check passed
  • Extract Module

    JetBrains/intellij-community

    Official

    Extract optional plugin dependencies into IntelliJ content modules.

    21k GitHub stars~5.2k tokensUpdated today
    MobileAuto-check passed

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.

    123 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.

    123 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.

    123 GitHub stars~864 tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Advanced Module Composition

    OmidZamani/dspy-skills

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

    123 GitHub stars~2.2k 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.

    123 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.

    123 GitHub stars~1.3k tokensUpdated 3 mo ago
    Auto-check passed

Questions about Dspy Custom Module Design

What does Dspy Custom Module Design do?

A skill your agent uses for creating custom DSPy modules, extending dspy.Module, reusable components, stateful modules, serialization, and module testing. Dspy Custom Module Design is an agent skill from OmidZamani/dspy-skills.Module, reusable components, stateful modules, serialization, and module testing.

When should I use Dspy Custom Module Design?

Dspy Custom Module Design fits situations like: creating custom DSPy modules; extending dspy.Module; reusable components; stateful modules.

How do I install Dspy Custom Module Design in Claude Code?

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

How do I install Dspy Custom Module Design in Codex?

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

Can I use Dspy Custom Module Design 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-custom-module-design -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-custom-module-design, .gemini/skills/dspy-custom-module-design, .github/skills/dspy-custom-module-design and .opencode/skills/dspy-custom-module-design in your project.

What does Dspy Custom Module Design need to run?

Going by SKILL.md and its folder, Dspy Custom Module Design 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 Custom Module Design 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 Custom Module Design 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 Custom Module Design use?

Dspy Custom Module Design 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 Custom Module Design use?

About 1.9k tokens (SKILL.md is roughly 7.7k 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 Custom Module Design?

Skills that share tags, products or a category with Dspy Custom Module Design: Abp Module (abpframework/abp, 14k stars), DSPy Language Model Programming (Orchestra-Research/AI-Research-SKILLs, 13k stars), Es Modules (thedaviddias/Front-End-Checklist, 74k stars) and Terraform Module Library (wshobson/agents, 40k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Dspy Custom Module Design?

OmidZamani (a GitHub user) maintains it in OmidZamani/dspy-skills, which has 123 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.