DSPy: The framework for programming—not prompting—language models
Python
fix(predict): reject ReActV2 input fields named 'history' or 'tools' (#10464)
Lichao Chena7f448abf7c4
diff --git a/dspy/predict/react_v2.py b/dspy/predict/react_v2.pyindex 548cbc86d..eb5cecbad 100644--- a/dspy/predict/react_v2.py+++ b/dspy/predict/react_v2.py@@ -20,6 +20,11 @@ logger = logging.getLogger(__name__)# expansion at the `Prediction(**final_outputs, history=..., termination_reason=...)` call sites._RESERVED_PREDICTION_KEYS = frozenset({"history", "termination_reason"})+# Internal input field names ReActV2 injects into its inner Predict signature. A user+# input with one of these names would be silently overwritten by `_make_react_signature`+# and popped out of the caller's kwargs by `forward`/`aforward`, so it must be rejected.+_RESERVED_INPUT_KEYS = frozenset({"history", "tools"})+if TYPE_CHECKING:from dspy.signatures.signature import Signature@@ -52,6 +57,14 @@ class ReActV2(Module):"returned Prediction. Rename these output fields on your signature.")+ reserved_inputs = _RESERVED_INPUT_KEYS.intersection(self.signature.input_fields)+ if reserved_inputs:+ names = ", ".join(f"`{name}`" for name in sorted(reserved_inputs))+ raise ValueError(+ f"Input field name(s) {names} are reserved by ReActV2 for its internal "+ "conversation history and tool list. Rename these input 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 f37b9dbde..f640f9a85 100644--- a/tests/predict/test_react_v2.py+++ b/tests/predict/test_react_v2.py@@ -362,6 +362,12 @@ def test_react_v2_rejects_reserved_output_field_names(reserved):dspy.ReActV2(f"question -> answer, {reserved}: str", tools=[])[email protected]("reserved", ["history", "tools"])+def test_react_v2_rejects_reserved_input_field_names(reserved):+ with pytest.raises(ValueError, match=reserved):+ dspy.ReActV2(f"{reserved}: str -> answer: str", tools=[])++@pytest.mark.asyncio@pytest.mark.parametrize("use_async", [False, True])@pytest.mark.parametrize("break_reason", ["max_iters", "empty_tool_calls", "parse_error", "context_window_exceeded"])