Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix: catch litellm.Timeout in HeadroomGuardrail to support fail_open on timeouts

Cursor Agent53d2331c700c
diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
index fe6d6bf7051..c218cac7aa2 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
@@ -8,6 +8,8 @@ from typing import TYPE_CHECKING, Any, Literal, Optional
import httpx
from fastapi import HTTPException
+
+import litellm
from httpx import Response as HttpxResponse
from typing_extensions import TypeGuard
@@ -297,7 +299,7 @@ class HeadroomGuardrail(CustomGuardrail):
"Headroom compression service returned an error",
{"status_code": e.response.status_code, "body": e.response.text},
)
- except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError) as e:
+ except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError, litellm.Timeout) as e:
return self._handle_compress_failure(
messages,
"Headroom compression service unreachable",
@@ -368,7 +370,7 @@ class HeadroomGuardrail(CustomGuardrail):
params=params,
headers=self._request_headers(),
)
- except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError) as e:
+ except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError, litellm.Timeout) as e:
verbose_proxy_logger.warning("Headroom: retrieve failed for hash=%s: %s", hash_value, e)
return f"[Headroom: retrieval failed for hash={hash_value}]"
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index fdf96c44f47..09422be04ab 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@ -24,6 +24,8 @@ import httpx
import pytest
from fastapi import HTTPException
+import litellm
+
from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import (
HeadroomGuardrail,
extract_hashes_from_messages,
@@ -1187,3 +1189,61 @@ async def test_async_should_run_agentic_loop_detects_responses_api_output_format
assert should_run is True
assert len(ctx["tool_calls"]) == 1
assert ctx["tool_calls"][0]["arguments"]["hash"] == "b573993006976af767214fac"
+
+
+async def test_apply_guardrail_litellm_timeout_raises_when_fail_closed():
+ guardrail = _make_guardrail()
+
+ inputs = GenericGuardrailAPIInputs(
+ texts=["hello"],
+ structured_messages=ORIGINAL_MESSAGES,
+ )
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ side_effect=litellm.Timeout(
+ message="Connection timed out after 10 seconds.",
+ model="default-model-name",
+ llm_provider="litellm-httpx-handler",
+ ),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data={},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 502
+ assert "unreachable" in str(exc_info.value.detail)
+
+
+async def test_apply_guardrail_litellm_timeout_fail_open_forwards_uncompressed():
+ guardrail = _make_guardrail(unreachable_fallback="fail_open")
+
+ inputs = GenericGuardrailAPIInputs(
+ texts=["hello"],
+ structured_messages=ORIGINAL_MESSAGES,
+ )
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ side_effect=litellm.Timeout(
+ message="Connection timed out after 10 seconds.",
+ model="default-model-name",
+ llm_provider="litellm-httpx-handler",
+ ),
+ ):
+ result = await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data={},
+ input_type="request",
+ )
+
+ assert result["structured_messages"] == ORIGINAL_MESSAGES