DSPy: The framework for programming—not prompting—language models
Python
Fix litellm retries (#8161)
Chen Qianbe1614a31700
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex f77bc40ec..2aad71aaf 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -7,7 +7,6 @@ from typing import Any, Dict, List, Literal, Optional, castimport litellmfrom anyio.streams.memory import MemoryObjectSendStreamfrom asyncer import syncify-from litellm import RetryPolicyimport dspyfrom dspy.clients.cache import request_cache@@ -85,9 +84,9 @@ class LM(BaseLM):if model_pattern:# Handle OpenAI reasoning models (o1, o3)- assert max_tokens >= 20_000 and temperature == 1.0, (- "OpenAI's reasoning models require passing temperature=1.0 and max_tokens >= 20_000 to `dspy.LM(...)`"- )+ assert (+ max_tokens >= 20_000 and temperature == 1.0+ ), "OpenAI's reasoning models require passing temperature=1.0 and max_tokens >= 20_000 to `dspy.LM(...)`"self.kwargs = dict(temperature=temperature, max_completion_tokens=max_tokens, **kwargs)else:self.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)@@ -233,7 +232,6 @@ class LM(BaseLM):def _get_stream_completion_fn(request: Dict[str, Any],- retry_kwargs: Dict[str, Any],cache_kwargs: Dict[str, Any],sync=True,):@@ -247,11 +245,10 @@ def _get_stream_completion_fn(stream = cast(MemoryObjectSendStream, stream)caller_predict_id = id(caller_predict) if caller_predict else None- async def stream_completion(request: Dict[str, Any], retry_kwargs: Dict[str, Any], cache_kwargs: Dict[str, Any]):+ async def stream_completion(request: Dict[str, Any], cache_kwargs: Dict[str, Any]):response = await litellm.acompletion(cache=cache_kwargs,stream=True,- **retry_kwargs,**request,)chunks = []@@ -265,10 +262,10 @@ def _get_stream_completion_fn(def sync_stream_completion():syncified_stream_completion = syncify(stream_completion)- return syncified_stream_completion(request, retry_kwargs, cache_kwargs)+ return syncified_stream_completion(request, cache_kwargs)async def async_stream_completion():- return await stream_completion(request, retry_kwargs, cache_kwargs)+ return await stream_completion(request, cache_kwargs)if sync:return sync_stream_completion@@ -277,20 +274,12 @@ def _get_stream_completion_fn(def litellm_completion(request: Dict[str, Any], num_retries: int, cache={"no-cache": True, "no-store": True}):- retry_kwargs = dict(- retry_policy=_get_litellm_retry_policy(num_retries),- retry_strategy="exponential_backoff_retry",- # In LiteLLM version 1.55.3 (the first version that supports retry_policy as an argument- # to completion()), the default value of max_retries is non-zero for certain providers, and- # max_retries is stacked on top of the retry_policy. To avoid this, we set max_retries=0- max_retries=0,- )-- stream_completion = _get_stream_completion_fn(request, retry_kwargs, cache, sync=True)+ stream_completion = _get_stream_completion_fn(request, cache, sync=True)if stream_completion is None:return litellm.completion(cache=cache,- **retry_kwargs,+ num_retries=num_retries,+ retry_strategy="exponential_backoff_retry",**request,)@@ -316,30 +305,19 @@ def litellm_text_completion(request: Dict[str, Any], num_retries: int, cache={"napi_key=api_key,api_base=api_base,prompt=prompt,- retry_policy=_get_litellm_retry_policy(num_retries),- # In LiteLLM version 1.55.3 (the first version that supports retry_policy as an argument- # to completion()), the default value of max_retries is non-zero for certain providers, and- # max_retries is stacked on top of the retry_policy. To avoid this, we set max_retries=0- max_retries=0,+ num_retries=num_retries,+ retry_strategy="exponential_backoff_retry",**request,)async def alitellm_completion(request: Dict[str, Any], num_retries: int, cache={"no-cache": True, "no-store": True}):- retry_kwargs = dict(- retry_policy=_get_litellm_retry_policy(num_retries),- retry_strategy="exponential_backoff_retry",- # In LiteLLM version 1.55.3 (the first version that supports retry_policy as an argument- # to completion()), the default value of max_retries is non-zero for certain providers, and- # max_retries is stacked on top of the retry_policy. To avoid this, we set max_retries=0- max_retries=0,- )-- stream_completion = _get_stream_completion_fn(request, retry_kwargs, cache, sync=False)+ stream_completion = _get_stream_completion_fn(request, cache, sync=False)if stream_completion is None:return await litellm.acompletion(cache=cache,- **retry_kwargs,+ num_retries=num_retries,+ retry_strategy="exponential_backoff_retry",**request,)@@ -365,32 +343,7 @@ async def alitellm_text_completion(api_key=api_key,api_base=api_base,prompt=prompt,- retry_policy=_get_litellm_retry_policy(num_retries),- # In LiteLLM version 1.55.3 (the first version that supports retry_policy as an argument- # to completion()), the default value of max_retries is non-zero for certain providers, and- # max_retries is stacked on top of the retry_policy. To avoid this, we set max_retries=0- max_retries=0,+ num_retries=num_retries,+ retry_strategy="exponential_backoff_retry",**request,)---def _get_litellm_retry_policy(num_retries: int) -> RetryPolicy:- """- Get a LiteLLM retry policy for retrying requests when transient API errors occur.- Args:- num_retries: The number of times to retry a request if it fails transiently due to- network error, rate limiting, etc. Requests are retried with exponential- backoff.- Returns:- A LiteLLM RetryPolicy instance.- """- return RetryPolicy(- TimeoutErrorRetries=num_retries,- RateLimitErrorRetries=num_retries,- InternalServerErrorRetries=num_retries,- ContentPolicyViolationErrorRetries=num_retries,- # We don't retry on errors that are unlikely to be transient- # (e.g. bad request, invalid auth credentials)- BadRequestErrorRetries=0,- AuthenticationErrorRetries=0,- )diff --git a/tests/clients/test_lm.py b/tests/clients/test_lm.pyindex 7616b9f79..3e214469c 100644--- a/tests/clients/test_lm.py+++ b/tests/clients/test_lm.py@@ -161,76 +161,31 @@ def test_lm_calls_support_pydantic_models(litellm_test_server):lm("Query")- ("error_code", "expected_exception", "expected_num_retries"),- [- ("429", litellm.RateLimitError, 2),- ("504", litellm.Timeout, 3),- # Don't retry on user errors- ("400", litellm.BadRequestError, 0),- ("401", litellm.AuthenticationError, 0),- # TODO: LiteLLM retry logic isn't implemented properly for internal server errors- # and content policy violations, both of which may be transient and should be retried- # ("content-policy-violation, litellm.BadRequestError, 1),- # ("500", litellm.InternalServerError, 0, 1),- ],-)-def test_lm_chat_calls_are_retried_for_expected_failures(- litellm_test_server,- error_code,- expected_exception,- expected_num_retries,-):- api_base, server_log_file_path = litellm_test_server+def test_retry_number_set_correctly():+ lm = dspy.LM("openai/gpt-4o-mini", num_retries=3)+ with mock.patch("litellm.completion") as mock_completion:+ lm("query")- openai_lm = dspy.LM(- model="openai/dspy-test-model",- api_base=api_base,- api_key="fakekey",- num_retries=expected_num_retries,- model_type="chat",- )- with pytest.raises(expected_exception):- openai_lm(error_code)+ assert mock_completion.call_args.kwargs["num_retries"] == 3- request_logs = read_litellm_test_server_request_logs(server_log_file_path)- assert len(request_logs) == expected_num_retries + 1 # 1 initial request + 1 retries+def test_retry_made_on_system_errors():+ retry_tracking = [0] # Using a list to track retries- ("error_code", "expected_exception", "expected_num_retries"),- [- ("429", litellm.RateLimitError, 2),- ("504", litellm.Timeout, 3),- # Don't retry on user errors- ("400", litellm.BadRequestError, 0),- ("401", litellm.AuthenticationError, 0),- # TODO: LiteLLM retry logic isn't implemented properly for internal server errors- # and content policy violations, both of which may be transient and should be retried- # ("content-policy-violation, litellm.BadRequestError, 2),- # ("500", litellm.InternalServerError, 0, 2),- ],-)-def test_lm_text_calls_are_retried_for_expected_failures(- litellm_test_server,- error_code,- expected_exception,- expected_num_retries,-):- api_base, server_log_file_path = litellm_test_server+ def mock_create(*args, **kwargs):+ retry_tracking[0] += 1+ # These fields are called during the error handling+ mock_response = mock.Mock()+ mock_response.headers = {}+ mock_response.status_code = 429+ raise RateLimitError(response=mock_response, message="message", body="error")- openai_lm = dspy.LM(- model="openai/dspy-test-model",- api_base=api_base,- api_key="fakekey",- num_retries=expected_num_retries,- model_type="text",- )- with pytest.raises(expected_exception):- openai_lm(error_code)+ lm = dspy.LM(model="openai/gpt-4o-mini", max_tokens=250, num_retries=3)+ with mock.patch.object(litellm.OpenAIChatCompletion, "completion", side_effect=mock_create):+ with pytest.raises(RateLimitError):+ lm("question")- request_logs = read_litellm_test_server_request_logs(server_log_file_path)- assert len(request_logs) == expected_num_retries + 1 # 1 initial request + 1 retries+ assert retry_tracking[0] == 4def test_reasoning_model_token_parameter():