liveBook · Manning

Multi-step module

As explained in Building LLM Applications with DSPy

A DSPy module that performs a task through multiple language-model calls, potentially passing intermediate results between calls.

A multi-step module performs a task through multiple language-model calls, passing intermediate results between steps. It can simplify an input before answering it or break a complex question into subquestions and combine their answers. section 5.3 section 7.4.2

Design and optimize the steps as a workflow:

  • Each call can have its own prompt; a complex-question workflow may use separate prompts for decomposition, subquestions, and the final answer. section 5.3
  • Training examples can specify only the module’s inputs and final outputs, without exposing intermediate calls; DSPy can bootstrap demonstrations for those calls. section 5.3
  • Multiple steps may cost more than one, so keep step inputs and outputs focused and consider lower-cost models for simpler processing. section 7.4.2
Listing 7.12 Rewording the input with a stronger LM
class PredictWithConciseQuestion(dspy.Module):
    def __init__(self):
        self.query1 = dspy.Predict("question -> concise_question")
        self.query2 = dspy.Predict("question -> answer")

    def forward(self, input: str):
        with dspy.context(lm=gpt4o): 
          concise_question = self.query1(question=input).concise_question
        return self.query2(question=concise_question)

gpt4o = dspy.LM(model='gpt-4o')
gpt4omini = dspy.LM(model='gpt-4o-mini')
dspy.configure(lm=gpt4omini)
prog = PredictWithConciseQuestion()
prog("I'm visiting Spain, a country I enjoy visiting, and would like to know what the capital of that country is")

A DSPy module first makes a question concise with one Predict submodule, then passes it to a second submodule to answer. section 7.4.2

How Building LLM Applications with DSPy covers it

How deep it goes
Explains intermediate calls and prompt optimization, contrasts endpoint-only examples, and illustrates a two-step implementation.
Examples
Uses question shortening before answering, airline utterance cleanup, and complex-question decomposition as examples.
What you can do after
Build it from scratch by composing DSPy Predict submodules and assigning different language models to steps.
How it connects
Connects DSPy modules with Predict, language models, prompting, and BootstrapFewShot optimization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building LLM Applications with DSPy. The section links point to the parts of the book it draws on.