DSPy: The framework for programming—not prompting—language models
Python
bug(lm): Avoid unnecessary cache key computation (#8862)
Isaac Miller930632ab13eb
diff --git a/dspy/clients/cache.py b/dspy/clients/cache.pyindex 187043538..72291d845 100644--- a/dspy/clients/cache.py+++ b/dspy/clients/cache.py@@ -96,6 +96,10 @@ class Cache:return sha256(orjson.dumps(params, option=orjson.OPT_SORT_KEYS)).hexdigest()def get(self, request: dict[str, Any], ignored_args_for_cache_key: list[str] | None = None) -> Any:++ if not self.enable_memory_cache and not self.enable_disk_cache:+ return None+try:key = self.cache_key(request, ignored_args_for_cache_key)except Exception:@@ -128,13 +132,19 @@ class Cache:ignored_args_for_cache_key: list[str] | None = None,enable_memory_cache: bool = True,) -> None:+ enable_memory_cache = self.enable_memory_cache and enable_memory_cache++ # Early return to avoid computing cache key if both memory and disk cache are disabled+ if not enable_memory_cache and not self.enable_disk_cache:+ return+try:key = self.cache_key(request, ignored_args_for_cache_key)except Exception:logger.debug(f"Failed to generate cache key for request: {request}")return- if self.enable_memory_cache and enable_memory_cache:+ if enable_memory_cache:with self._lock:self.memory_cache[key] = valuediff --git a/tests/clients/test_lm.py b/tests/clients/test_lm.pyindex 54068e512..e1d781585 100644--- a/tests/clients/test_lm.py+++ b/tests/clients/test_lm.py@@ -12,6 +12,7 @@ from litellm.utils import Choices, Message, ModelResponsefrom openai import RateLimitErrorimport dspy+from dspy.utils.dummies import DummyLMfrom dspy.utils.usage_tracker import track_usage@@ -96,6 +97,36 @@ def test_dspy_cache(litellm_test_server, tmp_path):dspy.cache = original_cache+def test_disabled_cache_skips_cache_key(monkeypatch):+ original_cache = dspy.cache+ dspy.configure_cache(enable_disk_cache=False, enable_memory_cache=False)+ cache = dspy.cache++ try:+ with mock.patch.object(cache, "cache_key", wraps=cache.cache_key) as cache_key_spy, \+ mock.patch.object(cache, "get", wraps=cache.get) as cache_get_spy, \+ mock.patch.object(cache, "put", wraps=cache.put) as cache_put_spy:++ def fake_completion(*, cache, num_retries, retry_strategy, **request):+ return ModelResponse(+ choices=[Choices(message=Message(role="assistant", content="Hi!"))],+ usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ model="dummy",+ )++ monkeypatch.setattr(litellm, "completion", fake_completion)++ dummy_lm = DummyLM([{"answer": "ignored"}])+ # TODO(isaacbmiller): Change from dummy_lm.forward to just dummy_lm.__call__ #8864+ dummy_lm.forward(messages=[{"role": "user", "content": "Hello"}])++ cache_key_spy.assert_not_called()+ cache_get_spy.assert_called_once()+ cache_put_spy.assert_called_once()+ finally:+ dspy.cache = original_cache++def test_rollout_id_bypasses_cache(monkeypatch, tmp_path):calls: list[dict] = []