DSPy: The framework for programming—not prompting—language models
Python
Support BaseLM state serialization (#9820)
Maxime Rivest492c5597a823
diff --git a/docs/docs/api/models/BaseLM.md b/docs/docs/api/models/BaseLM.mdnew file mode 100644index 000000000..8e7de6596--- /dev/null+++ b/docs/docs/api/models/BaseLM.md@@ -0,0 +1,25 @@+# dspy.BaseLM++<!-- START_API_REF -->+::: dspy.BaseLM+ handler: python+ options:+ members:+ - __call__+ - acall+ - aforward+ - copy+ - dump_state+ - forward+ - inspect_history+ - load_state+ - update_history+ show_source: true+ show_root_heading: true+ heading_level: 2+ docstring_style: google+ show_root_full_path: true+ show_object_full_path: false+ separate_signature: false+ inherited_members: true+<!-- END_API_REF -->diff --git a/docs/docs/api/models/LM.md b/docs/docs/api/models/LM.mdindex f2d8d8247..ffd32b66b 100644--- a/docs/docs/api/models/LM.md+++ b/docs/docs/api/models/LM.md@@ -16,6 +16,7 @@- inspect_history- kill- launch+ - load_state- reinforce- update_historyshow_source: truediff --git a/docs/docs/learn/programming/language_models.md b/docs/docs/learn/programming/language_models.mdindex b37ce0942..971583564 100644--- a/docs/docs/learn/programming/language_models.md+++ b/docs/docs/learn/programming/language_models.md@@ -284,3 +284,39 @@ Please note that not all models or providers support the Responses API, check [LThough rarely needed, you can write custom LMs by inheriting from `dspy.BaseLM`. Another advanced layer in the DSPy ecosystem is that of _adapters_, which sit between DSPy signatures and LMs. A future version of this guide will discuss these advanced features, though you likely don't need them.+### Saving programs that use custom LMs++When a DSPy program is saved, each LM attached to a module is serialized with `lm.dump_state()`. The built-in `dspy.LM` and `dspy.BaseLM` subclasses whose state is captured by `BaseLM.__init__` can use the default state format. If your custom LM needs extra constructor arguments or runtime state, override both `dump_state` and `load_state`.++```python linenums="1"+import dspy+++class MyLM(dspy.BaseLM):+ def __init__(self, model: str, *, deployment: str, **kwargs):+ super().__init__(model=model, **kwargs)+ self.deployment = deployment++ def dump_state(self):+ state = super().dump_state()+ state["deployment"] = self.deployment+ return state++ @classmethod+ def load_state(cls, state):+ state = dict(state)+ state.pop("_dspy_lm_class", None)+ return cls(**state)++ def forward(self, prompt=None, messages=None, **kwargs):+ ...+```++Custom LM classes are reloaded from their module-qualified class path, so they must be importable when you load the saved program. Loading a saved state that imports a custom LM class requires trusted opt-in:++```python linenums="1"+program.load("program.json", allow_unsafe_lm_state=True)+```++Use this only for files you trust. The flag also preserves serialized LM endpoint configuration such as `api_base`, `base_url`, and `model_list`.+diff --git a/docs/mkdocs.yml b/docs/mkdocs.ymlindex 1179b0a1e..0d5ab3c8b 100644--- a/docs/mkdocs.yml+++ b/docs/mkdocs.yml@@ -108,6 +108,7 @@ nav:- Citations: api/experimental/Citations.md- Document: api/experimental/Document.md- Models:+ - BaseLM: api/models/BaseLM.md- Embedder: api/models/Embedder.md- LM: api/models/LM.md- Modules:diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.pyindex 760a2679b..78d1a4c49 100644--- a/dspy/clients/base_lm.py+++ b/dspy/clients/base_lm.py@@ -1,4 +1,6 @@import datetime+import importlib+import inspectimport uuidfrom typing import Any, TextIO@@ -8,6 +10,36 @@ from dspy.utils.inspect_history import pretty_print_historyMAX_HISTORY_SIZE = 10_000GLOBAL_HISTORY = []+LM_CLASS_STATE_KEY = "_dspy_lm_class"+_BUILTIN_LM_CLASS_PATH = "dspy.clients.lm.LM"+++def _import_lm_class(class_path: str) -> type:+ parts = class_path.split(".")+ last_error = None++ for split_index in range(len(parts) - 1, 0, -1):+ module_name = ".".join(parts[:split_index])+ try:+ obj = importlib.import_module(module_name)+ except ModuleNotFoundError as exc:+ if exc.name == module_name or module_name.startswith(f"{exc.name}."):+ last_error = exc+ continue+ raise++ try:+ for attr in parts[split_index:]:+ obj = getattr(obj, attr)+ except AttributeError as exc:+ last_error = exc+ continue++ if not isinstance(obj, type):+ raise TypeError(f"Serialized LM class `{class_path}` did not resolve to a class.")+ return obj++ raise ImportError(f"Could not import serialized LM class `{class_path}`.") from last_errorclass BaseLM:@@ -18,6 +50,9 @@ class BaseLM:`forward` method and make sure the return format is identical to the[OpenAI response format](https://platform.openai.com/docs/api-reference/responses/object).+ Subclasses whose state is captured by `BaseLM.__init__` can use the default `dump_state` and `load_state`+ methods. Subclasses with extra persistent state should override both methods.+Examples:```python@@ -60,10 +95,20 @@ class BaseLM:```"""- def __init__(self, model, model_type="chat", temperature=0.0, max_tokens=1000, cache=True, **kwargs):+ def __init__(+ self,+ model,+ model_type="chat",+ temperature=0.0,+ max_tokens=1000,+ cache=True,+ num_retries=0,+ **kwargs,+ ):self.model = modelself.model_type = model_typeself.cache = cache+ self.num_retries = num_retriesself.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)self.history = []@@ -190,6 +235,75 @@ class BaseLM:"""raise NotImplementedError("Subclasses must implement this method.")+ def dump_state(self) -> dict[str, Any]:+ """Return a sanitized reconstruction state for this LM.++ Subclasses whose state is captured by `BaseLM.__init__` can use this+ default. Subclasses with extra persistent state should override both+ `dump_state` and `load_state`.++ Returns:+ A dictionary that can be passed to `BaseLM.load_state`. The state+ excludes API keys.+ """+ filtered_kwargs = {key: value for key, value in self.kwargs.items() if key not in ("api_key", LM_CLASS_STATE_KEY)}+ return {+ LM_CLASS_STATE_KEY: f"{type(self).__module__}.{type(self).__qualname__}",+ "model": self.model,+ "model_type": self.model_type,+ "cache": self.cache,+ "num_retries": getattr(self, "num_retries", 0),+ **filtered_kwargs,+ }++ @classmethod+ def load_state(cls, state: dict[str, Any], *, allow_custom_lm_class: bool = False) -> "BaseLM":+ """Reconstruct an LM from `dump_state` output.++ Legacy states without a class marker load as `dspy.LM`. Custom LM+ classes must be importable by their module-qualified class path and are+ only loaded when `allow_custom_lm_class=True`.++ Args:+ state: Serialized LM state produced by `dump_state`.+ allow_custom_lm_class: If True, allow importing and loading custom+ `BaseLM` subclasses recorded in `state`. Enable only for trusted+ state.++ Returns:+ The reconstructed LM instance.++ Raises:+ ValueError: If `state` references a custom LM class and+ `allow_custom_lm_class` is False.+ ImportError: If the serialized LM class cannot be imported.+ TypeError: If the serialized class is not a `BaseLM` subclass.+ """+ state = dict(state)+ class_path = state.pop(LM_CLASS_STATE_KEY, None)++ if cls is BaseLM:+ if class_path is None:+ # Legacy saved programs did not record the concrete LM class.+ from dspy.clients.lm import LM++ return LM(**state)++ if class_path != _BUILTIN_LM_CLASS_PATH and not allow_custom_lm_class:+ raise ValueError(+ f"Refusing to import custom serialized LM class `{class_path}`. "+ "Pass allow_unsafe_lm_state=True when loading trusted files to enable custom LM classes."+ )++ lm_cls = _import_lm_class(class_path)+ if not issubclass(lm_cls, BaseLM):+ raise TypeError(f"Serialized LM class `{class_path}` must be a subclass of dspy.BaseLM.")+ if "allow_custom_lm_class" in inspect.signature(lm_cls.load_state).parameters:+ return lm_cls.load_state(state, allow_custom_lm_class=allow_custom_lm_class)+ return lm_cls.load_state(state)++ return cls(**state)+def copy(self, **kwargs):"""Returns a copy of the language model with possibly updated parameters.diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 51ad677e0..599ffbdd4 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -20,7 +20,7 @@ from dspy.dsp.utils.settings import settingsfrom dspy.utils.callback import BaseCallbackfrom dspy.utils.exceptions import ContextWindowExceededError-from .base_lm import BaseLM+from .base_lm import LM_CLASS_STATE_KEY, BaseLMlogger = logging.getLogger(__name__)@@ -318,6 +318,12 @@ class LM(BaseLM):return Provider()def dump_state(self):+ """Return a sanitized reconstruction state for this LM.++ Returns:+ A dictionary that can be passed to `BaseLM.load_state` to+ reconstruct this `LM`. The state excludes API keys.+ """state_keys = ["model","model_type",@@ -327,9 +333,14 @@ class LM(BaseLM):"launch_kwargs","train_kwargs",]- # Exclude api_key from kwargs to prevent API keys from being saved in plain text- filtered_kwargs = {k: v for k, v in self.kwargs.items() if k != "api_key"}- return {key: getattr(self, key) for key in state_keys} | filtered_kwargs+ # Exclude api_key from kwargs to prevent API keys from being saved in plain text, and exclude the internal+ # class marker so callers cannot override the computed class path.+ filtered_kwargs = {k: v for k, v in self.kwargs.items() if k not in ("api_key", LM_CLASS_STATE_KEY)}+ return {+ LM_CLASS_STATE_KEY: f"{type(self).__module__}.{type(self).__qualname__}",+ **{key: getattr(self, key) for key in state_keys},+ **filtered_kwargs,+ }def _check_truncation(self, results):if self.model_type != "responses" and any(c.finish_reason == "length" for c in results["choices"]):diff --git a/dspy/predict/predict.py b/dspy/predict/predict.pyindex bd790a6f3..a7247b3c8 100644--- a/dspy/predict/predict.py+++ b/dspy/predict/predict.py@@ -8,7 +8,6 @@ from pydantic_core import PydanticUndefinedfrom dspy.adapters.chat_adapter import ChatAdapterfrom dspy.clients.base_lm import BaseLM-from dspy.clients.lm import LMfrom dspy.dsp.utils.settings import settingsfrom dspy.predict.parameter import Parameterfrom dspy.primitives.module import Module@@ -95,7 +94,7 @@ class Predict(Module, Parameter):Args:state: The saved state of a `Predict` object.allow_unsafe_lm_state: If True, preserves `api_base`, `base_url`, and `model_list` from- serialized LM state. Enable only when loading trusted files.+ serialized LM state and allows importing custom LM classes. Enable only when loading trusted files.Returns:Self to allow method chaining.@@ -108,7 +107,11 @@ class Predict(Module, Parameter):self.signature = self.signature.load_state(state["signature"])sanitized_lm_state = _sanitize_lm_state(state["lm"], allow_unsafe_lm_state) if state["lm"] else None- self.lm = LM(**sanitized_lm_state) if sanitized_lm_state else None+ self.lm = (+ BaseLM.load_state(sanitized_lm_state, allow_custom_lm_class=allow_unsafe_lm_state)+ if sanitized_lm_state+ else None+ )if "extended_signature" in state: # legacy, up to and including 2.5, for CoT.raise NotImplementedError("Loading extended_signature is no longer supported in DSPy 2.6+")@@ -354,7 +357,7 @@ def _check_type(value: Any, expected: type) -> bool:return all(_check_type(item, args[0]) for item in value)if len(value) != len(args):return False- return all(_check_type(item, arg) for item, arg in zip(value, args))+ return all(_check_type(item, arg) for item, arg in zip(value, args, strict=False))return True# set / frozensetdiff --git a/dspy/primitives/base_module.py b/dspy/primitives/base_module.pyindex fb0935376..ab2214a69 100644--- a/dspy/primitives/base_module.py+++ b/dspy/primitives/base_module.py@@ -260,7 +260,8 @@ class BaseModule:allow_pickle (bool): If True, allow loading .pkl files, which can run arbitrary code.This is dangerous and should only be used if you are sure about the source of the file and in a trusted environment.allow_unsafe_lm_state (bool): If True, preserves unsafe LM endpoint keys (e.g.,- `api_base`, `base_url`, and `model_list`) from loaded state. Enable only for trusted files.+ `api_base`, `base_url`, and `model_list`) from loaded state and allows importing custom LM classes.+ Enable only for trusted files."""path = Path(path)diff --git a/tests/clients/test_lm.py b/tests/clients/test_lm.pyindex 13a7e96ef..d9c3b246d 100644--- a/tests/clients/test_lm.py+++ b/tests/clients/test_lm.py@@ -390,6 +390,7 @@ def test_dump_state():)assert lm.dump_state() == {+ "_dspy_lm_class": "dspy.clients.lm.LM","model": "openai/gpt-4o-mini","model_type": "chat","temperature": 1,@@ -402,6 +403,35 @@ def test_dump_state():}+def test_dump_state_ignores_internal_class_marker_kwarg():+ lm = dspy.LM(+ model="openai/gpt-4o-mini",+ **{"_dspy_lm_class": "malicious.module.LM"},+ )++ dumped_state = lm.dump_state()++ assert dumped_state["_dspy_lm_class"] == "dspy.clients.lm.LM"+ assert lm.kwargs["_dspy_lm_class"] == "malicious.module.LM"+++def test_load_state():+ lm = dspy.LM(+ model="openai/gpt-4o-mini",+ model_type="chat",+ temperature=1,+ max_tokens=100,+ num_retries=10,+ launch_kwargs={"temperature": 1},+ train_kwargs={"temperature": 5},+ )++ loaded_lm = dspy.LM.load_state(lm.dump_state())++ assert isinstance(loaded_lm, dspy.LM)+ assert loaded_lm.dump_state() == lm.dump_state()++def test_exponential_backoff_retry():time_counter = []diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.pyindex 16107f31b..cdf414376 100644--- a/tests/predict/test_predict.py+++ b/tests/predict/test_predict.py@@ -15,10 +15,33 @@ from pydantic import BaseModel, HttpUrlimport dspyfrom dspy import Predict, Signature+from dspy.clients.base_lm import LM_CLASS_STATE_KEYfrom dspy.predict.predict import serialize_objectfrom dspy.utils.dummies import DummyLM+class CustomStateLM(dspy.BaseLM):+ def __init__(self, model, *, deployment: str, **kwargs):+ super().__init__(model=model, **kwargs)+ self.deployment = deployment++ def dump_state(self):+ state = super().dump_state()+ state["deployment"] = self.deployment+ return state++ @classmethod+ def load_state(cls, state):+ state = dict(state)+ state.pop(LM_CLASS_STATE_KEY, None)+ return cls(**state)+++class OuterLMContainer:+ class InnerLM(dspy.BaseLM):+ pass++def test_initialization_with_string_signature():signature_string = "input1, input2 -> output"predict = Predict(signature_string)@@ -51,6 +74,7 @@ def test_lm_after_dump_and_load_state():)predict_instance.lm = lmexpected_lm_state = {+ LM_CLASS_STATE_KEY: "dspy.clients.lm.LM","model": "openai/gpt-4o-mini","model_type": "chat","temperature": 1,@@ -68,6 +92,51 @@ def test_lm_after_dump_and_load_state():assert new_instance.lm.dump_state() == expected_lm_state+def test_base_lm_dump_state_ignores_internal_class_marker_kwarg():+ lm = CustomStateLM(model="custom-model", deployment="prod", **{LM_CLASS_STATE_KEY: "malicious.module.LM"})++ assert lm.dump_state()[LM_CLASS_STATE_KEY] == f"{CustomStateLM.__module__}.{CustomStateLM.__qualname__}"+++def test_legacy_lm_state_without_class_marker_loads_as_lm():+ predict_instance = Predict("input -> output")+ predict_instance.lm = dspy.LM(model="openai/gpt-4o-mini", temperature=1, max_tokens=100)+ dumped_state = predict_instance.dump_state()+ dumped_state["lm"].pop(LM_CLASS_STATE_KEY)++ loaded_instance = Predict("input -> output").load_state(dumped_state)++ assert isinstance(loaded_instance.lm, dspy.LM)+ assert loaded_instance.lm.model == "openai/gpt-4o-mini"+ assert LM_CLASS_STATE_KEY in loaded_instance.lm.dump_state()+++def test_custom_lm_load_state_requires_trusted_opt_in():+ predict_instance = Predict("input -> output")+ predict_instance.lm = CustomStateLM(model="custom-model", deployment="prod")+ dumped_state = predict_instance.dump_state()++ with pytest.raises(ValueError, match="Refusing to import custom serialized LM class"):+ Predict("input -> output").load_state(dumped_state)++ loaded_instance = Predict("input -> output").load_state(dumped_state, allow_unsafe_lm_state=True)++ assert isinstance(loaded_instance.lm, CustomStateLM)+ assert loaded_instance.lm.model == "custom-model"+ assert loaded_instance.lm.deployment == "prod"+++def test_nested_custom_lm_class_path_loads_for_trusted_state():+ predict_instance = Predict("input -> output")+ predict_instance.lm = OuterLMContainer.InnerLM(model="nested-model")+ dumped_state = predict_instance.dump_state()++ loaded_instance = Predict("input -> output").load_state(dumped_state, allow_unsafe_lm_state=True)++ assert isinstance(loaded_instance.lm, OuterLMContainer.InnerLM)+ assert loaded_instance.lm.model == "nested-model"++def test_call_method():predict_instance = Predict("input -> output")lm = DummyLM([{"output": "test output"}])