DSPy: The framework for programming—not prompting—language models
Python
Refactor: Introduce DSPy-owned `ContextWindowExceededError` to decouple error handling (#9521)
Maxime Rivest0d390ad2151c
diff --git a/dspy/__init__.py b/dspy/__init__.pyindex cdeb4b777..e7fa1bb6e 100644--- a/dspy/__init__.py+++ b/dspy/__init__.py@@ -10,6 +10,7 @@ from dspy.teleprompt import *from dspy.evaluate import Evaluate # isort: skipfrom dspy.clients import * # isort: skipfrom dspy.adapters import Adapter, ChatAdapter, JSONAdapter, XMLAdapter, TwoStepAdapter, Image, Audio, File, History, Type, Tool, ToolCalls, Code, Reasoning # isort: skip+from dspy.utils.exceptions import ContextWindowExceededErrorfrom dspy.utils.logging_utils import configure_dspy_loggers, disable_logging, enable_loggingfrom dspy.utils.asyncify import asyncifyfrom dspy.utils.syncify import syncifydiff --git a/dspy/adapters/chat_adapter.py b/dspy/adapters/chat_adapter.pyindex 7cd7c9e81..e75fbb97e 100644--- a/dspy/adapters/chat_adapter.py+++ b/dspy/adapters/chat_adapter.py@@ -2,7 +2,6 @@ import reimport textwrapfrom typing import Any, NamedTuple-from litellm import ContextWindowExceededErrorfrom pydantic.fields import FieldInfofrom dspy.adapters.base import Adapter@@ -16,7 +15,7 @@ from dspy.adapters.utils import (from dspy.clients.lm import LMfrom dspy.signatures.signature import Signaturefrom dspy.utils.callback import BaseCallback-from dspy.utils.exceptions import AdapterParseError+from dspy.utils.exceptions import AdapterParseError, ContextWindowExceededErrorfield_header_pattern = re.compile(r"\[\[ ## (\w+) ## \]\]")diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.pyindex d28e0fc2b..c5b271259 100644--- a/dspy/clients/base_lm.py+++ b/dspy/clients/base_lm.py@@ -113,9 +113,18 @@ class BaseLM:"""Forward pass for the language model.Subclasses must implement this method, and the response should be identical to either of the following formats:+- [OpenAI response format](https://platform.openai.com/docs/api-reference/responses/object)- [OpenAI chat completion format](https://platform.openai.com/docs/api-reference/chat/object)- [OpenAI text completion format](https://platform.openai.com/docs/api-reference/completions/object)++ Raises:+ dspy.ContextWindowExceededError: When the request fails because the+ input exceeds the model's context window. DSPy adapters and+ modules rely on this error to trigger fallback behavior (e.g.+ truncating the prompt and retrying). Each subclass is+ responsible for catching its provider's native error and+ re-raising it as `dspy.ContextWindowExceededError`."""raise NotImplementedError("Subclasses must implement this method.")@@ -128,9 +137,18 @@ class BaseLM:"""Async forward pass for the language model.Subclasses must implement this method, and the response should be identical to either of the following formats:+- [OpenAI response format](https://platform.openai.com/docs/api-reference/responses/object)- [OpenAI chat completion format](https://platform.openai.com/docs/api-reference/chat/object)- [OpenAI text completion format](https://platform.openai.com/docs/api-reference/completions/object)++ Raises:+ dspy.ContextWindowExceededError: When the request fails because the+ input exceeds the model's context window. DSPy adapters and+ modules rely on this error to trigger fallback behavior (e.g.+ truncating the prompt and retrying). Each subclass is+ responsible for catching its provider's native error and+ re-raising it as `dspy.ContextWindowExceededError`."""raise NotImplementedError("Subclasses must implement this method.")diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 5b027b211..4ed9e2bfc 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -9,6 +9,7 @@ import litellmimport pydanticfrom anyio.streams.memory import MemoryObjectSendStreamfrom asyncer import syncify+from litellm import ContextWindowExceededError as LitellmContextWindowExceededErrorimport dspyfrom dspy.clients.cache import request_cache@@ -17,6 +18,7 @@ from dspy.clients.provider import Provider, ReinforceJob, TrainingJobfrom dspy.clients.utils_finetune import TrainDataFormatfrom dspy.dsp.utils.settings import settingsfrom dspy.utils.callback import BaseCallback+from dspy.utils.exceptions import ContextWindowExceededErrorfrom .base_lm import BaseLM@@ -156,11 +158,14 @@ class LM(BaseLM):completion = litellm_responses_completioncompletion, litellm_cache_args = self._get_cached_completion_fn(completion, cache)- results = completion(- request=dict(model=self.model, messages=messages, **kwargs),- num_retries=self.num_retries,- cache=litellm_cache_args,- )+ try:+ results = completion(+ request=dict(model=self.model, messages=messages, **kwargs),+ num_retries=self.num_retries,+ cache=litellm_cache_args,+ )+ except LitellmContextWindowExceededError as e:+ raise ContextWindowExceededError(model=self.model) from eself._check_truncation(results)@@ -194,11 +199,14 @@ class LM(BaseLM):completion = alitellm_responses_completioncompletion, litellm_cache_args = self._get_cached_completion_fn(completion, cache)- results = await completion(- request=dict(model=self.model, messages=messages, **kwargs),- num_retries=self.num_retries,- cache=litellm_cache_args,- )+ try:+ results = await completion(+ request=dict(model=self.model, messages=messages, **kwargs),+ num_retries=self.num_retries,+ cache=litellm_cache_args,+ )+ except LitellmContextWindowExceededError as e:+ raise ContextWindowExceededError(model=self.model) from eself._check_truncation(results)diff --git a/dspy/predict/react.py b/dspy/predict/react.pyindex 1300f1272..eb1b0886d 100644--- a/dspy/predict/react.py+++ b/dspy/predict/react.py@@ -1,12 +1,11 @@import loggingfrom typing import TYPE_CHECKING, Any, Callable, Literal-from litellm import ContextWindowExceededError-import dspyfrom dspy.adapters.types.tool import Toolfrom dspy.primitives.module import Modulefrom dspy.signatures.signature import ensure_signature+from dspy.utils.exceptions import ContextWindowExceededErrorlogger = logging.getLogger(__name__)diff --git a/dspy/utils/exceptions.py b/dspy/utils/exceptions.pyindex 1fbb22beb..928bbe351 100644--- a/dspy/utils/exceptions.py+++ b/dspy/utils/exceptions.py@@ -2,6 +2,26 @@from dspy.signatures.signature import Signature+class ContextWindowExceededError(Exception):+ """Raised when the prompt exceeds the model's context window.++ Any `BaseLM` subclass should raise this error (or a subclass of it) when the+ request fails because the input is too long for the model. Adapters and some+ modules rely on catching this specific type to decide whether a fallback+ retry is appropriate.++ Args:+ model: The model identifier that rejected the request.+ message: Description of the error. Defaults to `"Context window exceeded"`.+ """++ def __init__(self, *, model: str | None = None, message: str = "Context window exceeded"):+ self.model = model+ msg = message+ prefix = f"[{model}] " if model else ""+ super().__init__(f"{prefix}{msg}")++class AdapterParseError(Exception):"""Exception raised when adapter cannot parse the LM response."""diff --git a/tests/predict/test_react.py b/tests/predict/test_react.pyindex f5a4caabd..77ad2f1b1 100644--- a/tests/predict/test_react.py+++ b/tests/predict/test_react.py@@ -1,6 +1,5 @@import re-import litellmimport pytestfrom pydantic import BaseModel@@ -8,6 +7,7 @@ import dspyimport dspy.adapters.base as adapter_baseimport dspy.adapters.utils as adapter_utilsfrom dspy.utils.dummies import DummyLM+from dspy.utils.exceptions import ContextWindowExceededError@pytest.mark.extra@@ -235,7 +235,7 @@ def test_trajectory_truncation():)elif call_count == 3:# The 3rd call raises context window exceeded error- raise litellm.ContextWindowExceededError("Context window exceeded", "dummy_model", "dummy_provider")+ raise ContextWindowExceededError()else:# The 4th call finishesreturn dspy.Prediction(next_thought="Final thought", next_tool_name="finish", next_tool_args={})@@ -260,7 +260,7 @@ async def test_context_window_exceeded_after_retries():react = dspy.ReAct("input_text -> output_text", tools=[echo])def mock_react(**kwargs):- raise litellm.ContextWindowExceededError("Context window exceeded", "dummy_model", "dummy_provider")+ raise ContextWindowExceededError()# Test sync versionextract_calls = []@@ -283,7 +283,7 @@ async def test_context_window_exceeded_after_retries():async_extract_calls = []async def mock_react_async(**kwargs):- raise litellm.ContextWindowExceededError("Context window exceeded", "dummy_model", "dummy_provider")+ raise ContextWindowExceededError()async def mock_extract_async(**kwargs):async_extract_calls.append(kwargs)diff --git a/tests/utils/test_exceptions.py b/tests/utils/test_exceptions.pyindex 2f852523d..21483b0bd 100644--- a/tests/utils/test_exceptions.py+++ b/tests/utils/test_exceptions.py@@ -1,5 +1,29 @@import dspy-from dspy.utils.exceptions import AdapterParseError+from dspy.utils.exceptions import AdapterParseError, ContextWindowExceededError+++def test_context_window_exceeded_error_defaults():+ error = ContextWindowExceededError()+ assert error.model is None+ assert str(error) == "Context window exceeded"+++def test_context_window_exceeded_error_with_model():+ error = ContextWindowExceededError(model="openai/gpt-4o")+ assert error.model == "openai/gpt-4o"+ assert str(error) == "[openai/gpt-4o] Context window exceeded"+++def test_context_window_exceeded_error_with_message():+ error = ContextWindowExceededError(model="openai/gpt-4o", message="Input is 200k tokens, limit is 128k")+ assert error.model == "openai/gpt-4o"+ assert str(error) == "[openai/gpt-4o] Input is 200k tokens, limit is 128k"+++def test_context_window_exceeded_error_message_without_model():+ error = ContextWindowExceededError(message="Too many tokens")+ assert error.model is None+ assert str(error) == "Too many tokens"def test_adapter_parse_error_basic():