DSPy: The framework for programming—not prompting—language models
Python
Add async callback (#8105)
Chen Qian3751a9b6cdaf
diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.pyindex 7d05e408c..4c7d15cc3 100644--- a/dspy/clients/base_lm.py+++ b/dspy/clients/base_lm.py@@ -91,6 +91,7 @@ class BaseLM(ABC):return outputs+ @with_callbacksasync def acall(self, prompt=None, messages=None, **kwargs):response = await self.aforward(prompt=prompt, messages=messages, **kwargs)outputs = self._process_lm_response(response, prompt, messages, **kwargs)diff --git a/dspy/predict/predict.py b/dspy/predict/predict.pyindex e6c800dd1..bde632616 100644--- a/dspy/predict/predict.py+++ b/dspy/predict/predict.py@@ -75,6 +75,7 @@ class Predict(Module, Parameter):def __call__(self, **kwargs):return self.forward(**kwargs)+ @with_callbacksasync def acall(self, **kwargs):return await self.aforward(**kwargs)diff --git a/dspy/primitives/program.py b/dspy/primitives/program.pyindex 23ccdec1f..b02c8e8da 100644--- a/dspy/primitives/program.py+++ b/dspy/primitives/program.py@@ -31,6 +31,7 @@ class Module(BaseModule, metaclass=ProgramMeta):return self.forward(*args, **kwargs)+ @with_callbacksasync def acall(self, *args, **kwargs):if settings.track_usage and settings.usage_tracker is None:with track_usage() as usage_tracker:diff --git a/dspy/utils/callback.py b/dspy/utils/callback.pyindex 6ba0c4cd0..2753c8f84 100644--- a/dspy/utils/callback.py+++ b/dspy/utils/callback.py@@ -256,60 +256,96 @@ class BaseCallback:def with_callbacks(fn):- @functools.wraps(fn)- def wrapper(instance, *args, **kwargs):- # Combine global and local (per-instance) callbacks.- callbacks = dspy.settings.get("callbacks", []) + getattr(instance, "callbacks", [])-- # If no callbacks are provided, just call the function- if not callbacks:- return fn(instance, *args, **kwargs)-- # Generate call ID as the unique identifier for the call, this is useful for instrumentation.- call_id = uuid.uuid4().hex+ """Decorator to add callback functionality to instance methods."""+ def _execute_start_callbacks(instance, fn, call_id, callbacks, args, kwargs):+ """Execute all start callbacks for a function call."""inputs = inspect.getcallargs(fn, instance, *args, **kwargs)-- # We don't include the instance information in the inpusif "self" in inputs:inputs.pop("self")elif "instance" in inputs:inputs.pop("instance")-for callback in callbacks:try:_get_on_start_handler(callback, instance, fn)(call_id=call_id, instance=instance, inputs=inputs)-except Exception as e:logger.warning(f"Error when calling callback {callback}: {e}")- results = None- exception = None- try:+ def _execute_end_callbacks(instance, fn, call_id, results, exception, callbacks):+ """Execute all end callbacks for a function call."""+ for callback in callbacks:+ try:+ _get_on_end_handler(callback, instance, fn)(+ call_id=call_id,+ outputs=results,+ exception=exception,+ )+ 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):+ """Get combined global and instance-level callbacks."""+ return dspy.settings.get("callbacks", []) + getattr(instance, "callbacks", [])++ if inspect.iscoroutinefunction(fn):++ @functools.wraps(fn)+ async def async_wrapper(instance, *args, **kwargs):+ callbacks = _get_active_callbacks(instance)+ if not callbacks:+ return await fn(instance, *args, **kwargs)++ call_id = uuid.uuid4().hex++ _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)++ results = None+ exception = None+ try:+ results = await fn(instance, *args, **kwargs)+ return results+ except Exception as e:+ exception = e+ raise exception+ finally:+ ACTIVE_CALL_ID.set(parent_call_id)+ _execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)++ return async_wrapper++ else:++ @functools.wraps(fn)+ def sync_wrapper(instance, *args, **kwargs):+ callbacks = _get_active_callbacks(instance)+ if not callbacks:+ return fn(instance, *args, **kwargs)++ call_id = uuid.uuid4().hex++ _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)- results = fn(instance, *args, **kwargs)- return results- except Exception as e:- exception = e- raise exception- finally:- # Execute the end handlers even if the function call raises an exception.- ACTIVE_CALL_ID.set(parent_call_id)- for callback in callbacks:- try:- _get_on_end_handler(callback, instance, fn)(- call_id=call_id,- outputs=results,- exception=exception,- )- except Exception as e:- logger.warning(- f"Error when applying callback {callback}'s end handler on function {fn.__name__}: {e}."- )-- return wrapper++ results = None+ exception = None+ try:+ results = fn(instance, *args, **kwargs)+ return results+ except Exception as e:+ exception = e+ raise exception+ finally:+ ACTIVE_CALL_ID.set(parent_call_id)+ _execute_end_callbacks(instance, fn, call_id, results, exception, callbacks)++ return sync_wrapperdef _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -> Callable:diff --git a/tests/callback/test_callback.py b/tests/callback/test_callback.pyindex 567b9f876..b3df2b0cd 100644--- a/tests/callback/test_callback.py+++ b/tests/callback/test_callback.py@@ -186,6 +186,38 @@ def test_callback_complex_module():"on_module_end",]+async def test_callback_async_module():+ callback = MyCallback()+ dspy.settings.configure(+ lm=DummyLM({"How are you?": {"answer": "test output", "reasoning": "No more responses"}}),+ callbacks=[callback],+ )++ cot = dspy.ChainOfThought("question -> answer", n=3)+ result = await cot.acall(question="How are you?")+ assert result["answer"] == "test output"+ assert result["reasoning"] == "No more responses"++ assert len(callback.calls) == 14+ assert [call["handler"] for call in callback.calls] == [+ "on_module_start",+ "on_module_start",+ "on_adapter_format_start",+ "on_adapter_format_end",+ "on_lm_start",+ "on_lm_end",+ # Parsing will run per output (n=3)+ "on_adapter_parse_start",+ "on_adapter_parse_end",+ "on_adapter_parse_start",+ "on_adapter_parse_end",+ "on_adapter_parse_start",+ "on_adapter_parse_end",+ "on_module_end",+ "on_module_end",+ ]+def test_tool_calls():callback = MyCallback()