DSPy: The framework for programming—not prompting—language models
Python
fix(react): ReAct.truncate_trajectory silently empties trajectory on single tool call (#10054)
Andrew Chen7eb5acce27c8
diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex eb1b0886d..1c2ad8534 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -172,7 +172,7 @@ class ReAct(Module):Users can override this method to implement their own truncation logic."""keys = list(trajectory.keys())- if len(keys) < 4:+ if len(keys) <= 4:# Every tool call has 4 keys: thought, tool_name, tool_args, and observation.raise ValueError("The trajectory is too long so your prompt exceeded the context window, but the trajectory cannot be "diff --git a/tests/predict/test_react.py b/tests/predict/test_react.pyindex 77ad2f1b1..92b149002 100644--- a/tests/predict/test_react.py+++ b/tests/predict/test_react.py@@ -252,6 +252,23 @@ def test_trajectory_truncation():assert result.output_text == "Final output"+def test_truncate_trajectory_raises_on_single_tool_call():+ # A trajectory with exactly one tool call has 4 keys (thought, tool_name, tool_args,+ # observation). Per truncate_trajectory's own docstring/error message, this is the+ # smallest trajectory that cannot be truncated further, so it must raise instead of+ # silently popping every key and returning an empty trajectory.+ react = dspy.ReAct("input_text -> output_text", tools=[])+ trajectory = {+ "thought_0": "Thought 0",+ "tool_name_0": "finish",+ "tool_args_0": {},+ "observation_0": "Completed.",+ }++ with pytest.raises(ValueError):+ react.truncate_trajectory(trajectory)++@pytest.mark.asyncioasync def test_context_window_exceeded_after_retries():def echo(text: str) -> str: