Skip to content

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

fix: apply Black formatting to 6 files after main merge

yuneng-jiange3b62c091541
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index f5856ab1f45..ee4cdbcdf36 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -240,10 +240,10 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
if key in ("max_tokens", "max_completion_tokens"):
responses_api_request["max_output_tokens"] = value
elif key == "tools" and value is not None:
- responses_api_request["tools"] = (
- self._convert_tools_to_responses_format(
- cast(List[Dict[str, Any]], value)
- )
+ responses_api_request[
+ "tools"
+ ] = self._convert_tools_to_responses_format(
+ cast(List[Dict[str, Any]], value)
)
elif key == "response_format":
text_format = self._transform_response_format_to_text_format(value)
@@ -1072,9 +1072,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator):
)
if provider_specific_fields:
- function_chunk["provider_specific_fields"] = (
- provider_specific_fields
- )
+ function_chunk[
+ "provider_specific_fields"
+ ] = provider_specific_fields
tool_call_index = parsed_chunk.get("output_index", 0)
tool_call_chunk = ChatCompletionToolCallChunk(
@@ -1147,9 +1147,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator):
# Add provider_specific_fields to function if present
if provider_specific_fields:
- function_chunk["provider_specific_fields"] = (
- provider_specific_fields
- )
+ function_chunk[
+ "provider_specific_fields"
+ ] = provider_specific_fields
tool_call_index = parsed_chunk.get("output_index", 0)
tool_call_chunk = ChatCompletionToolCallChunk(
diff --git a/litellm/integrations/langsmith.py b/litellm/integrations/langsmith.py
index ad4bee08345..b931d7ecfe7 100644
--- a/litellm/integrations/langsmith.py
+++ b/litellm/integrations/langsmith.py
@@ -83,7 +83,9 @@ class LangsmithLogger(CustomBatchLogger):
if _batch_size:
self.batch_size = int(_batch_size)
self.log_queue: List[LangsmithQueueObject] = []
- self._flush_task: Optional[asyncio.Task[Any]] = self._start_periodic_flush_task()
+ self._flush_task: Optional[
+ asyncio.Task[Any]
+ ] = self._start_periodic_flush_task()
def _start_periodic_flush_task(self) -> Optional[asyncio.Task[Any]]:
"""Start the periodic flush task only when an event loop is already running."""
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
index 82076ff3600..5d94cd42129 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py
@@ -105,11 +105,13 @@ class VertexAIPartnerModelsTokenCounter(VertexBase):
# Extract Vertex AI credentials and settings
vertex_credentials = self.get_vertex_ai_credentials(litellm_params)
vertex_project = self.get_vertex_ai_project(litellm_params)
-
+
# Check for count_tokens specific location override
- vertex_count_tokens_location = litellm_params.get("vertex_count_tokens_location")
+ vertex_count_tokens_location = litellm_params.get(
+ "vertex_count_tokens_location"
+ )
vertex_location_raw = self.get_vertex_ai_location(litellm_params)
-
+
# Determine final location with precedence:
# 1. vertex_count_tokens_location (if provided)
# 2. vertex_location (if provided)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/akto/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/akto/__init__.py
index 4ae26755409..c4aaea709ba 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/akto/__init__.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/akto/__init__.py
@@ -17,7 +17,9 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"
akto_api_key=getattr(litellm_params, "akto_api_key", None),
akto_account_id=getattr(litellm_params, "akto_account_id", None),
akto_vxlan_id=getattr(litellm_params, "akto_vxlan_id", None),
- unreachable_fallback=getattr(litellm_params, "unreachable_fallback", "fail_closed"),
+ unreachable_fallback=getattr(
+ litellm_params, "unreachable_fallback", "fail_closed"
+ ),
guardrail_timeout=getattr(litellm_params, "guardrail_timeout", None),
guardrail_name=guardrail.get("guardrail_name", ""),
event_hook=litellm_params.mode,
diff --git a/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py b/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py
index be9c9cb1be7..5058ee348db 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py
@@ -77,17 +77,27 @@ class AktoGuardrail(CustomGuardrail):
)
self.background_tasks: set = set()
- self.akto_base_url = (akto_base_url or os.environ.get("AKTO_GUARDRAIL_API_BASE", "")).rstrip("/")
+ self.akto_base_url = (
+ akto_base_url or os.environ.get("AKTO_GUARDRAIL_API_BASE", "")
+ ).rstrip("/")
if not self.akto_base_url:
- raise ValueError("akto_base_url is required. Set AKTO_GUARDRAIL_API_BASE or pass it in litellm_params.")
+ raise ValueError(
+ "akto_base_url is required. Set AKTO_GUARDRAIL_API_BASE or pass it in litellm_params."
+ )
self.akto_api_key = akto_api_key or os.environ.get("AKTO_API_KEY", "")
if not self.akto_api_key:
- raise ValueError("akto_api_key is required. Set AKTO_API_KEY or pass it in litellm_params.")
+ raise ValueError(
+ "akto_api_key is required. Set AKTO_API_KEY or pass it in litellm_params."
+ )
- self.unreachable_fallback: Literal["fail_closed", "fail_open"] = unreachable_fallback
+ self.unreachable_fallback: Literal[
+ "fail_closed", "fail_open"
+ ] = unreachable_fallback
self.guardrail_timeout = guardrail_timeout or DEFAULT_GUARDRAIL_TIMEOUT
- self.akto_account_id = akto_account_id or os.environ.get("AKTO_ACCOUNT_ID", "1000000")
+ self.akto_account_id = akto_account_id or os.environ.get(
+ "AKTO_ACCOUNT_ID", "1000000"
+ )
self.akto_vxlan_id = akto_vxlan_id or os.environ.get("AKTO_VXLAN_ID", "0")
kwargs["supported_event_hooks"] = [
@@ -173,7 +183,9 @@ class AktoGuardrail(CustomGuardrail):
body["model"] = request_data["model"]
else:
texts = inputs.get("texts", [])
- body["messages"] = [{"role": "user", "content": t} for t in texts] if texts else []
+ body["messages"] = (
+ [{"role": "user", "content": t} for t in texts] if texts else []
+ )
tools = inputs.get("tools")
if tools:
@@ -199,15 +211,23 @@ class AktoGuardrail(CustomGuardrail):
texts = inputs.get("texts", [])
if texts:
- return {"choices": [{"message": {"content": t, "role": "assistant"}} for t in texts]}
+ return {
+ "choices": [
+ {"message": {"content": t, "role": "assistant"}} for t in texts
+ ]
+ }
return {}
@staticmethod
def build_tag_metadata(request_data: dict) -> Dict[str, str]:
"""Build tag/metadata dict with user_id and team_id for Akto tracking."""
tag: Dict[str, str] = {"gen-ai": "Gen AI"}
- user_id = AktoGuardrail.resolve_metadata_value(request_data, "user_api_key_user_id")
- team_id = AktoGuardrail.resolve_metadata_value(request_data, "user_api_key_team_id")
+ user_id = AktoGuardrail.resolve_metadata_value(
+ request_data, "user_api_key_user_id"
+ )
+ team_id = AktoGuardrail.resolve_metadata_value(
+ request_data, "user_api_key_team_id"
+ )
if user_id:
tag["user_id"] = user_id
if team_id:
@@ -236,15 +256,23 @@ class AktoGuardrail(CustomGuardrail):
response_headers: Dict[str, str] = {}
if include_response:
response_body = self.build_response_body(inputs, request_data)
- response_payload = json.dumps({"body": json.dumps(response_body)}) # Double-encoded
+ response_payload = json.dumps(
+ {"body": json.dumps(response_body)}
+ ) # Double-encoded
response_headers = {"content-type": "application/json"}
# Extract client IP from proxy headers
ip = ""
proxy_req = request_data.get("proxy_server_request", {})
- proxy_headers = proxy_req.get("headers", {}) if isinstance(proxy_req, dict) else {}
+ proxy_headers = (
+ proxy_req.get("headers", {}) if isinstance(proxy_req, dict) else {}
+ )
if isinstance(proxy_headers, dict):
- ip = proxy_headers.get("x-forwarded-for") or proxy_headers.get("x-real-ip") or ""
+ ip = (
+ proxy_headers.get("x-forwarded-for")
+ or proxy_headers.get("x-real-ip")
+ or ""
+ )
if "," in ip:
ip = ip.split(",")[0].strip()
@@ -253,7 +281,9 @@ class AktoGuardrail(CustomGuardrail):
"requestHeaders": json.dumps(request_headers),
"responseHeaders": json.dumps(response_headers),
"method": "POST",
- "requestPayload": json.dumps({"body": json.dumps(request_body)}), # Double-encoded
+ "requestPayload": json.dumps(
+ {"body": json.dumps(request_body)}
+ ), # Double-encoded
"responsePayload": response_payload,
"ip": ip,
"destIp": "127.0.0.1",
@@ -393,7 +423,9 @@ class AktoGuardrail(CustomGuardrail):
if input_type == "request":
# Pre_call: awaited guardrail check (no ingestion)
- payload = self.build_akto_payload(inputs, request_data, include_response=False)
+ payload = self.build_akto_payload(
+ inputs, request_data, include_response=False
+ )
try:
response = await self.send_request(
guardrails=True,
@@ -419,7 +451,9 @@ class AktoGuardrail(CustomGuardrail):
)
blocked_payload["responsePayload"] = json.dumps(
{
- "body": json.dumps({"x-blocked-by": "Akto Proxy", "reason": reason}),
+ "body": json.dumps(
+ {"x-blocked-by": "Akto Proxy", "reason": reason}
+ ),
}
)
blocked_payload["responseHeaders"] = json.dumps(
@@ -442,7 +476,9 @@ class AktoGuardrail(CustomGuardrail):
elif input_type == "response":
# Post_call: fire-and-forget combined guardrail + ingest
- payload = self.build_akto_payload(inputs, request_data, include_response=True)
+ payload = self.build_akto_payload(
+ inputs, request_data, include_response=True
+ )
task = asyncio.create_task(
self.fire_and_forget_request(
guardrails=True,
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index ecf25d73cb6..5aa0b9ea4ad 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -639,9 +639,9 @@ except ImportError:
server_root_path = get_server_root_path()
_license_check = LicenseCheck()
premium_user: bool = _license_check.is_premium()
-premium_user_data: Optional["EnterpriseLicenseData"] = (
- _license_check.airgapped_license_data
-)
+premium_user_data: Optional[
+ "EnterpriseLicenseData"
+] = _license_check.airgapped_license_data
global_max_parallel_request_retries_env: Optional[str] = os.getenv(
"LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRIES"
)
@@ -1524,9 +1524,9 @@ master_key: Optional[str] = None
config_agents: Optional[List[AgentConfig]] = None
otel_logging = False
prisma_client: Optional[PrismaClient] = None
-shared_aiohttp_session: Optional["ClientSession"] = (
- None # Global shared session for connection reuse
-)
+shared_aiohttp_session: Optional[
+ "ClientSession"
+] = None # Global shared session for connection reuse
user_api_key_cache = DualCache(
default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value
)
@@ -1534,13 +1534,13 @@ model_max_budget_limiter = _PROXY_VirtualKeyModelMaxBudgetLimiter(
dual_cache=user_api_key_cache
)
litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)
-redis_usage_cache: Optional[RedisCache] = (
- None # redis cache used for tracking spend, tpm/rpm limits
-)
+redis_usage_cache: Optional[
+ RedisCache
+] = None # redis cache used for tracking spend, tpm/rpm limits
polling_via_cache_enabled: Union[Literal["all"], List[str], bool] = False
-native_background_mode: List[str] = (
- []
-) # Models that should use native provider background mode instead of polling
+native_background_mode: List[
+ str
+] = [] # Models that should use native provider background mode instead of polling
polling_cache_ttl: int = 3600 # Default 1 hour TTL for polling cache
user_custom_auth = None
user_custom_key_generate = None
@@ -1900,9 +1900,9 @@ async def update_cache( # noqa: PLR0915
_id = "team_id:{}".format(team_id)
try:
# Fetch the existing cost for the given user
- existing_spend_obj: Optional[LiteLLM_TeamTable] = (
- await user_api_key_cache.async_get_cache(key=_id)
- )
+ existing_spend_obj: Optional[
+ LiteLLM_TeamTable
+ ] = await user_api_key_cache.async_get_cache(key=_id)
if existing_spend_obj is None:
# do nothing if team not in api key cache
return
@@ -2023,9 +2023,11 @@ def run_ollama_serve():
with open(os.devnull, "w") as devnull:
subprocess.Popen(command, stdout=devnull, stderr=devnull)
except Exception as e:
- verbose_proxy_logger.debug(f"""
+ verbose_proxy_logger.debug(
+ f"""
LiteLLM Warning: proxy started with `ollama` model\n`ollama serve` failed with Exception{e}. \nEnsure you run `ollama serve`
- """)
+ """
+ )
def _get_process_rss_mb() -> Optional[float]:
@@ -4976,10 +4978,10 @@ class ProxyConfig:
)
try:
- guardrails_in_db: List[Guardrail] = (
- await GuardrailRegistry.get_all_guardrails_from_db(
- prisma_client=prisma_client
- )
+ guardrails_in_db: List[
+ Guardrail
+ ] = await GuardrailRegistry.get_all_guardrails_from_db(
+ prisma_client=prisma_client
)
verbose_proxy_logger.debug(
"guardrails from the DB %s", str(guardrails_in_db)
@@ -5361,9 +5363,9 @@ async def initialize( # noqa: PLR0915
user_api_base = api_base
dynamic_config[user_model]["api_base"] = api_base
if api_version:
- os.environ["AZURE_API_VERSION"] = (
- api_version # set this for azure - litellm can read this from the env
- )
+ os.environ[
+ "AZURE_API_VERSION"
+ ] = api_version # set this for azure - litellm can read this from the env
if max_tokens: # model-specific param
dynamic_config[user_model]["max_tokens"] = max_tokens
if temperature: # model-specific param
@@ -5700,9 +5702,9 @@ class ProxyStartupEvent:
"""
from litellm.secret_managers.main import str_to_bool
- _use_redis_transaction_buffer: Optional[Union[bool, str]] = (
- general_settings.get("use_redis_transaction_buffer", False)
- )
+ _use_redis_transaction_buffer: Optional[
+ Union[bool, str]
+ ] = general_settings.get("use_redis_transaction_buffer", False)
if isinstance(_use_redis_transaction_buffer, str):
_use_redis_transaction_buffer = str_to_bool(_use_redis_transaction_buffer)
@@ -12297,9 +12299,9 @@ async def get_config_list(
hasattr(sub_field_info, "description")
and sub_field_info.description is not None
):
- nested_fields[idx].field_description = (
- sub_field_info.description
- )
+ nested_fields[
+ idx
+ ].field_description = sub_field_info.description
idx += 1
_stored_in_db = None