DSPy: The framework for programming—not prompting—language models
Python
Merge
dilara6da66a0e94cb
diff --cc dspy/__init__.pyindex 93222530e,0c9348641..95b20e7a2--- a/dspy/__init__.py+++ b/dspy/__init__.py@@@ -57,3 -58,19 +58,19 @@@ You = dsp.Yoconfigure = settings.configurecontext = settings.context+++ import dspy.teleprompt++ LabeledFewShot = dspy.teleprompt.LabeledFewShot+ BootstrapFewShot = dspy.teleprompt.BootstrapFewShot+ BootstrapFewShotWithRandomSearch = dspy.teleprompt.BootstrapFewShotWithRandomSearch+ BootstrapRS = dspy.teleprompt.BootstrapFewShotWithRandomSearch+ COPRO = dspy.teleprompt.COPRO+ MIPROv2 = dspy.teleprompt.MIPROv2+ Ensemble = dspy.teleprompt.Ensemble+++ # TODO: Consider if this should access settings.lm *or* a list that's shared across all LMs in the program.+ def inspect_history(*args, **kwargs):- return settings.lm.inspect_history(*args, **kwargs)++ return settings.lm.inspect_history(*args, **kwargs)diff --cc dspy/predict/predict.pyindex 78dc0c20d,8bd42699d..88a74861a--- a/dspy/predict/predict.py+++ b/dspy/predict/predict.py@@@ -10,38 -8,17 +10,45 @@@ from dspy.primitives.program import Modfrom dspy.primitives.prediction import Predictionfrom dspy.signatures.signature import ensure_signature, signature_to_template+ import logging+ from functools import lru_cache++ @lru_cache(maxsize=None)+ def warn_once(msg: str):+ logging.warning(msg)++#-------------------------------------------------------------------------------+# Helper functions+#-------------------------------------------------------------------------------++def assert_structural_equivalency_for_predictors(+ predictor1: object,+ predictor2: object,+ ) -> Optional[AssertionError]:+ """Assert that the two predictors are structurally equivalent to each other.++ Args:+ predictor1: The predictor to compare with.+ predictor2: The predictor to compare with.++ Raises:+ AssertionError: If the predictors are not structurally equivalent.+ """+ # Assert that the objects are predictors+ assert isinstance(predictor1, Predict)+ assert isinstance(predictor2, Predict)++ # Assert that the predictors have equivalent signatures+ assert predictor1.signature.equals(predictor2.signature)+++#-------------------------------------------------------------------------------+# Classes+#-------------------------------------------------------------------------------+class Predict(Module, Parameter):- def __init__(self, signature, **config):+ def __init__(self, signature, _parse_values=True, **config):self.stage = random.randbytes(8).hex()self.signature = ensure_signature(signature)self.config = configdiff --cc dspy/primitives/module.pyindex c32d60bc3,5df2b308d..4fe9ea692--- a/dspy/primitives/module.py+++ b/dspy/primitives/module.py@@@ -102,17 -103,53 +103,52 @@@ class BaseModulereturn [param for _, param in self.named_parameters()]def deepcopy(self):- return copy.deepcopy(self)+ """Deep copy the module.++ This is a tweak to the default python deepcopy that only deep copies `self.parameters()`, and for other+ attributes, we just do the shallow copy.+ """+ try:+ # If the instance itself is copyable, we can just deep copy it.+ # Otherwise we will have to create a new instance and copy over the attributes one by one.+ return copy.deepcopy(self)+ except Exception:+ pass++ # Create an empty instance.+ new_instance = self.__class__.__new__(self.__class__)+ # Set attribuetes of the copied instance.+ for attr, value in self.__dict__.items():+ if isinstance(value, BaseModule):+ setattr(new_instance, attr, value.deepcopy())+ else:+ try:+ # Try to deep copy the attribute+ setattr(new_instance, attr, copy.deepcopy(value))+ except Exception:+ logging.warning(+ f"Failed to deep copy attribute '{attr}' of {self.__class__.__name__}, "+ "falling back to shallow copy or reference copy."+ )+ try:+ # Fallback to shallow copy if deep copy fails+ setattr(new_instance, attr, copy.copy(value))+ except Exception:+ # If even the shallow copy fails, we just copy over the reference.+ setattr(new_instance, attr, value)++ return new_instancedef reset_copy(self):- obj = copy.deepcopy(self)+ """Deep copy the module and reset all parameters."""+ new_instance = self.deepcopy()- for param in obj.parameters():+ for param in new_instance.parameters():param.reset()- return obj+ return new_instancedef dump_state(self, save_verbose):- print(self.named_parameters())return {name: param.dump_state(save_verbose) for name, param in self.named_parameters()}def load_state(self, state):