Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Fix the crash when usage tracker is enabled with non-prediction output (#8831)

TomuHiratae4330465d576
diff --git a/dspy/primitives/module.py b/dspy/primitives/module.py
index 6766a55a5..044e337ae 100644
--- a/dspy/primitives/module.py
+++ b/dspy/primitives/module.py
@@ -1,5 +1,6 @@
import inspect
import logging
+from typing import Any
import magicattr
@@ -73,20 +74,8 @@ class Module(BaseModule, metaclass=ProgramMeta):
with track_usage() as usage_tracker:
output = self.forward(*args, **kwargs)
tokens = usage_tracker.get_total_tokens()
+ self._set_lm_usage(tokens, output)
- # Some optimizers (e.g., GEPA bootstrap tracing) temporarily patch
- # module.forward to return a tuple: (prediction, trace).
- # When usage tracking is enabled, ensure we attach usage to the
- # prediction object if present.
- prediction_in_output = None
- if isinstance(output, Prediction):
- prediction_in_output = output
- elif isinstance(output, tuple) and len(output) > 0 and isinstance(output[0], Prediction):
- prediction_in_output = output[0]
- if not prediction_in_output:
- raise ValueError("No prediction object found in output to call set_lm_usage on.")
-
- prediction_in_output.set_lm_usage(tokens)
return output
return self.forward(*args, **kwargs)
@@ -101,7 +90,9 @@ class Module(BaseModule, metaclass=ProgramMeta):
if settings.track_usage and thread_local_overrides.get().get("usage_tracker") is None:
with track_usage() as usage_tracker:
output = await self.aforward(*args, **kwargs)
- output.set_lm_usage(usage_tracker.get_total_tokens())
+ tokens = usage_tracker.get_total_tokens()
+ self._set_lm_usage(tokens, output)
+
return output
return await self.aforward(*args, **kwargs)
@@ -187,6 +178,22 @@ class Module(BaseModule, metaclass=ProgramMeta):
results = parallel_executor.forward(exec_pairs)
return results
+ def _set_lm_usage(self, tokens: dict[str, Any], output: Any):
+ # Some optimizers (e.g., GEPA bootstrap tracing) temporarily patch
+ # module.forward to return a tuple: (prediction, trace).
+ # When usage tracking is enabled, ensure we attach usage to the
+ # prediction object if present.
+ prediction_in_output = None
+ if isinstance(output, Prediction):
+ prediction_in_output = output
+ elif isinstance(output, tuple) and len(output) > 0 and isinstance(output[0], Prediction):
+ prediction_in_output = output[0]
+ if prediction_in_output:
+ prediction_in_output.set_lm_usage(tokens)
+ else:
+ logger.warning("Failed to set LM usage. Please return `dspy.Prediction` object from dspy.Module to enable usage tracking.")
+
+
def __getattribute__(self, name):
attr = super().__getattribute__(name)
diff --git a/tests/primitives/test_base_module.py b/tests/primitives/test_base_module.py
index dda1ac137..f138ce521 100644
--- a/tests/primitives/test_base_module.py
+++ b/tests/primitives/test_base_module.py
@@ -370,6 +370,20 @@ async def test_usage_tracker_async_parallel():
assert lm_usage1["total_tokens"] == 1163
+def test_usage_tracker_no_side_effect():
+ class MyProgram(dspy.Module):
+ def __init__(self):
+ self.predict = dspy.Predict("question -> answer")
+
+ def forward(self, question: str, **kwargs) -> str:
+ return self.predict(question=question).answer
+
+ program = MyProgram()
+ with dspy.context(lm=DummyLM([{"answer": "Paris"}]), track_usage=True):
+ result = program(question="What is the capital of France?")
+ assert result == "Paris"
+
+
def test_module_history():
class MyProgram(dspy.Module):
def __init__(self, **kwargs):