liveBook · Manning

Forward

As explained in Building LLM Applications with DSPy

The method that defines a DSPy module’s synchronous computation.

In a custom DSPy module, `forward()` defines what happens when the module runs. Calling the module instance invokes `forward()` behind the scenes. Define it alongside `__init__()` in a `dspy.Module` subclass; use `__init__()` to create submodules and `forward()` to execute them and return a `Prediction`. section 7.2 section 2.6

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?")

The minimal module stores a `Predict` submodule, then passes its `forward()` input to that submodule. The caller uses `prog(...)`, not `prog.forward(...)`. section 7.2 section 2.6

For a workflow with several steps, `forward()` can:

  • Accept parameters covering the inputs needed by its submodules. section 7.2
  • Prepare inputs, call submodules or tools, and pass earlier results into later calls. section 7.2
  • Process the final result and return a `Prediction`. section 7.2

Keep normal execution at the module-call level: as of DSPy 3.0, explicitly calling `forward()` produces a warning. `aforward()` is the optional asynchronous counterpart for work that can run in parallel. section 2.6 section 7.2

How Building LLM Applications with DSPy covers it

How deep it goes
Works through a minimal wrapper and sketches chained processing; defers asynchronous execution to `aforward()`.
Examples
Uses a capital-of-France query in a minimal `Predict` wrapper and pseudocode chaining two `Predict` calls.
What it assumes
Assumes configured DSPy setup and basic Python class syntax while showing the required `__init__()` and `forward()` structure.
What you can do after
Build it from scratch by defining a `dspy.Module` subclass whose `forward()` calls submodules and returns a `Prediction`.
How it connects
Connects `dspy.Module`, `Predict`, signatures, `Prediction`, tools, and `aforward()`.

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.