Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

fix(rlm): normalize sub-LM responses (#10023)

Isaac Miller873bfd981660
diff --git a/dspy/predict/rlm.py b/dspy/predict/rlm.py
index cab1c40f3..0cc2536b0 100644
--- a/dspy/predict/rlm.py
+++ b/dspy/predict/rlm.py
@@ -256,14 +256,24 @@ class RLM(Module):
def _query_lm(prompt: str) -> str:
target_lm = lm if lm is not None else dspy.settings.lm
if target_lm is None:
- raise RuntimeError("No LM configured. Use dspy.configure(lm=...) or pass sub_lm to RLM.")
+ raise dspy.LMNotConfiguredError(
+ "No LM configured. Use dspy.configure(lm=...) or pass sub_lm to RLM."
+ )
response = target_lm(prompt)
- if isinstance(response, list) and response:
- item = response[0]
- if isinstance(item, dict) and "text" in item:
- return item["text"]
- return item
- return str(response)
+ if isinstance(response, dspy.LMResponse):
+ text = response.text
+ elif isinstance(response, list) and response:
+ first_output = response[0]
+ text = first_output.get("text") if isinstance(first_output, dict) else first_output
+ else:
+ raise TypeError(
+ "Sub-LM must return dspy.LMResponse or a non-empty list of text outputs, "
+ f"got {type(response).__name__}."
+ )
+
+ if not isinstance(text, str):
+ raise TypeError(f"Sub-LM response must contain text, got {type(text).__name__}.")
+ return text
def llm_query(prompt: str) -> str:
"""Query the LLM with a prompt string."""
@@ -273,7 +283,7 @@ class RLM(Module):
return _query_lm(prompt)
def llm_query_batched(prompts: list[str]) -> list[str]:
- """Query the LLM with multiple prompts concurrently."""
+ """Query prompts concurrently, isolating LM failures while propagating contract errors."""
if not prompts:
return []
_check_and_increment(len(prompts))
@@ -288,7 +298,7 @@ class RLM(Module):
idx = future_to_idx[future]
try:
results[idx] = future.result()
- except Exception as e:
+ except dspy.LMError as e:
results[idx] = f"[ERROR] {e}"
return [results[i] for i in range(len(prompts))]
diff --git a/tests/predict/test_rlm.py b/tests/predict/test_rlm.py
index 327ce2eca..f3bbe5e58 100644
--- a/tests/predict/test_rlm.py
+++ b/tests/predict/test_rlm.py
@@ -240,12 +240,51 @@ class TestRLMInitialization:
with pytest.raises(TypeError, match="first positional argument"):
rlm(query="test", interpreter=MockInterpreter())
+ def test_llm_query_returns_legacy_response_text(self):
+ from dspy.utils.dummies import DummyLM
+
+ tools = RLM("context -> answer", sub_lm=DummyLM([{"answer": "legacy answer"}]))._make_llm_tools()
+
+ assert tools["llm_query"]("test prompt") == "[[ ## answer ## ]]\nlegacy answer"
+
+ def test_llm_query_returns_typed_response_text(self):
+ import dspy
+ from dspy.utils.dummies import DummyLM
+
+ tools = RLM("context -> answer", sub_lm=DummyLM([{"answer": "typed answer"}]))._make_llm_tools()
+
+ with dspy.context(experimental=True):
+ result = tools["llm_query"]("test prompt")
+
+ assert result == "[[ ## answer ## ]]\ntyped answer"
+
+ def test_llm_query_rejects_unsupported_response_shape(self):
+ from unittest.mock import MagicMock
+
+ tools = RLM("context -> answer", sub_lm=MagicMock(return_value="untyped response"))._make_llm_tools()
+
+ with pytest.raises(TypeError, match="Sub-LM must return dspy.LMResponse or a non-empty list"):
+ tools["llm_query"]("test prompt")
+
+ def test_llm_query_reports_textless_response_type(self):
+ from unittest.mock import MagicMock
+
+ tools = RLM(
+ "context -> answer",
+ sub_lm=MagicMock(return_value=[{"tool_calls": []}]),
+ )._make_llm_tools()
+
+ with pytest.raises(TypeError, match="Sub-LM response must contain text, got NoneType"):
+ tools["llm_query"]("test prompt")
+
def test_batched_query_errors_have_clear_markers(self):
"""Test that errors in llm_query_batched are prefixed with [ERROR]."""
from unittest.mock import MagicMock
+ import dspy
+
mock_lm = MagicMock()
- mock_lm.side_effect = RuntimeError("LM failed")
+ mock_lm.side_effect = dspy.LMTransportError("LM failed")
rlm = RLM("context -> answer", max_llm_calls=10, sub_lm=mock_lm)
tools = rlm._make_llm_tools()
@@ -255,6 +294,25 @@ class TestRLMInitialization:
assert results[0].startswith("[ERROR]")
assert "LM failed" in results[0]
+ def test_batched_query_marks_missing_lm_configuration(self):
+ import dspy
+
+ with dspy.context(lm=None):
+ tools = RLM("context -> answer")._make_llm_tools()
+ results = tools["llm_query_batched"](["test prompt"])
+
+ assert results == ["[ERROR] No LM configured. Use dspy.configure(lm=...) or pass sub_lm to RLM."]
+
+ def test_batched_query_propagates_programming_errors(self):
+ from unittest.mock import MagicMock
+
+ mock_lm = MagicMock()
+ mock_lm.side_effect = TypeError("invalid LM implementation")
+ tools = RLM("context -> answer", max_llm_calls=10, sub_lm=mock_lm)._make_llm_tools()
+
+ with pytest.raises(TypeError, match="invalid LM implementation"):
+ tools["llm_query_batched"](["test prompt"])
+
def test_batched_query_inherits_request_context(self):
import contextvars