DSPy: The framework for programming—not prompting—language models
Python
Add evaluate callback (#7895)
TomuHiratac0d9098364c7
diff --git a/dspy/evaluate/evaluate.py b/dspy/evaluate/evaluate.pyindex 89be56893..407789cc0 100644--- a/dspy/evaluate/evaluate.py+++ b/dspy/evaluate/evaluate.py@@ -6,6 +6,7 @@ import pandas as pdimport tqdmimport dspy+from dspy.utils.callback import with_callbacksfrom dspy.utils.parallelizer import ParallelExecutortry:@@ -83,6 +84,7 @@ class Evaluate:self.provide_traceback = provide_tracebackself.failure_score = failure_score+ @with_callbacksdef __call__(self,program: "dspy.Module",diff --git a/dspy/utils/callback.py b/dspy/utils/callback.pyindex a1292ce52..ea88a8ac5 100644--- a/dspy/utils/callback.py+++ b/dspy/utils/callback.py@@ -222,6 +222,38 @@ class BaseCallback:"""pass+ def on_evaluate_start(+ self,+ call_id: str,+ instance: Any,+ inputs: Dict[str, Any],+ ):+ """A handler triggered when evaluation is started.++ Args:+ call_id: A unique identifier for the call. Can be used to connect start/end handlers.+ instance: The Evaluate instance.+ inputs: The inputs to the Evaluate's __call__ method. Each arguments is stored as+ a key-value pair in a dictionary.+ """+ pass++ def on_evaluate_end(+ self,+ call_id: str,+ outputs: Optional[Dict[str, Any]],+ exception: Optional[Exception] = None,+ ):+ """A handler triggered after evaluation is executed.++ Args:+ call_id: A unique identifier for the call. Can be used to connect start/end handlers.+ outputs: The outputs of the Evaluate's __call__ method. If the method is interrupted by+ an exception, this will be None.+ exception: If an exception is raised during the execution, it will be stored here.+ """+ pass+def with_callbacks(fn):@functools.wraps(fn)@@ -279,6 +311,8 @@ def _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -"""Selects the appropriate on_start handler of the callback based on the instance and function name."""if isinstance(instance, dspy.LM):return callback.on_lm_start+ elif isinstance(instance, dspy.Evaluate):+ return callback.on_evaluate_startif isinstance(instance, dspy.Adapter):if fn.__name__ == "format":@@ -299,6 +333,8 @@ def _get_on_end_handler(callback: BaseCallback, instance: Any, fn: Callable) ->"""Selects the appropriate on_end handler of the callback based on the instance and function name."""if isinstance(instance, (dspy.LM)):return callback.on_lm_end+ elif isinstance(instance, dspy.Evaluate):+ return callback.on_evaluate_endif isinstance(instance, (dspy.Adapter)):if fn.__name__ == "format":diff --git a/tests/evaluate/test_evaluate.py b/tests/evaluate/test_evaluate.pyindex 78935e3b8..8ac6f6564 100644--- a/tests/evaluate/test_evaluate.py+++ b/tests/evaluate/test_evaluate.py@@ -8,6 +8,7 @@ import dspyfrom dspy.evaluate.evaluate import Evaluatefrom dspy.evaluate.metrics import answer_exact_matchfrom dspy.predict import Predict+from dspy.utils.callback import BaseCallbackfrom dspy.utils.dummies import DummyLM@@ -173,3 +174,54 @@ def test_evaluate_display_table(program_with_example, display_table, is_in_ipyth# to the consoleexample_input = next(iter(example.inputs().values()))assert example_input in out++def test_evaluate_callback():+ class TestCallback(BaseCallback):+ def __init__(self):+ self.start_call_inputs = None+ self.start_call_count = 0+ self.end_call_outputs = None+ self.end_call_count = 0++ def on_evaluate_start(+ self,+ call_id: str,+ instance,+ inputs,+ ):+ self.start_call_inputs = inputs+ self.start_call_count += 1++ def on_evaluate_end(+ self,+ call_id: str,+ outputs,+ exception = None,+ ):+ self.end_call_outputs = outputs+ self.end_call_count += 1++ callback = TestCallback()+ dspy.settings.configure(+ lm=DummyLM(+ {+ "What is 1+1?": {"answer": "2"},+ "What is 2+2?": {"answer": "4"},+ }+ ),+ callbacks=[callback]+ )+ devset = [new_example("What is 1+1?", "2"), new_example("What is 2+2?", "4")]+ program = Predict("question -> answer")+ assert program(question="What is 1+1?").answer == "2"+ ev = Evaluate(+ devset=devset,+ metric=answer_exact_match,+ display_progress=False,+ )+ score = ev(program)+ assert score == 100.0+ assert callback.start_call_inputs["program"] == program+ assert callback.start_call_count == 1+ assert callback.end_call_outputs == 100.0+ assert callback.end_call_count == 1