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]

Merge branch 'litellm_internal_staging' into feature/improve-gigachat-provider and format

KnyazSh31d016a6ad58
diff --cc litellm/litellm_core_utils/get_llm_provider_logic.py
index 4a09e3f2b4d,122d09c855b..e186730d616
--- a/litellm/litellm_core_utils/get_llm_provider_logic.py
+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py
@@@ -391,23 -346,12 +346,15 @@@ def get_llm_provider
elif endpoint == "https://pinstripes.io/v1":
custom_llm_provider = "pinstripes"
dynamic_api_key = get_secret_str("PINSTRIPES_API_KEY")
+ elif endpoint == "https://gigachat.devices.sberbank.ru/api/v1":
+ custom_llm_provider = "gigachat"
+ dynamic_api_key = get_secret_str("GIGACHAT_API_KEY")
if api_base is not None and not isinstance(api_base, str):
+ raise Exception("api base needs to be a string. api_base={}".format(api_base))
+ if dynamic_api_key is not None and not isinstance(dynamic_api_key, str):
raise Exception(
- "api base needs to be a string. api_base={}".format(
- api_base
- )
- )
- if dynamic_api_key is not None and not isinstance(
- dynamic_api_key, str
- ):
- raise Exception(
- "dynamic_api_key needs to be a string. dynamic_api_key={}".format(
- dynamic_api_key
- )
+ "dynamic_api_key needs to be a string. dynamic_api_key={}".format(dynamic_api_key)
)
return model, custom_llm_provider, dynamic_api_key, api_base # type: ignore
@@@ -533,8 -467,15 +470,17 @@@
custom_llm_provider = "amazon_nova"
elif model.startswith("sap/"):
custom_llm_provider = "sap"
+ elif model in litellm.gigachat_models or model.startswith("gigachat/"):
+ custom_llm_provider = "gigachat"
+
+ # Last resort for an otherwise-unknown model: a declarative
+ # fallback-generalization rule (e.g. routes future claude-* to anthropic).
+ # Exact provider matches above always win; this only runs on a miss.
+ if not custom_llm_provider:
+ generalization = match_fallback_generalization(model)
+ if generalization is not None:
+ custom_llm_provider = generalization.get("litellm_provider") or None
+
if not custom_llm_provider:
if litellm.suppress_debug_info is False:
print() # noqa: T201
@@@ -1050,17 -837,8 +842,11 @@@ def _get_openai_compatible_provider_inf
dynamic_api_key = api_key or get_secret_str("LANGGRAPH_API_KEY")
elif custom_llm_provider == "manus":
# Manus is OpenAI compatible for responses API
- api_base = (
- api_base or get_secret_str("MANUS_API_BASE") or "https://api.manus.im"
- )
+ api_base = api_base or get_secret_str("MANUS_API_BASE") or "https://api.manus.im"
dynamic_api_key = api_key or get_secret_str("MANUS_API_KEY")
+ elif custom_llm_provider == "gigachat":
- api_base = (
- api_base
- or get_secret_str("GIGACHAT_API_BASE")
- or "https://gigachat.devices.sberbank.ru/api/v1"
- )
++ api_base = api_base or get_secret_str("GIGACHAT_API_BASE") or "https://gigachat.devices.sberbank.ru/api/v1"
+ dynamic_api_key = api_key or get_secret_str("GIGACHAT_API_KEY")
if api_base is not None and not isinstance(api_base, str):
raise Exception("api base needs to be a string. api_base={}".format(api_base))
diff --cc litellm/litellm_core_utils/litellm_logging.py
index 2fa78900447,da204855465..0f283fe2dab
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@@ -2003,19 -1830,10 +1830,13 @@@ class Logging(LiteLLMLoggingBaseClass)
logging_result = self.normalize_logging_result(result=result)
- if isinstance(result, Response) and isinstance(
- logging_result, ModelResponse
- ):
++ if isinstance(result, Response) and isinstance(logging_result, ModelResponse):
+ result = logging_result
+
- if (
- standard_logging_object is None
- and result is not None
- and self.stream is not True
- ):
- if self._is_recognized_call_type_for_logging(
- logging_result=logging_result
- ) or isinstance(logging_result, (dict, list)):
+ if standard_logging_object is None and result is not None and self.stream is not True:
+ if self._is_recognized_call_type_for_logging(logging_result=logging_result) or isinstance(
+ logging_result, (dict, list)
+ ):
self._process_hidden_params_and_response_cost(
logging_result=logging_result,
start_time=start_time,
@@@ -5977,14 -5389,7 +5392,10 @@@ def get_standard_logging_object_payload
def emit_standard_logging_payload(payload: StandardLoggingPayload):
if os.getenv("LITELLM_PRINT_STANDARD_LOGGING_PAYLOAD"):
- print(json.dumps(payload, indent=4)) # noqa: T201
+ try:
+ print(json.dumps(payload, indent=4, default=str)) # noqa: T201
+ except Exception as e: # noqa: BLE001
- verbose_logger.exception(
- "Error serializing standard logging payload for debug output: {}".format(
- str(e)
- )
- )
++ verbose_logger.exception("Error serializing standard logging payload for debug output: {}".format(str(e)))
def get_standard_logging_metadata(
diff --cc litellm/llms/gigachat/authenticator.py
index 6c6a3d58b46,e61015a4a21..db0fff3e302
--- a/litellm/llms/gigachat/authenticator.py
+++ b/litellm/llms/gigachat/authenticator.py
@@@ -80,15 -80,6 +80,13 @@@ def get_access_token
Raises:
GigaChatAuthError: If authentication fails
"""
+ if not litellm_params:
+ litellm_params = {}
+
- access_token = litellm_params.get("gigachat_access_token") or get_secret_str(
- "GIGACHAT_ACCESS_TOKEN"
- )
++ access_token = litellm_params.get("gigachat_access_token") or get_secret_str("GIGACHAT_ACCESS_TOKEN")
+ if access_token:
+ return access_token
+
credentials = credentials or _get_credentials()
if not credentials:
raise GigaChatAuthError(
@@@ -112,33 -103,20 +110,29 @@@
# Request new token
token, expires_at = _request_token_sync(credentials, scope, auth_url)
- # Cache token
- ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000)
- if ttl_seconds > 0:
- _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds)
+ if expires_at:
+ # Cache token
- ttl_seconds = max(
- 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000
- )
++ ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000)
+ if ttl_seconds > 0:
+ _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds)
return token
async def get_access_token_async(
- credentials: Optional[str] = None,
- scope: Optional[str] = None,
- auth_url: Optional[str] = None,
+ credentials: str | None = None,
+ scope: str | None = None,
+ auth_url: str | None = None,
+ litellm_params: dict | None = None,
) -> str:
"""Async version of get_access_token."""
+ if not litellm_params:
+ litellm_params = {}
+
- access_token = litellm_params.get("gigachat_access_token") or get_secret_str(
- "GIGACHAT_ACCESS_TOKEN"
- )
++ access_token = litellm_params.get("gigachat_access_token") or get_secret_str("GIGACHAT_ACCESS_TOKEN")
+ if access_token:
+ return access_token
+
credentials = credentials or _get_credentials()
if not credentials:
raise GigaChatAuthError(
@@@ -161,13 -139,10 +155,11 @@@
# Request new token
token, expires_at = await _request_token_async(credentials, scope, auth_url)
- # Cache token
- ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000)
- if ttl_seconds > 0:
- _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds)
+ if expires_at:
+ # Cache token
- ttl_seconds = max(
- 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000
- )
++ ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000)
+ if ttl_seconds > 0:
+ _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds)
return token
diff --cc litellm/llms/gigachat/chat/streaming.py
index 5c56a0c5d87,4f10f8bb658..260761645c0
--- a/litellm/llms/gigachat/chat/streaming.py
+++ b/litellm/llms/gigachat/chat/streaming.py
@@@ -71,27 -70,6 +71,23 @@@ class GigaChatModelResponseIterator
)
finish_reason = "tool_calls"
+ usage_block = None
+ if finish_reason == "stop":
+ usage_data = chunk.get("usage", {})
+ if usage_data:
+ usage = convert_usage(usage_data)
+ usage_block = ChatCompletionUsageBlock(
+ prompt_tokens=usage.prompt_tokens,
+ completion_tokens=usage.completion_tokens,
+ total_tokens=usage.total_tokens,
+ prompt_tokens_details=(
- usage.prompt_tokens_details.model_dump()
- if usage.prompt_tokens_details
- else None
++ usage.prompt_tokens_details.model_dump() if usage.prompt_tokens_details else None
+ ),
+ completion_tokens_details=(
- usage.completion_tokens_details.model_dump()
- if usage.completion_tokens_details
- else None
++ usage.completion_tokens_details.model_dump() if usage.completion_tokens_details else None
+ ),
+ )
+
if finish_reason is not None:
is_finished = True
diff --cc litellm/llms/gigachat/chat/transformation.py
index 9ffb7cd8a16,dbf04fd015d..b9a6ce30e48
--- a/litellm/llms/gigachat/chat/transformation.py
+++ b/litellm/llms/gigachat/chat/transformation.py
@@@ -109,14 -111,8 +109,10 @@@ class GigaChatConfig(BaseConfig)
Set up headers with OAuth token.
"""
# Get access token
- credentials = (
- api_key
- or get_secret_str("GIGACHAT_CREDENTIALS")
- or get_secret_str("GIGACHAT_API_KEY")
- )
- access_token = get_access_token(
- credentials=credentials, litellm_params=litellm_params
- )
+ credentials = api_key or get_secret_str("GIGACHAT_CREDENTIALS") or get_secret_str("GIGACHAT_API_KEY")
+ access_token = get_access_token(credentials=credentials)
++ credentials = api_key or get_secret_str("GIGACHAT_CREDENTIALS") or get_secret_str("GIGACHAT_API_KEY")
++ access_token = get_access_token(credentials=credentials, litellm_params=litellm_params)
# Store credentials for image uploads
self._current_credentials = credentials
@@@ -216,9 -212,7 +212,7 @@@
)
return functions
- def _map_tool_choice(
- self, tool_choice: Union[str, dict]
- ) -> Union[str, dict] | None:
- def _map_tool_choice(self, tool_choice: Union[str, dict]) -> Optional[Union[str, dict]]:
++ def _map_tool_choice(self, tool_choice: Union[str, dict]) -> Union[str, dict] | None:
"""
Map OpenAI tool_choice to GigaChat function_call format.
diff --cc litellm/llms/gigachat/embedding/transformation.py
index 6e4698120ee,0da6565050e..ba79f2205fc
--- a/litellm/llms/gigachat/embedding/transformation.py
+++ b/litellm/llms/gigachat/embedding/transformation.py
@@@ -192,9 -194,7 +192,7 @@@ class GigaChatEmbeddingConfig(BaseEmbed
Set up headers with OAuth token for GigaChat.
"""
# Get access token via OAuth
- access_token = get_access_token(
- credentials=api_key, litellm_params=litellm_params
- )
- access_token = get_access_token(api_key)
++ access_token = get_access_token(credentials=api_key, litellm_params=litellm_params)
default_headers = {
"Content-Type": "application/json",
diff --cc litellm/llms/gigachat/file_handler.py
index 8c7075f5599,200428a747a..ac03732a9bb
--- a/litellm/llms/gigachat/file_handler.py
+++ b/litellm/llms/gigachat/file_handler.py
@@@ -112,12 -114,10 +112,10 @@@ def upload_file_sync
filename = f"{uuid.uuid4()}.{ext}"
# Get access token
- access_token = get_access_token(
- credentials=credentials, litellm_params=litellm_params
- )
- access_token = get_access_token(credentials)
++ access_token = get_access_token(credentials=credentials, litellm_params=litellm_params)
# Upload to GigaChat
- base_url = api_base or GIGACHAT_BASE_URL
+ base_url = get_api_base(api_base)
upload_url = f"{base_url}/files"
client = _get_httpx_client(params={"ssl_verify": False})
@@@ -180,12 -179,10 +178,10 @@@ async def upload_file_async
filename = f"{uuid.uuid4()}.{ext}"
# Get access token
- access_token = await get_access_token_async(
- credentials=credentials, litellm_params=litellm_params
- )
- access_token = await get_access_token_async(credentials)
++ access_token = await get_access_token_async(credentials=credentials, litellm_params=litellm_params)
# Upload to GigaChat
- base_url = api_base or GIGACHAT_BASE_URL
+ base_url = get_api_base(api_base)
upload_url = f"{base_url}/files"
client = get_async_httpx_client(
diff --cc litellm/llms/gigachat/passthrough/transformation.py
index 4e6849b13d9,00000000000..7f37fb91bf6
mode 100644,000000..100644
--- a/litellm/llms/gigachat/passthrough/transformation.py
+++ b/litellm/llms/gigachat/passthrough/transformation.py
@@@ -1,227 -1,0 +1,217 @@@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, cast
+
+import httpx
+
+from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
+from litellm.llms.gigachat.authenticator import get_access_token
+from litellm.llms.gigachat.chat.streaming import GigaChatModelResponseIterator
+from litellm.llms.gigachat.utils import GIGACHAT_BASE_URL
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import EmbeddingResponse
+
+if TYPE_CHECKING:
+ from httpx import URL, Response
+
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.types.utils import CostResponseTypes
+
+
+class GigaChatPassthroughConfig(BasePassthroughConfig):
+ def is_streaming_request(self, endpoint: str, request_data: dict) -> bool:
+ return request_data.get("stream", False)
+
+ def get_complete_url(
+ self,
+ api_base: str | None,
+ api_key: str | None,
+ model: str,
+ endpoint: str,
+ request_query_params: dict | None,
+ litellm_params: dict,
+ ) -> tuple[URL, str]:
+ """Get complete API URL for chat completions."""
+ base_target_url = self.get_api_base(api_base)
+
+ if base_target_url is None:
+ raise Exception("GigaChat api base not found")
+
+ complete_url = f"{base_target_url}/{endpoint.lstrip('/')}"
+
+ return (
+ httpx.URL(complete_url),
+ base_target_url,
+ )
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: list[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: str | None = None,
+ api_base: str | None = None,
+ ) -> dict:
+ """
+ Set up headers with OAuth token.
+ """
+ # Get access token
- access_token = get_access_token(
- credentials=api_key, litellm_params=litellm_params
- )
++ access_token = get_access_token(credentials=api_key, litellm_params=litellm_params)
+
+ headers["Authorization"] = f"Bearer {access_token}"
+ headers["Content-Type"] = "application/json"
+ headers["Accept"] = "application/json"
+
+ return headers
+
+ def logging_non_streaming_response(
+ self,
+ model: str,
+ custom_llm_provider: str,
+ httpx_response: Response,
+ request_data: dict,
+ logging_obj: LiteLLMLoggingObj,
+ endpoint: str,
+ ) -> CostResponseTypes | None:
+ from litellm import encoding
+ from litellm.types.utils import LlmProviders, ModelResponse
+ from litellm.utils import ProviderConfigManager
+
+ # cost tracking only for completions and embeddings
+ if "completions" in endpoint:
+ provider_chat_config = ProviderConfigManager.get_provider_chat_config(
+ provider=LlmProviders(custom_llm_provider),
+ model=model,
+ )
+
+ if provider_chat_config is None:
+ raise ValueError(f"No provider config found for model: {model}")
+
- litellm_model_response: ModelResponse = (
- provider_chat_config.transform_response(
- model=model,
- messages=request_data.get("messages", []),
- raw_response=httpx_response,
- model_response=ModelResponse(),
- logging_obj=logging_obj,
- optional_params={},
- litellm_params={},
- api_key="",
- request_data=request_data,
- encoding=encoding,
- )
++ litellm_model_response: ModelResponse = provider_chat_config.transform_response(
++ model=model,
++ messages=request_data.get("messages", []),
++ raw_response=httpx_response,
++ model_response=ModelResponse(),
++ logging_obj=logging_obj,
++ optional_params={},
++ litellm_params={},
++ api_key="",
++ request_data=request_data,
++ encoding=encoding,
+ )
+
+ return litellm_model_response
+
+ if "embeddings" in endpoint:
- provider_embedding_config = (
- ProviderConfigManager.get_provider_embedding_config(
- provider=LlmProviders(custom_llm_provider),
- model=model,
- )
++ provider_embedding_config = ProviderConfigManager.get_provider_embedding_config(
++ provider=LlmProviders(custom_llm_provider),
++ model=model,
+ )
+
+ if provider_embedding_config is None:
+ raise ValueError(f"No provider config found for model: {model}")
+
- litellm_embedding_response: EmbeddingResponse = (
- provider_embedding_config.transform_embedding_response(
- model=model,
- raw_response=httpx_response,
- model_response=EmbeddingResponse(),
- logging_obj=logging_obj,
- optional_params={},
- api_key="",
- request_data=request_data,
- litellm_params={},
- )
++ litellm_embedding_response: EmbeddingResponse = provider_embedding_config.transform_embedding_response(
++ model=model,
++ raw_response=httpx_response,
++ model_response=EmbeddingResponse(),
++ logging_obj=logging_obj,
++ optional_params={},
++ api_key="",
++ request_data=request_data,
++ litellm_params={},
+ )
+
+ return litellm_embedding_response
+
+ return None
+
+ def handle_logging_collected_chunks(
+ self,
+ all_chunks: list[str],
+ litellm_logging_obj: LiteLLMLoggingObj,
+ model: str,
+ custom_llm_provider: str,
+ endpoint: str,
+ ) -> CostResponseTypes | None:
+ """
+ 1. Convert all_chunks to a ModelResponseStream
+ 2. combine model_response_stream to model_response
+ 3. Return the model_response
+ """
+
+ from litellm.litellm_core_utils.streaming_handler import (
+ convert_generic_chunk_to_model_response_stream,
+ generic_chunk_has_all_required_fields,
+ )
+ from litellm.main import stream_chunk_builder
+ from litellm.types.utils import GenericStreamingChunk, ModelResponseStream
+
+ all_translated_chunks = []
+
+ for chunk in all_chunks:
+ if isinstance(chunk, bytes):
+ chunk = chunk.decode("utf-8", errors="ignore")
+
+ if isinstance(chunk, str):
+ chunk = chunk.strip()
+ if not chunk or chunk == "[DONE]":
+ continue
+ if chunk.startswith("data: "):
+ chunk = chunk[6:]
+ try:
+ message = json.loads(chunk)
+ except json.JSONDecodeError:
+ continue
+ elif isinstance(chunk, dict):
+ message = chunk
+ else:
+ continue
+
+ gigachat_iterator = GigaChatModelResponseIterator(
+ streaming_response=None,
+ sync_stream=False,
+ )
+ translated_chunk = gigachat_iterator.chunk_parser(chunk=message)
+
- if isinstance(
- translated_chunk, dict
- ) and generic_chunk_has_all_required_fields(cast(dict, translated_chunk)):
++ if isinstance(translated_chunk, dict) and generic_chunk_has_all_required_fields(
++ cast(dict, translated_chunk)
++ ):
+ chunk_obj = convert_generic_chunk_to_model_response_stream(
+ cast(GenericStreamingChunk, translated_chunk)
+ )
+ elif isinstance(translated_chunk, ModelResponseStream):
+ chunk_obj = translated_chunk
+ else:
+ continue
+
+ all_translated_chunks.append(chunk_obj)
+
+ if len(all_translated_chunks) > 0:
+ model_response = stream_chunk_builder(
+ chunks=all_translated_chunks,
+ logging_obj=litellm_logging_obj,
+ )
+ return model_response
+ return None
+
+ @staticmethod
+ def get_api_base(api_base: str | None = None) -> str | None:
+ return api_base or get_secret_str("GIGACHAT_API_BASE") or GIGACHAT_BASE_URL
+
+ @staticmethod
+ def get_api_key(
+ api_key: str | None = None,
+ ) -> str | None:
+ return api_key or get_secret_str("GIGACHAT_API_KEY")
+
+ @staticmethod
+ def get_base_model(model: str) -> str | None:
+ return model
+
- def get_models(
- self, api_key: str | None = None, api_base: str | None = None
- ) -> list[str]:
++ def get_models(self, api_key: str | None = None, api_base: str | None = None) -> list[str]:
+ return super().get_models(api_key, api_base)
diff --cc litellm/llms/gigachat/utils.py
index 0895d1a4992,00000000000..d2b18f30b5d
mode 100644,000000..100644
--- a/litellm/llms/gigachat/utils.py
+++ b/litellm/llms/gigachat/utils.py
@@@ -1,32 -1,0 +1,30 @@@
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.utils import PromptTokensDetailsWrapper, Usage
+
+# GigaChat API endpoint
+GIGACHAT_BASE_URL = "https://gigachat.devices.sberbank.ru/api/v1"
+
+
+def convert_usage(usage_data: dict[str, int]) -> Usage:
+ prompt_tokens = usage_data.get("prompt_tokens", 0)
+ completion_tokens = usage_data.get("completion_tokens", 0)
+ precached_prompt_tokens = usage_data.get("precached_prompt_tokens", 0)
+ total_tokens = usage_data.get("total_tokens", 0)
+
+ prompt_tokens += precached_prompt_tokens
+ total_tokens += precached_prompt_tokens
+
+ prompt_tokens_details = None
+ if precached_prompt_tokens > 0:
- prompt_tokens_details = PromptTokensDetailsWrapper(
- cached_tokens=precached_prompt_tokens
- )
++ prompt_tokens_details = PromptTokensDetailsWrapper(cached_tokens=precached_prompt_tokens)
+
+ return Usage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ prompt_tokens_details=prompt_tokens_details,
+ total_tokens=total_tokens,
+ )
+
+
+def get_api_base(api_base: str | None = None) -> str | None:
+ return api_base or get_secret_str("GIGACHAT_API_BASE") or GIGACHAT_BASE_URL
diff --cc litellm/passthrough/main.py
index aa4aef74e13,66367513062..0a8c57fb482
--- a/litellm/passthrough/main.py
+++ b/litellm/passthrough/main.py
@@@ -35,205 -35,6 +35,193 @@@ if TYPE_CHECKING
from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
+class AsyncPassthroughStreamingResponse(AsyncGenerator[Any, Any]):
+ def __init__(
+ self,
+ response: Coroutine[Any, Any, httpx.Response],
+ litellm_logging_obj: "LiteLLMLoggingObj",
+ provider_config: "BasePassthroughConfig",
+ ) -> None:
+ self._initialized = False
+ self._status_code: int = 0
+ self._headers = httpx.Headers()
+ self._response_coro = response
+ self._response: httpx.Response
+ self._iterator: AsyncGenerator[bytes, Any]
+ self._litellm_logging_obj = litellm_logging_obj
+ self._provider_config = provider_config
+ self._raw_bytes: list[bytes] = []
+ self._flush_scheduled = False
+ self._background_tasks: set[asyncio.Task] = set()
+
+ @property
+ def status_code(self) -> int:
+ if not self._initialized:
- raise RuntimeError(
- "AsyncPassthroughStreamingResponse must be awaited "
- "before accessing status_code"
- )
++ raise RuntimeError("AsyncPassthroughStreamingResponse must be awaited before accessing status_code")
+ return self._status_code
+
+ @status_code.setter
+ def status_code(self, value: int) -> None:
+ self._status_code = value
+
+ @property
+ def headers(self) -> httpx.Headers:
+ if not self._initialized:
- raise RuntimeError(
- "AsyncPassthroughStreamingResponse must be awaited "
- "before accessing headers"
- )
++ raise RuntimeError("AsyncPassthroughStreamingResponse must be awaited before accessing headers")
+ return self._headers
+
+ @headers.setter
+ def headers(self, value: httpx.Headers) -> None:
+ self._headers = value
+
+ def __await__(self):
+ async def _init():
+ if not self._initialized:
+ self._response = await self._response_coro
+ self.headers = self._response.headers
+ self.status_code = self._response.status_code
+ self._initialized = True
+ try:
+ self._response.raise_for_status()
- self._iterator = cast(
- AsyncGenerator[bytes, Any], self._response.aiter_bytes()
- )
++ self._iterator = cast(AsyncGenerator[bytes, Any], self._response.aiter_bytes())
+ except Exception: # noqa: BLE001
+ try:
+ await self._response.aclose()
+ except Exception: # noqa: BLE001
+ pass
+ raise
+ return self
+
+ return _init().__await__()
+
+ def _start_flush(self) -> None:
+ if self._flush_scheduled or not self._raw_bytes:
+ return
+ self._flush_scheduled = True
+
+ try:
+ task = asyncio.create_task(
+ self._litellm_logging_obj.async_flush_passthrough_collected_chunks(
+ raw_bytes=self._raw_bytes,
+ provider_config=self._provider_config,
+ )
+ )
+
+ # Compliant: Save a strong reference to prevent GC
+ self._background_tasks.add(task)
+
+ # Remove the task from the set when it finishes to avoid memory leaks
+ task.add_done_callback(self._background_tasks.discard)
+ except Exception as e: # noqa: BLE001
+ verbose_logger.exception(
- "Failed to schedule passthrough spend-tracking flush; "
- "%d buffered chunks dropped: %s",
++ "Failed to schedule passthrough spend-tracking flush; %d buffered chunks dropped: %s",
+ len(self._raw_bytes),
+ e,
+ )
+
+ def __aiter__(self) -> "AsyncPassthroughStreamingResponse":
+ return self
+
+ async def __anext__(self) -> bytes:
+ if not self._initialized:
+ await self
+ try:
+ chunk = await self._iterator.__anext__()
+ self._raw_bytes.append(chunk)
+ return chunk
+ except Exception: # noqa: BLE001
+ self._start_flush()
+ try:
+ await self._response.aclose()
+ except Exception: # noqa: BLE001
+ pass
+ raise
+
+ async def asend(self, value: Any) -> bytes:
+ if not self._initialized:
+ await self
+ return await self._iterator.asend(value)
+
+ async def athrow(self, typ: Any, val: Any = None, tb: Any = None) -> bytes:
+ if not self._initialized:
+ await self
+ return await self._iterator.athrow(typ, val, tb)
+
+ async def aclose(self) -> None:
+ self._start_flush()
+ try:
+ if self._initialized:
+ await self._response.aclose()
+ except Exception: # noqa: BLE001
+ pass
+
+
+class PassthroughStreamingResponse(Generator[Any, Any, Any]):
+ def __init__(
+ self,
+ response: httpx.Response,
+ litellm_logging_obj: "LiteLLMLoggingObj",
+ provider_config: "BasePassthroughConfig",
+ ) -> None:
+ self._response = response
+ self.headers = response.headers
+ self.status_code = response.status_code
+ self._litellm_logging_obj = litellm_logging_obj
+ self._provider_config = provider_config
- self._iterator: Generator[bytes, Any, Any] = cast(
- Generator[bytes, Any, Any], response.iter_bytes()
- )
++ self._iterator: Generator[bytes, Any, Any] = cast(Generator[bytes, Any, Any], response.iter_bytes())
+ self._raw_bytes: List[bytes] = []
+ self._flush_scheduled = False
+
+ def _start_flush(self) -> None:
+ if self._flush_scheduled or not self._raw_bytes:
+ return
+ self._flush_scheduled = True
+
+ from litellm.utils import executor
+
+ try:
+ executor.submit(
+ self._litellm_logging_obj.flush_passthrough_collected_chunks,
+ raw_bytes=self._raw_bytes,
+ provider_config=self._provider_config,
+ )
+ except Exception as e: # noqa: BLE001
+ verbose_logger.exception(
- "Failed to schedule passthrough spend-tracking flush; "
- "%d buffered chunks dropped: %s",
++ "Failed to schedule passthrough spend-tracking flush; %d buffered chunks dropped: %s",
+ len(self._raw_bytes),
+ e,
+ )
+
+ def __iter__(self) -> "PassthroughStreamingResponse":
+ return self
+
+ def __next__(self) -> bytes:
+ try:
+ chunk = next(self._iterator)
+ self._raw_bytes.append(chunk)
+ return chunk
+ except Exception: # noqa: BLE001
+ self._start_flush()
+ try:
+ self._response.close()
+ except Exception: # noqa: BLE001
+ pass
+ raise
+
+ def send(self, value: Any) -> bytes:
+ return self._iterator.send(value)
+
+ def throw(self, typ: Any, val: Any = None, tb: Any = None) -> bytes:
+ return self._iterator.throw(typ, val, tb)
+
+ def close(self) -> None:
+ self._start_flush()
+ try:
+ self._response.close()
+ except Exception: # noqa: BLE001
+ pass
+
+
@client
async def allm_passthrough_route(
*,
@@@ -544,16 -343,15 +530,12 @@@ def llm_passthrough_route
)
else:
# Sync path - client.client.send returns Response directly
- response: httpx.Response = client.client.send(
- request=request, stream=is_streaming_request
- ) # type: ignore
+ response: httpx.Response = client.client.send(request=request, stream=is_streaming_request) # type: ignore
response.raise_for_status()
- if (
- hasattr(response, "iter_bytes") and is_streaming_request
- ): # yield the chunk, so we can store it in the logging object
- return _sync_streaming(response, litellm_logging_obj, provider_config)
+ if hasattr(response, "iter_bytes") and is_streaming_request:
- return PassthroughStreamingResponse(
- response, litellm_logging_obj, provider_config
- )
++ return PassthroughStreamingResponse(response, litellm_logging_obj, provider_config)
else:
- # For non-streaming responses, yield the entire response
return response
except Exception as e:
if provider_config is None:
diff --cc litellm/proxy/common_request_processing.py
index 0f7d40c1181,97f7d51970c..73678c5271a
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@@ -728,37 -785,6 +785,35 @@@ class ProxyBaseLLMRequestProcessing
def __init__(self, data: dict):
self.data = data
+ @staticmethod
+ def _merge_passthrough_streaming_headers(
+ response_headers: Any | None,
+ custom_headers: dict,
+ ) -> dict:
+ """
+ Merge upstream passthrough headers with proxy/custom headers.
+
+ Proxy/custom headers win on key collisions.
+ """
+ excluded_headers = {
+ "transfer-encoding",
+ "content-encoding",
+ "set-cookie",
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailer",
+ "upgrade",
+ }
+
+ merged_headers = {
- key: value
- for key, value in dict(response_headers or {}).items()
- if key.lower() not in excluded_headers
++ key: value for key, value in dict(response_headers or {}).items() if key.lower() not in excluded_headers
+ }
+ merged_headers.update(custom_headers)
+ return merged_headers
+
@staticmethod
def get_custom_headers(
*,
@@@ -1537,18 -1517,9 +1546,16 @@@
cache_hit=cache_hit,
)
- logging_obj._on_deferred_stream_complete = (
- _on_deferred_stream_complete # type: ignore[union-attr]
- )
+ logging_obj._on_deferred_stream_complete = _on_deferred_stream_complete # type: ignore[union-attr]
if route_type == "allm_passthrough_route":
+ streaming_headers = custom_headers
+ if hasattr(response, "headers"):
+ streaming_headers = ProxyBaseLLMRequestProcessing._merge_passthrough_streaming_headers(
+ response_headers=getattr(response, "headers", None),
+ custom_headers=custom_headers,
+ )
+
# Check if response is an async generator
if self._is_streaming_response(response):
if asyncio.iscoroutine(response):
@@@ -1586,20 -1553,16 +1589,16 @@@
# since we're dealing with raw binary data (e.g., AWS event streams)
return StreamingResponse(
content=generator, # type: ignore[arg-type]
- status_code=getattr(
- response, "status_code", status.HTTP_200_OK
- ),
- status_code=status.HTTP_200_OK,
- headers=custom_headers,
++ status_code=getattr(response, "status_code", status.HTTP_200_OK),
+ headers=streaming_headers,
)
else:
- _early = (
- await self._handle_non_streaming_allm_passthrough_route(
- response=response,
- proxy_logging_obj=proxy_logging_obj,
- user_api_key_dict=user_api_key_dict,
- custom_headers=custom_headers,
- request_headers=dict(request.headers),
- )
+ _early = await self._handle_non_streaming_allm_passthrough_route(
+ response=response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ custom_headers=custom_headers,
+ request_headers=dict(request.headers),
)
if _early is not None:
return _early
diff --cc litellm/proxy/management_endpoints/credential_migration.py
index 00000000000,4d51295f8dc..6f79a39c883
mode 000000,100644..100644
--- a/litellm/proxy/management_endpoints/credential_migration.py
+++ b/litellm/proxy/management_endpoints/credential_migration.py
@@@ -1,0 -1,702 +1,661 @@@
+ """
+ At-rest credential re-encryption migration.
+
+ Switches every encrypted-at-rest value from the legacy XSalsa20-Poly1305 (nacl)
+ format to the versioned AES-256-GCM (``v2:gcm:``) format produced by
+ ``encrypt_decrypt_utils`` when ``general_settings.encryption_algorithm`` is set to
+ ``aes-256-gcm``.
+
+ Design properties (see case 2026-06-24 fix plan):
+
+ * **Same key, new algorithm.** The migration does not change the encryption key;
+ it re-encrypts existing ciphertext under the same derived key but in the new
+ AES format. This is achieved by decrypting with the format-detecting reader and
+ re-encrypting through ``encrypt_value_helper`` with the AES gate enabled.
+ * **Idempotent.** A value already carrying the ``v2:gcm:`` prefix is recognised
+ and left untouched, so re-running the migration is a no-op on migrated rows.
+ * **Resumable.** Walkers commit per row (or per small table), so an interrupted
+ run leaves a clean mixed state that a re-run completes.
+ * **Skip-on-undecryptable.** A value that cannot be decrypted is never
+ overwritten — corrupt rows are preserved and reported, never destroyed.
+ * **Attestable.** :func:`check_encryption` is a read-only scan that classifies
+ every value as ``migrated`` / ``legacy`` / ``plaintext`` / ``undecryptable``.
+ A residual ``legacy == 0`` is the compliance attestation.
+
+ Coverage. The covered tables (model table, credentials table, MCP credential/env
+ tables, config ``environment_variables``) already have a re-encryption path in
+ ``_rotate_master_key``; this module delegates to it in *same-key* mode and adds
+ walkers for the locations that had no rotation path: team / verification-token
+ ``callback_vars`` metadata, the ``vantage_settings`` / ``cloudzero_settings``
+ config rows, and the SSO config table.
+ """
+
+ import json
+ from dataclasses import dataclass, field
+ from typing import TYPE_CHECKING, Literal, cast
+
+ from litellm._logging import verbose_proxy_logger
+
+ if TYPE_CHECKING:
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.utils import PrismaClient
+ from litellm.proxy.common_utils.encrypt_decrypt_utils import (
+ _ALGO_AES_GCM,
+ _ENCRYPTION_ALGORITHM_SETTING,
+ _V2_GCM_PREFIX,
+ _get_salt_key,
+ decrypt_value_helper,
+ encrypt_value_helper,
+ )
+
+ ValueClass = Literal["migrated", "legacy", "plaintext", "undecryptable", "not-a-string"]
+
+
+ @dataclass
+ class LocationReport:
+ """Per-location counters for one migration / check pass."""
+
+ location: str
+ scanned: int = 0
+ migrated: int = 0 # values rewritten to v2 this run
+ already_v2: int = 0 # values already migrated (skipped)
+ plaintext: int = 0 # legacy-plaintext values (no ciphertext to migrate)
+ undecryptable: int = 0 # could not decrypt — preserved, not overwritten
+
+ # Used by --check (read-only classification):
+ legacy: int = 0 # nacl ciphertext still awaiting migration
+
+ def as_dict(self) -> dict[str, int]:
+ return {
+ "scanned": self.scanned,
+ "migrated": self.migrated,
+ "already_v2": self.already_v2,
+ "plaintext": self.plaintext,
+ "undecryptable": self.undecryptable,
+ "legacy": self.legacy,
+ }
+
+
+ @dataclass
+ class MigrationReport:
+ """Aggregate report across all locations."""
+
+ locations: list[LocationReport] = field(default_factory=list)
+
+ def add(self, report: LocationReport) -> None:
+ self.locations.append(report)
+
+ @property
+ def residual_legacy(self) -> int:
+ """Total legacy ciphertext still un-migrated (the TRO attestation number)."""
+ return sum(loc.legacy for loc in self.locations)
+
+ @property
+ def total_undecryptable(self) -> int:
+ return sum(loc.undecryptable for loc in self.locations)
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "residual_legacy": self.residual_legacy,
+ "total_undecryptable": self.total_undecryptable,
+ "locations": {loc.location: loc.as_dict() for loc in self.locations},
+ }
+
+
+ # ---------------------------------------------------------------------------
+ # Pure engine — no DB I/O, fully unit-testable.
+ # ---------------------------------------------------------------------------
+
+
+ def is_migrated(value: object) -> bool:
+ """True if ``value`` is already an AES-256-GCM (``v2:gcm:``) ciphertext."""
+ return isinstance(value, str) and value.startswith(_V2_GCM_PREFIX)
+
+
+ def classify_value(value: object, key: str = "scan") -> ValueClass:
+ """Classify a stored value for the residual scanner.
+
+ * ``not-a-string`` — not a string (numbers/bools/None left as-is on disk).
+ * ``migrated`` — carries the ``v2:gcm:`` prefix.
+ * ``legacy`` — decrypts under the legacy nacl reader (still needs migrating).
+ * ``plaintext`` — a non-empty string that does not decrypt and is not v2;
+ treated as legacy plaintext (nothing to migrate).
+ * ``undecryptable`` — reserved for callers that already know a value is
+ ciphertext but cannot decrypt it; ``classify_value`` itself cannot tell a
+ corrupt ciphertext from plaintext, so it returns ``plaintext`` for both.
+ """
+ if not isinstance(value, str):
+ return "not-a-string"
+ if value == "":
+ return "plaintext"
+ if value.startswith(_V2_GCM_PREFIX):
+ return "migrated"
- decrypted = decrypt_value_helper(
- value=value, key=key, exception_type="debug", return_original_value=False
- )
++ decrypted = decrypt_value_helper(value=value, key=key, exception_type="debug", return_original_value=False)
+ if decrypted is None:
+ # Did not decrypt under nacl and has no v2 marker: legacy plaintext.
+ return "plaintext"
+ return "legacy"
+
+
+ def reencrypt_value(value: object, key: str = "migrate") -> object:
+ """Re-encrypt a single stored string into the configured (AES) format.
+
+ Returns the value unchanged if it is not a string, is already ``v2:``, or
+ cannot be decrypted (skip-on-undecryptable). Otherwise decrypts under the
+ format-detecting reader and re-encrypts through ``encrypt_value_helper``
+ (which writes AES when the gate is on).
+ """
+ if not isinstance(value, str) or value == "":
+ return value
+ if value.startswith(_V2_GCM_PREFIX):
+ return value # idempotent: already migrated
- decrypted = decrypt_value_helper(
- value=value, key=key, exception_type="debug", return_original_value=False
- )
++ decrypted = decrypt_value_helper(value=value, key=key, exception_type="debug", return_original_value=False)
+ if decrypted is None:
+ # Either legacy plaintext (no ciphertext to migrate) or corrupt. Either
+ # way, do not overwrite — preserve the value as stored.
+ return value
+ return encrypt_value_helper(decrypted)
+
+
-def reencrypt_selective_dict(
- data: dict[str, object], sensitive_keys: list[str]
-) -> dict[str, object]:
++def reencrypt_selective_dict(data: dict[str, object], sensitive_keys: list[str]) -> dict[str, object]:
+ """Return a copy of ``data`` with only ``sensitive_keys`` re-encrypted.
+
+ Non-sensitive fields (e.g. ``base_url``, ``connection_id``) are left as-is.
+ Null/missing fields are skipped.
+ """
+ out = dict(data)
+ for k in sensitive_keys:
+ v = out.get(k)
+ if v is None:
+ continue
+ out[k] = reencrypt_value(v, key=k)
+ return out
+
+
+ def _assert_aes_gate_enabled() -> None:
+ """Fail fast if the AES algorithm gate is not enabled.
+
+ Running the migration with the gate off would decrypt then re-encrypt right
+ back into the legacy format — a no-op that silently fails the migration.
+ """
+ from litellm.proxy.proxy_server import general_settings
+
+ algo = general_settings.get(_ENCRYPTION_ALGORITHM_SETTING)
+ if not (isinstance(algo, str) and algo.lower() == _ALGO_AES_GCM):
+ raise RuntimeError(
+ "Encryption migration requires general_settings.encryption_algorithm: "
+ f"'{_ALGO_AES_GCM}'. Current value: {algo!r}. Set it before migrating "
+ "so re-encrypted values are written in the AES-256-GCM format."
+ )
+
+
+ # ---------------------------------------------------------------------------
+ # Walkers for the locations with no pre-existing rotation path.
+ # Each walker delegates the structural transform to the existing, tested helper
+ # for that table and only adds the per-row re-encrypt + commit + counters.
+ # ---------------------------------------------------------------------------
+
+
+ async def _migrate_config_settings_row(
+ prisma_client: object,
+ param_name: str,
+ sensitive_fields: list[str],
+ dry_run: bool,
+ ) -> LocationReport:
+ """Migrate a single ``LiteLLM_Config`` row whose ``param_value`` is a JSON
+ dict with selected sensitive fields (vantage_settings / cloudzero_settings).
+ """
+ report = LocationReport(location=param_name)
- record = await prisma_client.db.litellm_config.find_unique(
- where={"param_name": param_name}
- )
++ record = await prisma_client.db.litellm_config.find_unique(where={"param_name": param_name})
+ if record is None or record.param_value is None:
+ return report
+
+ settings = record.param_value
+ if isinstance(settings, str):
+ settings = json.loads(settings)
+ if not isinstance(settings, dict):
+ return report
+
+ changed = False
+ for fld in sensitive_fields:
+ v = settings.get(fld)
+ if v is None:
+ continue
+ report.scanned += 1
+ cls = classify_value(v, key=fld)
+ if cls == "migrated":
+ report.already_v2 += 1
+ continue
+ if cls == "legacy":
+ if dry_run:
+ # Residual: would migrate, but a dry run writes nothing, so it
+ # stays legacy for the attestation (never counted as migrated).
+ report.legacy += 1
+ continue
+ new_v = reencrypt_value(v, key=fld)
+ if new_v != v:
+ settings[fld] = new_v
+ report.migrated += 1
+ changed = True
+ else:
+ # Defensive: a legacy value that did not re-encrypt is still
+ # residual, not migrated.
+ report.legacy += 1
+ else: # plaintext / not-a-string — nothing to migrate
+ report.plaintext += 1
+
+ if changed and not dry_run:
+ await prisma_client.db.litellm_config.update(
+ where={"param_name": param_name},
+ data={"param_value": json.dumps(settings)},
+ )
+ return report
+
+
+ async def _migrate_sso_config(prisma_client: object, dry_run: bool) -> LocationReport:
+ """Migrate the ``LiteLLM_SSOConfig`` row. All non-null fields are encrypted
+ (via the same ``_encrypt_env_variables`` path used on save), so we re-encrypt
+ every present string field.
+ """
+ report = LocationReport(location="sso_config")
- record = await prisma_client.db.litellm_ssoconfig.find_unique(
- where={"id": "sso_config"}
- )
++ record = await prisma_client.db.litellm_ssoconfig.find_unique(where={"id": "sso_config"})
+ if record is None or record.sso_settings is None:
+ return report
+
+ settings = record.sso_settings
+ if isinstance(settings, str):
+ settings = json.loads(settings)
+ if not isinstance(settings, dict):
+ return report
+
+ new_settings = dict(settings)
+ changed = False
+ for fld, v in settings.items():
+ if not isinstance(v, str) or v == "":
+ continue
+ report.scanned += 1
+ cls = classify_value(v, key=fld)
+ if cls == "migrated":
+ report.already_v2 += 1
+ continue
+ if cls == "legacy":
+ if dry_run:
+ # Residual: would migrate, but a dry run writes nothing, so it
+ # stays legacy for the attestation (never counted as migrated).
+ report.legacy += 1
+ continue
+ new_v = reencrypt_value(v, key=fld)
+ if new_v != v:
+ new_settings[fld] = new_v
+ report.migrated += 1
+ changed = True
+ else:
+ # Defensive: a legacy value that did not re-encrypt is still
+ # residual, not migrated.
+ report.legacy += 1
+ else:
+ report.plaintext += 1
+
+ if changed and not dry_run:
+ await prisma_client.db.litellm_ssoconfig.update(
+ where={"id": "sso_config"},
+ data={"sso_settings": json.dumps(new_settings)},
+ )
+ return report
+
+
+ async def _migrate_callback_vars_table(
+ prisma_client: object,
+ table_name: Literal["team", "verification_token"],
+ dry_run: bool,
+ ) -> LocationReport:
+ """Migrate callback-var credentials on the team or verification-token table.
+
+ Covers both shapes the ``decrypt_callback_vars`` / ``encrypt_callback_vars``
+ transforms understand: ``metadata.logging[*].callback_vars.<sensitive>`` and
+ the top-level ``metadata.callback_settings.callback_vars.<sensitive>``. Reuses
+ those proven transforms (selective, prefix-marked; legacy plaintext is left
+ alone until re-encrypted).
+ """
+ from litellm.proxy.common_utils.callback_utils import (
+ decrypt_callback_vars,
+ encrypt_callback_vars,
+ )
+
+ report = LocationReport(location=f"{table_name}.callback_vars")
+
+ if table_name == "team":
+ table = prisma_client.db.litellm_teamtable
+ pk = "team_id"
+ else:
+ table = prisma_client.db.litellm_verificationtoken
+ pk = "token"
+
+ rows = await table.find_many()
+ for row in rows or []:
+ metadata = getattr(row, "metadata", None)
- if not isinstance(metadata, dict) or (
- "logging" not in metadata and "callback_settings" not in metadata
- ):
++ if not isinstance(metadata, dict) or ("logging" not in metadata and "callback_settings" not in metadata):
+ continue
+
+ # Classify every callback-var value directly (strip the litellm_enc::
+ # marker, then prefix/decrypt-classify), exactly like the covered-table
+ # scanner. Detecting legacy this way is independent of the AES gate, so
+ # the check_encryption (dry-run) attestation is correct even when run
+ # before the gate is enabled -- a re-encrypt-delta heuristic would read
+ # zero residual here with the gate off.
+ row_legacy = 0
+ for cvs in _iter_callback_var_dicts(metadata):
+ for v in cvs.values():
+ report.scanned += 1
+ cls = _classify_callback_value(v)
+ if cls == "migrated":
+ report.already_v2 += 1
+ elif cls == "legacy":
+ row_legacy += 1
+ else: # plaintext / not-a-string
+ report.plaintext += 1
+
+ if row_legacy == 0:
+ continue # no legacy ciphertext in this row
+
+ if dry_run:
+ # Residual for the attestation; a dry run writes nothing.
+ report.legacy += row_legacy
+ continue
+
+ # Real run: re-encrypt the legacy ciphertext to AES via the proven
+ # selective transforms and persist. Never drop a row on failure.
+ try:
+ re_encrypted = encrypt_callback_vars(decrypt_callback_vars(metadata))
+ except Exception as e: # pragma: no cover - defensive; never drop a row
+ verbose_proxy_logger.warning(
+ "Skipping %s row %s callback_vars (transform failed): %s",
+ table_name,
+ getattr(row, pk, "?"),
+ str(e),
+ )
+ report.undecryptable += row_legacy
+ continue
+ report.migrated += row_legacy
+ await table.update(
+ where={pk: getattr(row, pk)},
+ data={"metadata": json.dumps(re_encrypted)},
+ )
+
+ return report
+
+
+ def _iter_callback_var_dicts(metadata: dict[str, object]):
+ """Yield each ``callback_vars`` dict in a metadata structure.
+
+ Mirrors ``_transform_callback_vars``: credentials live both under
+ ``logging[*].callback_vars`` and under the top-level
+ ``callback_settings.callback_vars``. Counting only the former would let the
+ walker report success while leaving ``callback_settings`` secrets in legacy
+ format at rest.
+ """
+ for entry in metadata.get("logging", []) or []:
+ if isinstance(entry, dict):
+ cvs = entry.get("callback_vars")
+ if isinstance(cvs, dict):
+ yield cvs
+ callback_settings = metadata.get("callback_settings")
+ if isinstance(callback_settings, dict):
+ cvs = callback_settings.get("callback_vars")
+ if isinstance(cvs, dict):
+ yield cvs
+
+
+ def _classify_callback_value(value: object) -> ValueClass:
+ """Classify one stored callback-var value, independent of the AES gate.
+
+ Encrypted callback vars carry the ``litellm_enc::`` marker in front of the
+ ciphertext; strip it, then classify the inner value the same way the
+ covered-table scanner does (``v2:gcm:`` prefix -> migrated, nacl-decryptable
+ -> legacy, otherwise plaintext). Detecting legacy by decrypt rather than by a
+ re-encrypt delta is what makes the ``check_encryption`` attestation correct
+ even when run with the AES write gate off.
+ """
+ from litellm.proxy.common_utils.callback_utils import (
+ _CALLBACK_VAR_ENCRYPTED_PREFIX,
+ )
+
+ if not isinstance(value, str):
+ return "not-a-string"
+ inner = value
+ if inner.startswith(_CALLBACK_VAR_ENCRYPTED_PREFIX):
+ inner = inner[len(_CALLBACK_VAR_ENCRYPTED_PREFIX) :]
+ return classify_value(inner, key="callback")
+
+
+ # ---------------------------------------------------------------------------
+ # Read-only scanner for the rotation-covered tables.
+ #
+ # ``_rotate_master_key`` re-encrypts these tables but returns no counts, so on
+ # its own it can neither attest residual legacy nor report how many rows it
+ # migrated. This scanner reads (never writes) the same encrypted columns the
+ # rotation path touches and classifies every value, giving both the attestation
+ # coverage and the pre/post counts the rotation path can't supply itself.
+ # ---------------------------------------------------------------------------
+
+ # (location, prisma db attribute, JSON columns to walk, scalar string columns).
+ _COVERED_TABLE_SPECS = [
+ ("model_table", "litellm_proxymodeltable", ("litellm_params",), ()),
+ ("credentials", "litellm_credentialstable", ("credential_values",), ()),
+ ("mcp_server", "litellm_mcpservertable", ("credentials", "env_vars"), ()),
+ ("mcp_user_credentials", "litellm_mcpusercredentials", (), ("credential_b64",)),
+ ("mcp_user_env_vars", "litellm_mcpuserenvvars", (), ("values_b64",)),
+ ]
+
+
+ def _iter_encrypted_strings(obj: object):
+ """Yield every string leaf in a nested dict/list/scalar structure.
+
+ Iterative (explicit stack) on purpose: recursion here is banned by the
+ code-quality recursive-function detector (unbounded nesting has caused CPU
+ spikes in the past), and an explicit stack walks arbitrary depth safely.
+ """
+ stack: list[object] = [obj]
+ while stack:
+ cur = stack.pop()
+ if isinstance(cur, str):
+ yield cur
+ elif isinstance(cur, dict):
+ stack.extend(cur.values())
+ elif isinstance(cur, list):
+ stack.extend(cur)
+
+
+ def _classify_into_report(report: LocationReport, value: str) -> None:
+ """Classify one stored string and bump the matching read-only counter.
+
+ Only genuine nacl ciphertext lands in ``legacy``; non-secret strings (model
+ names, base URLs, …) do not decrypt and fall through to ``plaintext``, so
+ over-scanning a column is harmless to the residual count.
+ """
+ report.scanned += 1
+ cls = classify_value(value, key="scan")
+ if cls == "migrated":
+ report.already_v2 += 1
+ elif cls == "legacy":
+ report.legacy += 1
+ else: # plaintext / not-a-string
+ report.plaintext += 1
+
+
+ async def _scan_one_table(
+ prisma_client: object,
+ location: str,
+ db_attr: str,
+ json_columns: tuple,
+ scalar_columns: tuple,
+ ) -> LocationReport:
+ report = LocationReport(location=location)
+ table = getattr(prisma_client.db, db_attr, None)
+ if table is None:
+ return report
+ try:
+ rows = await table.find_many()
+ except Exception as e: # pragma: no cover - table absent / not migrated
+ verbose_proxy_logger.debug("scan: %s unavailable: %s", location, str(e))
+ return report
+ for row in rows or []:
+ for col in json_columns:
+ raw = getattr(row, col, None)
+ if raw is None:
+ continue
+ if isinstance(raw, str):
+ try:
+ raw = json.loads(raw)
+ except (ValueError, TypeError):
+ pass
+ for s in _iter_encrypted_strings(raw):
+ _classify_into_report(report, s)
+ for col in scalar_columns:
+ v = getattr(row, col, None)
+ if isinstance(v, str):
+ _classify_into_report(report, v)
+ return report
+
+
+ async def _scan_config_env_vars(prisma_client: object) -> LocationReport:
+ """Scan the ``environment_variables`` config row (``param_value`` dict)."""
+ report = LocationReport(location="config_environment_variables")
+ try:
- record = await prisma_client.db.litellm_config.find_unique(
- where={"param_name": "environment_variables"}
- )
++ record = await prisma_client.db.litellm_config.find_unique(where={"param_name": "environment_variables"})
+ except Exception as e: # pragma: no cover - defensive
+ verbose_proxy_logger.debug("scan: config env vars unavailable: %s", str(e))
+ return report
+ if record is None or record.param_value is None:
+ return report
+ value = record.param_value
+ if isinstance(value, str):
+ try:
+ value = json.loads(value)
+ except (ValueError, TypeError):
+ value = {}
+ for s in _iter_encrypted_strings(value):
+ _classify_into_report(report, s)
+ return report
+
+
+ async def _scan_covered_tables(prisma_client: object) -> list[LocationReport]:
+ """Read-only classification of every rotation-covered table. No writes."""
+ reports: list[LocationReport] = []
+ for location, db_attr, json_cols, scalar_cols in _COVERED_TABLE_SPECS:
- reports.append(
- await _scan_one_table(
- prisma_client, location, db_attr, json_cols, scalar_cols
- )
- )
++ reports.append(await _scan_one_table(prisma_client, location, db_attr, json_cols, scalar_cols))
+ reports.append(await _scan_config_env_vars(prisma_client))
+ return reports
+
+
+ # ---------------------------------------------------------------------------
+ # Orchestrator
+ # ---------------------------------------------------------------------------
+
+ # vantage_settings / cloudzero_settings sensitive fields (see *_endpoints.py).
+ _VANTAGE_SENSITIVE = ["api_key", "integration_token"]
+ _CLOUDZERO_SENSITIVE = ["api_key"]
+
+
-async def _migrate_covered_tables(
- prisma_client: object, user_api_key_dict: object
-) -> list[LocationReport]:
++async def _migrate_covered_tables(prisma_client: object, user_api_key_dict: object) -> list[LocationReport]:
+ """Re-encrypt the tables already covered by ``_rotate_master_key`` (model
+ table, credentials, MCP credential/env tables, config environment_variables)
+ by running that orchestrator in *same-key* mode. With the AES gate on, the
+ re-encrypt writes land in ``v2:`` format.
+
+ ``_rotate_master_key`` returns no counts, so we bracket it with read-only
+ scans: the pre-scan's legacy total minus the post-scan's gives the number
+ actually migrated per location, and the post-scan supplies the residual /
+ already-v2 / scanned figures. Returns one report per covered location.
+ """
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ _rotate_master_key,
+ )
+
+ pre = {r.location: r for r in await _scan_covered_tables(prisma_client)}
+
+ current_key = _get_salt_key()
+ if current_key is None:
+ raise RuntimeError(
- "Cannot migrate covered tables: no salt key / master key is set. "
- "Set LITELLM_SALT_KEY before migrating."
++ "Cannot migrate covered tables: no salt key / master key is set. Set LITELLM_SALT_KEY before migrating."
+ )
+ await _rotate_master_key(
+ prisma_client=cast("PrismaClient", prisma_client),
+ user_api_key_dict=cast("UserAPIKeyAuth", user_api_key_dict),
+ current_master_key=current_key,
+ new_master_key=current_key, # same key, algorithm-only switch
+ )
+
+ post = await _scan_covered_tables(prisma_client)
+ for post_report in post:
+ pre_report = pre.get(post_report.location)
+ pre_legacy = pre_report.legacy if pre_report else 0
+ # Everything that was legacy before and is no longer legacy now was
+ # converted this run.
+ post_report.migrated = max(0, pre_legacy - post_report.legacy)
+ return post
+
+
+ async def migrate_encryption(
+ prisma_client: object,
+ user_api_key_dict: object,
+ dry_run: bool = False,
+ ) -> MigrationReport:
+ """Run the full at-rest re-encryption migration.
+
+ Requires ``general_settings.encryption_algorithm == 'aes-256-gcm'`` so writes
+ are produced in the AES format. Idempotent and resumable: re-running skips
+ already-migrated values and finishes any partial run.
+
+ A ``dry_run`` performs no writes: the covered tables are scanned read-only
+ (so their residual legacy still counts toward the attestation) and the
+ net-new walkers run in dry-run mode.
+ """
+ _assert_aes_gate_enabled()
+
+ report = MigrationReport()
+
+ # Tables that already have a rotation path (items 1, 2, 5-10). On a real run
+ # delegate to the rotation path (with bracketing scans for counts); on a dry
+ # run only classify them read-only.
+ if dry_run:
+ for covered in await _scan_covered_tables(prisma_client):
+ report.add(covered)
+ else:
+ for covered in await _migrate_covered_tables(prisma_client, user_api_key_dict):
+ report.add(covered)
+
+ # Net-new walkers (items 3, 4, 11, 12, 13).
+ report.add(await _migrate_callback_vars_table(prisma_client, "team", dry_run))
- report.add(
- await _migrate_callback_vars_table(prisma_client, "verification_token", dry_run)
- )
- report.add(
- await _migrate_config_settings_row(
- prisma_client, "vantage_settings", _VANTAGE_SENSITIVE, dry_run
- )
- )
- report.add(
- await _migrate_config_settings_row(
- prisma_client, "cloudzero_settings", _CLOUDZERO_SENSITIVE, dry_run
- )
- )
++ report.add(await _migrate_callback_vars_table(prisma_client, "verification_token", dry_run))
++ report.add(await _migrate_config_settings_row(prisma_client, "vantage_settings", _VANTAGE_SENSITIVE, dry_run))
++ report.add(await _migrate_config_settings_row(prisma_client, "cloudzero_settings", _CLOUDZERO_SENSITIVE, dry_run))
+ report.add(await _migrate_sso_config(prisma_client, dry_run))
+
+ return report
+
+
+ async def check_encryption(prisma_client: object) -> MigrationReport:
+ """Read-only residual scan across **every** at-rest location. No writes.
+
+ Covers both the rotation-managed tables (model / credentials / MCP credential
+ and env-var tables / config ``environment_variables``) and the net-new walker
+ locations (team and verification-token ``callback_vars``, vantage / cloudzero
+ config rows, SSO config). Reports how many values are still ``legacy``;
+ ``residual_legacy == 0`` across this full scan is the compliance attestation.
+ """
+ report = MigrationReport()
+
+ # Rotation-covered tables (read-only classification).
+ for covered in await _scan_covered_tables(prisma_client):
+ report.add(covered)
+
+ # Net-new walker locations, in dry-run (read-only) mode.
+ report.add(await _migrate_callback_vars_table(prisma_client, "team", dry_run=True))
++ report.add(await _migrate_callback_vars_table(prisma_client, "verification_token", dry_run=True))
++ report.add(await _migrate_config_settings_row(prisma_client, "vantage_settings", _VANTAGE_SENSITIVE, dry_run=True))
+ report.add(
- await _migrate_callback_vars_table(
- prisma_client, "verification_token", dry_run=True
- )
- )
- report.add(
- await _migrate_config_settings_row(
- prisma_client, "vantage_settings", _VANTAGE_SENSITIVE, dry_run=True
- )
- )
- report.add(
- await _migrate_config_settings_row(
- prisma_client, "cloudzero_settings", _CLOUDZERO_SENSITIVE, dry_run=True
- )
++ await _migrate_config_settings_row(prisma_client, "cloudzero_settings", _CLOUDZERO_SENSITIVE, dry_run=True)
+ )
+ report.add(await _migrate_sso_config(prisma_client, dry_run=True))
+ return report
diff --cc litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
index 689b574d5bc,7e573de261b..c80e5860571
--- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
@@@ -84,9 -75,7 +84,7 @@@ def create_request_copy(request: Reques
}
- def is_passthrough_request_using_router_model(
- request_body: dict, llm_router: litellm.Router | None
- ) -> bool:
-def is_passthrough_request_using_router_model(request_body: dict, llm_router: Optional[litellm.Router]) -> bool:
++def is_passthrough_request_using_router_model(request_body: dict, llm_router: litellm.Router | None) -> bool:
"""
Returns True if the model is in the llm_router model names
"""
@@@ -1514,9 -1411,7 +1420,7 @@@ class BaseVertexAIPassThroughHandler(AB
@staticmethod
@abstractmethod
- def update_base_target_url_with_credential_location(
- base_target_url: str, vertex_location: str | None
- ) -> str:
- def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: Optional[str]) -> str:
++ def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: str | None) -> str:
pass
@@@ -1526,9 -1421,7 +1430,7 @@@ class VertexAIDiscoveryPassThroughHandl
return "https://discoveryengine.googleapis.com/"
@staticmethod
- def update_base_target_url_with_credential_location(
- base_target_url: str, vertex_location: str | None
- ) -> str:
- def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: Optional[str]) -> str:
++ def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: str | None) -> str:
return base_target_url
@@@ -1538,9 -1431,7 +1440,7 @@@ class VertexAIPassThroughHandler(BaseVe
return get_vertex_base_url(vertex_location)
@staticmethod
- def update_base_target_url_with_credential_location(
- base_target_url: str, vertex_location: str | None
- ) -> str:
- def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: Optional[str]) -> str:
++ def update_base_target_url_with_credential_location(base_target_url: str, vertex_location: str | None) -> str:
return get_vertex_base_url(vertex_location)
@@@ -2124,9 -1990,7 +1999,7 @@@ class BaseOpenAIPassThroughHandler
return headers
@staticmethod
- def _assemble_headers(
- api_key: str | None, request: Request, extra_headers: dict | None = None
- ) -> dict:
- def _assemble_headers(api_key: Optional[str], request: Request, extra_headers: Optional[dict] = None) -> dict:
++ def _assemble_headers(api_key: str | None, request: Request, extra_headers: dict | None = None) -> dict:
base_headers = {}
if api_key is not None:
base_headers = {
@@@ -2441,265 -2283,6 +2292,247 @@@ def create_generic_websocket_passthroug
)
+ "/gigachat/{endpoint:path}",
+ methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
+ tags=["Gigachat Pass-through", "pass-through"],
+)
+async def gigachat_proxy_route(
+ endpoint: str,
+ request: Request,
+ fastapi_response: Response,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ [Docs](https://docs.litellm.ai/docs/pass_through/gigachat)
+ """
+ from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
+ from litellm.proxy.proxy_server import (
+ general_settings,
+ llm_router,
+ proxy_config,
+ proxy_logging_obj,
+ select_data_generator,
+ user_api_base,
+ user_max_tokens,
+ user_model,
+ user_request_timeout,
+ user_temperature,
+ version,
+ )
+
+ ## check for streaming
+ request_body = await get_request_body(request)
+ is_router_model = False
+
+ model = request_body.get("model")
+ if model:
- is_router_model = is_passthrough_request_using_router_model(
- request_body, llm_router
- )
++ is_router_model = is_passthrough_request_using_router_model(request_body, llm_router)
+ elif any(word in endpoint for word in ("completions", "embeddings")):
- raise HTTPException(
- status_code=400, detail={"error": "Model is required in request body"}
- )
++ raise HTTPException(status_code=400, detail={"error": "Model is required in request body"})
+
+ # If router model, use dedicated router passthrough handler
+ # This uses the same common processing path as non-router models
+ if model and is_router_model and llm_router:
+ return await handle_gigachat_passthrough_router_model(
+ model=model,
+ endpoint=endpoint,
+ request=request,
+ request_body=request_body,
+ fastapi_response=fastapi_response,
+ llm_router=llm_router,
+ user_api_key_dict=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ general_settings=general_settings,
+ proxy_config=proxy_config,
+ select_data_generator=select_data_generator,
+ user_model=user_model,
+ user_temperature=user_temperature,
+ user_request_timeout=user_request_timeout,
+ user_max_tokens=user_max_tokens,
+ user_api_base=user_api_base,
+ version=version,
+ )
+
+ # Fall back to existing implementation for direct GigaChat models
- verbose_proxy_logger.debug(
- f"Gigachat passthrough: Using direct Gigachat model '{model}' for endpoint '{endpoint}'"
- )
++ verbose_proxy_logger.debug(f"Gigachat passthrough: Using direct Gigachat model '{model}' for endpoint '{endpoint}'")
+
+ data: Dict[str, Any] = {}
+
+ data["method"] = request.method
+ data["endpoint"] = endpoint
+ data["json"] = request_body
+ data["custom_llm_provider"] = "gigachat"
+
+ client = get_async_httpx_client( # type: ignore
+ llm_provider=LlmProviders.GIGACHAT,
+ params={
+ "timeout": httpx.Timeout(timeout=600.0, connect=5.0),
+ "ssl_verify": False,
+ },
+ )
+ data["client"] = client
+
+ base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)
+
+ try:
+ result = await base_llm_response_processor.base_passthrough_process_llm_request(
+ request=request,
+ fastapi_response=fastapi_response,
+ user_api_key_dict=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ llm_router=llm_router,
+ general_settings=general_settings,
+ proxy_config=proxy_config,
+ select_data_generator=select_data_generator,
+ model=model,
+ user_model=user_model,
+ user_temperature=user_temperature,
+ user_request_timeout=user_request_timeout,
+ user_max_tokens=user_max_tokens,
+ user_api_base=user_api_base,
+ version=version,
+ )
+
+ return result
+ except Exception as e: # noqa: BLE001
+ raise await base_llm_response_processor._handle_llm_api_exception(
+ e=e,
+ user_api_key_dict=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+async def handle_gigachat_passthrough_router_model(
+ model: str,
+ endpoint: str,
+ request: Request,
+ request_body: dict,
+ fastapi_response: Response,
+ llm_router: litellm.Router,
+ user_api_key_dict: UserAPIKeyAuth,
+ proxy_logging_obj: ProxyLogging,
+ general_settings: dict,
+ proxy_config: ProxyConfig,
+ select_data_generator: Callable,
+ user_model: str | None,
+ user_temperature: float | None,
+ user_request_timeout: float | None,
+ user_max_tokens: int | None,
+ user_api_base: str | None,
+ version: str | None,
+) -> Union[Response, StreamingResponse]:
+ """
+ Handle Gigachat passthrough for router models (models defined in config.yaml).
+
+ Uses the same common processing path as non-router models to ensure
+ metadata and hooks are properly initialized.
+
+ Args:
+ model: The router model name (e.g., "gigachat/gigachat-2")
+ endpoint: The Gigachat endpoint path (e.g., "/chat/completions")
+ request: The FastAPI request object
+ request_body: The parsed request body
+ llm_router: The LiteLLM router instance
+ user_api_key_dict: The user API key authentication dictionary
+ proxy_logging_obj: Proxy logging
+ general_settings: Proxy general settings
+ proxy_config: Proxy config
+ select_data_generator: Select data generator function
+ (additional args for common processing)
+
+ Returns:
+ Response or StreamingResponse depending on endpoint type
+ """
+ from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
+
+ # Detect streaming based on request body
+ is_streaming = request_body.get("stream", False)
+
+ data: Dict[str, Any] = await _read_request_body(request=request)
+ if user_api_key_dict is not None:
+ if data.get("metadata") is None:
+ data["metadata"] = {}
- if (
- hasattr(user_api_key_dict, "user_id")
- and user_api_key_dict.user_id is not None
- ):
++ if hasattr(user_api_key_dict, "user_id") and user_api_key_dict.user_id is not None:
+ data["metadata"]["user_api_key_user_id"] = user_api_key_dict.user_id
- if (
- hasattr(user_api_key_dict, "team_id")
- and user_api_key_dict.team_id is not None
- ):
++ if hasattr(user_api_key_dict, "team_id") and user_api_key_dict.team_id is not None:
+ data["metadata"]["user_api_key_team_id"] = user_api_key_dict.team_id
- if (
- hasattr(user_api_key_dict, "org_id")
- and user_api_key_dict.org_id is not None
- ):
++ if hasattr(user_api_key_dict, "org_id") and user_api_key_dict.org_id is not None:
+ data["metadata"]["user_api_key_org_id"] = user_api_key_dict.org_id
- if (
- hasattr(user_api_key_dict, "agent_id")
- and user_api_key_dict.agent_id is not None
- ):
++ if hasattr(user_api_key_dict, "agent_id") and user_api_key_dict.agent_id is not None:
+ data["metadata"]["agent_id"] = user_api_key_dict.agent_id
+
+ verbose_proxy_logger.debug(
+ f"Gigachat router passthrough: model='{model}', endpoint='{endpoint}', streaming={is_streaming}"
+ )
+
+ # Use the common processing path (same as non-router models)
+ # This ensures all metadata, hooks, and logging are properly initialized
+
+ data["model"] = model
+ data["method"] = request.method
+ data["endpoint"] = endpoint
+ data["json"] = request_body
+ data["custom_llm_provider"] = "gigachat"
+
+ # Remove sensitive keys from data
+ keys = [
+ "gigachat_auth_url",
+ "gigachat_access_token",
+ "gigachat_scope",
+ "api_base",
+ "api_key",
+ ]
+ for key in keys:
+ data.pop(key, None)
+
+ client = get_async_httpx_client( # type: ignore
+ llm_provider=LlmProviders.GIGACHAT,
+ params={
+ "timeout": httpx.Timeout(timeout=600.0, connect=5.0),
+ "ssl_verify": False,
+ },
+ )
+
+ data["client"] = client
+ base_llm_response_processor = ProxyBaseLLMRequestProcessing(data=data)
+
+ # Use the common passthrough processing to handle metadata and hooks
+ # This also handles all response formatting (streaming/non-streaming) and exceptions
+ try:
+ result = await base_llm_response_processor.base_passthrough_process_llm_request(
+ request=request,
+ fastapi_response=fastapi_response,
+ user_api_key_dict=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ llm_router=llm_router,
+ general_settings=general_settings,
+ proxy_config=proxy_config,
+ select_data_generator=select_data_generator,
+ model=model,
+ user_model=user_model,
+ user_temperature=user_temperature,
+ user_request_timeout=user_request_timeout,
+ user_max_tokens=user_max_tokens,
+ user_api_base=user_api_base,
+ version=version,
+ )
+
+ if isinstance(result, StreamingResponse):
+ if result.headers.get("Content-Type") is None:
+ result.headers["Content-Type"] = "text/event-stream; charset=utf-8"
+ return result
+
+ return result
+ except Exception as e: # noqa: BLE001
+ # Use common exception handling
+ raise await base_llm_response_processor._handle_llm_api_exception(
+ e=e,
+ user_api_key_dict=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
@router.api_route(
"/watsonx/{endpoint:path}",
methods=["GET", "POST", "PUT", "DELETE", "PATCH"],