DSPy: The framework for programming—not prompting—language models
Python
Handle ReAct tool selection failures more gracefully (#8114)
Omar Khattabd6de70c0b1ec
diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex 21fa17576..0580a7f7b 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -29,16 +29,19 @@ class ReAct(Module):instr.extend([- f"You will be given {inputs} and your goal is to finish with {outputs}.\n",- "To do this, you will interleave Thought, Tool Name, and Tool Args, and receive a resulting Observation.\n",- "Thought can reason about the current situation, and Tool Name can be the following types:\n",+ f"You are an Agent. In each episode, you will be given the fields {inputs} as input. And you can see your past trajectory so far.",+ f"Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\n",+ "To do this, you will interleave next_thought, next_tool_name, and next_tool_args in each turn, and also when finishing the task.",+ "After each tool call, you receive a resulting observation, which gets appended to your trajectory.\n",+ "When writing next_thought, you may reason about the current situation and plan for future steps.",+ "When selecting the next_tool_name and its next_tool_args, the tool must be one of:\n",])tools["finish"] = Tool(- func=lambda **kwargs: "Completed.",+ func=lambda: "Completed.",name="finish",- desc=f"Signals that the final outputs, i.e. {outputs}, are now available and marks the task as complete.",+ desc=f"Marks the task as complete. That is, signals that all infomration for producing the outputs, i.e. {outputs}, are now available to be extracted.",args={},)@@ -74,7 +77,11 @@ class ReAct(Module):trajectory = {}max_iters = input_args.pop("max_iters", self.max_iters)for idx in range(max_iters):- pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)+ try:+ pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)+ except ValueError as err:+ logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}")+ breaktrajectory[f"thought_{idx}"] = pred.next_thoughttrajectory[f"tool_name_{idx}"] = pred.next_tool_name@@ -82,8 +89,8 @@ class ReAct(Module):try:trajectory[f"observation_{idx}"] = self.tools[pred.next_tool_name](**pred.next_tool_args)- except Exception as e:- trajectory[f"observation_{idx}"] = f"Failed to execute: {e}"+ except Exception as err:+ trajectory[f"observation_{idx}"] = f"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}"if pred.next_tool_name == "finish":break@@ -92,7 +99,7 @@ class ReAct(Module):return dspy.Prediction(trajectory=trajectory, **extract)def _call_with_potential_trajectory_truncation(self, module, trajectory, **input_args):- while True:+ for _ in range(3):try:return module(**input_args,@@ -121,6 +128,17 @@ class ReAct(Module):return trajectory+def _fmt_exc(err: BaseException, *, limit: int = 5) -> str:+ """+ Return a one-string traceback summary.+ * `limit` – how many stack frames to keep (from the innermost outwards).+ """++ import traceback++ return "\n" + "".join(traceback.format_exception(type(err), err, err.__traceback__, limit=limit)).strip()++"""Thoughts and Planned Improvements for dspy.ReAct.diff --git a/tests/predict/test_react.py b/tests/predict/test_react.pyindex ba4bf0fe5..3a39b09b7 100644--- a/tests/predict/test_react.py+++ b/tests/predict/test_react.py@@ -1,9 +1,11 @@from pydantic import BaseModel+import reimport dspy-from dspy.utils.dummies import DummyLMimport litellm+from dspy.utils.dummies import DummyLM+# def test_example_no_tools():# # Create a simple dataset which the model will use with the Retrieve tool.# lm = DummyLM(@@ -276,35 +278,48 @@ def test_trajectory_truncation():def test_error_retry():- def foo(a, b):+ # --- a tiny tool that always fails -------------------------------------+ def foo(a, b): # noqa: D401, ANN001raise Exception("tool error")+ # --- program under test -------------------------------------------------react = dspy.ReAct("a, b -> c:int", tools=[foo])- max_iters = 2lm = DummyLM([- {"next_thought": "I need to add two numbers.", "next_tool_name": "foo", "next_tool_args": {"a": 1, "b": 2}},- {"next_thought": "I need to add two numbers.", "next_tool_name": "foo", "next_tool_args": {"a": 1, "b": 2}},+ {+ "next_thought": "I need to add two numbers.",+ "next_tool_name": "foo",+ "next_tool_args": {"a": 1, "b": 2},+ },+ {+ "next_thought": "I need to add two numbers.",+ "next_tool_name": "foo",+ "next_tool_args": {"a": 1, "b": 2},+ },+ # (The model *would* succeed on the 3rd turn, but max_iters=2 stops earlier.){"reasoning": "I added the numbers successfully", "c": 3},])dspy.settings.configure(lm=lm)- outputs = react(a=1, b=2, max_iters=max_iters)- expected_trajectory = {+ outputs = react(a=1, b=2, max_iters=2)+ traj = outputs.trajectory++ # --- exact-match checks (thoughts + tool calls) -------------------------+ control_expected = {"thought_0": "I need to add two numbers.","tool_name_0": "foo",- "tool_args_0": {- "a": 1,- "b": 2,- },- 'observation_0': 'Failed to execute: tool error',- 'thought_1': 'I need to add two numbers.',- 'tool_name_1': 'foo',- "tool_args_1": {- "a": 1,- "b": 2,- },- 'observation_1': 'Failed to execute: tool error',+ "tool_args_0": {"a": 1, "b": 2},+ "thought_1": "I need to add two numbers.",+ "tool_name_1": "foo",+ "tool_args_1": {"a": 1, "b": 2},}- assert outputs.trajectory == expected_trajectory\ No newline at end of file+ for k, v in control_expected.items():+ assert traj[k] == v, f"{k} mismatch"++ # --- flexible checks for observations ----------------------------------+ # We only care that each observation mentions our error string; we ignore+ # any extra traceback detail or differing prefixes.+ for i in range(2):+ obs = traj[f"observation_{i}"]+ assert re.search(r"\btool error\b", obs), f"unexpected observation_{i!r}: {obs}"