Chapter 3

Modules

Modules are the building blocks that bring signatures to lifeβ€”they implement the actual LM calls and can be composed into complex pipelines.

7 Sections ~2-3 hours ⭐⭐ Intermediate

🧩 Building with Modules

From simple predictors to complex multi-step pipelines

What You'll Learn

By the end of this chapter, you will:

βœ… Understand the role of modules in DSPy
βœ… Use all built-in modules (Predict, ChainOfThought, ReAct, etc.)
βœ… Create custom modules by subclassing dspy.Module
βœ… Compose modules into multi-step pipelines
βœ… Handle state and data flow between modules
βœ… Build production-ready modular systems

Chapter Overview

This chapter takes you from basic module usage to building sophisticated LM applications:

πŸ“–

What Are Modules?

Understand modules as the "how" to signatures' "what"β€”the executable components.

πŸ”§

Built-in Modules

Master Predict, ChainOfThought, ProgramOfThought, ReAct, and more.

πŸ—οΈ

Creating Custom Modules

Build your own modules with __init__ and forward methods.

πŸ”—

Module Composition

Combine modules into pipelines and handle complex workflows.

πŸ‹οΈ

Exercises

Build real-world modules and pipelines hands-on.

Modules vs. Signatures

Understanding the relationship between signatures and modules is key:

πŸ“ Signatures

# WHAT to do (specification)
class Summarize(dspy.Signature):
    """Summarize the text."""
    text: str = dspy.InputField()
    summary: str = dspy.OutputField()
Defines inputs/outputs Declarative contract No execution logic

🧩 Modules

# HOW to do it (implementation)
summarize = dspy.Predict(Summarize)

# Or with reasoning
summarize = dspy.ChainOfThought(Summarize)

result = summarize(text="...")
Executes the signature Adds behavior (CoT, etc.) Can be composed

Key Concepts Preview

⚑

dspy.Predict

Basic module that executes a signature with a single LM call.

πŸ’­

dspy.ChainOfThought

Adds step-by-step reasoning before generating the final answer.

πŸ› οΈ

dspy.ReAct

Enables tool use with an action-observation loop.

πŸ”„

dspy.Module

Base class for creating custom modules with complex logic.

Prerequisites

Before starting this chapter, ensure you have:

βœ… Completed Chapter 1 (DSPy Fundamentals)
βœ… Completed Chapter 2 (Signatures)
βœ… Python classes understanding (init, methods, inheritance)
βœ… Working DSPy environment with API keys
πŸ’‘

Note: This chapter builds heavily on Signatures from Chapter 2. Make sure you're comfortable creating class-based signatures.

πŸš€

Let's Build!

Ready to turn your signatures into powerful, composable modules? Let's start!