DSPy: The framework for programming—not prompting—language models
Python
fix(rlm): execute tools through dspy.Tool (#10025)
Isaac Miller579e6a2f9d5d
diff --git a/dspy/predict/rlm.py b/dspy/predict/rlm.pyindex 7febd2bd9..cab1c40f3 100644--- a/dspy/predict/rlm.py+++ b/dspy/predict/rlm.py@@ -12,6 +12,8 @@ from __future__ import annotationsimport base64import contextvars+import functools+import inspectimport loggingimport threadingfrom concurrent.futures import ThreadPoolExecutor, as_completed@@ -441,11 +443,23 @@ class RLM(Module):# CodeInterpreter Lifecycle# =========================================================================+ def _make_interpreter_tool(self, tool: Tool) -> Callable:+ """Preserve function metadata while routing execution through Tool."""+ if inspect.iscoroutinefunction(tool.func) or inspect.iscoroutinefunction(getattr(tool.func, "__call__", None)):+ async def invoke(**kwargs):+ return await tool.acall(**kwargs)+ else:+ def invoke(**kwargs):+ return tool(**kwargs)++ functools.update_wrapper(invoke, tool.func)+ invoke.__signature__ = inspect.signature(tool.func)+ return invoke+def _prepare_execution_tools(self) -> dict[str, Callable]:"""Create fresh LLM tools and merge with user-provided tools."""execution_tools = self._make_llm_tools()- # Extract underlying functions from Tool objects for the interpreter- execution_tools.update({name: tool.func for name, tool in self._user_tools.items()})+ execution_tools.update({name: self._make_interpreter_tool(tool) for name, tool in self._user_tools.items()})return execution_toolsdef _inject_execution_context(self, interpreter: CodeInterpreter, execution_tools: dict[str, Callable]) -> None:diff --git a/tests/predict/test_rlm.py b/tests/predict/test_rlm.pyindex bf3e68084..327ce2eca 100644--- a/tests/predict/test_rlm.py+++ b/tests/predict/test_rlm.py@@ -1277,6 +1277,54 @@ class TestRLMWithDummyLM:assert result.color == "red"+ def test_dspy_tool_execution_semantics_e2e(self):+ import inspect++ from pydantic import BaseModel++ import dspy+ from dspy.utils.callback import BaseCallback++ class Payload(BaseModel):+ value: int++ received = []+ callback_events = []++ async def score(payload: Payload, factor: int = 2):+ received.append((payload, factor))+ return payload.value * factor++ class Recorder(BaseCallback):+ def on_tool_start(self, call_id, instance, inputs):+ callback_events.append(("start", instance))++ def on_tool_end(self, call_id, outputs, exception):+ callback_events.append(("end", outputs, exception))++ tool = Tool(score, name="score_payload")+ rlm = RLM("query -> answer: int", max_iters=1, tools=[tool])+ execution_tool = rlm._prepare_execution_tools()["score_payload"]++ assert execution_tool.__name__ == score.__name__+ assert inspect.signature(execution_tool) == inspect.signature(score)++ with dummy_lm_context([+ {+ "reasoning": "Call the tool",+ "code": 'result = score_payload({"value": 3})\nSUBMIT(result)',+ },+ ]):+ with dspy.context(callbacks=[Recorder()]):+ result = rlm.forward(query="test")++ assert result.answer == 6+ assert len(received) == 1+ assert isinstance(received[0][0], Payload)+ assert received[0][0].value == 3+ assert received[0][1] == 2+ assert callback_events == [("start", tool), ("end", 6, None)]+@pytest.mark.asyncioasync def test_aforward_simple_computation_e2e(self):"""Test aforward() full pipeline: DummyLM -> RLM -> PythonInterpreter -> result."""