Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

refactor(dspy): share LM-facing exception formatting (#10135)

Isaac Miller0525a70f91d3
diff --git a/dspy/predict/program_of_thought.py b/dspy/predict/program_of_thought.py
index 3b29ea008..175e027be 100644
--- a/dspy/predict/program_of_thought.py
+++ b/dspy/predict/program_of_thought.py
@@ -16,6 +16,7 @@ from dspy.primitives.code_interpreter import (
from dspy.primitives.module import Module
from dspy.primitives.python_interpreter import PythonInterpreter
from dspy.signatures.signature import Signature, ensure_signature
+from dspy.utils.exceptions import format_error_for_lm
logger = logging.getLogger(__name__)
@@ -181,7 +182,7 @@ class ProgramOfThought(Module):
output = json.dumps(result)
return output, None
except (CodeExecutionError, SyntaxError) as e:
- return None, str(e)
+ return None, format_error_for_lm(e)
def forward(self, interpreter: CodeInterpreter | None = None, /, **kwargs):
"""Run the program with a fresh interpreter or a caller-owned override.
diff --git a/dspy/predict/react.py b/dspy/predict/react.py
index 1c2ad8534..b7541d07c 100644
--- a/dspy/predict/react.py
+++ b/dspy/predict/react.py
@@ -5,7 +5,7 @@ import dspy
from dspy.adapters.types.tool import Tool
from dspy.primitives.module import Module
from dspy.signatures.signature import ensure_signature
-from dspy.utils.exceptions import ContextWindowExceededError
+from dspy.utils.exceptions import ContextWindowExceededError, format_error_for_lm
logger = logging.getLogger(__name__)
@@ -99,7 +99,7 @@ class ReAct(Module):
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)}")
+ logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {format_error_for_lm(err, traceback_frames=5)}")
break
trajectory[f"thought_{idx}"] = pred.next_thought
@@ -109,7 +109,7 @@ class ReAct(Module):
try:
trajectory[f"observation_{idx}"] = self.tools[pred.next_tool_name](**pred.next_tool_args)
except Exception as err:
- trajectory[f"observation_{idx}"] = f"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}"
+ trajectory[f"observation_{idx}"] = f"Execution error in {pred.next_tool_name}: {format_error_for_lm(err, traceback_frames=5)}"
if pred.next_tool_name == "finish":
break
@@ -124,7 +124,7 @@ class ReAct(Module):
try:
pred = await self._async_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)}")
+ logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {format_error_for_lm(err, traceback_frames=5)}")
break
trajectory[f"thought_{idx}"] = pred.next_thought
@@ -134,7 +134,7 @@ class ReAct(Module):
try:
trajectory[f"observation_{idx}"] = await self.tools[pred.next_tool_name].acall(**pred.next_tool_args)
except Exception as err:
- trajectory[f"observation_{idx}"] = f"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}"
+ trajectory[f"observation_{idx}"] = f"Execution error in {pred.next_tool_name}: {format_error_for_lm(err, traceback_frames=5)}"
if pred.next_tool_name == "finish":
break
@@ -185,17 +185,6 @@ 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/dspy/predict/react_v2.py b/dspy/predict/react_v2.py
index 0e87e446a..cf7241577 100644
--- a/dspy/predict/react_v2.py
+++ b/dspy/predict/react_v2.py
@@ -11,7 +11,7 @@ from dspy.primitives.module import Module
from dspy.primitives.prediction import Prediction
from dspy.signatures.signature import ensure_signature
from dspy.utils.annotation import experimental
-from dspy.utils.exceptions import AdapterParseError, ContextWindowExceededError
+from dspy.utils.exceptions import AdapterParseError, ContextWindowExceededError, format_error_for_lm
logger = logging.getLogger(__name__)
@@ -100,7 +100,7 @@ class ReActV2(Module):
)
tool_calls = _coerce_tool_calls(getattr(pred, "tool_calls", None))
except (AdapterParseError, ValueError) as err:
- logger.warning("Ending ReActV2 loop after parse failure: %s", _fmt_exc(err))
+ logger.warning("Ending ReActV2 loop after parse failure: %s", format_error_for_lm(err, traceback_frames=5))
break_reason = "parse_error"
break
except ContextWindowExceededError:
@@ -143,7 +143,7 @@ class ReActV2(Module):
if tool_call.name == "submit" and isinstance(value, dict):
final_outputs = value
except Exception as err:
- values.append(f"Execution error in {tool_call.name}: {_fmt_exc(err)}")
+ values.append(f"Execution error in {tool_call.name}: {format_error_for_lm(err, traceback_frames=5)}")
is_errors.append(True)
return ToolCallResults.from_tool_calls_and_values(tool_calls, values, is_errors), final_outputs
@@ -183,7 +183,7 @@ class ReActV2(Module):
)
tool_calls = _ensure_tool_call_ids(_coerce_tool_calls(getattr(pred, "tool_calls", None)), turn_index)
except (AdapterParseError, ValueError, ContextWindowExceededError) as err:
- logger.warning("Forced submit failed: %s", _fmt_exc(err))
+ logger.warning("Forced submit failed: %s", format_error_for_lm(err, traceback_frames=5))
return Prediction(history=history, termination_reason=break_reason or "failed")
submit_calls = ToolCalls(tool_calls=[call for call in tool_calls.tool_calls if call.name == "submit"])
@@ -244,9 +244,3 @@ def _ensure_tool_call_ids(tool_calls: ToolCalls, turn_index: int) -> ToolCalls:
def _append_history_event(history: dspy.History, event: dict[str, Any]) -> None:
if event:
history.messages.append(event)
-
-
-def _fmt_exc(err: BaseException, *, limit: int = 5) -> str:
- import traceback
-
- return "\n" + "".join(traceback.format_exception(type(err), err, err.__traceback__, limit=limit)).strip()
diff --git a/dspy/predict/rlm.py b/dspy/predict/rlm.py
index 09ec51f38..066b3593b 100644
--- a/dspy/predict/rlm.py
+++ b/dspy/predict/rlm.py
@@ -42,6 +42,7 @@ from dspy.primitives.repl_types import REPLEntry, REPLHistory, REPLVariable
from dspy.primitives.sandbox_serializable import SandboxSerializable, build_repl_variable
from dspy.signatures.signature import ensure_signature
from dspy.utils.annotation import experimental
+from dspy.utils.exceptions import format_error_for_lm
if TYPE_CHECKING:
@@ -318,7 +319,7 @@ class RLM(Module):
try:
results[idx] = future.result()
except dspy.LMError as e:
- results[idx] = f"[ERROR] {e}"
+ results[idx] = f"[ERROR] {format_error_for_lm(e)}"
return [results[i] for i in range(len(prompts))]
return {"llm_query": llm_query, "llm_query_batched": llm_query_batched}
@@ -655,7 +656,7 @@ class RLM(Module):
try:
return repl.execute(code, variables=dict(input_args))
except (CodeExecutionError, SyntaxError) as e:
- return f"[Error] {e}"
+ return f"[Error] {format_error_for_lm(e)}"
def _execute_iteration(
self,
@@ -683,7 +684,7 @@ class RLM(Module):
code = _strip_code_fences(action.code)
except SyntaxError as e:
code = action.code
- result = f"[Error] {e}"
+ result = f"[Error] {format_error_for_lm(e)}"
return self._process_execution_result(action, code, result, history, output_field_names)
result = self._execute_code(repl, code, input_args)
return self._process_execution_result(action, code, result, history, output_field_names)
@@ -776,7 +777,7 @@ class RLM(Module):
code = _strip_code_fences(pred.code)
except SyntaxError as e:
code = pred.code
- result = f"[Error] {e}"
+ result = f"[Error] {format_error_for_lm(e)}"
return self._process_execution_result(pred, code, result, history, output_field_names)
result = self._execute_code(repl, code, input_args)
return self._process_execution_result(pred, code, result, history, output_field_names)
diff --git a/dspy/utils/exceptions.py b/dspy/utils/exceptions.py
index f088dbca7..4e786b710 100644
--- a/dspy/utils/exceptions.py
+++ b/dspy/utils/exceptions.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import traceback
from typing import Any
from dspy.signatures.signature import Signature
@@ -221,6 +222,27 @@ def is_retryable_lm_error(error: Exception) -> bool:
return isinstance(error, _RETRYABLE_LM_ERRORS)
+def format_error_for_lm(error: BaseException, *, traceback_frames: int = 0) -> str:
+ """Format an exception as a string to be fed back to an LM.
+
+ Modules that surface execution failures to the LM (`ReAct`, `ProgramOfThought`,
+ `RLM`) share this formatter, keeping only their surrounding wrapper text
+ (e.g. `"[Error] "` prefixes) at the call site.
+
+ Args:
+ error: The exception to format.
+ traceback_frames: Maximum number of stack frames to include. When 0
+ (the default), only `str(error)` is returned; when positive, a
+ newline-prefixed traceback summary limited to that many frames is
+ returned.
+ """
+ if traceback_frames <= 0:
+ return str(error)
+ return "\n" + "".join(
+ traceback.format_exception(type(error), error, error.__traceback__, limit=traceback_frames)
+ ).strip()
+
+
class AdapterParseError(DSPyError):
"""Raised when an adapter cannot parse an LM response into signature outputs.
diff --git a/tests/predict/test_react.py b/tests/predict/test_react.py
index 92b149002..0c434492a 100644
--- a/tests/predict/test_react.py
+++ b/tests/predict/test_react.py
@@ -365,6 +365,30 @@ def test_error_retry():
assert re.search(r"\btool error\b", obs), f"unexpected observation_{i!r}: {obs}"
+def test_tool_error_observation_format():
+ def failing_tool():
+ raise ValueError("tool blew up")
+
+ react = dspy.ReAct("question -> answer", tools=[failing_tool])
+ lm = DummyLM(
+ [
+ {
+ "next_thought": "I will call the tool.",
+ "next_tool_name": "failing_tool",
+ "next_tool_args": {},
+ },
+ {"reasoning": "The tool failed.", "answer": "n/a"},
+ ]
+ )
+ dspy.configure(lm=lm)
+
+ outputs = react(question="What happens?", max_iters=1)
+ obs = outputs.trajectory["observation_0"]
+
+ assert obs.startswith("Execution error in failing_tool: \nTraceback (most recent call last):")
+ assert obs.endswith("ValueError: tool blew up")
+
+
@pytest.mark.asyncio
async def test_async_tool_calling_with_pydantic_args():
class CalendarEvent(BaseModel):
diff --git a/tests/utils/test_exceptions.py b/tests/utils/test_exceptions.py
index 707ddea3e..a2392a34f 100644
--- a/tests/utils/test_exceptions.py
+++ b/tests/utils/test_exceptions.py
@@ -5,6 +5,7 @@ from dspy.utils.exceptions import (
DSPyError,
LMError,
LMInvalidRequestError,
+ format_error_for_lm,
)
@@ -132,3 +133,42 @@ def test_adapter_parse_error_with_parsed_result():
"Expected to find output fields in the LM response: [answer1, answer2] \n\n"
"Actual output fields parsed from the LM response: [answer1] \n\n"
)
+
+
+def test_format_error_for_lm_without_traceback():
+ error = ValueError("bad value")
+ assert format_error_for_lm(error) == "bad value"
+ assert format_error_for_lm(error, traceback_frames=0) == str(error)
+
+
+def test_format_error_for_lm_with_traceback():
+ try:
+ raise ValueError("boom")
+ except ValueError as error:
+ formatted = format_error_for_lm(error, traceback_frames=5)
+
+ assert formatted.startswith("\nTraceback (most recent call last):")
+ assert formatted.endswith("ValueError: boom")
+ assert "test_exceptions.py" in formatted
+
+
+def test_format_error_for_lm_limits_traceback_frames():
+ def level_one():
+ raise RuntimeError("deep failure")
+
+ def level_two():
+ level_one()
+
+ def level_three():
+ level_two()
+
+ try:
+ level_three()
+ except RuntimeError as error:
+ limited = format_error_for_lm(error, traceback_frames=1)
+ full = format_error_for_lm(error, traceback_frames=5)
+
+ assert limited.count('File "') == 1
+ assert full.count('File "') == 4
+ assert limited.endswith("RuntimeError: deep failure")
+ assert full.endswith("RuntimeError: deep failure")