DSPy: The framework for programming—not prompting—language models
Python
reject reserved output names in ReActV2 signatures (#9852)
Tejas Dharamsib3897e271f69
diff --git a/dspy/predict/react_v2.py b/dspy/predict/react_v2.pyindex cf7241577..5bd208b90 100644--- a/dspy/predict/react_v2.py+++ b/dspy/predict/react_v2.py@@ -15,6 +15,11 @@ from dspy.utils.exceptions import AdapterParseError, ContextWindowExceededError,logger = logging.getLogger(__name__)+# Keys ReActV2 attaches to every returned `Prediction` alongside the user's output fields.+# A user signature that declares any of these as an output would collide with the keyword+# expansion at the `Prediction(**final_outputs, history=..., termination_reason=...)` call sites.+_RESERVED_PREDICTION_KEYS = frozenset({"history", "termination_reason"})+if TYPE_CHECKING:from dspy.signatures.signature import Signature@@ -26,6 +31,14 @@ class ReActV2(Module):self.signature = ensure_signature(signature)self.max_iters = max_iters+ reserved_outputs = _RESERVED_PREDICTION_KEYS.intersection(self.signature.output_fields)+ if reserved_outputs:+ names = ", ".join(f"`{name}`" for name in sorted(reserved_outputs))+ raise ValueError(+ f"Output field name(s) {names} are reserved by ReActV2 and attached to every "+ "returned Prediction. Rename these output fields on your signature."+ )+user_tools = [tool if isinstance(tool, Tool) else Tool(tool) for tool in tools]self.tools = {tool.name: tool for tool in user_tools}if "submit" in self.tools:diff --git a/tests/predict/test_react_v2.py b/tests/predict/test_react_v2.pyindex 6f9bf3dbc..323f7abae 100644--- a/tests/predict/test_react_v2.py+++ b/tests/predict/test_react_v2.py@@ -1,3 +1,5 @@+import pytest+import dspyfrom dspy.dsp.utils.utils import dotdict@@ -324,3 +326,9 @@ def test_react_v2_native_parallel_tool_calls_are_requested_and_replayed():"call_provider_1","call_provider_2",]++[email protected]("reserved", ["history", "termination_reason"])+def test_react_v2_rejects_reserved_output_field_names(reserved):+ with pytest.raises(ValueError, match=reserved):+ dspy.ReActV2(f"question -> answer, {reserved}: str", tools=[])