Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Preserve callback decorator signatures with ty (#10684)

Isaac Miller351b87285716
diff --git a/dspy/utils/callback.py b/dspy/utils/callback.py
index 901b20bcf..7fc99f997 100644
--- a/dspy/utils/callback.py
+++ b/dspy/utils/callback.py
@@ -2,11 +2,14 @@ import functools
import inspect
import logging
import uuid
-from typing import Any, Callable
+from types import FunctionType
+from typing import Any, Callable, TypeVar, cast
import dspy
import dspy.utils.callback_context as callback_context
+F = TypeVar("F", bound=FunctionType)
+
ACTIVE_CALL_ID = callback_context.ACTIVE_CALL_ID
logger = logging.getLogger(__name__)
@@ -306,12 +309,20 @@ class BaseCallback:
pass
-def with_callbacks(fn):
- """Decorator to add callback functionality to instance methods."""
+def with_callbacks(fn: F) -> F:
+ """Add callbacks to an instance method while preserving its parameters and return type."""
- def _execute_start_callbacks(instance, fn, call_id, callbacks, args, kwargs):
+ def _execute_start_callbacks(
+ instance: object,
+ fn: F,
+ call_id: str,
+ callbacks: list[BaseCallback],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ ) -> None:
"""Execute all start callbacks for a function call."""
- inputs = inspect.getcallargs(fn, instance, *args, **kwargs)
+ # Keep the existing argument-binding behavior during this typing-only migration.
+ inputs = inspect.getcallargs(fn, instance, *args, **kwargs) # ty: ignore[deprecated]
if "self" in inputs:
inputs.pop("self")
elif "instance" in inputs:
@@ -322,7 +333,14 @@ def with_callbacks(fn):
except Exception as e:
logger.warning(f"Error when calling callback {callback}: {e}")
- def _execute_end_callbacks(instance, fn, call_id, results, exception, callbacks):
+ def _execute_end_callbacks(
+ instance: object,
+ fn: F,
+ call_id: str,
+ results: object,
+ exception: BaseException | None,
+ callbacks: list[BaseCallback],
+ ) -> None:
"""Execute all end callbacks for a function call."""
for callback in callbacks:
try:
@@ -334,14 +352,15 @@ def with_callbacks(fn):
except Exception as e:
logger.warning(f"Error when applying callback {callback}'s end handler on function {fn.__name__}: {e}.")
- def _get_active_callbacks(instance):
+ def _get_active_callbacks(instance: object) -> list[BaseCallback]:
"""Get combined global and instance-level callbacks."""
- return dspy.settings.get("callbacks", []) + getattr(instance, "callbacks", [])
+ callbacks: list[BaseCallback] = dspy.settings.get("callbacks", []) + getattr(instance, "callbacks", [])
+ return callbacks
if inspect.iscoroutinefunction(fn):
@functools.wraps(fn)
- async def async_wrapper(instance, *args, **kwargs):
+ async def async_wrapper(instance: object, *args: Any, **kwargs: Any) -> object:
callbacks = _get_active_callbacks(instance)
if not callbacks:
return await fn(instance, *args, **kwargs)
@@ -366,12 +385,14 @@ def with_callbacks(fn):
callback_context.ACTIVE_CALL_ID.set(parent_call_id)
_execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)
- return async_wrapper
+ # Both wrappers forward arguments and results unchanged. Preserve the full
+ # callable type, including generic/overloaded methods and coroutine results.
+ return cast(F, async_wrapper)
else:
@functools.wraps(fn)
- def sync_wrapper(instance, *args, **kwargs):
+ def sync_wrapper(instance: object, *args: Any, **kwargs: Any) -> object:
callbacks = _get_active_callbacks(instance)
if not callbacks:
return fn(instance, *args, **kwargs)
@@ -396,10 +417,10 @@ def with_callbacks(fn):
callback_context.ACTIVE_CALL_ID.set(parent_call_id)
_execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)
- return sync_wrapper
+ return cast(F, sync_wrapper)
-def _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -> Callable:
+def _get_on_start_handler(callback: BaseCallback, instance: object, fn: FunctionType) -> Callable[..., Any]:
"""Selects the appropriate on_start handler of the callback based on the instance and function name."""
from dspy.teleprompt.teleprompt import Teleprompter
@@ -427,7 +448,7 @@ def _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -
return callback.on_module_start
-def _get_on_end_handler(callback: BaseCallback, instance: Any, fn: Callable) -> Callable:
+def _get_on_end_handler(callback: BaseCallback, instance: object, fn: FunctionType) -> Callable[..., Any]:
"""Selects the appropriate on_end handler of the callback based on the instance and function name."""
from dspy.teleprompt.teleprompt import Teleprompter
diff --git a/dspy/utils/callback_context.py b/dspy/utils/callback_context.py
index ca848409c..c412acd71 100644
--- a/dspy/utils/callback_context.py
+++ b/dspy/utils/callback_context.py
@@ -1,17 +1,20 @@
import functools
from contextvars import ContextVar
-from typing import Callable
+from typing import Callable, ParamSpec, TypeVar
-ACTIVE_CALL_ID = ContextVar("active_call_id", default=None)
+P = ParamSpec("P")
+T = TypeVar("T")
+
+ACTIVE_CALL_ID: ContextVar[str | None] = ContextVar("active_call_id", default=None)
_ACTIVE_COMPILES = ContextVar("active_compiles", default=())
-def _bind_active_call_id(fn: Callable) -> Callable:
+def _bind_active_call_id(fn: Callable[P, T]) -> Callable[P, T]:
"""Bind the current callback call ID to each synchronous invocation of ``fn``."""
parent_call_id = ACTIVE_CALL_ID.get()
@functools.wraps(fn)
- def wrapper(*args, **kwargs):
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
token = ACTIVE_CALL_ID.set(parent_call_id)
try:
return fn(*args, **kwargs)
diff --git a/pyproject.toml b/pyproject.toml
index d90c64616..b48d1fbd7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -140,6 +140,8 @@ filterwarnings = [
# inputs/outputs are not part of this initial type-checking contract.
include = [
"dspy/utils/asyncify.py",
+ "dspy/utils/callback.py",
+ "dspy/utils/callback_context.py",
"dspy/utils/usage_tracker.py",
"tests/typing",
]
diff --git a/tests/typing/callbacks.py b/tests/typing/callbacks.py
new file mode 100644
index 000000000..a1bdb68ec
--- /dev/null
+++ b/tests/typing/callbacks.py
@@ -0,0 +1,78 @@
+"""Callback decorators preserve caller-visible sync and async contracts.
+
+Deliberately invalid calls use ignores to assert expected diagnostics. Unused-ignore
+errors make these checks fail if the decorators stop rejecting invalid calls.
+"""
+
+import asyncio
+from typing import Any, Coroutine, TypeVar, overload
+
+from typing_extensions import assert_type
+
+from dspy import Evaluate, Module
+from dspy.evaluate import EvaluationResult
+from dspy.utils.callback import with_callbacks
+from dspy.utils.callback_context import _bind_active_call_id
+
+T = TypeVar("T")
+
+
+class Runner:
+ @with_callbacks
+ def run(self, count: int, /, *, prefix: str) -> str:
+ return f"{prefix}: {count}"
+
+ @with_callbacks
+ async def arun(self, count: int, /, *, prefix: str) -> int:
+ return count + len(prefix)
+
+ @with_callbacks
+ def deferred(self, count: int) -> Coroutine[Any, Any, int]:
+ return self.arun(count, prefix="later")
+
+ @with_callbacks
+ def identity(self, value: T) -> T:
+ return value
+
+ @overload
+ def echo(self, value: int) -> int: ...
+
+ @overload
+ def echo(self, value: str) -> str: ...
+
+ def echo(self, value: int | str) -> int | str:
+ return value
+
+
+class UnnamedCallable:
+ def __call__(self, count: int) -> int:
+ return count
+
+
+async def check_callbacks(evaluate: Evaluate, program: Module, value: str) -> None:
+ runner = Runner()
+ assert_type(runner.run(3, prefix="count"), str)
+ assert_type(Runner.run(runner, 3, prefix="count"), str)
+ assert_type(runner.identity(value), str)
+ assert_type(await runner.arun(3, prefix="count"), int)
+ assert_type(await asyncio.create_task(runner.arun(3, prefix="count")), int)
+ assert_type(await runner.deferred(3), int)
+ assert_type(evaluate(program), EvaluationResult)
+
+ runner.run("three", prefix="count") # ty: ignore[invalid-argument-type]
+ runner.run(3) # ty: ignore[missing-argument]
+ runner.run(3, "count", prefix="count") # ty: ignore[too-many-positional-arguments]
+ runner.run(count=3, prefix="count") # ty: ignore[positional-only-parameter-as-kwarg]
+ await runner.arun("three", prefix="count") # ty: ignore[invalid-argument-type]
+ await runner.arun(3) # ty: ignore[missing-argument]
+
+ bound = _bind_active_call_id(runner.run)
+ assert_type(bound(3, prefix="bound"), str)
+ bound("three", prefix="bound") # ty: ignore[invalid-argument-type]
+
+ overloaded = with_callbacks(Runner.echo)
+ assert_type(overloaded(runner, 3), int)
+ assert_type(overloaded(runner, "three"), str)
+ overloaded(runner, []) # ty: ignore[no-matching-overload]
+
+ with_callbacks(UnnamedCallable()) # ty: ignore[invalid-argument-type]