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

KnyazShd8477bb665f9
diff --cc litellm/litellm_core_utils/get_llm_provider_logic.py
index 8844578f722,e674fc37673..28ac74967cc
--- a/litellm/litellm_core_utils/get_llm_provider_logic.py
+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py
@@@ -349,9 -349,9 +349,12 @@@ def get_llm_provider
elif endpoint == "https://api.meta.ai/v1":
custom_llm_provider = "meta"
dynamic_api_key = get_secret_str("META_API_KEY")
+ elif endpoint == "https://gigachat.devices.sberbank.ru/api/v1":
+ custom_llm_provider = "gigachat"
+ dynamic_api_key = get_secret_str("GIGACHAT_API_KEY")
+ elif (json_provider := JSONProviderRegistry.get_by_base_url(endpoint)) is not None:
+ custom_llm_provider = json_provider.slug
+ dynamic_api_key = api_key if api_key is not None else get_secret_str(json_provider.api_key_env)
if api_base is not None and not isinstance(api_base, str):
raise Exception(f"api base needs to be a string. api_base={api_base}")
diff --cc litellm/llms/gigachat/passthrough/transformation.py
index 605037020e3,00000000000..c1100bd40e4
mode 100644,000000..100644
--- a/litellm/llms/gigachat/passthrough/transformation.py
+++ b/litellm/llms/gigachat/passthrough/transformation.py
@@@ -1,216 -1,0 +1,215 @@@
+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)
+
+ 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,
+ )
+
+ return litellm_model_response
+
+ if "embeddings" in endpoint:
+ 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={},
+ )
+
+ 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(translated_chunk):
+ chunk_obj = convert_generic_chunk_to_model_response_stream(
+ # cast-ok: validated TypedDict
+ 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(
++ return 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]:
+ return super().get_models(api_key, api_base)
diff --cc litellm/main.py
index 1434864d173,2cf53833c5a..f9ec12ba923
--- a/litellm/main.py
+++ b/litellm/main.py
@@@ -5440,10 -5453,7 +5453,10 @@@ def completion
tpm=kwargs.get("tpm"),
rpm=kwargs.get("rpm"),
use_xai_oauth=kwargs.get("use_xai_oauth", False),
+ gigachat_scope=kwargs.get("gigachat_scope"),
+ gigachat_auth_url=kwargs.get("gigachat_auth_url"),
+ gigachat_access_token=kwargs.get("gigachat_access_token"),
- **{key: kwargs[key] for key in AWS_CREDENTIAL_KWARGS_KEYS if key in kwargs},
+ **{key: kwargs[key] for key in FORWARDED_KWARGS_KEYS if key in kwargs},
)
cast(LiteLLMLoggingObj, logging).update_environment_variables(
model=model,
diff --cc litellm/passthrough/main.py
index 2d9da5cfdbc,8a2ee2a3af8..fda95a54137
--- a/litellm/passthrough/main.py
+++ b/litellm/passthrough/main.py
@@@ -8,7 -6,7 +8,7 @@@ import asynci
import contextvars
from collections.abc import AsyncGenerator, Coroutine, Generator
from functools import partial
- from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, Final, Optional, cast
-from typing import TYPE_CHECKING, Any, Final, Optional, cast
++from typing import Any, AsyncIterator, Iterator, Final, cast
import httpx
from httpx._types import CookieTypes, QueryParamTypes, RequestFiles
@@@ -25,203 -21,9 +25,203 @@@ from litellm.utils import clien
base_llm_http_handler = BaseLLMHTTPHandler()
from .utils import BasePassthroughUtils
-if TYPE_CHECKING:
- from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
- from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
+
+async def _as_async_generator(iterable: AsyncIterator[bytes]) -> AsyncGenerator[bytes, Any]:
+ async for chunk in iterable:
+ yield chunk
+
+
+def _as_generator(iterable: Iterator[bytes]) -> Generator[bytes, Any, Any]:
+ for chunk in iterable:
+ yield chunk
+
+
+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")
+ 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")
+ return self._headers
+
+ @headers.setter
+ def headers(self, value: httpx.Headers) -> None:
+ self._headers = value
+
- def __await__(self):
++ def __await__(self) -> Iterator[Any]:
+ 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 = _as_async_generator(self._response.aiter_bytes())
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ try:
+ await self._response.aclose()
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ 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 # Safe catch-all for verbose logging
+ verbose_logger.exception(
+ "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 anext(self._iterator)
+ self._raw_bytes.append(chunk)
+ return chunk
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ self._start_flush()
+ try:
+ await self._response.aclose()
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ 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._iterator.aclose()
+ await self._response.aclose()
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ 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] = _as_generator(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 # Safe catch-all for verbose logging
+ verbose_logger.exception(
+ "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 # Safe catch-all for cleanup logic
+ self._start_flush()
+ try:
+ self._response.close()
+ except Exception: # noqa: BLE001 # Safe catch-all for cleanup logic
+ 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 # Safe catch-all for cleanup logic
+ pass
@client
diff --cc litellm/proxy/common_request_processing.py
index 15498c286e6,dbbf9cb673e..caad3f1209f
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@@ -2073,9 -2412,10 +2448,10 @@@ class ProxyBaseLLMRequestProcessing
# For passthrough routes, stream directly without error parsing
# since we're dealing with raw binary data (e.g., AWS event streams)
return StreamingResponse(
- content=generator,
- status_code=status.HTTP_200_OK,
+ content=generator, # type: ignore[arg-type]
+ status_code=getattr(response, "status_code", status.HTTP_200_OK),
+ media_type=self._passthrough_event_stream_media_type(),
- headers=custom_headers,
+ headers=streaming_headers,
)
else:
_early = await self._handle_non_streaming_allm_passthrough_route(
diff --cc litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
index 2aa494468ec,7ce41c1d5b6..f1d00ee480c
--- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
@@@ -11,8 -9,9 +11,9 @@@ from __future__ import annotation
import json
import os
import re
+ from collections.abc import Callable
from types import MappingProxyType
- from typing import Annotated, Any, Final, Callable, cast
-from typing import TYPE_CHECKING, Annotated, Any, Final, cast
++from typing import TYPE_CHECKING, Annotated, Any, Final, Callable, cast
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, Response, WebSocket
@@@ -64,21 -63,8 +66,13 @@@ from litellm.utils import ProviderConfi
from .passthrough_endpoint_router import PassthroughEndpointRouter
if TYPE_CHECKING:
+ from litellm.proxy.proxy_server import ProxyConfig as _ProxyConfig
+ from litellm.router import Router
+ ProxyConfig = _ProxyConfig
+else:
+ ProxyConfig = Any
+
-
- if TYPE_CHECKING:
- from litellm.proxy.proxy_server import ProxyConfig as _ProxyConfig
-
- ProxyConfig = _ProxyConfig
- else:
- ProxyConfig = Any
-
-
vertex_llm_base: Final = VertexBase()
router: Final = APIRouter()
openai_passthrough_router: Final = APIRouter()
diff --cc tests/test_litellm/passthrough/test_async_streaming_error_propagation.py
index f7052fee3b9,faf4ea46c43..7bf5dc874a8
--- a/tests/test_litellm/passthrough/test_async_streaming_error_propagation.py
+++ b/tests/test_litellm/passthrough/test_async_streaming_error_propagation.py
@@@ -60,13 -60,13 +60,13 @@@ async def test_async_streaming_429_rais
{"error": {"code": "429", "message": "Rate limit exceeded."}}
).encode()
mock_response = _make_mock_response(429, error_body)
-
+
async def response_coro():
return mock_response
-
+
chunks = []
- with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ async def _drain():
- async for chunk in _async_streaming(
+ async for chunk in AsyncPassthroughStreamingResponse(
response=response_coro(),
litellm_logging_obj=_make_mock_logging_obj(),
provider_config=MagicMock(),
diff --cc tests/test_litellm/passthrough/test_passthrough_main.py
index 40d38bfb1c7,b8f265ad7ea..6cd6b754c07
--- a/tests/test_litellm/passthrough/test_passthrough_main.py
+++ b/tests/test_litellm/passthrough/test_passthrough_main.py
@@@ -708,20 -701,29 +703,29 @@@ async def test_allm_passthrough_route_4
patch.object(async_client.client, "send", mock_send),
patch.object(async_client.client, "build_request", mock_build_request),
):
- result = await allm_passthrough_route(
- model="azure/gpt-4",
- endpoint="openai/deployments/gpt-4/responses",
- method="POST",
- custom_llm_provider="azure",
- api_base="https://my-azure.openai.azure.com",
- api_key="fake-azure-key",
- json={"model": "gpt-4", "input": "hello", "stream": True},
- client=async_client,
- litellm_logging_obj=mock_logging_obj,
- )
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await allm_passthrough_route(
+ model="azure/gpt-4",
+ endpoint="openai/deployments/gpt-4/responses",
+ method="POST",
+ custom_llm_provider="azure",
+ api_base="https://my-azure.openai.azure.com",
+ api_key="fake-azure-key",
+ json={"model": "gpt-4", "input": "hello", "stream": True},
+ client=async_client,
+ litellm_logging_obj=mock_logging_obj,
+ )
+ # result is an async generator — consuming it must raise, not silently yield error bytes
+ chunks = []
+ async def _drain():
+ async for chunk in result: # type: ignore[union-attr]
+ chunks.append(chunk)
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await _drain()
+
assert exc_info.value.response.status_code == 429
- assert len(chunks) == 0, "No chunks should be yielded before the 429 raises"
def test_llm_passthrough_route_propagates_allm_passthrough_route_to_logging_obj():
diff --cc tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py
index 27d265e6f5d,3783e218e4e..a88b0ef0c4b
--- a/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py
+++ b/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py
@@@ -181,8 -164,8 +181,8 @@@ async def test_asyncpassthroughstreamin
provider_config = MagicMock()
received = []
- with pytest.raises(httpx.ReadError):
+ async def _drain():
- async for chunk in _async_streaming(
+ async for chunk in AsyncPassthroughStreamingResponse(
response=response_coro(),
litellm_logging_obj=mock_logging_obj,
provider_config=provider_config,
diff --cc tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
index 3c0c2b0294e,ac140abe31f..1e1771864eb
--- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
@@@ -9,15 -11,10 +11,12 @@@ from unittest.mock import AsyncMock, Ma
import httpx
import pytest
from fastapi import HTTPException, Request, Response
+from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
- sys.path.insert(
- 0, os.path.abspath("../../../..")
- ) # Adds the parent directory to the system path
import litellm
+from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (
BaseOpenAIPassThroughHandler,
RouteChecks,