Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

backward compatibility

chenmoneygithub691ab1016bfb
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index ead7cae1f..aa4f2c368 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -57,7 +57,17 @@ class Predict(Module, Parameter):
return state
- def load_state(self, state):
+ def load_state(self, state, use_legacy_loading=False):
+ """Load the saved state of a `Predict` object.
+
+ Args:
+ state (dict): The saved state of a `Predict` object.
+ use_legacy_loading (bool): Whether to use the legacy loading method. Only use it when you are loading a
+ saved state from a version of DSPy prior to v2.5.3.
+ """
+ if use_legacy_loading:
+ self._load_state_legacy(state)
+ return
excluded_keys = ["signature", "extended_signature"]
for name, value in state.items():
# `excluded_keys` are fields that go through special handling.
@@ -69,6 +79,34 @@ class Predict(Module, Parameter):
if "extended_signature" in state:
self.extended_signature.load_state(state["extended_signature"])
+ def _load_state_legacy(self, state):
+ """Legacy state loading for backwards compatibility.
+
+ This method is used to load the saved state of a `Predict` object from a version of DSPy prior to v2.5.3.
+ """
+ for name, value in state.items():
+ setattr(self, name, value)
+
+ # Reconstruct the signature.
+ if "signature_instructions" in state:
+ instructions = state["signature_instructions"]
+ self.signature = self.signature.with_instructions(instructions)
+
+ if "signature_prefix" in state:
+ prefix = state["signature_prefix"]
+ *_, last_key = self.signature.fields.keys()
+ self.signature = self.signature.with_updated_fields(last_key, prefix=prefix)
+
+ # Some special stuff for CoT.
+ if "extended_signature_instructions" in state:
+ instructions = state["extended_signature_instructions"]
+ self.extended_signature = self.extended_signature.with_instructions(instructions)
+
+ if "extended_signature_prefix" in state:
+ prefix = state["extended_signature_prefix"]
+ *_, last_key = self.extended_signature.fields.keys()
+ self.extended_signature = self.extended_signature.with_updated_fields(last_key, prefix=prefix)
+
def __call__(self, **kwargs):
return self.forward(**kwargs)