liveBook · Manning

Chapter 7: Custom modules

What you will learn in chapter 7 of Building LLM Applications with DSPy

The introduction explains why custom DSPy modules are useful for implementing prompting techniques and building LM-based applications.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction explains why custom DSPy modules are useful for implementing prompting techniques and building LM-based applications.

Key terms: custom modules, built-in modules, prompting techniques, agents, retrieval-augmented generation (RAG)

7.1 Types of DSPy modules

This section distinguishes single-call prompting modules from multistep workflows and explains how DSPy’s modular design makes custom modules reusable and optimizable.

Key terms: DSPy modules, LM call, prompting technique, workflow, submodules, Predict, ChainOfThought, modularity, adapters, retries

7.2 Coding a custom module

This section explains the required structure of a DSPy custom module, how its forward method coordinates work, and when the module itself needs a signature.

Key terms: dspy.Module, __init__(), forward(), Prediction, submodules, tools, inputs, outputs, signature, input fields

7.3 DSPy’s built-in modules

Introduces the four built-in DSPy modules covered in the following subsections.

7.3.1 ChainOfThought

Explains how ChainOfThought adds a reasoning output to a signature while making just one Predict call, and what that design shows about building custom DSPy modules.

Key terms: ChainOfThought, Predict, rationale field, OutputField, signature, __init__(), forward(), aforward(), Predict submodule, ensure_signature()

7.3.2 BestOfN

This section explains how BestOfN runs one submodule repeatedly, scores its predictions, and returns the best one.

Key terms: BestOfN, submodule, N, temperature, best_pred, threshold, reward_fn, reward function, inference time, ground truth output fields

7.3.3 MultiChainComparison

Explains how MultiChainComparison combines earlier predictions and their reasoning into one final prediction, using a single Predict submodule.

Key terms: MultiChainComparison, prediction, BestOfN, Predict, __init__(), forward(), signature, completions, kwargs, last output field

7.3.4 Refine

This section explains how DSPy Refine scores a submodule’s responses, generates advice after unsuccessful attempts, and uses that advice to improve subsequent calls.

Key terms: Refine, submodule, reward function, N, threshold, Predict, trajectory, discussion, advice, hint

7.4 Examples of custom modules

This section introduces custom DSPy modules as a way to implement application-specific workflows or established prompting techniques and test whether they improve performance.

Key terms: custom modules, workflows specific to your application, standard prompting techniques, performance

7.4.1 Adding a closing section

This section shows how a custom module can add text to prompt instructions and explains why such additions should remain a baseline rather than become extensive manual prompt tuning.

Key terms: instructions, fields, prompting techniques, baseline, optimizer, prompt engineering

7.4.2 Rewording the inputs

Shows how a custom DSPy module can reword an input before answering it, using separate LMs while managing the cost of the extra step.

Key terms: two-step method, submodules, cleaning, gpt-4o, gpt-4o-mini, two steps, lower-cost LMs, inputs and outputs

7.4.3 Separating out toxic comments

This subsection shows how a custom module can check user input for toxicity before classification and explains why separating that check is useful.

Key terms: toxic, custom module, utterance, classify, LM, toxicity checks, submodules, gpt-4o-mini

7.4.4 Module for checking security

The section shows how a custom DSPy module can screen user messages with reusable security checks before running its main task.

Key terms: prompt injections, personally identifiable information (PII), submodule, main submodule, security_prog, pii_prog, has_problem, preoptimized DSPy programs, PII, self-hosted LM

7.4.5 Chain of Draft

This section explains how Chain of Draft keeps the potential benefit of a reasoning rationale while reducing its length and output-token overhead through a custom ChainOfThought rationale field.

Key terms: Chain of Draft, Chain of Thought, rationale, output tokens, ChainOfThought, rationale_field, five words

7.4.6 Creating a critic-based module

This section explains how a critic-based custom module improves a response through a loop of execution, critique, and prompt revision, and weighs that approach against optimizing a prompt once.

Key terms: CriticModule, Critic, prompt_writer, critique object, inference time, optimizer, Predict, production, custom module, submodule

7.5 Parallelism in custom modules

The section introduces two kinds of DSPy parallelism and explains when their potential speed gains justify the complexity of asyncio.

Key terms: parallelism, DSPy programs, submodules, tools, asyncio, synchronous, asynchronous processing, error handling, debugging

7.5.1 The asyncio library

This section explains how asyncio uses coroutines and an event loop to overlap waiting tasks, then shows how to start and await concurrent tasks.

Key terms: asyncio, asynchronous, concurrent, thread, coroutine, async def, await, task, event loop, asyncio.run()

7.5.2 Calling modules in parallel

This section explains how to call DSPy modules concurrently, what custom modules need to support asynchronous calls, and the benefits and limits of doing so.

Key terms: parallel, concurrent LM calls, rate limits, acall(), aforward(), forward(), async, await, asyncio task

7.5.3 Parallel execution within modules

This section explains how to run awaitable work concurrently inside a DSPy module, using candidate-answer generation as an example.

Key terms: concurrent execution, gather(), create_task(), asyncio tasks, await, submodules

7.5.4 Asynchronous Skeleton-of-Thought

The section shows how an asynchronous Skeleton-of-Thought module splits a question into independent jobs, runs them concurrently, and combines their answers.

Key terms: Skeleton-of-Thought, subtasks, independent, parallel, submodule, concurrently, awaits, combine, create_task(), gather()

7.6 Optimizing custom modules

This section establishes that custom DSPy modules can be optimized like built-in modules and identifies the setup needed for the examples.

Key terms: custom modules, built-in modules, optimized

7.6.1 Using BootstrapFewShot

Shows how BootstrapFewShot creates demonstrations for each step of a custom module from successful runs of the whole program.

Key terms: BootstrapFewShot, bootstrapped demos, metric function, submodules, clear_question, custom module, prog, inspect_history()

7.6.2 Optimizing using MIPROv2

This section explains how MIPROv2 optimizes a custom module’s submodules and why joint optimization can be preferable to optimizing prompts one at a time.

Key terms: MIPROv2, bootstrapped demos, instructions, submodule, COPRO, submodules, LM calls

7.6.3 Examining the set of submodules

This subsection shows how to inspect the Predict modules inside a nested DSPy module, including after optimization.

Key terms: named_predictors(), Predict modules, signature, instructions, fields, compilation

7.7 Creating complex vs. simple modules

This section explains when to put a multi-call workflow in one custom DSPy module and when to keep its programs separate.

Key terms: custom module, submodules, full workflow, intermediate results, optimize the programs separately

7.8 Using DSPy to create custom modules

This section explains how DSPy can generate custom-module code from a workflow description, how to test and improve that code, and when the approach is worth using.

Key terms: custom module, workflow, powerful LM, validation set, metric function, exec, python_code_content, coding errors, instructions, optimizers

7.9 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 6: Optimizing prompt instructions Chapter 8: Summarization and more effective metric functions →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.