dspy.ChainOfThought¶
dspy.ChainOfThought(signature: str | type[Signature], rationale_field: FieldInfo | None = None, rationale_field_type: type = str, **config: dict[str, Any])
¶
Bases: Module
A module that reasons step by step in order to predict the output of a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
Type[Signature]
|
The signature of the module. |
required |
rationale_field
|
Optional[Union[OutputField, FieldInfo]]
|
The field that will contain the reasoning. |
None
|
rationale_field_type
|
Type
|
The type of the rationale field. |
str
|
**config
|
dict[str, Any]
|
The configuration for the module. |
{}
|
Source code in .venv/lib/python3.14/site-packages/dspy/predict/chain_of_thought.py
Functions¶
__call__(*args, **kwargs) -> Prediction
¶
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
acall(*args, **kwargs) -> Prediction
async
¶
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
aforward(**kwargs)
async
¶
batch(examples: list[Example], num_threads: int | None = None, max_errors: int | None = None, return_failed_examples: bool = False, provide_traceback: bool | None = None, disable_progress_bar: bool = False, timeout: int = 120, straggler_limit: int = 3) -> list[Example] | tuple[list[Example], list[Example], list[Exception]]
¶
Processes a list of dspy.Example instances in parallel using the Parallel module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
examples
|
list[Example]
|
List of dspy.Example instances to process. |
required |
num_threads
|
int | None
|
Number of threads to use for parallel processing. |
None
|
max_errors
|
int | None
|
Maximum number of errors allowed before stopping execution.
If |
None
|
return_failed_examples
|
bool
|
Whether to return failed examples and exceptions. |
False
|
provide_traceback
|
bool | None
|
Whether to include traceback information in error logs. |
None
|
disable_progress_bar
|
bool
|
Whether to display the progress bar. |
False
|
timeout
|
int
|
Seconds before a straggler task is resubmitted. Set to 0 to disable. |
120
|
straggler_limit
|
int
|
Only check for stragglers when this many or fewer tasks remain. |
3
|
Returns:
| Type | Description |
|---|---|
list[Example] | tuple[list[Example], list[Example], list[Exception]]
|
List of results, and optionally failed examples and exceptions. |
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
deepcopy()
¶
Deep copy the module.
This is a tweak to the default python deepcopy that only deep copies self.parameters(), and for other
attributes, we just do the shallow copy.
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/base_module.py
dump_state(json_mode=True)
¶
forward(**kwargs)
¶
get_lm()
¶
Get the language model used by this module's predictors.
Returns the language model if all predictors use the same LM. Raises an error if multiple different LMs are in use.
Returns:
| Type | Description |
|---|---|
|
The language model instance used by this module's predictors. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If multiple different language models are being used by the predictors in this module. |
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
inspect_history(n: int = 1)
¶
Display the LM call history for this module.
Prints a formatted view of the most recent language model calls made by this module, useful for debugging and understanding the module's behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of recent history entries to display. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
|
The formatted history output. |
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
load(path, allow_pickle=False)
¶
Load the saved module. You may also want to check out dspy.load, if you want to load an entire program, not just the state for an existing program.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the saved state file, which should be a .json or a .pkl file |
required |
allow_pickle
|
bool
|
If True, allow loading .pkl files, which can run arbitrary code. This is dangerous and should only be used if you are sure about the source of the file and in a trusted environment. |
False
|
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/base_module.py
load_state(state)
¶
map_named_predictors(func)
¶
Apply a function to all named predictors in this module.
This method iterates through all Predict instances in the module and applies the given function to each, replacing the original predictor with the function's return value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
A callable that takes a Predict instance and returns a new Predict instance (or compatible object). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Module |
Returns self for method chaining. |
Example
import dspy class MyProgram(dspy.Module): ... def init(self): ... super().init() ... self.qa = dspy.Predict("question -> answer") ... program = MyProgram() program.map_named_predictors(lambda p: p)
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
named_parameters()
¶
Unlike PyTorch, handles (non-recursive) lists of parameters too.
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/base_module.py
named_predictors()
¶
Return all named Predict modules in this module.
Iterates through all parameters and returns those that are instances
of dspy.Predict, along with their names.
Returns:
| Type | Description |
|---|---|
|
list[tuple[str, Predict]]: A list of (name, predictor) tuples where name is the attribute path and predictor is the Predict instance. |
Example
import dspy class MyProgram(dspy.Module): ... def init(self): ... super().init() ... self.qa = dspy.Predict("question -> answer") ... self.summarize = dspy.Predict("text -> summary") ... program = MyProgram() for name, p in program.named_predictors(): ... print(name) qa summarize
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
named_sub_modules(type_=None, skip_compiled=False) -> Generator[tuple[str, BaseModule], None, None]
¶
Find all sub-modules in the module, as well as their names.
Say self.children[4]['key'].sub_module is a sub-module. Then the name will be
children[4]['key'].sub_module. But if the sub-module is accessible at different
paths, only one of the paths will be returned.
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/base_module.py
parameters()
¶
predictors()
¶
Return all Predict modules in this module.
Returns:
| Type | Description |
|---|---|
|
list[Predict]: A list of all Predict instances in this module. |
Example
import dspy class MyProgram(dspy.Module): ... def init(self): ... super().init() ... self.qa = dspy.Predict("question -> answer") ... program = MyProgram() len(program.predictors()) 1
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
reset_copy()
¶
Deep copy the module and reset all parameters.
save(path, save_program=False, modules_to_serialize=None)
¶
Save the module.
Save the module to a directory or a file. There are two modes:
- save_program=False: Save only the state of the module to a json or pickle file, based on the value of
the file extension.
- save_program=True: Save the whole module to a directory via cloudpickle, which contains both the state and
architecture of the model.
If save_program=True and modules_to_serialize are provided, it will register those modules for serialization
with cloudpickle's register_pickle_by_value. This causes cloudpickle to serialize the module by value rather
than by reference, ensuring the module is fully preserved along with the saved program. This is useful
when you have custom modules that need to be serialized alongside your program. If None, then no modules
will be registered for serialization.
We also save the dependency versions, so that the loaded model can check if there is a version mismatch on critical dependencies or DSPy version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the saved state file, which should be a .json or .pkl file when |
required |
save_program
|
bool
|
If True, save the whole module to a directory via cloudpickle, otherwise only save the state. |
False
|
modules_to_serialize
|
list
|
A list of modules to serialize with cloudpickle's |
None
|
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/base_module.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
set_lm(lm)
¶
Set the language model for all predictors in this module.
This method recursively sets the language model for all Predict instances contained within this module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lm
|
The language model instance to use for all predictors. |
required |
Example
import dspy lm = dspy.LM("openai/gpt-4o-mini") program = dspy.Predict("question -> answer") program.set_lm(lm)
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/module.py
:::