The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
chore(lint): zero out crash-class pyright rules and ban new type: ignore comments (#32152)
Mateo Wang5f864c83ce7b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7108dfd4f32..651a88bf9aa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -47,6 +47,8 @@ If you're trying to create a new function that relies on untyped stuff, insteadIf you get an LIT001 or LIT002 fail, refactor the code to follow functional programming best practices rather than introducing mutable data structures. For example, build values in one shot with comprehensions or generators wrapped in `tuple()` / `frozenset()` instead of seeding an empty `list`/`dict`/`set` and mutating it over time. Ideally `# mutable-ok` is never used; reach for it only as a genuine last resort when an immutable rewrite is truly impossible, and always pair it with a real reason+Every lint or type suppression must name the exact rule inside brackets and carry a reason comment, e.g. `# pyright: ignore[reportArgumentType] # stubs lack async overload` or `# noqa: TID251 # <reason>`. `# type: ignore` is banned (LIT009): pyrightconfig.json sets `enableTypeIgnoreComments` to false, so it silently does nothing+Commit and push your work when you're done without askingWhen you must use real LLM models to, for example, write e2e tests, write a QA runbook, etc., make sure to use the latest models (doesn't have to be smartest, can also be a modern small, fast one. No strong preference for smart vs fast here, just use something modern) as of the year and month of the current date. Do a web search as necessary to figure that outdiff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex b65cd01e1eb..7e3f6a20281 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -3,16 +3,16 @@"limit": 37484},"reportArgumentType": {- "limit": 2721+ "limit": 2704},"reportAssignmentType": {"limit": 330},"reportAttributeAccessIssue": {- "limit": 519+ "limit": 516},"reportCallIssue": {- "limit": 131+ "limit": 124},"reportConstantRedefinition": {"limit": 59@@ -42,7 +42,7 @@"limit": 18},"reportIndexIssue": {- "limit": 39+ "limit": 37},"reportInvalidTypeForm": {"limit": 35@@ -51,7 +51,7 @@"limit": 5},"reportMatchNotExhaustive": {- "limit": 2+ "limit": 0},"reportMissingParameterType": {"limit": 5900@@ -63,25 +63,25 @@"limit": 41},"reportOperatorIssue": {- "limit": 9+ "limit": 0},"reportOptionalCall": {- "limit": 7+ "limit": 0},"reportOptionalIterable": {- "limit": 6+ "limit": 0},"reportOptionalMemberAccess": {- "limit": 1086+ "limit": 1085},"reportOptionalOperand": {- "limit": 6+ "limit": 0},"reportOptionalSubscript": {- "limit": 17+ "limit": 0},"reportPossiblyUnboundVariable": {- "limit": 78+ "limit": 77},"reportPrivateUsage": {"limit": 2438@@ -90,28 +90,28 @@"limit": 12},"reportReturnType": {- "limit": 226+ "limit": 225},"reportTypedDictNotRequiredAccess": {- "limit": 30+ "limit": 27},"reportUndefinedVariable": {- "limit": 5+ "limit": 0},"reportUnknownArgumentType": {- "limit": 45905+ "limit": 45895},"reportUnknownLambdaType": {"limit": 113},"reportUnknownMemberType": {- "limit": 40556+ "limit": 40541},"reportUnknownParameterType": {"limit": 20418},"reportUnknownVariableType": {- "limit": 32168+ "limit": 32151},"reportUnnecessaryCast": {"limit": 177diff --git a/litellm/caching/disk_cache.py b/litellm/caching/disk_cache.pyindex b51acbe9cfd..d9f65ce949e 100644--- a/litellm/caching/disk_cache.py+++ b/litellm/caching/disk_cache.py@@ -59,8 +59,9 @@ class DiskCache(BaseCache):def increment_cache(self, key, value: int, **kwargs) -> int:# get the value- init_value = self.get_cache(key=key) or 0- value = init_value + value # type: ignore+ cached_value = self.get_cache(key=key)+ init_value = cached_value if isinstance(cached_value, int) else 0+ value = init_value + valueself.set_cache(key, value, **kwargs)return value@@ -76,8 +77,9 @@ class DiskCache(BaseCache):async def async_increment(self, key, value: int, **kwargs) -> int:# get the value- init_value = await self.async_get_cache(key=key) or 0- value = init_value + value # type: ignore+ cached_value = await self.async_get_cache(key=key)+ init_value = cached_value if isinstance(cached_value, int) else 0+ value = init_value + valueawait self.async_set_cache(key, value, **kwargs)return valuediff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 2cb94e02d9c..63ffe9d308b 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -222,7 +222,7 @@ def _cost_per_token_custom_pricing_helper(output_cost = completion_tokens * output_cost_per_tokenreturn input_cost, output_costelif custom_cost_per_second is not None:- output_cost = custom_cost_per_second * response_time_ms / 1000 # type: ignore+ output_cost = custom_cost_per_second * (response_time_ms or 0.0) / 1000return 0, output_costreturn None@@ -662,29 +662,27 @@ def cost_per_token(data_residency=data_residency,)- if model_info.get("input_cost_per_second", None) is not None and response_time_ms is not None:+ input_cost_per_second = model_info.get("input_cost_per_second")+ if input_cost_per_second is not None and response_time_ms is not None:verbose_logger.debug("For model=%s - input_cost_per_second: %s; response time: %s",model,- model_info.get("input_cost_per_second", None),+ input_cost_per_second,response_time_ms,)## COST PER SECOND ##- prompt_tokens_cost_usd_dollar = (- model_info["input_cost_per_second"] * response_time_ms / 1000 # type: ignore- )+ prompt_tokens_cost_usd_dollar = input_cost_per_second * response_time_ms / 1000- if model_info.get("output_cost_per_second", None) is not None and response_time_ms is not None:+ output_cost_per_second = model_info.get("output_cost_per_second")+ if output_cost_per_second is not None and response_time_ms is not None:verbose_logger.debug("For model=%s - output_cost_per_second: %s; response time: %s",model,- model_info.get("output_cost_per_second", None),+ output_cost_per_second,response_time_ms,)## COST PER SECOND ##- completion_tokens_cost_usd_dollar = (- model_info["output_cost_per_second"] * response_time_ms / 1000 # type: ignore- )+ completion_tokens_cost_usd_dollar = output_cost_per_second * response_time_ms / 1000verbose_logger.debug("Returned custom cost for model=%s - prompt_tokens_cost_usd_dollar: %s, completion_tokens_cost_usd_dollar: %s",diff --git a/litellm/fine_tuning/main.py b/litellm/fine_tuning/main.pyindex 8a8a916fa9c..ce5074cdaf5 100644--- a/litellm/fine_tuning/main.py+++ b/litellm/fine_tuning/main.py@@ -256,8 +256,6 @@ def create_fine_tuning_job(extra_body = optional_params.get("extra_body", {})if extra_body is not None:extra_body.pop("azure_ad_token", None)- else:- get_secret_str("AZURE_AD_TOKEN") # type: ignore# Prepare Azure-specific parameters for extra_bodyextra_body = _prepare_azure_extra_body(extra_body, kwargs, azure_specific_hyperparams)@@ -442,7 +440,7 @@ def cancel_fine_tuning_job()# Azure OpenAIelif custom_llm_provider == "azure":- api_base = optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") # type: ignore+ api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE")api_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") # type: ignore@@ -457,8 +455,6 @@ def cancel_fine_tuning_job(extra_body = optional_params.get("extra_body", {})if extra_body is not None:extra_body.pop("azure_ad_token", None)- else:- get_secret_str("AZURE_AD_TOKEN") # type: ignoreresponse = azure_fine_tuning_apis_instance.cancel_fine_tuning_job(api_base=api_base,@@ -616,8 +612,6 @@ def list_fine_tuning_jobs(extra_body = optional_params.get("extra_body", {})if extra_body is not None:extra_body.pop("azure_ad_token", None)- else:- get_secret("AZURE_AD_TOKEN") # type: ignoreresponse = azure_fine_tuning_apis_instance.list_fine_tuning_jobs(api_base=api_base,@@ -759,8 +753,6 @@ def retrieve_fine_tuning_job(extra_body = optional_params.get("extra_body", {})if extra_body is not None:extra_body.pop("azure_ad_token", None)- else:- get_secret_str("AZURE_AD_TOKEN") # type: ignoreresponse = azure_fine_tuning_apis_instance.retrieve_fine_tuning_job(api_base=api_base,diff --git a/litellm/integrations/datadog/datadog.py b/litellm/integrations/datadog/datadog.pyindex 6775858c124..bd62d1e303a 100644--- a/litellm/integrations/datadog/datadog.py+++ b/litellm/integrations/datadog/datadog.py@@ -354,14 +354,14 @@ class DataDogLogger(Raises:Raises a NON Blocking verbose_logger.exception if an error occurs"""- try:- if not self.log_queue:- verbose_logger.exception("Datadog: log_queue does not exist")- return+ if not self.log_queue:+ verbose_logger.exception("Datadog: log_queue does not exist")+ return- batch_to_send = self.log_queue[:]- self.log_queue = []+ batch_to_send = self.log_queue[:]+ self.log_queue = []+ try:verbose_logger.debug("Datadog - about to flush %s events on %s",len(batch_to_send),diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.pyindex 58107d9804b..47daf33824e 100644--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py@@ -656,7 +656,7 @@ def convert_to_model_response_object(message: Optional[Message] = Nonefinish_reason: Optional[str] = None- if _should_convert_tool_call_to_json_mode(+ if tool_calls is not None and _should_convert_tool_call_to_json_mode(tool_calls=tool_calls,convert_tool_call_to_json_mode=convert_tool_call_to_json_mode,):diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 587a3a58a94..128ba0bf3ab 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -1884,7 +1884,7 @@ class CustomStreamWrapper:await self.fetch_stream()if is_async_iterable(self.completion_stream):- async for chunk in self.completion_stream: # type: ignore[union-attr]+ async for chunk in self.completion_stream: # pyright: ignore[reportOptionalIterable] # is_async_iterable guard proves __aiter__if chunk == "None" or chunk is None:continue # skip None chunksdiff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex b381b5a85fe..4c256be1ab8 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -1558,7 +1558,7 @@ class AWSEventStreamDecoder:text = chunk_data["outputText"]# ai21 mappingelif "ai21" in self.model: # fake ai21 streaming- text = chunk_data.get("completions")[0].get("data").get("text") # type: ignore+ text = chunk_data["completions"][0]["data"]["text"]is_finished = Truefinish_reason = "stop"######## /bedrock/converse mappings ###############diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.pyindex d63642c806f..a2aa98d6676 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py@@ -51,10 +51,7 @@ class AmazonQwen2Config(AmazonQwen3Config):Qwen2 uses "text" field, but we also support "generation" field for compatibility."""try:- if hasattr(raw_response, "json"):- response_data = raw_response.json()- else:- response_data = raw_response+ response_data = raw_response.json()# Extract the generated text - Qwen2 uses "text" field, but also support "generation" for compatibilitygenerated_text = response_data.get("generation", "") or response_data.get("text", "")diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.pyindex 762631cac5e..4f496df084e 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py@@ -175,10 +175,7 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig):Transform Qwen3 Bedrock response to OpenAI format"""try:- if hasattr(raw_response, "json"):- response_data = raw_response.json()- else:- response_data = raw_response+ response_data = raw_response.json()# Extract the generated text - Qwen3 uses "generation" fieldgenerated_text = response_data.get("generation", "")diff --git a/litellm/llms/oci/chat/cohere.py b/litellm/llms/oci/chat/cohere.pyindex 3661ac908d2..ca85a6309d7 100644--- a/litellm/llms/oci/chat/cohere.py+++ b/litellm/llms/oci/chat/cohere.py@@ -110,7 +110,7 @@ def adapt_messages_to_cohere_standard(tool_calls: Optional[List[CohereToolCall]] = Noneif role == "assistant" and msg.get("tool_calls"): # type: ignore[union-attr,typeddict-item]tool_calls = []- for tc in msg["tool_calls"]: # type: ignore[union-attr,typeddict-item]+ for tc in msg["tool_calls"]: # pyright: ignore[reportOptionalIterable] # truthiness check above rules out Noneraw_arguments: Any = tc.get("function", {}).get("arguments", {})if isinstance(raw_arguments, str):try:diff --git a/litellm/llms/ollama/chat/transformation.py b/litellm/llms/ollama/chat/transformation.pyindex 3152ded2367..694f8cdd6c2 100644--- a/litellm/llms/ollama/chat/transformation.py+++ b/litellm/llms/ollama/chat/transformation.py@@ -363,7 +363,11 @@ class OllamaChatConfig(BaseConfig):response_json_message["reasoning_content"] = reasoning_contentresponse_json_message["content"] = content- if request_data.get("format", "") == "json" and litellm_params.get("function_name") is not None:+ if (+ request_data.get("format", "") == "json"+ and litellm_params.get("function_name") is not None+ and response_json_message is not None+ ):function_call = json.loads(response_json_message["content"])message = litellm.Message(content=None,diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.pyindex c7a49a2e47f..a6b6a6267c3 100644--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@ -716,7 +716,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):elif isinstance(content, list) and content_idx_optional is not None:# Replace specific text item in list content- choice.message.content[content_idx_optional]["text"] = guardrail_response # type: ignore+ content[content_idx_optional]["text"] = guardrail_responseasync def _apply_guardrail_responses_to_output_tool_calls(self,diff --git a/litellm/llms/sap/chat/transformation.py b/litellm/llms/sap/chat/transformation.pyindex d9d0f9bc236..4bf8272a334 100755--- a/litellm/llms/sap/chat/transformation.py+++ b/litellm/llms/sap/chat/transformation.py@@ -155,7 +155,7 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):def headers(self) -> Dict[str, str]:if self.token_creator is None:self.run_env_setup()- access_token = self.token_creator() # type: ignore+ access_token = self.token_creator() # pyright: ignore[reportOptionalCall] # run_env_setup set it or raisedreturn {"Authorization": access_token,"AI-Resource-Group": self.resource_group,diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.pyindex 678877c0721..f9ed8cea9b5 100644--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py@@ -2315,17 +2315,15 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):# Store thoughtSignatures in provider_specific_fieldsif thought_signatures is not None:- if "provider_specific_fields" not in chat_completion_message:- chat_completion_message["provider_specific_fields"] = {}- chat_completion_message["provider_specific_fields"]["thought_signatures"] = thought_signatures # type: ignore+ thought_signature_fields = chat_completion_message.get("provider_specific_fields") or {}+ thought_signature_fields["thought_signatures"] = thought_signatures+ chat_completion_message["provider_specific_fields"] = thought_signature_fields# Store server-side tool invocations in provider_specific_fieldsif server_side_tool_invocations is not None:- if "provider_specific_fields" not in chat_completion_message:- chat_completion_message["provider_specific_fields"] = {}- chat_completion_message["provider_specific_fields"]["server_side_tool_invocations"] = (- server_side_tool_invocations # type: ignore- )+ tool_invocation_fields = chat_completion_message.get("provider_specific_fields") or {}+ tool_invocation_fields["server_side_tool_invocations"] = server_side_tool_invocations+ chat_completion_message["provider_specific_fields"] = tool_invocation_fieldsif isinstance(model_response, ModelResponseStream):choice = VertexGeminiConfig._create_streaming_choice(diff --git a/litellm/main.py b/litellm/main.pyindex 567930a4999..b3c176a1347 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -8304,26 +8304,6 @@ def stream_chunk_builder_text_completion(chunks: list, messages: Optional[List]finish_reason = chunks[-1]["choices"][0]["finish_reason"]logprobs = chunks[-1]["choices"][0]["logprobs"]- response = {- "id": id,- "object": object,- "created": created,- "model": model,- "system_fingerprint": system_fingerprint,- "choices": [- {- "text": None,- "index": 0,- "logprobs": logprobs,- "finish_reason": finish_reason,- }- ],- "usage": {- "prompt_tokens": None,- "completion_tokens": None,- "total_tokens": None,- },- }content_list = []for chunk in chunks:choices = chunk["choices"]@@ -8335,25 +8315,37 @@ def stream_chunk_builder_text_completion(chunks: list, messages: Optional[List]# Combine the "content" strings into a single string || combine the 'function' strings into a single stringcombined_content = "".join(content_list)- # Update the "content" field within the response dictionary- response["choices"][0]["text"] = combined_content-- if len(combined_content) > 0:- pass- else:- pass- # # Update usage information if neededtry:- response["usage"]["prompt_tokens"] = token_counter(model=model, messages=messages)+ prompt_tokens = token_counter(model=model, messages=messages)except Exception: # don't allow this failing to block a complete streaming response from being returnedprint_verbose("token_counter failed, assuming prompt tokens is 0")- response["usage"]["prompt_tokens"] = 0- response["usage"]["completion_tokens"] = token_counter(+ prompt_tokens = 0+ completion_tokens = token_counter(model=model,text=combined_content,count_response_tokens=True, # count_response_tokens is a Flag to tell token counter this is a response, No need to add extra tokens we do for input messages)- response["usage"]["total_tokens"] = response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"]++ response = {+ "id": id,+ "object": object,+ "created": created,+ "model": model,+ "system_fingerprint": system_fingerprint,+ "choices": [+ {+ "text": combined_content,+ "index": 0,+ "logprobs": logprobs,+ "finish_reason": finish_reason,+ }+ ],+ "usage": {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ },+ }return TextCompletionResponse(**response)diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex a6067a60105..ce0698cb7ac 100644--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@ -1079,11 +1079,6 @@ if MCP_AVAILABLE:forwarded_authorization = (effective_oauth2_headers.get("Authorization") if effective_oauth2_headers else None)- is_interactive_authz_code = (- server_model.auth_type == MCPAuth.oauth2- and forwarded_authorization is not None- and to_server_spec(server_model) is not None- )preview_cred_provider = (UpstreamCredentialProvider(oauth_token_store=PresentedOAuthTokenStore(@@ -1094,7 +1089,11 @@ if MCP_AVAILABLE:)))- if is_interactive_authz_code+ if (+ server_model.auth_type == MCPAuth.oauth2+ and forwarded_authorization is not None+ and to_server_spec(server_model) is not None+ )else None)diff --git a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.pyindex 15d8c6c5d1e..c924448669d 100644--- a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py+++ b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py@@ -525,10 +525,11 @@ class RedisUpdateBuffer:# Slots 1-5: daily spend categoriesdaily_results: List[Optional[Dict[str, Any]]] = []for slot in range(1, 6):- if raw_results[slot] is None:+ slot_result = raw_results[slot]+ if slot_result is None:daily_results.append(None)else:- list_of_daily = [json.loads(t) for t in raw_results[slot]] # type: ignore+ list_of_daily = [json.loads(t) for t in slot_result]aggregated = DailySpendUpdateQueue.get_aggregated_daily_spend_update_transactions(list_of_daily)daily_results.append(aggregated)diff --git a/litellm/proxy/guardrails/guardrail_hooks/semantic_guard/semantic_guard.py b/litellm/proxy/guardrails/guardrail_hooks/semantic_guard/semantic_guard.pyindex 5840480f0da..3f802485a8e 100644--- a/litellm/proxy/guardrails/guardrail_hooks/semantic_guard/semantic_guard.py+++ b/litellm/proxy/guardrails/guardrail_hooks/semantic_guard/semantic_guard.py@@ -225,7 +225,7 @@ def _handle_match(detection_info=detection_info,)else:- raise HTTPException( # type: ignore[reportOptionalCall]+ raise HTTPException( # pyright: ignore[reportOptionalCall] # fastapi is installed wherever this proxy hook runsstatus_code=400,detail={"error": violation_msg,diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.pyindex 2b3ec231ac8..4250b9668ff 100644--- a/litellm/proxy/health_endpoints/_health_endpoints.py+++ b/litellm/proxy/health_endpoints/_health_endpoints.py@@ -6,7 +6,7 @@ import secretsimport timeimport tracebackfrom datetime import datetime, timedelta-from typing import Any, Dict, Iterable, Literal, Optional, Union, cast+from typing import Any, Dict, Iterable, Literal, Optional, TypedDict, Union, castimport fastapifrom fastapi import APIRouter, Depends, HTTPException, Request, Response, status@@ -1271,7 +1271,12 @@ async def health_license_endpoint(}-db_health_cache = {"status": "unknown", "last_updated": datetime.now()}+class DBHealthCache(TypedDict):+ status: str+ last_updated: datetime+++db_health_cache: DBHealthCache = {"status": "unknown", "last_updated": datetime.now()}async def _db_health_readiness_check():diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 8522294d120..78c43715dad 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -956,7 +956,7 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):for _idx, (keys, args, meta) in enumerate(descriptor_groups):try:- raw = await self.check_and_increment_by_n_script(+ raw = await self.check_and_increment_by_n_script( # pyright: ignore[reportOptionalCall] # sole caller guards it is not Nonekeys=keys,args=args,)diff --git a/litellm/proxy/hooks/prompt_injection_detection.py b/litellm/proxy/hooks/prompt_injection_detection.pyindex 390074bf005..2d55a644bb2 100644--- a/litellm/proxy/hooks/prompt_injection_detection.py+++ b/litellm/proxy/hooks/prompt_injection_detection.py@@ -250,7 +250,9 @@ class _OPTIONAL_PromptInjectionDetection(CustomLogger):self.print_verbose(f"Received LLM Moderation response: {response}")self.print_verbose(f"llm_api_fail_call_string: {self.prompt_injection_params.llm_api_fail_call_string}")if isinstance(response, litellm.ModelResponse) and isinstance(response.choices[0], litellm.Choices):- if self.prompt_injection_params.llm_api_fail_call_string in response.choices[0].message.content: # type: ignore+ fail_call_string = self.prompt_injection_params.llm_api_fail_call_string+ content = response.choices[0].message.content+ if fail_call_string is not None and content is not None and fail_call_string in content:is_prompt_attack = Trueif is_prompt_attack is True:diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex ff849240292..d92aea57063 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -343,7 +343,7 @@ def _personal_key_membership_check(if user_api_key_dict.user_role not in personal_key_generation["allowed_user_roles"]:raise HTTPException(status_code=400,- detail=f"Personal key creation has been restricted by admin. Allowed roles={litellm.key_generation_settings['personal_key_generation']['allowed_user_roles']}. Your role={user_api_key_dict.user_role}", # type: ignore+ detail=f"Personal key creation has been restricted by admin. Allowed roles={personal_key_generation['allowed_user_roles']}. Your role={user_api_key_dict.user_role}",)return Truediff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.pyindex 34ca43c603f..0c9aa667751 100644--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py@@ -771,7 +771,7 @@ async def get_file_content(version=version,)- if should_route:+ if should_route and credentials is not None:# Use model-based routing with credentials from configprepare_data_with_credentials(data=data,@@ -1129,7 +1129,7 @@ async def delete_file(check_file_id_encoding=True,)- if should_route:+ if should_route and credentials is not None:# Use model-based routing with credentials from configprepare_data_with_credentials(data=data,@@ -1308,7 +1308,7 @@ async def list_files(check_file_id_encoding=False,)- if should_route:+ if should_route and credentials is not None:# Use model-based routing with credentials from configdata.update(credentials) # type: ignoreresponse = await litellm.afile_list(diff --git a/litellm/router.py b/litellm/router.pyindex 8c1f2021501..9f333e471f3 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -845,6 +845,8 @@ class Router:router_cache=self.cache,routing_args={},)+ case _:+ passif selector is not None and register_callbacks and isinstance(litellm.callbacks, list):litellm.logging_callback_manager.add_litellm_callback(selector) # type: ignorediff --git a/litellm/router_strategy/auto_router/auto_router.py b/litellm/router_strategy/auto_router/auto_router.pyindex dc24623f505..c01e2f10d2c 100644--- a/litellm/router_strategy/auto_router/auto_router.py+++ b/litellm/router_strategy/auto_router/auto_router.py@@ -130,11 +130,12 @@ class AutoRouter(CustomLogger):# do nothing, return same inputsreturn None- if self.routelayer is None:+ routelayer = self.routelayer+ if routelayer is None:######################## Create the route layer#######################- self.routelayer = SemanticRouter(+ routelayer = SemanticRouter(routes=self.loaded_routes,encoder=LiteLLMRouterEncoder(litellm_router_instance=self.litellm_router_instance,@@ -142,9 +143,10 @@ class AutoRouter(CustomLogger):),auto_sync=self.auto_sync_value,)+ self.routelayer = routelayermessage_content = self._extract_text_from_messages(messages)- route_choice: Optional[Union[RouteChoice, List[RouteChoice]]] = self.routelayer(text=message_content)+ route_choice: Optional[Union[RouteChoice, List[RouteChoice]]] = routelayer(text=message_content)verbose_router_logger.debug(f"route_choice: {route_choice}")if isinstance(route_choice, RouteChoice):model = route_choice.name or self.default_modeldiff --git a/ruff-strict-budget.json b/ruff-strict-budget.jsonindex dcf6e9868b7..a66b80d6400 100644--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@ -264,7 +264,7 @@"limit": 63},"SIM102": {- "limit": 325+ "limit": 324},"SIM103": {"limit": 129diff --git a/scripts/check_type_discipline.py b/scripts/check_type_discipline.pyindex 6e152541863..809dc141eb8 100644--- a/scripts/check_type_discipline.py+++ b/scripts/check_type_discipline.py@@ -23,7 +23,7 @@ LIT002 Mutable-collection *construction*: a list/dict/set literal or comprehensstr]`) are exempt. Suppress with `# mutable-ok: <reason>`.LIT003 noqa suppression without rule codes or without a reason.Required shape: `# noqa: TID251 # <reason>`-LIT004 type/pyright/mypy ignore without bracketed codes or without a reason.+LIT004 pyright/mypy ignore without bracketed codes or without a reason.Required shape: `# pyright: ignore[reportArgumentType] # <reason>`LIT005 A `# mutable-ok` / `# cast-ok` / `# guard-ok` / `# kwargs-ok`suppression without a reason.@@ -38,6 +38,10 @@ LIT008 `**kwargs` parameter. The keyword contract is erased and everything it cis effectively Any. ruff can force it to be typed (ANN003) but can't ban thesyntax. Declare explicit keyword params, or accept one frozen payload. `*args`,by contrast, is fine when typed (it's just a tuple). Suppress: `# kwargs-ok: <reason>`.+LIT009 `# type: ignore` in any shape (bare, with codes, with a reason).+ pyrightconfig.json sets enableTypeIgnoreComments to false, so basedpyright+ never honors it: the comment is inert dead syntax that suppresses nothing.+ Use `# pyright: ignore[ruleName] # <reason>` instead.LIT000 Setup failure: a target file could not be read, or contains a syntax error.Reported as a violation rather than crashing the run.@@ -95,8 +99,9 @@ NOQA_RE = re.compile(r"(?P<rest>.*)",re.IGNORECASE,)+TYPE_IGNORE_RE = re.compile(r"#\s*type:\s*ignore\b")IGNORE_RE = re.compile(- r"#\s*(?:type|pyright|mypy):\s*ignore(?P<codes>\[[^\]]*\])?(?P<rest>.*)"+ r"#\s*(?:pyright|mypy):\s*ignore(?P<codes>\[[^\]]*\])?(?P<rest>.*)")MUTABLE_OK_RE = re.compile(r"#\s*mutable-ok(?::\s*(?P<reason>.*))?")CAST_OK_RE = re.compile(r"#\s*cast-ok(?::\s*(?P<reason>.*))?")@@ -161,6 +166,11 @@ def _comment_violations(path: Path, line_no: int, text: str) -> Iterator[Violatielif len(_reason_of(m.group("rest"))) < MIN_REASON_LEN:yield Violation(path, line_no, "LIT003", "noqa requires a reason: `# noqa: XXX123 # <reason>`")+ if TYPE_IGNORE_RE.search(text):+ yield Violation(path, line_no, "LIT009",+ "`# type: ignore` is inert (enableTypeIgnoreComments is false, so "+ "basedpyright never honors it); use `# pyright: ignore[ruleName] # <reason>`")+m = IGNORE_RE.search(text)if m:codes = m.group("codes")diff --git a/scripts/type_discipline_gate.py b/scripts/type_discipline_gate.pyindex bd63a42dcab..bd8d16553b1 100644--- a/scripts/type_discipline_gate.py+++ b/scripts/type_discipline_gate.py@@ -9,12 +9,14 @@ adds, never for drift that already exists in the base.Rules not present in the budget are ignored, but today every rule the checkeremits is gated: LIT001 (mutable collection in any annotation), LIT002-(mutable-collection construction), LIT003/LIT004 (noqa / ignore without codes or-reason), LIT006 (cast), and LIT008 (`**kwargs`) carry limits above their current-count to ratchet down; LIT005 (`*-ok` suppression without a reason) is frozen at-limit 0 so any net-new reasonless suppression trips the gate; and LIT007-(TypeGuard/TypeIs) is a hard zero. ``--update`` ratchets a limit down by the-violations this branch fixed relative to its branch point (the merge-base).+(mutable-collection construction), LIT003/LIT004 (noqa / pyright-mypy ignore+without codes or reason), LIT006 (cast), LIT008 (`**kwargs`), and LIT009 (inert+`# type: ignore`, dead syntax while enableTypeIgnoreComments is false) carry+limits at or above their current count to ratchet down; LIT005 (`*-ok`+suppression without a reason) is frozen at limit 0 so any net-new reasonless+suppression trips the gate; and LIT007 (TypeGuard/TypeIs) is a hard zero.+``--update`` ratchets a limit down by the violations this branch fixed relative+to its branch point (the merge-base)."""import argparsediff --git a/tests/test_litellm/caching/test_disk_cache.py b/tests/test_litellm/caching/test_disk_cache.pynew file mode 100644index 00000000000..b8d3b7b8d36--- /dev/null+++ b/tests/test_litellm/caching/test_disk_cache.py@@ -0,0 +1,41 @@+import pytest++pytest.importorskip("diskcache")++from litellm.caching.disk_cache import DiskCache+++def cache(tmp_path):+ return DiskCache(disk_cache_dir=str(tmp_path))+++def test_increment_cache_starts_from_zero_when_key_missing(cache):+ assert cache.increment_cache("counter", 3) == 3+ assert cache.get_cache("counter") == 3+++def test_increment_cache_adds_to_existing_int(cache):+ cache.set_cache("counter", 7)+ assert cache.increment_cache("counter", 5) == 12+ assert cache.get_cache("counter") == 12+++def test_increment_cache_treats_non_int_cached_value_as_zero(cache):+ cache.set_cache("counter", "not-a-number")+ assert cache.increment_cache("counter", 4) == 4+ assert cache.get_cache("counter") == 4+++async def test_async_increment_starts_from_zero_when_key_missing(cache):+ assert await cache.async_increment("counter", 2) == 2+++async def test_async_increment_adds_to_existing_int(cache):+ await cache.async_set_cache("counter", 10)+ assert await cache.async_increment("counter", 5) == 15+++async def test_async_increment_treats_non_int_cached_value_as_zero(cache):+ await cache.async_set_cache("counter", "corrupt")+ assert await cache.async_increment("counter", 9) == 9diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.pyindex 20e7aec377b..51f13affa3f 100644--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py@@ -5210,3 +5210,41 @@ class TestModelResponseIteratorCleanup:mock_iterator.aclose.assert_awaited_once()mock_response.aclose.assert_awaited_once()+++def test_process_candidates_merges_thought_signatures_and_server_side_tools():+ """+ thought_signatures and server_side_tool_invocations must both survive in+ provider_specific_fields when a candidate carries the two at once; the second+ merge must extend the dict created by the first, not replace it.+ """+ candidates = [+ {+ "content": {+ "role": "model",+ "parts": [+ {"text": "the weather is sunny", "thoughtSignature": "sig-text"},+ {+ "toolCall": {+ "toolType": "google_search",+ "id": "tool-1",+ "args": {"query": "weather"},+ }+ },+ ],+ },+ "finishReason": "STOP",+ }+ ]+ model_response = ModelResponse()++ VertexGeminiConfig._process_candidates(+ _candidates=candidates,+ model_response=model_response,+ standard_optional_params={},+ cumulative_tool_call_index=0,+ )++ fields = model_response.choices[-1].message.provider_specific_fields+ assert fields["thought_signatures"] == ["sig-text"]+ assert fields["server_side_tool_invocations"][0]["id"] == "tool-1"diff --git a/tests/test_litellm/test_check_type_discipline.py b/tests/test_litellm/test_check_type_discipline.pyindex 436904b017c..13edf6d1a95 100644--- a/tests/test_litellm/test_check_type_discipline.py+++ b/tests/test_litellm/test_check_type_discipline.py@@ -62,12 +62,38 @@ def test_noqa_with_codes_and_reason_is_clean(tmp_path):assert "LIT003" not in _codes(tmp_path, "x = 1 # noqa: TID251 # legacy import, removed in #123\n")-def test_ignore_without_reason_is_flagged(tmp_path):- assert "LIT004" in _codes(tmp_path, "x = 1 # type: ignore[arg-type]\n")+def test_pyright_ignore_without_codes_is_flagged(tmp_path):+ assert "LIT004" in _codes(tmp_path, "x = 1 # pyright: ignore\n")+++def test_pyright_ignore_without_reason_is_flagged(tmp_path):+ assert "LIT004" in _codes(tmp_path, "x = 1 # pyright: ignore[reportArgumentType]\n")def test_ignore_with_codes_and_reason_is_clean(tmp_path):- assert "LIT004" not in _codes(tmp_path, "x = 1 # pyright: ignore[reportArgumentType] # upstream stub is wrong\n")+ codes = _codes(tmp_path, "x = 1 # pyright: ignore[reportArgumentType] # upstream stub is wrong\n")+ assert "LIT004" not in codes+ assert "LIT009" not in codes+++def test_bare_type_ignore_is_flagged(tmp_path):+ assert "LIT009" in _codes(tmp_path, "x = 1 # type: ignore\n")+++def test_type_ignore_with_codes_and_reason_is_still_flagged(tmp_path):+ codes = _codes(tmp_path, "x = 1 # type: ignore[arg-type] # inertness is the point\n")+ assert "LIT009" in codes+ assert "LIT004" not in codes+++def test_prose_mentioning_type_ignored_is_not_flagged(tmp_path):+ assert "LIT009" not in _codes(tmp_path, "x = 1 # type: ignored by the stub refresh, revisit\n")+++def test_mypy_ignore_shape_is_lit004_not_lit009(tmp_path):+ codes = _codes(tmp_path, "x = 1 # mypy: ignore[assignment]\n")+ assert "LIT004" in codes+ assert "LIT009" not in codesdef test_ok_suppression_without_reason_is_flagged(tmp_path):@@ -196,4 +222,4 @@ def test_typed_args_is_clean_but_kwargs_ok_suppresses(tmp_path):def test_budget_covers_exactly_the_checker_rules():budget = json.loads((_REPO_ROOT / "type-discipline-budget.json").read_text())- assert set(budget) == {f"LIT00{n}" for n in range(1, 9)}+ assert set(budget) == {f"LIT00{n}" for n in range(1, 10)}diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.pyindex 0198a396b9b..7f1ceba532c 100644--- a/tests/test_litellm/test_cost_calculator.py+++ b/tests/test_litellm/test_cost_calculator.py@@ -3262,3 +3262,35 @@ def test_completion_cost_logs_reasoning_and_cache_breakdown():assert logging_obj.cost_breakdown is not Noneassert logging_obj.cost_breakdown["reasoning_cost"] == pytest.approx(3114 * 2.5e-06)assert logging_obj.cost_breakdown["cache_read_cost"] == pytest.approx(100 * 3e-08)+++def test_cost_per_token_per_second_pricing(monkeypatch):+ """+ Models priced by duration (input/output_cost_per_second) with no per-token rates+ must be billed as cost_per_second * response_time_ms / 1000 in cost_per_token.+ """+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")+ monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))++ model = "test-per-second-pricing-model"+ litellm.register_model(+ model_cost={+ model: {+ "input_cost_per_second": 0.02,+ "output_cost_per_second": 0.04,+ "litellm_provider": "together_ai",+ "mode": "chat",+ }+ }+ )++ prompt_cost, completion_cost_value = cost_per_token(+ model=model,+ custom_llm_provider="together_ai",+ prompt_tokens=10,+ completion_tokens=20,+ response_time_ms=1500.0,+ )++ assert prompt_cost == pytest.approx(0.02 * 1.5)+ assert completion_cost_value == pytest.approx(0.04 * 1.5)diff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.pyindex 113e1bc0df8..f24df599505 100644--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@ -1962,3 +1962,35 @@ class TestCallTypesOCR:call_type = CallTypes("aocr")assert call_type == CallTypes.aocr+++def test_stream_chunk_builder_text_completion_combines_text_and_usage():+ from litellm.main import stream_chunk_builder_text_completion+ from litellm.types.utils import TextCompletionResponse++ chunks = [+ TextCompletionResponse(+ id="cmpl-1",+ object="text_completion",+ created=1,+ model="gpt-3.5-turbo-instruct",+ choices=[{"text": "Hello", "index": 0, "logprobs": None, "finish_reason": None}],+ ),+ TextCompletionResponse(+ id="cmpl-1",+ object="text_completion",+ created=1,+ model="gpt-3.5-turbo-instruct",+ choices=[{"text": " world", "index": 0, "logprobs": None, "finish_reason": "stop"}],+ ),+ ]++ response = stream_chunk_builder_text_completion(+ chunks=chunks, messages=[{"role": "user", "content": "say hello"}]+ )++ assert response.choices[0].text == "Hello world"+ assert response.choices[0].finish_reason == "stop"+ assert response.usage.prompt_tokens > 0+ assert response.usage.completion_tokens > 0+ assert response.usage.total_tokens == response.usage.prompt_tokens + response.usage.completion_tokensdiff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex aa16b30b215..8d12528d8ab 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -9,7 +9,7 @@"limit": 422},"LIT004": {- "limit": 2565+ "limit": 44},"LIT005": {"limit": 0@@ -22,5 +22,8 @@},"LIT008": {"limit": 1004+ },+ "LIT009": {+ "limit": 2501}}