DSPy: The framework for programming—not prompting—language models
Python
fix(dspy): preserve typed ReAct context window errors (#10132)
Isaac Miller6a4afda97e32
diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex b7541d07c..a1c76bcb0 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -98,6 +98,9 @@ class ReAct(Module):for idx in range(max_iters):try:pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)+ except ContextWindowExceededError as err:+ logger.warning(f"Ending the trajectory: {_fmt_exc(err)}")+ breakexcept ValueError as err:logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {format_error_for_lm(err, traceback_frames=5)}")break@@ -123,6 +126,9 @@ class ReAct(Module):for idx in range(max_iters):try:pred = await self._async_call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)+ except ContextWindowExceededError as err:+ logger.warning(f"Ending the trajectory: {_fmt_exc(err)}")+ breakexcept ValueError as err:logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {format_error_for_lm(err, traceback_frames=5)}")break@@ -143,28 +149,36 @@ class ReAct(Module):return dspy.Prediction(trajectory=trajectory, **extract)def _call_with_potential_trajectory_truncation(self, module, trajectory, **input_args):+ last_error = Nonefor _ in range(3):try:return module(**input_args,trajectory=self._format_trajectory(trajectory),)- except ContextWindowExceededError:+ except ContextWindowExceededError as err:logger.warning("Trajectory exceeded the context window, truncating the oldest tool call information.")+ last_error = errtrajectory = self.truncate_trajectory(trajectory)- raise ValueError("The context window was exceeded even after 3 attempts to truncate the trajectory.")+ raise ContextWindowExceededError(+ message="The context window was exceeded even after 3 attempts to truncate the trajectory."+ ) from last_errorasync def _async_call_with_potential_trajectory_truncation(self, module, trajectory, **input_args):+ last_error = Nonefor _ in range(3):try:return await module.acall(**input_args,trajectory=self._format_trajectory(trajectory),)- except ContextWindowExceededError:+ except ContextWindowExceededError as err:logger.warning("Trajectory exceeded the context window, truncating the oldest tool call information.")+ last_error = errtrajectory = self.truncate_trajectory(trajectory)- raise ValueError("The context window was exceeded even after 3 attempts to truncate the trajectory.")+ raise ContextWindowExceededError(+ message="The context window was exceeded even after 3 attempts to truncate the trajectory."+ ) from last_errordef truncate_trajectory(self, trajectory):"""Truncates the trajectory so that it fits in the context window.@@ -174,9 +188,9 @@ class ReAct(Module):keys = list(trajectory.keys())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 "- "truncated because it only has one tool call."+ raise ContextWindowExceededError(+ message="The trajectory is too long so your prompt exceeded the context window, but the trajectory "+ "cannot be truncated because it only has one tool call.")for key in keys[:4]:diff --git a/tests/predict/test_react.py b/tests/predict/test_react.pyindex 0c434492a..97cc2d828 100644--- a/tests/predict/test_react.py+++ b/tests/predict/test_react.py@@ -265,10 +265,32 @@ def test_truncate_trajectory_raises_on_single_tool_call():"observation_0": "Completed.",}- with pytest.raises(ValueError):+ with pytest.raises(ContextWindowExceededError):react.truncate_trajectory(trajectory)+def test_truncation_exhausted_raises_context_window_exceeded_error():+ def echo(text: str) -> str:+ return f"Echoed: {text}"++ react = dspy.ReAct("input_text -> output_text", tools=[echo])++ def always_exceed(**kwargs):+ raise ContextWindowExceededError()++ trajectory = {}+ for i in range(4):+ trajectory[f"thought_{i}"] = f"Thought {i}"+ trajectory[f"tool_name_{i}"] = "echo"+ trajectory[f"tool_args_{i}"] = {"text": f"Text {i}"}+ trajectory[f"observation_{i}"] = f"Echoed: Text {i}"++ with pytest.raises(ContextWindowExceededError, match="even after 3 attempts") as exc_info:+ react._call_with_potential_trajectory_truncation(always_exceed, trajectory, input_text="test input")++ assert isinstance(exc_info.value.__cause__, ContextWindowExceededError)++@pytest.mark.asyncioasync def test_context_window_exceeded_after_retries():def echo(text: str) -> str: