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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_lit4395_cursor_agent
mateo-berri23d26d5e648b
diff --cc basedpyright-code-budget.jsonindex 73b9d0c8192,f6dd90077b1..4e55978793e--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -21,7 -21,7 +21,7 @@@"limit": 325},"reportDuplicateImport": {-- "limit": 42++ "limit": 38},"reportExplicitAny": {"limit": 9473@@@ -42,7 -42,7 +42,7 @@@"limit": 18},"reportIndexIssue": {- "limit": 36- "limit": 37++ "limit": 35},"reportInvalidTypeForm": {"limit": 35@@@ -57,7 -57,7 +57,7 @@@"limit": 5855},"reportMissingTypeArgument": {-- "limit": 15852++ "limit": 15849},"reportMissingTypeStubs": {"limit": 41@@@ -84,7 -84,7 +84,7 @@@"limit": 77},"reportPrivateUsage": {-- "limit": 2437++ "limit": 2436},"reportRedeclaration": {"limit": 12@@@ -99,7 -99,7 +99,7 @@@"limit": 0},"reportUnknownArgumentType": {-- "limit": 45324++ "limit": 45269},"reportUnknownLambdaType": {"limit": 113@@@ -114,16 -114,16 +114,16 @@@"limit": 31978},"reportUnnecessaryCast": {- "limit": 175- "limit": 177++ "limit": 173},"reportUnnecessaryComparison": {- "limit": 1019- "limit": 1021++ "limit": 1017},"reportUnnecessaryContains": {"limit": 7},"reportUnnecessaryIsInstance": {-- "limit": 1204++ "limit": 1203},"reportUntypedBaseClass": {"limit": 165diff --cc litellm/completion_extras/litellm_responses_transformation/transformation.pyindex d999c9f4e60,3825854852d..1cc1e88f1fa--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py@@@ -4,7 -4,7 +4,7 @@@ Handler for transforming /chat/completiimport jsonimport os- from collections.abc import Mapping-from collections.abc import AsyncIterator, Callable, Iterable, Iterator++from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mappingfrom typing import (TYPE_CHECKING,Any,@@@ -111,55 -93,11 +103,55 @@@ def _build_reasoning_item}+class _ChatToolCallDict(ChatCompletionToolCallChunk, total=False):+ provider_specific_fields: Mapping[str, Any]+++def _tool_call_dict_from_output_item(item: Mapping[str, Any], index: int) -> _ChatToolCallDict:+ """Convert a ``function_call`` or ``custom_tool_call`` output item dict to a chat+ completions tool_call dict. Custom (grammar/freeform) tool calls carry their raw+ string payload in ``input`` rather than ``arguments``; both map to+ ``function.arguments`` so chat clients (e.g. Cursor agent mode) receive them like+ any other tool call. The single conversion rule shared by the non-streaming+ accumulator and the streaming ``output_item.added`` branch."""+ from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+ )++ is_custom = item.get("type") == "custom_tool_call"+ arguments = (item.get("input") if is_custom else item.get("arguments")) or ""+ name = item.get("name") or ("custom_tool" if is_custom else "")+ function_chunk = ChatCompletionToolCallFunctionChunk(name=name, arguments=arguments)+ tool_call_dict = _ChatToolCallDict(+ id=LiteLLMCompletionResponsesConfig._tool_call_id_from_responses_item(item.get("id"), item.get("call_id")),+ type="function",+ function=function_chunk,+ index=index,+ )+ raw_provider_fields = item.get("provider_specific_fields")+ if isinstance(raw_provider_fields, dict):+ provider_specific_fields = raw_provider_fields+ elif raw_provider_fields and hasattr(raw_provider_fields, "__dict__"):+ provider_specific_fields = vars(raw_provider_fields)+ else:+ provider_specific_fields = None+ if provider_specific_fields:+ tool_call_dict["provider_specific_fields"] = provider_specific_fields+ function_chunk["provider_specific_fields"] = provider_specific_fields+ return tool_call_dict+++def _flat_responses_tool_choice(choice_type: str, name: str) -> Union[ToolChoiceFunctionParam, ToolChoiceCustomParam]:+ if choice_type == "custom":+ return ToolChoiceCustomParam(type="custom", name=name)+ return ToolChoiceFunctionParam(type="function", name=name)++def _reasoning_item_to_response_input(- r_item: Union[ChatCompletionReasoningItem, Dict[str, Any]],- ) -> Dict[str, Any]:+ r_item: ChatCompletionReasoningItem | dict[str, Any],+ ) -> dict[str, Any]:"""Convert a stored ChatCompletionReasoningItem back to a Responses API input item."""- r_input: Dict[str, Any] = {+ r_input: dict[str, Any] = {"type": "reasoning","id": r_item.get("id") or f"rs_{id(r_item)}",# summary is always required by the Responses API, even when empty@@@ -179,23 -117,20 +171,23 @@@ class LiteLLMResponsesTransformationHanpassdef _normalize_tool_choice_for_responses_api(self, tool_choice: Any) -> Any:- """Chat tool_choice uses function.name; Responses API expects top-level name."""- if not isinstance(tool_choice, dict) or tool_choice.get("type") != "function":+ """Chat tool_choice nests the name under function/custom; Responses API expects top-level name."""+ if not isinstance(tool_choice, dict):+ return tool_choice+ choice_type = tool_choice.get("type")+ if choice_type not in ("function", "custom"):return tool_choiceif isinstance(tool_choice.get("name"), str) and tool_choice.get("name"):- # Return only Responses shape so stray chat ``function`` key is not sent upstream.- return {"type": "function", "name": tool_choice["name"]}- fn = tool_choice.get("function")- if isinstance(fn, dict):- fn_name = fn.get("name")- if isinstance(fn_name, str) and fn_name:- return {"type": "function", "name": fn_name}+ # Return only Responses shape so stray chat ``function``/``custom`` keys are not sent upstream.+ return _flat_responses_tool_choice(choice_type, tool_choice["name"])+ nested = tool_choice.get(choice_type)+ if isinstance(nested, dict):+ nested_name = nested.get("name")+ if isinstance(nested_name, str) and nested_name:+ return _flat_responses_tool_choice(choice_type, nested_name)return tool_choice- def _handle_raw_dict_response_item(self, item: Dict[str, Any], index: int) -> Tuple[Optional[Any], int]:+ def _handle_raw_dict_response_item(self, item: dict[str, Any], index: int) -> tuple[Any | None, int]:"""Handle raw dict response items from Responses API (e.g., GPT-5 Codex format).@@@ -241,19 -204,10 +233,19 @@@return None, indexdef convert_chat_completion_messages_to_responses_api(- self, messages: List["AllMessageValues"]- ) -> Tuple[List[Any], Optional[str]]:- input_items: List[Any] = []- instructions: Optional[str] = None+ self, messages: list["AllMessageValues"]+ ) -> tuple[list[Any], str | None]:+ input_items: list[Any] = []+ instructions: str | None = None+ custom_tool_call_ids = frozenset(+ tool_call["id"]+ for msg in messages+ if msg.get("role") == "assistant" and isinstance(msg.get("tool_calls"), list)+ for tool_call in msg.get("tool_calls") or ()+ if isinstance(tool_call, dict)+ and not tool_call.get("function")+ and isinstance(tool_call.get("custom"), dict)+ )for msg in messages:role = msg.get("role")@@@ -320,9 -265,8 +312,9 @@@input_items.append(_reasoning_item_to_response_input(r_item))for tool_call in tool_calls:function = tool_call.get("function")+ custom = tool_call.get("custom")if function:- input_tool_call: Dict[str, Any] = {+ input_tool_call: dict[str, Any] = {"type": "function_call","call_id": tool_call["id"],}@@@ -1155,10 -1059,9 +1138,10 @@@class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator):- def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False):+ def __init__(self, streaming_response, sync_stream: bool, json_mode: bool | None = False):super().__init__(streaming_response, sync_stream, json_mode)self._chat_completion_id: str | None = None+ self._tool_call_index_map: dict[int, int] = {} # mutable-ok: per-stream accumulator statedef _handle_string_chunk(self, str_line: Union[str, "BaseModel"]@@@ -1177,28 -1080,9 +1160,28 @@@return self.chunk_parser(json.loads(str_line))+ @staticmethod+ def _sequential_tool_call_index(+ tool_call_index_map: dict[int, int] | None, # mutable-ok: per-stream state, remapped in place+ output_index: int,+ ) -> int:+ """Chat-completions tool_call indices must be 0-based and sequential, but+ Responses API ``output_index`` counts every output item (reasoning,+ message, ...), so the first tool call of a reasoning model arrives at+ output_index >= 1 and strict SSE accumulators (e.g. Cursor agent mode)+ misplace it. When a per-stream map is provided, remap each distinct+ output_index to the next sequential slot; without a map (stateless+ callers), fall back to the raw output_index."""+ if tool_call_index_map is None:+ return output_index+ if output_index not in tool_call_index_map:+ tool_call_index_map[output_index] = len(tool_call_index_map) # mutable-ok: per-stream accumulator state+ return tool_call_index_map[output_index]+@staticmethoddef translate_responses_chunk_to_openai_stream(- parsed_chunk: Union[dict, BaseModel],+ parsed_chunk: dict | BaseModel,+ tool_call_index_map: dict[int, int] | None = None, # mutable-ok: per-stream state, remapped in place) -> "ModelResponseStream":"""Translate a Responses API streaming chunk to OpenAI chat completion streaming format.@@@ -1288,15 -1182,10 +1271,15 @@@)])- elif event_type == "response.function_call_arguments.delta":+ elif event_type in (+ ResponsesAPIStreamEvents.FUNCTION_CALL_ARGUMENTS_DELTA,+ ResponsesAPIStreamEvents.CUSTOM_TOOL_CALL_INPUT_DELTA,+ ):- content_part: Optional[str] = parsed_chunk.get("delta", None)+ content_part: str | None = parsed_chunk.get("delta", None)if content_part:- tool_call_index = parsed_chunk.get("output_index", 0)+ tool_call_index = OpenAiResponsesToChatCompletionStreamIterator._sequential_tool_call_index(+ tool_call_index_map, parsed_chunk.get("output_index", 0)+ )return ModelResponseStream(choices=[StreamingChoices(diff --cc litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.pyindex cf3937072c2,8177391a74c..88789ca414c--- 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@@@ -3,8 -3,8 +3,8 @@@ import jsoimport reimport timeimport traceback- from collections.abc import Sequence- from typing import Dict, Iterable, List, Literal, Optional, Tuple, Union, cast-from collections.abc import Iterable++from collections.abc import Iterable, Sequence+ from typing import Literal, castimport litellmfrom litellm._logging import verbose_logger@@@ -45,8 -41,8 +42,9 @@@ from litellm.types.utils importTranscriptionUsageDurationObject,TranscriptionUsageTokensObject,Usage,+ chat_completion_tool_call_from_dict,)+ from litellm.types.utils import Logprobs as TextCompletionLogprobsfrom .get_headers import get_response_headers@@@ -372,9 -368,7 +370,9 @@@ from collections import defaultdicdef _handle_invalid_parallel_tool_calls(- tool_calls: List[- Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]- tool_calls: list[ChatCompletionMessageToolCall],++ tool_calls: list[++ ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall+ ], # mutable-ok: patched in place via slice assignment):"""Handle hallucinated parallel tool call from openai - https://community.openai.com/t/model-tries-to-call-unknown-function-multi-tool-use-parallel/490653@@@ -385,10 -379,8 +383,10 @@@if tool_calls is None:returntry:- replacements: Dict[int, List[ChatCompletionMessageToolCall]] = defaultdict(list)+ replacements: dict[int, list[ChatCompletionMessageToolCall]] = defaultdict(list)for i, tool_call in enumerate(tool_calls):+ if isinstance(tool_call, ChatCompletionMessageCustomToolCall):+ continuecurrent_function = tool_call.function.namefunction_args = json.loads(tool_call.function.arguments)if current_function == "multi_tool_use.parallel":@@@ -534,10 -525,8 +531,10 @@@ class LiteLLMResponseObjectHandlerdef _should_convert_tool_call_to_json_mode(- tool_calls: list[ChatCompletionMessageToolCall] | list[DatabricksTool] | None = None,+ tool_calls: (+ Sequence[ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall] | Sequence[DatabricksTool] | None+ ) = None,- convert_tool_call_to_json_mode: Optional[bool] = None,+ convert_tool_call_to_json_mode: bool | None = None,) -> bool:"""Determine if tool calls should be converted to JSON modediff --cc litellm/litellm_core_utils/prompt_templates/common_utils.pyindex 52974d42b96,639c93dfb80..4a44a614d4d--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@@ -1260,39 -1250,7 +1258,39 @@@ def is_function_call(optional_params: dreturn False+def convert_custom_tool_format_to_chat_shape(format_obj: Mapping[str, Any]) -> Mapping[str, Any]:+ """+ Responses API grammar formats are flat ({"type": "grammar", "definition", "syntax"});+ Chat Completions wraps the same fields in a "grammar" object. Text formats are+ identical on both surfaces and pass through, as does anything unrecognized.+ """+ if format_obj.get("type") != "grammar" or "grammar" in format_obj:+ return format_obj+ grammar = CustomFormatGrammarGrammar()+ if "definition" in format_obj:+ grammar["definition"] = format_obj["definition"]+ if "syntax" in format_obj:+ grammar["syntax"] = format_obj["syntax"]+ return CustomFormatGrammar(type="grammar", grammar=grammar)+++def convert_custom_tool_format_to_responses_shape(format_obj: Mapping[str, Any]) -> Mapping[str, Any]:+ """+ Inverse of convert_custom_tool_format_to_chat_shape: unwrap the Chat Completions+ "grammar" object into the flat Responses API grammar shape.+ """+ grammar = format_obj.get("grammar")+ if format_obj.get("type") != "grammar" or not isinstance(grammar, dict):+ return format_obj+ flat = ResponsesGrammarFormat(type="grammar")+ if "definition" in grammar:+ flat["definition"] = grammar["definition"]+ if "syntax" in grammar:+ flat["syntax"] = grammar["syntax"]+ return flat++- def get_file_ids_from_messages(messages: List[AllMessageValues]) -> List[str]:+ def get_file_ids_from_messages(messages: list[AllMessageValues]) -> list[str]:"""Gets file ids from messages"""diff --cc litellm/litellm_core_utils/streaming_chunk_builder_utils.pyindex 6d013718668,2e62a151f98..6e7ed370294--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py@@@ -1,8 -1,8 +1,9 @@@import base64import time+from collections.abc import Mapping, Sequence- from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast+ from typing import TYPE_CHECKING, Any, Union, cast+ from litellm._logging import verbose_loggerfrom litellm.types.llms.openai import (ChatCompletionAssistantContentValue,ChatCompletionAudioDelta,@@@ -205,15 -202,9 +205,15 @@@ class ChunkProcessorresponse = self.update_model_response_with_hidden_params(model_response=response, chunk=chunk)return response- def get_combined_tool_content(self, tool_call_chunks: list[dict[str, Any]]) -> list[ChatCompletionMessageToolCall]:- tool_calls_list: list[ChatCompletionMessageToolCall] = []+ def get_combined_tool_content(+ self, tool_call_chunks: Sequence[Mapping[str, Any]]- ) -> List[- Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]- ]: # mutable-ok: assigned verbatim to Message.tool_calls, a List field- tool_calls_list: List[- Union[ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall]++ ) -> list[++ ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall++ ]: # mutable-ok: assigned verbatim to Message.tool_calls, a list field++ tool_calls_list: list[++ ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall+ ] = [] # mutable-ok: see return type- tool_call_map: Dict[int, Dict[str, Any]] = {} # Map to store tool calls by index+ tool_call_map: dict[int, dict[str, Any]] = {} # Map to store tool calls by indexfor chunk in tool_call_chunks:choices = chunk["choices"]diff --cc litellm/main.pyindex cadf65c3e50,cea9d44fb1a..6073e858522--- a/litellm/main.py+++ b/litellm/main.py@@@ -976,36 -967,18 +967,36 @@@ def mock_completionexcept Exception as e:if isinstance(e, openai.APIError):raise e- raise Exception("Mock completion response failed - {}".format(e))+ raise Exception(f"Mock completion response failed - {e}")+_OPENAI_DEFAULT_API_BASE = "https://api.openai.com/v1"+++def _resolve_openai_api_base(api_base: str | None) -> str:+ """Effective OpenAI base a chat request will hit: arg > global > env > default. The bridge gate+ and the ``_complete_custom_openai`` chat handler MUST resolve this identically, or a custom base+ set via ``litellm.api_base`` or ``OPENAI_BASE_URL``/``OPENAI_API_BASE`` is invisible to the gate,+ which then misreads it as the default OpenAI endpoint and bridges a request the backend can't serve."""+ return (+ api_base+ or litellm.api_base+ or get_secret_str("OPENAI_BASE_URL")+ or get_secret_str("OPENAI_API_BASE")+ or _OPENAI_DEFAULT_API_BASE+ )++def responses_api_bridge_check(model: str,custom_llm_provider: str,- web_search_options: Optional[OpenAIWebSearchOptions] = None,- tools: Optional[List[Any]] = None,- reasoning_effort: Optional[Any] = None,- reasoning_summary: Optional[Any] = None,+ web_search_options: OpenAIWebSearchOptions | None = None,+ tools: list[Any] | None = None,+ reasoning_effort: Any | None = None,+ reasoning_summary: Any | None = None,+ api_base: str | None = None,- ) -> Tuple[dict, str]:- model_info: Dict[str, Any] = {}+ ) -> tuple[dict, str]:+ model_info: dict[str, Any] = {}# Global flag: route ALL OpenAI chat completions through Responses API.# Returns early with minimal model_info; callers only inspect the "mode" key.diff --cc litellm/proxy/response_api_endpoints/endpoints.pyindex 2068de17785,f17d546b88b..7dcb01d3e59--- a/litellm/proxy/response_api_endpoints/endpoints.py+++ b/litellm/proxy/response_api_endpoints/endpoints.py@@@ -1,9 -1,8 +1,9 @@@import asyncioimport jsonimport time- from collections.abc import Mapping-from collections.abc import AsyncIterator++from collections.abc import AsyncIterator, Mapping+from types import MappingProxyType- from typing import Any, AsyncIterator, Dict, Optional, cast+ from typing import Any, castfrom uuid import uuid4import fastapidiff --cc ruff-strict-budget.jsonindex 4c8132ff859,d3ef01940bb..4f1ab0130f5--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@@ -69,7 -69,7 +69,7 @@@"limit": 4},"C405": {- "limit": 23- "limit": 22++ "limit": 21},"C408": {"limit": 14@@@ -81,7 -81,7 +81,7 @@@"limit": 4},"C901": {- "limit": 314- "limit": 312++ "limit": 311},"D419": {"limit": 9@@@ -237,16 -237,16 +237,16 @@@"limit": 41},"RUF022": {- "limit": 85+ "limit": 0},"RUF023": {- "limit": 5+ "limit": 0},"RUF046": {- "limit": 8- "limit": 6++ "limit": 5},"RUF051": {- "limit": 6+ "limit": 0},"RUF059": {"limit": 73@@@ -312,7 -312,7 +312,7 @@@"limit": 547},"TRY004": {-- "limit": 98++ "limit": 97},"TRY201": {"limit": 420diff --cc type-discipline-budget.jsonindex bc28630a4e5,f071c381916..9976be98522--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -1,9 -1,9 +1,9 @@@{"LIT001": {- "limit": 23180+ "limit": 23350},"LIT002": {- "limit": 27259- "limit": 27256++ "limit": 27239},"LIT003": {"limit": 292@@@ -15,7 -15,7 +15,7 @@@"limit": 0},"LIT006": {- "limit": 1106- "limit": 1105++ "limit": 1103},"LIT007": {"limit": 0@@@ -24,6 -24,6 +24,6 @@@"limit": 1004},"LIT009": {-- "limit": 2465++ "limit": 2460}}