From 498b1959782b401684955395c702c3b52b2a78de Mon Sep 17 00:00:00 2001 From: Alexsander Hamir Date: Thu, 22 Jan 2026 08:53:44 -0800 Subject: [PATCH] Fix RuntimeError when checking httpx.Response.request property - Replace unsafe hasattr(response, 'request') check with safe _request attribute check - httpx.Response.request is a property that raises RuntimeError when _request is None - Check private _request attribute directly to avoid triggering property getter - Use minimal error response when response is None, not httpx.Response, or lacks _request - Fixes test_context_window_exceeded_error_from_litellm_proxy test failure --- litellm/exceptions.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/litellm/exceptions.py b/litellm/exceptions.py index ce8bb6fa182..eb027334606 100644 --- a/litellm/exceptions.py +++ b/litellm/exceptions.py @@ -142,18 +142,17 @@ class BadRequestError(openai.BadRequestError): # type: ignore self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries + # Use response if it's a valid httpx.Response with a request, otherwise use minimal error response + # Note: We check _request (not .request property) to avoid RuntimeError when _request is None if ( response is not None and isinstance(response, httpx.Response) + and hasattr(response, "_request") + and getattr(response, "_request", None) is not None ): - # Check if response has a request attribute safely - # httpx.Response.request is a property that raises RuntimeError if _request is None - # We check the private _request attribute to avoid triggering the property getter - if hasattr(response, "_request") and getattr(response, "_request", None) is not None: - self.response = response - else: - # Response doesn't have a valid request, use minimal error response - self.response = _get_minimal_error_response() + self.response = response + else: + self.response = _get_minimal_error_response() super().__init__( self.message, response=self.response, body=body ) # Call the base class constructor with the parameters it needs