Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

feat(callbacks): expose interpreter lifecycle events (#10119)

Isaac Millerb11cfe874d46
diff --git a/dspy/primitives/python_interpreter.py b/dspy/primitives/python_interpreter.py
index b7c90e510..a947982cb 100644
--- a/dspy/primitives/python_interpreter.py
+++ b/dspy/primitives/python_interpreter.py
@@ -24,6 +24,7 @@ from pydantic import BaseModel
from pydantic_core import PydanticSerializationError, to_jsonable_python
from dspy.primitives.code_interpreter import SIMPLE_TYPES, CodeExecutionError, CodeInterpreterError, FinalOutput
+from dspy.utils.callback import BaseCallback, with_callbacks
__all__ = ["PythonInterpreter", "FinalOutput", "CodeExecutionError", "CodeInterpreterError"]
@@ -173,6 +174,7 @@ class PythonInterpreter:
sync_files: bool = True,
tools: dict[str, Callable[..., str]] | None = None,
output_fields: list[dict] | None = None,
+ callbacks: list[BaseCallback] | None = None,
) -> None:
"""
Args:
@@ -188,6 +190,7 @@ class PythonInterpreter:
Tools are callable directly from sandbox code by name.
output_fields: List of output field definitions for typed SUBMIT signature.
Each dict should have 'name' and optionally 'type' keys.
+ callbacks: Optional instance-level callback handlers.
"""
if isinstance(deno_command, dict):
raise TypeError("deno_command must be a list of strings, not a dict")
@@ -199,6 +202,7 @@ class PythonInterpreter:
self.sync_files = sync_files
self.tools = dict(tools) if tools else {}
self.output_fields = output_fields
+ self.callbacks = list(callbacks or [])
self._tools_registered = False
# TODO later on add enable_run (--allow-run) by proxying subprocess.run through Deno.run() to fix 'emscripten does not support processes' error
@@ -397,11 +401,7 @@ class PythonInterpreter:
kwargs = params.get("kwargs", {})
try:
- if tool_name not in self.tools:
- raise CodeInterpreterError(f"Unknown tool: {tool_name}")
- result = self.tools[tool_name](**kwargs)
- if asyncio.iscoroutine(result):
- result = _await_in_sync(result)
+ result = self.invoke_tool(tool_name, kwargs)
result = _make_jsonable(result)
if result is None or isinstance(result, str):
response = _jsonrpc_result({"value": str(result) if result is not None else "", "type": "string"}, request_id)
@@ -417,6 +417,13 @@ class PythonInterpreter:
self._write_message(response, "while returning a tool result")
+ @with_callbacks
+ def invoke_tool(self, tool_name: str, kwargs: dict[str, Any]) -> Any:
+ if tool_name not in self.tools:
+ raise CodeInterpreterError(f"Unknown tool: {tool_name}")
+ result = self.tools[tool_name](**kwargs)
+ return _await_in_sync(result) if asyncio.iscoroutine(result) else result
+
def _ensure_deno_process(self) -> None:
self._check_session_active()
@@ -429,6 +436,9 @@ class PythonInterpreter:
"Create a new interpreter for a fresh session."
)
+ self.start()
+
+ def _spawn_process(self) -> None:
try:
self.deno_process = subprocess.Popen(
self.deno_command,
@@ -615,6 +625,7 @@ class PythonInterpreter:
"""Inject a large variable via the virtual filesystem."""
self._send_request("inject_var", {"name": name, "value": value}, f"injecting variable '{name}'")
+ @with_callbacks
def execute(
self,
code: str,
@@ -697,6 +708,7 @@ class PythonInterpreter:
self._raise_terminal_error(f"Too many non-JSON lines ({skipped}) during execution")
+ @with_callbacks
def start(self) -> None:
"""Initialize the Deno/Pyodide sandbox.
@@ -707,7 +719,11 @@ class PythonInterpreter:
Idempotent while the session is active. A stopped or shut-down session
cannot be restarted because its Python state cannot be reconstructed.
"""
- self._ensure_deno_process()
+ if self.deno_process is None:
+ self._check_session_active()
+ self._spawn_process()
+ else:
+ self._ensure_deno_process()
def __enter__(self):
return self
@@ -722,6 +738,7 @@ class PythonInterpreter:
) -> Any:
return self.execute(code, variables)
+ @with_callbacks
def shutdown(self) -> None:
session_was_active = not self._session_ended
self._session_ended = True
diff --git a/dspy/utils/callback.py b/dspy/utils/callback.py
index 8c8dc0033..4652c8c7a 100644
--- a/dspy/utils/callback.py
+++ b/dspy/utils/callback.py
@@ -5,10 +5,19 @@ import uuid
from typing import Any, Callable
import dspy
-from dspy.utils.callback_context import ACTIVE_CALL_ID
+import dspy.utils.callback_context as callback_context
+
+ACTIVE_CALL_ID = callback_context.ACTIVE_CALL_ID
logger = logging.getLogger(__name__)
+_INTERPRETER_OPERATIONS = {
+ "execute": "execute",
+ "invoke_tool": "tool_call",
+ "start": "startup",
+ "shutdown": "shutdown",
+}
+
class BaseCallback:
"""A base class for defining callback handlers for DSPy components.
@@ -252,6 +261,30 @@ class BaseCallback:
"""
pass
+ def on_interpreter_execute_start(self, call_id: str, instance: Any, inputs: dict[str, Any]):
+ pass
+
+ def on_interpreter_execute_end(self, call_id: str, outputs: Any | None, exception: Exception | None = None):
+ pass
+
+ def on_interpreter_tool_call_start(self, call_id: str, instance: Any, inputs: dict[str, Any]):
+ pass
+
+ def on_interpreter_tool_call_end(self, call_id: str, outputs: Any | None, exception: Exception | None = None):
+ pass
+
+ def on_interpreter_startup_start(self, call_id: str, instance: Any, inputs: dict[str, Any]):
+ pass
+
+ def on_interpreter_startup_end(self, call_id: str, outputs: Any | None, exception: Exception | None = None):
+ pass
+
+ def on_interpreter_shutdown_start(self, call_id: str, instance: Any, inputs: dict[str, Any]):
+ pass
+
+ def on_interpreter_shutdown_end(self, call_id: str, outputs: Any | None, exception: Exception | None = None):
+ pass
+
def with_callbacks(fn):
"""Decorator to add callback functionality to instance methods."""
@@ -298,8 +331,8 @@ def with_callbacks(fn):
_execute_start_callbacks(instance, fn, call_id, callbacks, args, kwargs)
# Active ID must be set right before the function is called, not before calling the callbacks.
- parent_call_id = ACTIVE_CALL_ID.get()
- ACTIVE_CALL_ID.set(call_id)
+ parent_call_id = callback_context.ACTIVE_CALL_ID.get()
+ callback_context.ACTIVE_CALL_ID.set(call_id)
results = None
exception = None
@@ -310,7 +343,7 @@ def with_callbacks(fn):
exception = e
raise exception
finally:
- ACTIVE_CALL_ID.set(parent_call_id)
+ callback_context.ACTIVE_CALL_ID.set(parent_call_id)
_execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)
return async_wrapper
@@ -328,8 +361,8 @@ def with_callbacks(fn):
_execute_start_callbacks(instance, fn, call_id, callbacks, args, kwargs)
# Active ID must be set right before the function is called, not before calling the callbacks.
- parent_call_id = ACTIVE_CALL_ID.get()
- ACTIVE_CALL_ID.set(call_id)
+ parent_call_id = callback_context.ACTIVE_CALL_ID.get()
+ callback_context.ACTIVE_CALL_ID.set(call_id)
results = None
exception = None
@@ -340,7 +373,7 @@ def with_callbacks(fn):
exception = e
raise exception
finally:
- ACTIVE_CALL_ID.set(parent_call_id)
+ callback_context.ACTIVE_CALL_ID.set(parent_call_id)
_execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)
return sync_wrapper
@@ -352,6 +385,8 @@ def _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -
return callback.on_lm_start
elif isinstance(instance, dspy.Evaluate):
return callback.on_evaluate_start
+ elif isinstance(instance, dspy.CodeInterpreter):
+ return getattr(callback, f"on_interpreter_{_INTERPRETER_OPERATIONS[fn.__name__]}_start")
if isinstance(instance, dspy.Adapter):
if fn.__name__ == "format":
@@ -374,6 +409,8 @@ def _get_on_end_handler(callback: BaseCallback, instance: Any, fn: Callable) ->
return callback.on_lm_end
elif isinstance(instance, dspy.Evaluate):
return callback.on_evaluate_end
+ elif isinstance(instance, dspy.CodeInterpreter):
+ return getattr(callback, f"on_interpreter_{_INTERPRETER_OPERATIONS[fn.__name__]}_end")
if isinstance(instance, (dspy.Adapter)):
if fn.__name__ == "format":
diff --git a/tests/callback/test_callback.py b/tests/callback/test_callback.py
index 3b4d3ee9a..d13392fa9 100644
--- a/tests/callback/test_callback.py
+++ b/tests/callback/test_callback.py
@@ -1,5 +1,6 @@
import time
+import cloudpickle
import pytest
import dspy
@@ -75,6 +76,18 @@ def test_bind_active_call_id_restores_context_after_exception():
assert ACTIVE_CALL_ID.get() is None
+async def test_with_callbacks_wrappers_round_trip_through_cloudpickle():
+ async def async_fn(self):
+ return "async"
+
+ sync_fn = cloudpickle.loads(cloudpickle.dumps(with_callbacks(lambda self: "sync")))
+ async_fn = cloudpickle.loads(cloudpickle.dumps(with_callbacks(async_fn)))
+
+ assert sync_fn(object()) == "sync"
+ assert await async_fn(object()) == "async"
+
+
@pytest.mark.parametrize(
("args", "kwargs"),
[
diff --git a/tests/callback/test_interpreter_callback.py b/tests/callback/test_interpreter_callback.py
new file mode 100644
index 000000000..89e62d1b2
--- /dev/null
+++ b/tests/callback/test_interpreter_callback.py
@@ -0,0 +1,264 @@
+import json
+
+import pytest
+
+import dspy
+from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreterError, FinalOutput
+from dspy.utils.callback import ACTIVE_CALL_ID, BaseCallback, with_callbacks
+
+
+class RecordingCallback(BaseCallback):
+ def __init__(self, name=None, observed=None):
+ self.events = []
+ self.name = name
+ self.observed = observed
+
+ def _record(self, event):
+ self.events.append(event)
+ if self.observed is not None:
+ self.observed.append((self.name, event["handler"]))
+
+ def _start(self, handler, call_id, instance, inputs):
+ self._record({
+ "handler": handler,
+ "call_id": call_id,
+ "parent_call_id": ACTIVE_CALL_ID.get(),
+ "instance": instance,
+ "inputs": inputs,
+ })
+
+ def _end(self, handler, call_id, outputs, exception):
+ self._record({
+ "handler": handler,
+ "call_id": call_id,
+ "parent_call_id": ACTIVE_CALL_ID.get(),
+ "outputs": outputs,
+ "exception": exception,
+ })
+
+ def on_interpreter_execute_start(self, call_id, instance, inputs):
+ self._start("execute_start", call_id, instance, inputs)
+
+ def on_interpreter_execute_end(self, call_id, outputs, exception):
+ self._end("execute_end", call_id, outputs, exception)
+
+ def on_interpreter_tool_call_start(self, call_id, instance, inputs):
+ self._start("tool_start", call_id, instance, inputs)
+
+ def on_interpreter_tool_call_end(self, call_id, outputs, exception):
+ self._end("tool_end", call_id, outputs, exception)
+
+ def on_interpreter_startup_start(self, call_id, instance, inputs):
+ self._start("startup_start", call_id, instance, inputs)
+
+ def on_interpreter_startup_end(self, call_id, outputs, exception):
+ self._end("startup_end", call_id, outputs, exception)
+
+ def on_interpreter_shutdown_start(self, call_id, instance, inputs):
+ self._start("shutdown_start", call_id, instance, inputs)
+
+ def on_interpreter_shutdown_end(self, call_id, outputs, exception):
+ self._end("shutdown_end", call_id, outputs, exception)
+
+
+def events_for(callback, handler):
+ return [event for event in callback.events if event["handler"] == handler]
+
+
+def test_custom_interpreter_protocol_methods_use_interpreter_callbacks():
+ class CustomInterpreter:
+ def __init__(self):
+ self.tools = {}
+
+ @with_callbacks
+ def start(self):
+ pass
+
+ @with_callbacks
+ def execute(self, code, variables=None):
+ return code
+
+ def shutdown(self):
+ pass
+
+ callback = RecordingCallback()
+ interpreter = CustomInterpreter()
+
+ with dspy.context(callbacks=[callback]):
+ interpreter.start()
+ assert interpreter.execute("result", {"x": 1}) == "result"
+
+ startup_start, startup_end, execute_start, execute_end = callback.events
+ assert startup_start["handler"] == "startup_start"
+ assert startup_start["instance"] is interpreter
+ assert startup_start["inputs"] == {}
+ assert startup_end["handler"] == "startup_end"
+ assert startup_end["call_id"] == startup_start["call_id"]
+ assert startup_end["outputs"] is None
+ assert startup_end["exception"] is None
+ assert execute_start["handler"] == "execute_start"
+ assert execute_start["instance"] is interpreter
+ assert execute_start["inputs"] == {"code": "result", "variables": {"x": 1}}
+ assert execute_end["handler"] == "execute_end"
+ assert execute_end["call_id"] == execute_start["call_id"]
+ assert execute_end["outputs"] == "result"
+ assert execute_end["exception"] is None
+
+
+def test_invoke_tool_reports_raw_result_and_propagates_exception():
+ callback = RecordingCallback()
+ raw_result = object()
+ expected_error = RuntimeError("tool failed")
+
+ def fail():
+ raise expected_error
+
+ interpreter = dspy.PythonInterpreter(
+ tools={"succeed": lambda: raw_result, "fail": fail},
+ callbacks=[callback],
+ )
+
+ assert interpreter.invoke_tool("succeed", {}) is raw_result
+ with pytest.raises(RuntimeError) as exc_info:
+ interpreter.invoke_tool("fail", {})
+
+ starts = events_for(callback, "tool_start")
+ ends = events_for(callback, "tool_end")
+ assert starts[0]["inputs"] == {"tool_name": "succeed", "kwargs": {}}
+ assert ends[0]["call_id"] == starts[0]["call_id"]
+ assert ends[0]["outputs"] is raw_result
+ assert ends[0]["exception"] is None
+ assert ends[1]["outputs"] is None
+ assert ends[1]["exception"] is expected_error
+ assert exc_info.value is expected_error
+
+
+def test_handle_tool_call_reports_host_exception_before_jsonrpc_conversion(monkeypatch):
+ callback = RecordingCallback()
+ expected_error = ValueError("invalid tool input")
+
+ def fail():
+ raise expected_error
+
+ interpreter = dspy.PythonInterpreter(tools={"fail": fail}, callbacks=[callback])
+ writes = []
+ monkeypatch.setattr(interpreter, "_write_message", lambda message, context: writes.append((message, context)))
+
+ interpreter._handle_tool_call({"id": 7, "params": {"name": "fail", "kwargs": {}}})
+
+ end = events_for(callback, "tool_end")[0]
+ response = json.loads(writes[0][0])
+ assert end["outputs"] is None
+ assert end["exception"] is expected_error
+ assert response["id"] == 7
+ assert response["error"]["data"]["type"] == "ValueError"
+ assert response["error"]["message"] == "invalid tool input"
+
+
+def test_unknown_tool_reports_code_interpreter_error():
+ callback = RecordingCallback()
+ interpreter = dspy.PythonInterpreter(callbacks=[callback])
+
+ with pytest.raises(CodeInterpreterError, match="Unknown tool: missing") as exc_info:
+ interpreter.invoke_tool("missing", {})
+
+ end = events_for(callback, "tool_end")[0]
+ assert end["outputs"] is None
+ assert end["exception"] is exc_info.value
+
+
+def test_shutdown_callbacks_fire_for_each_idempotent_call():
+ callback = RecordingCallback()
+ interpreter = dspy.PythonInterpreter(callbacks=[callback])
+
+ interpreter.shutdown()
+ interpreter.shutdown()
+
+ starts = events_for(callback, "shutdown_start")
+ ends = events_for(callback, "shutdown_end")
+ assert len(starts) == len(ends) == 2
+ assert [event["call_id"] for event in starts] == [event["call_id"] for event in ends]
+ assert all(event["outputs"] is None and event["exception"] is None for event in ends)
+
+
+def test_real_interpreter_callbacks_preserve_lazy_startup_tool_nesting_and_final_output():
+ observed = []
+ global_callback = RecordingCallback("global", observed)
+ instance_callback = RecordingCallback("instance", observed)
+ with dspy.context(callbacks=[global_callback]):
+ with dspy.PythonInterpreter(
+ tools={"echo": lambda value: value}, callbacks=[instance_callback]
+ ) as interpreter:
+ assert interpreter.execute("echo(value=payload)", variables={"payload": "first"}) == "first"
+ final_output = interpreter.execute("SUBMIT('done')")
+
+ assert final_output == FinalOutput({"output": "done"})
+
+ expected_handlers = [
+ "execute_start",
+ "startup_start",
+ "startup_end",
+ "tool_start",
+ "tool_end",
+ "execute_end",
+ "execute_start",
+ "execute_end",
+ "shutdown_start",
+ "shutdown_end",
+ ]
+ assert [event["handler"] for event in global_callback.events] == expected_handlers
+ assert [event["handler"] for event in instance_callback.events] == expected_handlers
+ assert observed == [
+ (source, handler)
+ for handler in expected_handlers
+ for source in ("global", "instance")
+ ]
+ first_execute, startup_start, startup_end, tool_start, tool_end, first_end = instance_callback.events[:6]
+ second_execute, second_end, shutdown_start, shutdown_end = instance_callback.events[6:]
+ assert first_execute["inputs"] == {
+ "code": "echo(value=payload)",
+ "variables": {"payload": "first"},
+ }
+ assert startup_start["parent_call_id"] == first_execute["call_id"]
+ assert tool_start["parent_call_id"] == first_execute["call_id"]
+ assert startup_end["call_id"] == startup_start["call_id"]
+ assert tool_end["call_id"] == tool_start["call_id"]
+ assert tool_end["outputs"] == "first"
+ assert first_end["call_id"] == first_execute["call_id"]
+ assert first_end["outputs"] == "first"
+ assert second_end["call_id"] == second_execute["call_id"]
+ assert second_end["outputs"] is final_output
+ assert shutdown_end["call_id"] == shutdown_start["call_id"]
+
+
+def test_explicit_startup_callbacks_fire_for_each_idempotent_start_call():
+ callback = RecordingCallback()
+ interpreter = dspy.PythonInterpreter(callbacks=[callback])
+
+ interpreter.start()
+ interpreter.start()
+ interpreter.shutdown()
+
+ starts = events_for(callback, "startup_start")
+ ends = events_for(callback, "startup_end")
+ assert len(starts) == len(ends) == 2
+ assert all(event["inputs"] == {} for event in starts)
+ assert all(event["parent_call_id"] is None for event in starts)
+ assert [event["call_id"] for event in starts] == [event["call_id"] for event in ends]
+ assert all(event["outputs"] is None and event["exception"] is None for event in ends)
+
+
+def test_real_interpreter_execute_error_is_reported_and_propagated():
+ callback = RecordingCallback()
+ with dspy.PythonInterpreter(callbacks=[callback]) as interpreter:
+ with pytest.raises(CodeExecutionError) as exc_info:
+ interpreter.execute("raise ValueError('boom')")
+
+ execute_end = events_for(callback, "execute_end")[0]
+ assert execute_end["outputs"] is None
+ assert execute_end["exception"] is exc_info.value
+ assert events_for(callback, "startup_end")[0]["exception"] is None
+ assert events_for(callback, "shutdown_end")[0]["exception"] is None