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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
build: squash merge litellm_dev_10_10_2025_p1
Krrish Dholakiab90e916c681b
diff --git a/litellm/exceptions.py b/litellm/exceptions.pyindex 77fb9c1faef..ccb3ce90e9c 100644--- a/litellm/exceptions.py+++ b/litellm/exceptions.py@@ -153,6 +153,7 @@ class BadRequestError(openai.BadRequestError): # type: ignore_message += f", LiteLLM Max Retries: {self.max_retries}"return _message+class ImageFetchError(BadRequestError):def __init__(self,@@ -914,3 +915,17 @@ class MidStreamFallbackError(ServiceUnavailableError): # type: ignoredef __repr__(self):return self.__str__()+++class GuardrailInterventionNormalStringError(+ Exception+): # custom exception to raise when a guardrail intervenes, but we want to return a normal string to the user+ def __init__(self, message: str):+ self.message = message+ super().__init__(self.message)++ def __str__(self):+ return self.message++ def __repr__(self):+ return self.__str__()diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.pyindex 347301e7b37..6953b1c5878 100644--- a/litellm/llms/base_llm/base_model_iterator.py+++ b/litellm/llms/base_llm/base_model_iterator.py@@ -13,6 +13,50 @@ from litellm.types.utils import ()+def convert_model_response_to_streaming(+ model_response: ModelResponse,+) -> ModelResponseStream:+ """+ Convert a ModelResponse to ModelResponseStream.++ This function transforms a standard completion response into a streaming chunk format+ by converting 'message' fields to 'delta' fields.++ Args:+ model_response: The ModelResponse to convert++ Returns:+ ModelResponseStream: A streaming chunk version of the response++ Raises:+ ValueError: If the conversion fails+ """+ try:+ streaming_choices: List[StreamingChoices] = []+ for choice in model_response.choices:+ streaming_choices.append(+ StreamingChoices(+ index=choice.index,+ delta=Delta(+ **cast(Choices, choice).message.model_dump(),+ ),+ finish_reason=choice.finish_reason,+ )+ )+ processed_chunk = ModelResponseStream(+ id=model_response.id,+ object="chat.completion.chunk",+ created=model_response.created,+ model=model_response.model,+ choices=streaming_choices,+ )+ return processed_chunk+ except Exception as e:+ raise ValueError(+ f"Failed to convert ModelResponse to ModelResponseStream: {model_response}. Error: {e}"+ )++class BaseModelResponseIterator:def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False@@ -147,28 +191,7 @@ class MockResponseIterator: # for returning ai21 streaming responsesreturn selfdef _chunk_parser(self, chunk_data: ModelResponse) -> ModelResponseStream:- try:- streaming_choices: List[StreamingChoices] = []- for choice in chunk_data.choices:- streaming_choices.append(- StreamingChoices(- index=choice.index,- delta=Delta(- **cast(Choices, choice).message.model_dump(),- ),- finish_reason=choice.finish_reason,- )- )- processed_chunk = ModelResponseStream(- id=chunk_data.id,- object="chat.completion",- created=chunk_data.created,- model=chunk_data.model,- choices=streaming_choices,- )- return processed_chunk- except Exception as e:- raise ValueError(f"Failed to decode chunk: {chunk_data}. Error: {e}")+ return convert_model_response_to_streaming(chunk_data)def __next__(self):if self.is_done:diff --git a/litellm/main.py b/litellm/main.pyindex 14aca084f9d..48cdcea629c 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -83,6 +83,9 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (get_content_from_model_response,)from litellm.llms.base_llm import BaseConfig, BaseImageGenerationConfig+from litellm.llms.base_llm.base_model_iterator import (+ convert_model_response_to_streaming,+)from litellm.llms.bedrock.common_utils import BedrockModelInfofrom litellm.llms.cohere.common_utils import CohereModelInfofrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler@@ -93,7 +96,7 @@ from litellm.llms.vertex_ai.common_utils import (from litellm.realtime_api.main import _realtime_health_checkfrom litellm.secret_managers.main import get_secret_bool, get_secret_strfrom litellm.types.router import GenericLiteLLMParams-from litellm.types.utils import RawRequestTypedDict+from litellm.types.utils import RawRequestTypedDict, StreamingChoicesfrom litellm.utils import (CustomStreamWrapper,ProviderConfigManager,@@ -227,6 +230,7 @@ from .types.utils import ()encoding = tiktoken.get_encoding("cl100k_base")+from litellm.types.utils import ModelResponseStreamfrom litellm.utils import (Choices,EmbeddingResponse,@@ -278,10 +282,13 @@ heroku_transformation = HerokuChatConfig()oci_transformation = OCIChatConfig()ovhcloud_transformation = OVHCloudChatConfig()lemonade_transformation = LemonadeChatConfig()++MOCK_RESPONSE_TYPE = Union[str, Exception, dict, ModelResponse, ModelResponseStream]####### COMPLETION ENDPOINTS ################class LiteLLM:+def __init__(self,*,@@ -631,7 +638,7 @@ async def _async_streaming(response, model, custom_llm_provider, args):def _handle_mock_potential_exceptions(- mock_response: Union[str, Exception, dict],+ mock_response: Union[str, Exception],model: str,custom_llm_provider: Optional[str] = None,):@@ -735,9 +742,6 @@ async def _sleep_for_timeout_async(timeout: Union[float, str, httpx.Timeout]):await asyncio.sleep(timeout.connect)-MOCK_RESPONSE_TYPE = Union[str, Exception, dict]--def mock_completion(model: str,messages: List,@@ -788,15 +792,16 @@ def mock_completion(api_key="mock-key",)- _handle_mock_potential_exceptions(- mock_response=mock_response,- model=model,- custom_llm_provider=custom_llm_provider,- )+ if isinstance(mock_response, str) or isinstance(mock_response, Exception):+ _handle_mock_potential_exceptions(+ mock_response=mock_response,+ model=model,+ custom_llm_provider=custom_llm_provider,+ )mock_response = cast(- Union[str, dict], mock_response- ) # after this point, mock_response is a string or dict+ Union[str, dict, ModelResponse, ModelResponseStream], mock_response+ ) # after this point, mock_response is a string, dict, ModelResponse, or ModelResponseStreamif isinstance(mock_response, str) and mock_response.startswith("Exception: mock_streaming_error"):@@ -813,7 +818,14 @@ def mock_completion(if isinstance(mock_response, dict):return ModelResponse(**mock_response)- model_response = ModelResponse(stream=stream)+ if isinstance(mock_response, ModelResponse):+ if not stream:+ return mock_response+ # convert to ModelResponseStream+ mock_response = convert_model_response_to_streaming(mock_response) # type: ignore++ model_response = ModelResponseStream()+if stream is True:# don't try to access stream object,if kwargs.get("acompletion", False) is True:@@ -835,6 +847,8 @@ def mock_completion()if isinstance(mock_response, litellm.MockException):raise mock_response+ # At this point, mock_response must be a string (all other types have been handled or returned early)+ mock_response = cast(str, mock_response)if n is None:model_response.choices[0].message.content = mock_response # type: ignoreelse:@@ -2872,7 +2886,7 @@ def completion( # type: ignore # noqa: PLR0915extra_headers=headers,)- elif custom_llm_provider == "vertex_ai":+ elif custom_llm_provider == "vertex_ai":vertex_ai_project = (optional_params.pop("vertex_project", None)or optional_params.pop("vertex_ai_project", None)@@ -2894,8 +2908,10 @@ def completion( # type: ignore # noqa: PLR0915api_base = api_base or litellm.api_base or get_secret("VERTEXAI_API_BASE")new_params = safe_deep_copy(optional_params or {})- model_route = get_vertex_ai_model_route(model=model, litellm_params=litellm_params)-+ model_route = get_vertex_ai_model_route(+ model=model, litellm_params=litellm_params+ )+if model_route == VertexAIModelRoute.PARTNER_MODELS:model_response = vertex_partner_models_chat_completion.completion(model=model,@@ -3595,7 +3611,6 @@ def completion( # type: ignore # noqa: PLR0915pass-elif custom_llm_provider == "ovhcloud" or model in litellm.ovhcloud_models:api_key = (api_key@@ -5218,12 +5233,11 @@ async def aadapter_completion(except Exception as e:raise e+async def aadapter_generate_content(**kwargs,) -> Union[Dict[str, Any], AsyncIterator[bytes]]:- from litellm.google_genai.adapters.handler import (- GenerateContentToCompletionHandler,- )+ from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandlercoro = cast(Coroutine[Any, Any, Union[Dict[str, Any], AsyncIterator[bytes]]],diff --git a/litellm/proxy/_experimental/out/api-reference.html b/litellm/proxy/_experimental/out/api-reference/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/api-reference.htmlrename to litellm/proxy/_experimental/out/api-reference/index.htmldiff --git a/litellm/proxy/_experimental/out/guardrails.html b/litellm/proxy/_experimental/out/guardrails/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/guardrails.htmlrename to litellm/proxy/_experimental/out/guardrails/index.htmldiff --git a/litellm/proxy/_experimental/out/logs.html b/litellm/proxy/_experimental/out/logs/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/logs.htmlrename to litellm/proxy/_experimental/out/logs/index.htmldiff --git a/litellm/proxy/_experimental/out/model-hub.html b/litellm/proxy/_experimental/out/model-hub/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/model-hub.htmlrename to litellm/proxy/_experimental/out/model-hub/index.htmldiff --git a/litellm/proxy/_experimental/out/model_hub_table.html b/litellm/proxy/_experimental/out/model_hub_table/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/model_hub_table.htmlrename to litellm/proxy/_experimental/out/model_hub_table/index.htmldiff --git a/litellm/proxy/_experimental/out/models-and-endpoints.html b/litellm/proxy/_experimental/out/models-and-endpoints/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/models-and-endpoints.htmlrename to litellm/proxy/_experimental/out/models-and-endpoints/index.htmldiff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.htmldeleted file mode 100644index 2a8f10662b7..00000000000--- a/litellm/proxy/_experimental/out/onboarding.html+++ /dev/null@@ -1 +0,0 @@-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/litellm-asset-prefix/_next/static/chunks/webpack-db32e14ed3b4a921.js"/><script src="/litellm-asset-prefix/_next/static/chunks/fd9d1056-64e84c4092e0c5d7.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/2117-2da5ec8fad6a6c25.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/main-app-1547e82c186a7d1e.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/favicon.ico" type="image/x-icon" sizes="16x16"/><link rel="icon" href="./favicon.ico"/><meta name="next-size-adjust"/><script src="/litellm-asset-prefix/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/litellm-asset-prefix/_next/static/chunks/webpack-db32e14ed3b4a921.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/litellm-asset-prefix/_next/static/media/e4af272ccee01ff0-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"style\"]\n3:HL[\"/litellm-asset-prefix/_next/static/css/39bc5c75b4e5b054.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[12011,[\"3665\",\"static/chunks/3014691f-702e24806fe9cec4.js\",\"9820\",\"static/chunks/9820-b0722f821c1af1ee.js\",\"1491\",\"static/chunks/1491-8280340b5391aa11.js\",\"1526\",\"static/chunks/1526-8e2976ed10cb2fa0.js\",\"8806\",\"static/chunks/8806-85c2bcba4ca300e2.js\",\"8049\",\"static/chunks/8049-26a565b2b753c5e8.js\",\"8461\",\"static/chunks/app/onboarding/page-d6c503dc2753c910.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\na:I[31857,[\"3185\",\"static/chunks/app/layout-6d8e06b275ad8577.js\"],\"FeatureFlagsProvider\"]\nc:I[61060,[],\"\"]\nd:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"HJ-3T7pZxIFnXkBv06NZY\",\"assetPrefix\":\"/litellm-asset-prefix\",\"urlParts\":[\"\",\"onboarding\"],\"initialTree\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"onboarding\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/39bc5c75b4e5b054.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_1c856b\",\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$Lb\"],\"globalErrorComponent\":\"$c\",\"missingSlots\":\"$Wd\"}]\n"])</script><script>self.__next_f.push([1,"b:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"link\",\"5\",{\"rel\":\"icon\",\"href\":\"./favicon.ico\"}],[\"$\",\"meta\",\"6\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>\ No newline at end of filediff --git a/litellm/proxy/_experimental/out/organizations.html b/litellm/proxy/_experimental/out/organizations/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/organizations.htmlrename to litellm/proxy/_experimental/out/organizations/index.htmldiff --git a/litellm/proxy/_experimental/out/teams.html b/litellm/proxy/_experimental/out/teams/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/teams.htmlrename to litellm/proxy/_experimental/out/teams/index.htmldiff --git a/litellm/proxy/_experimental/out/test-key.html b/litellm/proxy/_experimental/out/test-key/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/test-key.htmlrename to litellm/proxy/_experimental/out/test-key/index.htmldiff --git a/litellm/proxy/_experimental/out/usage.html b/litellm/proxy/_experimental/out/usage/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/usage.htmlrename to litellm/proxy/_experimental/out/usage/index.htmldiff --git a/litellm/proxy/_experimental/out/users.html b/litellm/proxy/_experimental/out/users/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/users.htmlrename to litellm/proxy/_experimental/out/users/index.htmldiff --git a/litellm/proxy/_experimental/out/virtual-keys.html b/litellm/proxy/_experimental/out/virtual-keys/index.htmlsimilarity index 100%rename from litellm/proxy/_experimental/out/virtual-keys.htmlrename to litellm/proxy/_experimental/out/virtual-keys/index.htmldiff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 33028903cb2..e163d3dfbf2 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -22,6 +22,7 @@ from fastapi import HTTPExceptionimport litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.caching import DualCache+from litellm.exceptions import GuardrailInterventionNormalStringErrorfrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.llms.bedrock.base_aws_llm import BaseAWSLLMfrom litellm.llms.custom_httpx.http_handler import (@@ -386,7 +387,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):)# Re-raise the exception to maintain existing behaviorraise-+########################################################## Add guardrail information to request trace#########################################################@@ -461,7 +462,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):) -> GuardrailStatus:"""Get the status of the bedrock guardrail response.-+Returns:"success": Content allowed through with no violations"guardrail_intervened": Content blocked due to policy violations@@ -470,22 +471,24 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if response.status_code == 200:if self._check_bedrock_response_for_exception(response):return "guardrail_failed_to_respond"-+# Check if the guardrail would block contenttry:_json_response = response.json()bedrock_guardrail_response = BedrockGuardrailResponse(**_json_response)- if self._should_raise_guardrail_blocked_exception(bedrock_guardrail_response):+ if self._should_raise_guardrail_blocked_exception(+ bedrock_guardrail_response+ ):return "guardrail_intervened"except Exception:pass-+return "success"return "guardrail_failed_to_respond"def _get_http_exception_for_blocked_guardrail(self, response: BedrockGuardrailResponse- ) -> HTTPException:+ ) -> Union[HTTPException, GuardrailInterventionNormalStringError]:"""Get the HTTP exception for a blocked guardrail."""@@ -498,13 +501,18 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if output.get("text"):bedrock_guardrail_output_text += output.get("text") or ""- return HTTPException(- status_code=400,- detail={- "error": "Violated guardrail policy",- "bedrock_guardrail_response": bedrock_guardrail_output_text,- },- )+ if self.disable_exception_on_block is True:+ return GuardrailInterventionNormalStringError(+ message=bedrock_guardrail_output_text+ )+ else:+ return HTTPException(+ status_code=400,+ detail={+ "error": "Violated guardrail policy",+ "bedrock_guardrail_response": bedrock_guardrail_output_text,+ },+ )def _should_raise_guardrail_blocked_exception(self, response: BedrockGuardrailResponse@@ -519,9 +527,6 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if self.mask_request_content or self.mask_response_content:return False- if self.disable_exception_on_block is True:- return False-# if no intervention, return Falseif response.get("action") != "GUARDRAIL_INTERVENED":return False@@ -586,6 +591,18 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):# This means all actions were ANONYMIZED or NONE, so don't raise exceptionreturn False+ def create_guardrail_blocked_response(self, response: str) -> ModelResponse:+ from litellm.types.utils import Choices, Message, ModelResponse++ return ModelResponse(+ choices=[+ Choices(+ message=Message(content=response),+ )+ ],+ model="bedrock-guardrail",+ )+async def async_pre_call_hook(self,user_api_key_dict: UserAPIKeyAuth,@@ -604,7 +621,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):"anthropic_messages",],) -> Union[Exception, str, dict, None]:- verbose_proxy_logger.debug("Inside Bedrock Pre-Call Hook for call_type: %s", call_type)+ verbose_proxy_logger.debug(+ "Inside Bedrock Pre-Call Hook for call_type: %s", call_type+ )from litellm.proxy.common_utils.callback_utils import (add_guardrail_to_applied_guardrails_header,@@ -613,25 +632,31 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):event_type: GuardrailEventHooks = GuardrailEventHooks.pre_callif self.should_run_guardrail(data=data, event_type=event_type) is not True:return data-+new_messages = self.get_guardrails_messages_for_call_type(call_type=cast(CallTypes, call_type),data=data,)-+# Handle None caseif new_messages is None:- verbose_proxy_logger.debug("No messages found for call_type, skipping guardrail")+ verbose_proxy_logger.debug(+ "No messages found for call_type, skipping guardrail"+ )return data-+################################################################### 1. Make the Bedrock API request ###################################################################- bedrock_guardrail_response = await self.make_bedrock_api_request(- source="INPUT",- messages=new_messages,- request_data=data,+ bedrock_guardrail_response: Optional[Union[BedrockGuardrailResponse, str]] = (+ None)+ try:+ bedrock_guardrail_response = await self.make_bedrock_api_request(+ source="INPUT", messages=new_messages, request_data=data+ )+ except GuardrailInterventionNormalStringError as e:+ bedrock_guardrail_response = e.message##################################################################################################################@@ -643,6 +668,10 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):bedrock_guardrail_response=bedrock_guardrail_response,))+ if isinstance(bedrock_guardrail_response, str):+ data["mock_response"] = self.create_guardrail_blocked_response(+ response=bedrock_guardrail_response+ )################################################################### 3. Add the guardrail to the applied guardrails header ##########@@ -679,7 +708,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):call_type=cast(CallTypes, call_type),data=data,)-+if new_messages is None:verbose_proxy_logger.warning("Bedrock AI: not running guardrail. No messages in data"@@ -689,9 +718,15 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):################################################################### 1. Make the Bedrock API request ###################################################################- bedrock_guardrail_response = await self.make_bedrock_api_request(- source="INPUT", messages=new_messages, request_data=data+ bedrock_guardrail_response: Optional[Union[BedrockGuardrailResponse, str]] = (+ None)+ try:+ bedrock_guardrail_response = await self.make_bedrock_api_request(+ source="INPUT", messages=new_messages, request_data=data+ )+ except GuardrailInterventionNormalStringError as e:+ bedrock_guardrail_response = e.message##################################################################################################################@@ -703,6 +738,10 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):bedrock_guardrail_response=bedrock_guardrail_response,))+ if isinstance(bedrock_guardrail_response, str):+ data["mock_response"] = self.create_guardrail_blocked_response(+ response=bedrock_guardrail_response+ )################################################################### 3. Add the guardrail to the applied guardrails header ##########@@ -745,10 +784,12 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):has_text_content = Falsefor choice in response.choices:if isinstance(choice, litellm.Choices):- if choice.message.content and isinstance(choice.message.content, str):+ if choice.message.content and isinstance(+ choice.message.content, str+ ):has_text_content = Truebreak-+if not has_text_content:verbose_proxy_logger.warning("Bedrock AI: not running guardrail. No output text in response"@@ -758,17 +799,26 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):################################################################### 1. Make parallel Bedrock API requests ###################################################################- output_content_bedrock = await self.make_bedrock_api_request(- source="OUTPUT", response=response, request_data=data- ) # Only response+ output_content_bedrock: Optional[Union[BedrockGuardrailResponse, str]] = None+ try:+ output_content_bedrock = await self.make_bedrock_api_request(+ source="OUTPUT", response=response, request_data=data+ )+ except GuardrailInterventionNormalStringError as e:+ output_content_bedrock = e.message################################################################### 2. Apply masking to response with output guardrail response ###################################################################- self._apply_masking_to_response(- response=response,- bedrock_guardrail_response=output_content_bedrock,- )+ if isinstance(output_content_bedrock, str):+ response = self.create_guardrail_blocked_response(+ response=output_content_bedrock+ )+ else:+ self._apply_masking_to_response(+ response=response,+ bedrock_guardrail_response=output_content_bedrock,+ )################################################################### 3. Add the guardrail to the applied guardrails header ##########@@ -783,7 +833,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):def _update_messages_with_updated_bedrock_guardrail_response(self,messages: List[AllMessageValues],- bedrock_guardrail_response: BedrockGuardrailResponse,+ bedrock_guardrail_response: Union[BedrockGuardrailResponse, str],) -> List[AllMessageValues]:"""Use the output from the bedrock guardrail to mask sensitive content in messages.@@ -795,6 +845,8 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):Returns:List of messages with content masked according to guardrail response"""+ if isinstance(bedrock_guardrail_response, str):+ return messages# Get masked texts from guardrail responsemasked_texts = self._extract_masked_texts_from_response(bedrock_guardrail_response@@ -859,20 +911,33 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):messages=request_data.get("messages"),request_data=request_data,) # Only input messages+ output_guardrail_response: Optional[+ Union[BedrockGuardrailResponse, str]+ ] = Noneoutput_task = self.make_bedrock_api_request(source="OUTPUT", response=assembled_model_response) # Only response# Execute both requests in parallel- _, output_guardrail_response = await asyncio.gather(input_task, output_task)+ try:+ _, output_guardrail_response = await asyncio.gather(+ input_task, output_task+ )+ except GuardrailInterventionNormalStringError as e:+ output_guardrail_response = e.message################################################################################### 2. Apply masking to response with output guardrail response ###################################################################################- self._apply_masking_to_response(- response=assembled_model_response,- bedrock_guardrail_response=output_guardrail_response,- )+ if isinstance(output_guardrail_response, str):+ assembled_model_response = self.create_guardrail_blocked_response(+ response=output_guardrail_response+ )+ elif output_guardrail_response is not None:+ self._apply_masking_to_response(+ response=assembled_model_response,+ bedrock_guardrail_response=output_guardrail_response,+ )################################################################################### 3. Return the (potentially masked) chunks ##########@@ -1094,24 +1159,26 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):) -> str:"""Apply Bedrock guardrail to the given text for testing purposes.-+This method allows users to test Bedrock guardrails without making actual LLM calls.It creates a mock request and response to test the guardrail functionality."""try:- verbose_proxy_logger.debug(- "Bedrock Guardrail: Applying guardrail"- )- mock_messages: List[AllMessageValues] = [ChatCompletionUserMessage(role="user", content=text)]+ verbose_proxy_logger.debug("Bedrock Guardrail: Applying guardrail")+ mock_messages: List[AllMessageValues] = [+ ChatCompletionUserMessage(role="user", content=text)+ ]bedrock_response = await self.make_bedrock_api_request(source="INPUT",messages=mock_messages,- request_data={"messages": mock_messages}+ request_data={"messages": mock_messages},)-+if bedrock_response.get("action") == "BLOCKED":- raise Exception(f"Content blocked by Bedrock guardrail: {bedrock_response.get('reason', 'Unknown reason')}")-+ raise Exception(+ f"Content blocked by Bedrock guardrail: {bedrock_response.get('reason', 'Unknown reason')}"+ )+# Apply any masking that was applied by the guardrailmasked_text = textoutput_list = bedrock_response.get("output")@@ -1131,15 +1198,15 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if text_content:masked_text = str(text_content)break-+verbose_proxy_logger.debug("Bedrock Guardrail: Successfully applied guardrail")-+return masked_text-+except Exception as e:verbose_proxy_logger.error("Bedrock Guardrail: Failed to apply guardrail: %s", str(e))- raise Exception(f"Bedrock guardrail failed: {str(e)}")\ No newline at end of file+ raise Exception(f"Bedrock guardrail failed: {str(e)}")diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.pyindex d8ce39aaf8a..216de57769e 100644--- a/litellm/proxy/health_endpoints/_health_endpoints.py+++ b/litellm/proxy/health_endpoints/_health_endpoints.py@@ -34,7 +34,22 @@ from litellm.proxy.health_check import (#### Health ENDPOINTS ####router = APIRouter()-services = Union[Literal["slack_budget_alerts", "langfuse", "slack", "openmeter", "webhook", "email", "braintrust", "datadog", "generic_api", "arize"], str]+services = Union[+ Literal[+ "slack_budget_alerts",+ "langfuse",+ "slack",+ "openmeter",+ "webhook",+ "email",+ "braintrust",+ "datadog",+ "generic_api",+ "arize",+ ],+ str,+]+@router.get("/test",@@ -617,43 +632,42 @@ async def shared_health_check_status_endpoint():"""Get the status of shared health check coordination across pods.-+Returns information about Redis connectivity, lock status, and cache status."""from litellm.proxy.proxy_server import redis_usage_cache, use_shared_health_check-+if not use_shared_health_check:return {"shared_health_check_enabled": False,- "message": "Shared health check is not enabled"+ "message": "Shared health check is not enabled",}-+if redis_usage_cache is None:return {"shared_health_check_enabled": True,"redis_available": False,- "message": "Redis is not configured"+ "message": "Redis is not configured",}-+try:from litellm.proxy.health_check_utils.shared_health_check_manager import (SharedHealthCheckManager,)-+shared_health_manager = SharedHealthCheckManager(redis_cache=redis_usage_cache,)-+health_status = await shared_health_manager.get_health_check_status()- return {- "shared_health_check_enabled": True,- "status": health_status- }+ return {"shared_health_check_enabled": True, "status": health_status}except Exception as e:verbose_proxy_logger.error(f"Error getting shared health check status: {e}")raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail={"error": f"Failed to retrieve shared health check status: {str(e)}"},+ status_code=fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={+ "error": f"Failed to retrieve shared health check status: {str(e)}"+ },)diff --git a/litellm/utils.py b/litellm/utils.pyindex 5ad1553b03f..b36872b0e12 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -266,12 +266,12 @@ from litellm.llms.base_llm.image_generation.transformation import (from litellm.llms.base_llm.image_variations.transformation import (BaseImageVariationConfig,)-from litellm.llms.base_llm.videos.transformation import BaseVideoConfigfrom litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfigfrom litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfigfrom litellm.llms.base_llm.rerank.transformation import BaseRerankConfigfrom litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfigfrom litellm.llms.base_llm.vector_store.transformation import BaseVectorStoreConfig+from litellm.llms.base_llm.videos.transformation import BaseVideoConfigfrom ._logging import _is_debugging_on, verbose_loggerfrom .caching.caching import (@@ -307,6 +307,9 @@ from .types.llms.openai import ()from .types.router import LiteLLM_Params+if TYPE_CHECKING:+ from litellm import MockException+####### ENVIRONMENT VARIABLES ##################### Adjust to your specific application needs / system capabilities.sentry_sdk_instance = None@@ -6035,6 +6038,9 @@ def mock_completion_streaming_obj():if isinstance(mock_response, litellm.MockException):raise mock_response+ if isinstance(mock_response, ModelResponseStream):+ yield mock_response+ returnfor i in range(0, len(mock_response), 3):completion_obj = Delta(role="assistant", content=mock_response[i : i + 3])if n is None:@@ -6054,10 +6060,16 @@ def mock_completion_streaming_obj(async def async_mock_completion_streaming_obj(- model_response, mock_response, model, n: Optional[int] = None+ model_response,+ mock_response: Union[str, "MockException", ModelResponseStream],+ model,+ n: Optional[int] = None,):if isinstance(mock_response, litellm.MockException):raise mock_response+ if isinstance(mock_response, ModelResponseStream):+ yield mock_response+ returnfor i in range(0, len(mock_response), 3):completion_obj = Delta(role="assistant", content=mock_response[i : i + 3])if n is None:@@ -7609,15 +7621,11 @@ class ProviderConfigManager:provider: LlmProviders,) -> Optional[BaseVideoConfig]:if LlmProviders.OPENAI == provider:- from litellm.llms.openai.videos.transformation import (- OpenAIVideoConfig,- )+ from litellm.llms.openai.videos.transformation import OpenAIVideoConfigreturn OpenAIVideoConfig()elif LlmProviders.AZURE == provider:- from litellm.llms.azure.videos.transformation import (- AzureVideoConfig,- )+ from litellm.llms.azure.videos.transformation import AzureVideoConfigreturn AzureVideoConfig()return Nonediff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.pyindex 870d3c40512..9f209c1b8d0 100644--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@ -1125,59 +1125,65 @@ async def test_retrying() -> None:def test_anthropic_disable_url_suffix_env_var():"""Test that LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX prevents /v1/messages suffix."""- from unittest.mock import patch, MagicMockimport os+ from unittest.mock import MagicMock, patch+from litellm import completion# Test with environment variable disabled (default behavior)with patch.dict(os.environ, {"ANTHROPIC_API_BASE": "https://api.example.com"}):actual_api_base = None-+with patch("litellm.main.anthropic_chat_completions") as mock_anthropic:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")mock_response = MagicMock()mock_response.choices = [MagicMock()]return mock_response-+mock_anthropic.completion = capture_completion-+# This should append /v1/messagescompletion(model="anthropic/claude-3-sonnet",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base has /v1/messages appendedassert actual_api_base.endswith("/v1/messages")assert actual_api_base == "https://api.example.com/v1/messages"# Test with environment variable enabled- with patch.dict(os.environ, {- "ANTHROPIC_API_BASE": "https://api.example.com/custom/path",- "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true"- }):+ with patch.dict(+ os.environ,+ {+ "ANTHROPIC_API_BASE": "https://api.example.com/custom/path",+ "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true",+ },+ ):actual_api_base = None-+with patch("litellm.main.anthropic_chat_completions") as mock_anthropic:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")mock_response = MagicMock()mock_response.choices = [MagicMock()]return mock_response-+mock_anthropic.completion = capture_completion-+# This should NOT append /v1/messagescompletion(model="anthropic/claude-3-sonnet",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base does not have /v1/messages appendedassert actual_api_base == "https://api.example.com/custom/path"assert not actual_api_base.endswith("/v1/messages")@@ -1185,55 +1191,61 @@ def test_anthropic_disable_url_suffix_env_var():def test_anthropic_text_disable_url_suffix_env_var():"""Test that LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX prevents /v1/complete suffix for anthropic_text."""- from unittest.mock import patch, MagicMockimport os+ from unittest.mock import MagicMock, patch+from litellm import completion# Test with environment variable disabled (default behavior)with patch.dict(os.environ, {"ANTHROPIC_API_BASE": "https://api.example.com"}):actual_api_base = None-+with patch("litellm.main.base_llm_http_handler") as mock_handler:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")return MagicMock()-+mock_handler.completion = capture_completion-+# This should append /v1/completecompletion(model="anthropic_text/claude-instant-1",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base has /v1/complete appendedassert actual_api_base.endswith("/v1/complete")assert actual_api_base == "https://api.example.com/v1/complete"# Test with environment variable enabled- with patch.dict(os.environ, {- "ANTHROPIC_API_BASE": "https://api.example.com/custom/complete",- "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true"- }):+ with patch.dict(+ os.environ,+ {+ "ANTHROPIC_API_BASE": "https://api.example.com/custom/complete",+ "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true",+ },+ ):actual_api_base = None-+with patch("litellm.main.base_llm_http_handler") as mock_handler:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")return MagicMock()-+mock_handler.completion = capture_completion-+# This should NOT append /v1/completecompletion(model="anthropic_text/claude-instant-1",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base does not have /v1/complete appendedassert actual_api_base == "https://api.example.com/custom/complete"assert not actual_api_base.endswith("/v1/complete")@@ -1247,17 +1259,20 @@ def test_image_edit_merges_headers_and_extra_headers():mock_image_edit_config = MagicMock()mock_image_edit_config.get_supported_openai_params.return_value = set()- mock_image_edit_config.map_openai_params.side_effect = (- lambda **kwargs: dict(kwargs["image_edit_optional_params"])+ mock_image_edit_config.map_openai_params.side_effect = lambda **kwargs: dict(+ kwargs["image_edit_optional_params"])- with patch(- "litellm.images.main.ProviderConfigManager.get_provider_image_edit_config",- return_value=mock_image_edit_config,- ) as mock_config, patch(- "litellm.images.main.base_llm_http_handler.image_edit_handler",- return_value="ok",- ) as mock_handler:+ with (+ patch(+ "litellm.images.main.ProviderConfigManager.get_provider_image_edit_config",+ return_value=mock_image_edit_config,+ ) as mock_config,+ patch(+ "litellm.images.main.base_llm_http_handler.image_edit_handler",+ return_value="ok",+ ) as mock_handler,+ ):response = litellm.image_edit(image=MagicMock(name="image"),prompt="test",@@ -1274,3 +1289,124 @@ def test_image_edit_merges_headers_and_extra_headers():handler_kwargs = mock_handler.call_args.kwargsassert handler_kwargs["extra_headers"] == combined_headersassert "extra_headers" not in handler_kwargs["image_edit_optional_request_params"]+++def test_mock_completion_stream_with_model_response():+ """Test that mock_completion correctly handles stream=True with a ModelResponse as mock_response."""+ from litellm import completion+ from litellm.types.utils import Choices, Message, ModelResponse, Usage++ # Create a ModelResponse object+ mock_model_response = ModelResponse(+ id="chatcmpl-test-123",+ created=1234567890,+ model="gpt-4o-mini",+ object="chat.completion",+ choices=[+ Choices(+ finish_reason="stop",+ index=0,+ message=Message(+ content="This is a test response",+ role="assistant",+ ),+ )+ ],+ usage=Usage(+ prompt_tokens=10,+ completion_tokens=20,+ total_tokens=30,+ ),+ )++ # Call completion with stream=True and mock_response as ModelResponse+ response = completion(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "Hello"}],+ stream=True,+ mock_response=mock_model_response,+ )++ # Verify that the response is a stream+ assert response is not None++ # Collect all chunks from the stream+ chunks = []+ for chunk in response:+ chunks.append(chunk)+ print(f"Chunk: {chunk}")++ # Verify we got chunks+ assert len(chunks) > 0++ # Verify the content is streamed correctly+ accumulated_content = ""+ for chunk in chunks:+ if (+ hasattr(chunk.choices[0].delta, "content")+ and chunk.choices[0].delta.content+ ):+ accumulated_content += chunk.choices[0].delta.content++ assert "This is a test response" in accumulated_content or len(chunks) > 0+++async def test_async_mock_completion_stream_with_model_response():+ """Test that async mock_completion correctly handles stream=True with a ModelResponse as mock_response."""+ from litellm import acompletion+ from litellm.types.utils import Choices, Message, ModelResponse, Usage++ # Create a ModelResponse object+ mock_model_response = ModelResponse(+ id="chatcmpl-test-456",+ created=1234567890,+ model="gpt-4o-mini",+ object="chat.completion",+ choices=[+ Choices(+ finish_reason="stop",+ index=0,+ message=Message(+ content="This is an async test response",+ role="assistant",+ ),+ )+ ],+ usage=Usage(+ prompt_tokens=15,+ completion_tokens=25,+ total_tokens=40,+ ),+ )++ # Call acompletion with stream=True and mock_response as ModelResponse+ response = await acompletion(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "Hello async"}],+ stream=True,+ mock_response=mock_model_response,+ )++ # Verify that the response is a stream+ assert response is not None++ # Collect all chunks from the stream+ chunks = []+ async for chunk in response:+ chunks.append(chunk)+ print(f"Async Chunk: {chunk}")++ # Verify we got chunks+ assert len(chunks) > 0++ # Verify the content is streamed correctly+ accumulated_content = ""+ for chunk in chunks:+ if (+ hasattr(chunk.choices[0].delta, "content")+ and chunk.choices[0].delta.content+ ):+ accumulated_content += chunk.choices[0].delta.content++ assert "This is an async test response" in accumulated_content or len(chunks) > 0