DSPy: The framework for programming—not prompting—language models
Python
misc fix for assertions
Shangyintc531c4653ba2
diff --git a/dspy/primitives/assertions.py b/dspy/primitives/assertions.pyindex 103389a43..3992c1c55 100644--- a/dspy/primitives/assertions.py+++ b/dspy/primitives/assertions.py@@ -2,22 +2,27 @@# things to consider: what we want to assert, and what would be the syntax?# One possible starting point would be constraints on the output of a modulefrom typing import Any+import dspimport dspyclass DSPyAssertionError(AssertionError):"""DSPy custom error message."""+def __init__(self, msg: str, state: Any = None) -> None:super().__init__(msg)+ self.msg = msgself.state = stateclass Assert:"""Compile time assertion."""+def __init__(self, assert_fun, *args, **kwargs):self.assert_fun = assert_funself.args = argsself.kwargs = kwargs+ self.__call__()# assert fun should always return booldef __call__(self) -> bool:@@ -26,7 +31,9 @@ class Assert:if result:return Trueelse:- raise DSPyAssertionError(f"Assertion {self.assert_fun} failed")+ raise DSPyAssertionError(+ f"Assertion {self.assert_fun} failed", state=dsp.settings.trace+ )else:raise ValueError("Assertion function should always return [bool]")@@ -37,14 +44,20 @@ class Assert:def assert_transform(backtrack=2):"""Decorator for transforming a function into a rewindable function."""+def wrapper(func):def inner(*args, **kwargs):for i in range(backtrack):try:return func(*args, **kwargs)except DSPyAssertionError as e:- # Add metadata to state- pass+ print(f"{e.msg}")+ if dsp.settings.trace:+ print(dsp.settings.trace[-1])+ else:+ print(+ "UNREACHABLE: No trace available, this should not happen. Is this run time?"+ )return inner