A DSPy module encapsulates a prompting technique or workflow. A module composed inside another module is a submodule: the enclosing module invokes it as part of its computation. A module instance, also called a program, can be called like a function. section 2.2 section 7.1 section 7.2
A signature specifies inputs and outputs; a module determines how to carry out the task. For example, Predict uses a simple prompting technique, while ChainOfThought also requests reasoning. A program normally returns a Prediction. Calling it invokes its forward() method; in DSPy 3.0, calling forward() directly produces a warning. section 2.6 section 2.9
To compose a custom module, subclass dspy.Module, call super().__init__(), and create or accept submodules in __init__(). Implement forward() to gather inputs, call submodules, process their outputs, and return the result, normally a Prediction. Inputs may come from the caller or earlier submodule results. Custom modules can themselves be nested as submodules. section 7.2 section 7.9
Listing 7.2 A minimal custom module
class SimpleModule(dspy.Module):
def __init__(self): #1
super().__init__()
self.query = dspy.Predict("input -> output") #2
def forward(self, input): #3
return self.query(input=input)
prog = SimpleModule() #4
prog(input="What is the capital of France?")
This minimal wrapper creates a Predict submodule and delegates its input to it. Configure an LM before running it. section 7.2
Composition can add ordinary Python logic, tool calls, or multiple LM calls. For example, a workflow can check a message for toxicity before invoking an intent classifier, or pass a clarified question to a second submodule. A submodule can also be supplied as a parameter: BestOfN calls one repeatedly and uses a reward function to select a result. section 7.1 section 7.4.3 section 7.6.1 section 7.3.2
Encapsulating a repeated workflow avoids duplicating its call sequence and allows the full workflow to be optimized together. BootstrapFewShot can use a successful end-to-end run to create demonstrations from intermediate submodule inputs and outputs. Keep programs separate when intermediate results are useful elsewhere or specialized steps are easier to optimize independently. section 7.6.1 section 7.7
