Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

fix(saving): block unsafe LM loading keys (#9334)

Isaac Milleraf2a955f176f
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index 8b64df2c1..3fb1da53a 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -16,6 +16,26 @@ from dspy.utils.callback import BaseCallback
logger = logging.getLogger(__name__)
+UNSAFE_LM_STATE_KEYS = {"api_base", "base_url", "model_list"}
+
+
+def _sanitize_lm_state(lm_state: dict, allow_unsafe_lm_state: bool) -> dict:
+ if allow_unsafe_lm_state:
+ return lm_state
+
+ unsafe_keys = sorted(UNSAFE_LM_STATE_KEYS.intersection(lm_state))
+
+ if not unsafe_keys:
+ return lm_state
+
+ sanitized_lm_state = {k: v for k, v in lm_state.items() if k not in UNSAFE_LM_STATE_KEYS}
+ logger.warning(
+ "Ignoring unsafe LM config key(s) during state load: %s. "
+ "Pass allow_unsafe_lm_state=True to preserve these keys for trusted files.",
+ unsafe_keys,
+ )
+ return sanitized_lm_state
+
class Predict(Module, Parameter):
"""Basic DSPy module that maps inputs to outputs using a language model.
@@ -66,11 +86,13 @@ class Predict(Module, Parameter):
state["lm"] = self.lm.dump_state() if self.lm else None
return state
- def load_state(self, state: dict) -> "Predict":
+ def load_state(self, state: dict, *, allow_unsafe_lm_state: bool = False) -> "Predict":
"""Load the saved state of a `Predict` object.
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.
Returns:
Self to allow method chaining.
@@ -82,7 +104,8 @@ class Predict(Module, Parameter):
setattr(self, name, value)
self.signature = self.signature.load_state(state["signature"])
- self.lm = LM(**state["lm"]) if state["lm"] else None
+ 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
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+")
diff --git a/dspy/primitives/base_module.py b/dspy/primitives/base_module.py
index ce8037339..2a44e1416 100644
--- a/dspy/primitives/base_module.py
+++ b/dspy/primitives/base_module.py
@@ -156,9 +156,14 @@ class BaseModule:
def dump_state(self, json_mode=True):
return {name: param.dump_state(json_mode=json_mode) for name, param in self.named_parameters()}
- def load_state(self, state):
+ def load_state(self, state, *, allow_unsafe_lm_state=False):
+ from dspy.predict.predict import Predict
+
for name, param in self.named_parameters():
- param.load_state(state[name])
+ if isinstance(param, Predict):
+ param.load_state(state[name], allow_unsafe_lm_state=allow_unsafe_lm_state)
+ else:
+ param.load_state(state[name])
def save(self, path, save_program=False, modules_to_serialize=None):
"""Save the module.
@@ -243,7 +248,7 @@ class BaseModule:
else:
raise ValueError(f"`path` must end with `.json` or `.pkl` when `save_program=False`, but received: {path}")
- def load(self, path, allow_pickle=False):
+ def load(self, path, allow_pickle=False, allow_unsafe_lm_state=False):
"""Load the saved module. You may also want to check out dspy.load, if you want to
load an entire program, not just the state for an existing program.
@@ -251,6 +256,8 @@ class BaseModule:
path (str): Path to the saved state file, which should be a .json or a .pkl file
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.
"""
path = Path(path)
@@ -278,4 +285,4 @@ class BaseModule:
"on the loaded model, please consider loading the model in the same environment as the "
"saving environment."
)
- self.load_state(state)
+ self.load_state(state, allow_unsafe_lm_state=allow_unsafe_lm_state)
diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.py
index 65b73636c..b82da3b2f 100644
--- a/tests/predict/test_predict.py
+++ b/tests/predict/test_predict.py
@@ -258,6 +258,234 @@ def test_lm_field_after_dump_and_load_state(tmp_path, filename):
assert original_predict.dump_state() == loaded_predict.dump_state()
[email protected]("endpoint_override_key", ["api_base", "base_url"])
+def test_load_ignores_serialized_endpoint_override_by_default(tmp_path, endpoint_override_key):
+ file_path = tmp_path / "model.json"
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ original_predict.save(file_path)
+
+ with open(file_path, "rb") as f:
+ saved_state = orjson.loads(f.read())
+ saved_state["lm"][endpoint_override_key] = override_url
+ with open(file_path, "wb") as f:
+ f.write(orjson.dumps(saved_state))
+
+ with patch("dspy.predict.predict.logger.warning") as warning_mock:
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load(file_path)
+
+ assert loaded_predict.lm is not None
+ assert endpoint_override_key not in loaded_predict.lm.kwargs
+ warning_mock.assert_called_once()
+ assert warning_mock.call_args.args[1] == [endpoint_override_key]
+
+
[email protected]("endpoint_override_key", ["api_base", "base_url"])
+def test_load_allows_serialized_endpoint_override_with_opt_in(tmp_path, endpoint_override_key):
+ file_path = tmp_path / "model.json"
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ original_predict.save(file_path)
+
+ with open(file_path, "rb") as f:
+ saved_state = orjson.loads(f.read())
+ saved_state["lm"][endpoint_override_key] = override_url
+ with open(file_path, "wb") as f:
+ f.write(orjson.dumps(saved_state))
+
+ with patch("dspy.predict.predict.logger.warning") as warning_mock:
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load(file_path, allow_unsafe_lm_state=True)
+
+ assert loaded_predict.lm is not None
+ assert loaded_predict.lm.kwargs[endpoint_override_key] == override_url
+ warning_mock.assert_not_called()
+
+
[email protected]("endpoint_override_key", ["api_base", "base_url"])
+def test_load_state_ignores_serialized_endpoint_override_by_default(endpoint_override_key):
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ saved_state = copy.deepcopy(original_predict.dump_state())
+ saved_state["lm"][endpoint_override_key] = override_url
+
+ with patch("dspy.predict.predict.logger.warning") as warning_mock:
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load_state(saved_state)
+
+ assert loaded_predict.lm is not None
+ assert endpoint_override_key not in loaded_predict.lm.kwargs
+ warning_mock.assert_called_once()
+ assert warning_mock.call_args.args[1] == [endpoint_override_key]
+
+
[email protected]("endpoint_override_key", ["api_base", "base_url"])
+def test_load_state_allows_serialized_endpoint_override_with_opt_in(endpoint_override_key):
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ saved_state = copy.deepcopy(original_predict.dump_state())
+ saved_state["lm"][endpoint_override_key] = override_url
+
+ with patch("dspy.predict.predict.logger.warning") as warning_mock:
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load_state(saved_state, allow_unsafe_lm_state=True)
+
+ assert loaded_predict.lm is not None
+ assert loaded_predict.lm.kwargs[endpoint_override_key] == override_url
+ warning_mock.assert_not_called()
+
+
+def test_load_state_ignores_serialized_model_list_endpoint_override_by_default():
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ saved_state = copy.deepcopy(original_predict.dump_state())
+ saved_state["lm"]["model_list"] = [
+ {
+ "model_name": "openai/gpt-4o-mini",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_base": override_url,
+ },
+ }
+ ]
+
+ with patch("dspy.predict.predict.logger.warning") as warning_mock:
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load_state(saved_state)
+
+ assert loaded_predict.lm is not None
+ assert "model_list" not in loaded_predict.lm.kwargs
+ warning_mock.assert_called_once()
+ assert "model_list" in warning_mock.call_args.args[1]
+
+
[email protected]("endpoint_override_key", ["api_base", "base_url"])
+def test_load_prevents_serialized_endpoint_override_reaching_litellm(tmp_path, endpoint_override_key):
+ file_path = tmp_path / "model.json"
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ original_predict.save(file_path)
+
+ with open(file_path, "rb") as f:
+ saved_state = orjson.loads(f.read())
+ saved_state["lm"][endpoint_override_key] = override_url
+ with open(file_path, "wb") as f:
+ f.write(orjson.dumps(saved_state))
+
+ loaded_predict = dspy.Predict("q->a")
+ loaded_predict.load(file_path)
+
+ class FakeResp(dict):
+ cache_hit = False
+ usage = {}
+
+ def __init__(self):
+ super().__init__({"choices": []})
+
+ with patch("litellm.completion", return_value=FakeResp()) as completion_mock:
+ loaded_predict.lm.forward(prompt="hello", cache=False)
+
+ assert completion_mock.call_count == 1
+ assert completion_mock.call_args.kwargs.get(endpoint_override_key) != override_url
+
+
+def test_load_blocks_serialized_model_list_unless_opted_in(tmp_path):
+ file_path = tmp_path / "model.json"
+ override_url = "http://override.local/v1"
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini")
+ original_predict.save(file_path)
+
+ with open(file_path, "rb") as f:
+ saved_state = orjson.loads(f.read())
+ saved_state["lm"]["model_list"] = [
+ {
+ "model_name": "openai/gpt-4o-mini",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_base": override_url,
+ },
+ }
+ ]
+ with open(file_path, "wb") as f:
+ f.write(orjson.dumps(saved_state))
+
+ class FakeResp(dict):
+ cache_hit = False
+ usage = {}
+
+ def __init__(self):
+ super().__init__({"choices": []})
+
+ safe_loaded_predict = dspy.Predict("q->a")
+ safe_loaded_predict.load(file_path)
+ with patch("litellm.batch_completion_models", return_value=FakeResp()) as batch_completion_mock:
+ with patch("litellm.completion", return_value=FakeResp()) as completion_mock:
+ safe_loaded_predict.lm.forward(prompt="hello", cache=False)
+
+ assert completion_mock.called
+ assert not batch_completion_mock.called
+
+ opt_in_loaded_predict = dspy.Predict("q->a")
+ opt_in_loaded_predict.load(file_path, allow_unsafe_lm_state=True)
+ with patch("litellm.batch_completion_models", return_value=FakeResp()) as batch_completion_mock:
+ opt_in_loaded_predict.lm.forward(prompt="hello", cache=False)
+
+ opt_in_deployments = batch_completion_mock.call_args.kwargs["deployments"]
+ assert opt_in_deployments[0]["api_base"] == override_url
+
+
+def test_load_uses_env_api_key_without_honoring_serialized_endpoint_override(tmp_path, monkeypatch):
+ file_path = tmp_path / "model.json"
+ override_url = "http://override.local/v1"
+ env_api_key = "sk-live-test-secret"
+
+ original_predict = dspy.Predict("q->a")
+ original_predict.lm = dspy.LM(model="openai/gpt-4o-mini", model_type="text")
+ original_predict.save(file_path)
+
+ with open(file_path, "rb") as f:
+ saved_state = orjson.loads(f.read())
+ assert "api_key" not in saved_state["lm"]
+ saved_state["lm"]["api_base"] = override_url
+ with open(file_path, "wb") as f:
+ f.write(orjson.dumps(saved_state))
+
+ monkeypatch.setenv("openai_API_KEY", env_api_key)
+
+ class FakeResp(dict):
+ cache_hit = False
+ usage = {}
+
+ def __init__(self):
+ super().__init__({"choices": []})
+
+ # Simulates legacy behavior by allowing serialized endpoint overrides.
+ opt_in_loaded_predict = dspy.Predict("q->a")
+ opt_in_loaded_predict.load(file_path, allow_unsafe_lm_state=True)
+ with patch("litellm.text_completion", return_value=FakeResp()) as text_completion_mock:
+ opt_in_loaded_predict.lm.forward(prompt="hello", cache=False)
+
+ assert text_completion_mock.call_args.kwargs["api_base"] == override_url
+ assert text_completion_mock.call_args.kwargs["api_key"] == env_api_key
+
+ safe_loaded_predict = dspy.Predict("q->a")
+ safe_loaded_predict.load(file_path)
+ with patch("litellm.text_completion", return_value=FakeResp()) as text_completion_mock:
+ safe_loaded_predict.lm.forward(prompt="hello", cache=False)
+
+ # In the safe path, the key still comes from the environment, but the serialized endpoint override does not.
+ assert text_completion_mock.call_args.kwargs["api_key"] == env_api_key
+ assert text_completion_mock.call_args.kwargs["api_base"] != override_url
+
+
def test_forward_method():
program = Predict("question -> answer")
dspy.configure(lm=DummyLM([{"answer": "No more responses"}]))