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_google_interactions_cost
mateo-berri9906770e419f
diff --cc litellm/constants.pyindex be880b72854,c33e5a53b76..534a8e8ce4d--- a/litellm/constants.py+++ b/litellm/constants.py@@@ -1455,21 -1559,11 +1559,24 @@@ STALE_OBJECT_CLEANUP_BATCH_SIZE: Final# Set PROXY_BATCH_POLLING_ENABLED=false to disable the CheckBatchCost and# CheckResponsesCost background polling jobs entirely (e.g. to avoid DB load on# installations with large numbers of stale managed objects).- _batch_polling_env = os.getenv("PROXY_BATCH_POLLING_ENABLED", "true").lower()- PROXY_BATCH_POLLING_ENABLED = _batch_polling_env == "true"- BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS = float(- os.getenv("BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS", 5)+ _batch_polling_env: Final = os.getenv("PROXY_BATCH_POLLING_ENABLED", "true").lower()+ PROXY_BATCH_POLLING_ENABLED: Final = _batch_polling_env == "true"++BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS: Final = float(++ os.getenv("BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS", "5")+)- BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS = float(- os.getenv("BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS", 60)++BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS: Final = float(++ os.getenv("BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS", "60")+)- BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS = float(- os.getenv("BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS", 3600)++BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS: Final = float(++ os.getenv("BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS", "3600")+)- _background_interaction_cost_polling_env = os.getenv("BACKGROUND_INTERACTION_COST_POLLING_ENABLED", "true").lower()- BACKGROUND_INTERACTION_COST_POLLING_ENABLED = _background_interaction_cost_polling_env == "true"- PROXY_BUDGET_RESCHEDULER_MAX_TIME = int(os.getenv("PROXY_BUDGET_RESCHEDULER_MAX_TIME", 605))- PROXY_BATCH_WRITE_AT = int(os.getenv("PROXY_BATCH_WRITE_AT", 10)) # in seconds, increased from 10++_background_interaction_cost_polling_env: Final = os.getenv(++ "BACKGROUND_INTERACTION_COST_POLLING_ENABLED", "true"++).lower()++BACKGROUND_INTERACTION_COST_POLLING_ENABLED: Final = _background_interaction_cost_polling_env == "true"+ PROXY_BUDGET_RESCHEDULER_MAX_TIME: Final = int(os.getenv("PROXY_BUDGET_RESCHEDULER_MAX_TIME", 605))+ PROXY_BATCH_WRITE_AT: Final = int(os.getenv("PROXY_BATCH_WRITE_AT", 10)) # in seconds, increased from 10+ PROXY_CONFIG_RELOAD_INTERVAL_SECONDS: Final = get_env_int("PROXY_CONFIG_RELOAD_INTERVAL_SECONDS", 30)# APScheduler Configuration - MEMORY LEAK FIX# These settings prevent memory leaks in APScheduler's normalize() and _apply_jitter() functionsdiff --cc litellm/interactions/background_cost_polling.pyindex ed30d2573bd,00000000000..ccf4c2dd853mode 100644,000000..100644--- a/litellm/interactions/background_cost_polling.py+++ b/litellm/interactions/background_cost_polling.py@@@ -1,236 -1,0 +1,241 @@@+"""+Cost tracking for background interactions.++A create request with ``background=true`` returns ``in_progress`` with no+usage block, and GET polls are deliberately never billed (billing them would+double-charge every poll; the GET response also does not echo ``background``,+so a poll cannot be told apart from a re-fetch of an already-billed+interaction). The create call is therefore the only place that can own+billing: it schedules a poll task that fetches the interaction until it+reaches a terminal status and logs the final usage as a single success event+attributed to the original request.++Deleting an interaction makes every subsequent poll fail, which would let a+caller retrieve the completed output themselves and then delete it before the+poll task settles, leaving the work unbilled and the budget reservation+refunded at the poll timeout. ``adelete`` therefore settles any pending poll+for the interaction before dispatching the delete: it fetches the current+state with the create's credentials, bills it if it is terminal with usage,+and releases the reservation otherwise. A settlement gate on the create's+logging object makes the poll task and the delete path mutually exclusive, so+the interaction is billed exactly once no matter who settles first.+"""++import asyncio++from collections.abc import Awaitable, Callable, Iterator, Mapping+from dataclasses import dataclass- from typing import TYPE_CHECKING, Any, Awaitable, Callable, Iterator, Optional++from typing import TYPE_CHECKING, TypeAlias++from litellm._logging import verbose_logger+from litellm.constants import (+ BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS,+ BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS,+ BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS,+ BACKGROUND_INTERACTION_COST_POLLING_ENABLED,+)+from litellm.litellm_core_utils.core_helpers import get_litellm_metadata_from_kwargs+from litellm.types.interactions import InteractionsAPIResponse++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj++_TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled", "incomplete", "budget_exceeded"})+++@dataclass(frozen=True, slots=True)+class BackgroundInteractionPollContext:+ interaction_id: str+ custom_llm_provider: str+ logging_obj: "LiteLLMLoggingObj"- api_key: Optional[str] = None- api_base: Optional[str] = None++ api_key: str | None = None++ api_base: str | None = None+ initial_interval_seconds: float = BACKGROUND_INTERACTION_COST_POLL_INITIAL_INTERVAL_SECONDS+ max_interval_seconds: float = BACKGROUND_INTERACTION_COST_POLL_MAX_INTERVAL_SECONDS+ timeout_seconds: float = BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS++- FetchInteraction = Callable[[BackgroundInteractionPollContext], Awaitable[InteractionsAPIResponse]]++FetchInteraction: TypeAlias = Callable[[BackgroundInteractionPollContext], Awaitable[InteractionsAPIResponse]]+++async def _fetch_interaction(context: BackgroundInteractionPollContext) -> InteractionsAPIResponse:+ from litellm.interactions import aget++ return await aget(+ interaction_id=context.interaction_id,+ custom_llm_provider=context.custom_llm_provider,- **{"api_key": context.api_key, "api_base": context.api_base, "no-log": True},++ api_key=context.api_key,++ api_base=context.api_base,++ **{++ "no-log": True++ }, # mutable-ok: "no-log" is not a valid identifier, so it can only be passed through a mapping+ )+++def _poll_intervals(initial: float, maximum: float, timeout: float) -> Iterator[float]:+ elapsed = 0.0+ interval = initial+ while elapsed + interval <= timeout:+ yield interval+ elapsed += interval+ interval = min(interval * 2, maximum)+++_SETTLED_KEY = "background_interaction_settled"+++def _is_settled(logging_obj: "LiteLLMLoggingObj") -> bool:+ return logging_obj.model_call_details.get(_SETTLED_KEY) is True+++def _claim_settlement(logging_obj: "LiteLLMLoggingObj") -> bool:+ """+ Exactly-once gate between the poll task and the delete-time settlement:+ both run on the same event loop and neither awaits between reading and+ setting the flag, so whichever claims first owns billing or release.+ """+ if _is_settled(logging_obj):+ return False- logging_obj.model_call_details[_SETTLED_KEY] = True++ logging_obj.model_call_details[_SETTLED_KEY] = True # rebind-ok: both settlers must see the same settlement flag+ return True+++async def poll_and_log_background_interaction_cost(+ context: BackgroundInteractionPollContext,+ fetch_interaction: FetchInteraction = _fetch_interaction,+) -> None:+ for interval in _poll_intervals(+ initial=context.initial_interval_seconds,+ maximum=context.max_interval_seconds,+ timeout=context.timeout_seconds,+ ):+ await asyncio.sleep(interval)+ if _is_settled(context.logging_obj):+ return+ try:+ response = await fetch_interaction(context)+ except Exception as e: # noqa: BLE001 # any fetch error must not kill the billing poll loop+ verbose_logger.debug(+ "Background interaction cost poll for %s failed, will retry: %s",+ context.interaction_id,+ e,+ )+ continue+ if response.status not in _TERMINAL_STATUSES:+ continue+ if not _claim_settlement(context.logging_obj):+ return+ if response.usage is not None:+ await context.logging_obj.async_log_background_interaction_completion(result=response)+ else:+ await _release_open_budget_reservation(logging_obj=context.logging_obj)+ return+ if not _claim_settlement(context.logging_obj):+ return+ verbose_logger.warning(+ "Gave up cost polling for background interaction %s after %ss; its usage will not be tracked",+ context.interaction_id,+ context.timeout_seconds,+ )+ await _release_open_budget_reservation(logging_obj=context.logging_obj)+++async def _release_open_budget_reservation(logging_obj: "LiteLLMLoggingObj") -> None:+ """+ The proxy keeps the pre-call budget reservation open for an in-progress+ background interaction so concurrent creates cannot stack past the budget.+ The completion success event reconciles it to the actual cost; when the+ interaction terminates without billable usage (or polling gives up, or it+ is deleted before settling), no such event fires, so whoever claims the+ settlement must release the reservation here or the spend counters stay+ pinned at the estimated cost.+ """+ metadata = get_litellm_metadata_from_kwargs(kwargs=logging_obj.model_call_details)+ budget_reservation = metadata.get("user_api_key_budget_reservation")+ if not isinstance(budget_reservation, dict):+ return++ from litellm.proxy.spend_tracking.budget_reservation import release_budget_reservation++ try:+ await release_budget_reservation(budget_reservation=budget_reservation)+ except Exception: # noqa: BLE001 # a failed release must not crash the poll task; counters expire via TTL+ verbose_logger.exception("Failed to release budget reservation for an unbilled background interaction")+++@dataclass(frozen=True, slots=True)+class _ActiveBackgroundPoll:+ task: "asyncio.Task[None]"+ context: BackgroundInteractionPollContext++- _ACTIVE_POLLS: dict[- str, _ActiveBackgroundPoll- ] = {} # mutable-ok: asyncio requires strong refs to running tasks, and delete settlement looks polls up by interaction id++_ACTIVE_POLLS: dict[str, _ActiveBackgroundPoll] = {} # mutable-ok: asyncio needs strong refs to running poll tasks+++def _discard_poll(interaction_id: str, task: "asyncio.Task[None]") -> None:+ entry = _ACTIVE_POLLS.get(interaction_id)+ if entry is not None and entry.task is task:+ del _ACTIVE_POLLS[interaction_id]+++def maybe_schedule_background_interaction_cost_polling(- response: Any,- create_kwargs: dict[str, Any],++ response: object,++ create_kwargs: Mapping[str, object],+ custom_llm_provider: str,- ) -> Optional["asyncio.Task[None]"]:++) -> "asyncio.Task[None] | None":+ from litellm.litellm_core_utils.litellm_logging import Logging++ if not BACKGROUND_INTERACTION_COST_POLLING_ENABLED:+ return None+ if not isinstance(response, InteractionsAPIResponse):+ return None+ if response.status != "in_progress" or not response.id:+ return None+ logging_obj = create_kwargs.get("litellm_logging_obj")+ if not isinstance(logging_obj, Logging):+ return None+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return None++ api_key = create_kwargs.get("api_key")++ api_base = create_kwargs.get("api_base")+ context = BackgroundInteractionPollContext(+ interaction_id=response.id,+ custom_llm_provider=custom_llm_provider,+ logging_obj=logging_obj,- api_key=create_kwargs.get("api_key"),- api_base=create_kwargs.get("api_base"),++ api_key=api_key if isinstance(api_key, str) else None,++ api_base=api_base if isinstance(api_base, str) else None,+ )+ task = asyncio.create_task(poll_and_log_background_interaction_cost(context))+ _ACTIVE_POLLS[context.interaction_id] = _ActiveBackgroundPoll(task=task, context=context)+ task.add_done_callback(+ lambda finished, interaction_id=context.interaction_id: _discard_poll(interaction_id, finished)+ )+ return task+++async def maybe_settle_background_interaction_before_delete(+ interaction_id: str,+ fetch_interaction: FetchInteraction = _fetch_interaction,+) -> None:+ entry = _ACTIVE_POLLS.get(interaction_id)+ if entry is None:+ return+ context = entry.context+ try:+ response = await fetch_interaction(context)+ except Exception as e: # noqa: BLE001 # unfetchable pre-delete state settles by releasing the reservation+ verbose_logger.debug(+ "Could not fetch background interaction %s before delete, releasing its reservation: %s",+ interaction_id,+ e,+ )+ if _claim_settlement(context.logging_obj):+ await _release_open_budget_reservation(logging_obj=context.logging_obj)+ return+ if not _claim_settlement(context.logging_obj):+ return+ if response.status in _TERMINAL_STATUSES and response.usage is not None:+ await context.logging_obj.async_log_background_interaction_completion(result=response)+ return+ await _release_open_budget_reservation(logging_obj=context.logging_obj)diff --cc litellm/interactions/main.pyindex 985c60c2cc2,3e8c381fdf7..a2c3d510fae--- a/litellm/interactions/main.py+++ b/litellm/interactions/main.py@@@ -174,13 -171,7 +175,13 @@@ async def acreateelse:response = init_response+ maybe_schedule_background_interaction_cost_polling(+ response=response,+ create_kwargs=kwargs,+ custom_llm_provider=custom_llm_provider,+ )+- return response # type: ignore+ return responseexcept Exception as e:raise litellm.exception_type(model=model,@@@ -470,14 -457,12 +467,14 @@@ async def adelete**kwargs,) -> DeleteInteractionResult:"""Async: Delete an interaction by its ID."""- local_vars = locals()+ local_vars: Final = locals()try:- loop = asyncio.get_event_loop()+ loop: Final = asyncio.get_event_loop()kwargs["adelete_interaction"] = True+ await maybe_settle_background_interaction_before_delete(interaction_id=interaction_id)+- func = partial(+ func: Final = partial(delete,interaction_id=interaction_id,extra_headers=extra_headers,diff --cc litellm/litellm_core_utils/litellm_logging.pyindex ac6334bea76,c14dd6c3d8b..e7d7213b47c--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@@ -83,6 -83,6 +86,10 @@@ from litellm.llms.base_llm.search.transfrom litellm.responses.utils import ResponseAPILoggingUtilsfrom litellm.types.agents import LiteLLMSendMessageResponsefrom litellm.types.containers.main import ContainerObject++from litellm.types.interactions import (++ InteractionsAPIResponse,++ InteractionsAPIStreamingResponse,++)from litellm.types.llms.openai import (AllMessageValues,Batch,@@@ -1905,6 -2145,6 +2152,11 @@@ class Logging(LiteLLMLoggingBaseClass)or isinstance(logging_result, OpenAIModerationResponse)or isinstance(logging_result, OCRResponse) # OCRor isinstance(logging_result, SearchResponse) # Search API++ or (++ isinstance(logging_result, InteractionsAPIResponse)++ and logging_result.usage is not None++ and self._is_interactions_create_call_type()++ )or isinstance(logging_result, dict)and logging_result.get("object") == "vector_store.search_results.page"or isinstance(logging_result, dict)@@@ -1917,50 -2157,13 +2169,50 @@@return Truereturn False+ def _is_interactions_create_call_type(self) -> bool:+ """+ Only interaction creation is billable. GET polls, deletes, and cancels+ also return an ``InteractionsAPIResponse`` (with usage once completed),+ so recognizing those would write spend on every poll of a background+ interaction. The proxy sets ``call_type`` from its route_type+ (``create_interaction``/``acreate_interaction``); the SDK sets it from+ the decorated function name (``create``/``acreate``).++ Recognition additionally requires a usage block (checked at the call+ site): a ``background=true`` create returns ``in_progress`` without+ usage, and billing it would write a $0 spend log under the interaction+ id that collides with the row the background poll task writes once the+ interaction completes (see+ ``litellm.interactions.background_cost_polling``).+ """+ return self.call_type in (+ CallTypes.create_interaction.value,+ CallTypes.acreate_interaction.value,+ "create",+ "acreate",+ )++ async def async_log_background_interaction_completion(+ self,+ result: InteractionsAPIResponse,+ ) -> None:+ """+ Log the terminal result of a background interaction as a fresh success+ event. The create request already ran success logging for its+ ``in_progress`` response (no usage, so no cost was tracked); clearing+ the dedup flag lets the completed result flow through cost calculation+ and spend tracking exactly once, spanning create to completion.+ """+ self.model_call_details.pop("has_logged_async_success", None)+ await self.async_success_handler(result=result)+def _flush_passthrough_collected_chunks_helper(self,- raw_bytes: List[bytes],+ raw_bytes: list[bytes],provider_config: "BasePassthroughConfig",) -> Optional["CostResponseTypes"]:- all_chunks = provider_config._convert_raw_bytes_to_str_lines(raw_bytes)- complete_streaming_response = provider_config.handle_logging_collected_chunks(+ all_chunks: Final = provider_config._convert_raw_bytes_to_str_lines(raw_bytes)+ complete_streaming_response: Final = provider_config.handle_logging_collected_chunks(all_chunks=all_chunks,litellm_logging_obj=self,model=self.model,@@@ -2018,12 -2279,10 +2328,12 @@@standard_logging_object=kwargs.get("standard_logging_object", None),)litellm_params = self.model_call_details.get("litellm_params", {})- is_sync_request = self._is_sync_litellm_request(litellm_params)+ is_sync_request: Final = self._is_sync_litellm_request(litellm_params)try:## BUILD COMPLETE STREAMED RESPONSE- complete_streaming_response: Optional[- Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse, InteractionsAPIResponse]- ] = None- complete_streaming_response: ModelResponse | TextCompletionResponse | ResponsesAPIResponse | None = None++ complete_streaming_response: (++ ModelResponse | TextCompletionResponse | ResponsesAPIResponse | InteractionsAPIResponse | None++ ) = Noneif "complete_streaming_response" in self.model_call_details:return # break out of this.complete_streaming_response = self._get_assembled_streaming_response(@@@ -2477,14 -2768,14 +2819,14 @@@## BUILD COMPLETE STREAMED RESPONSEif "async_complete_streaming_response" in self.model_call_details:return # break out of this.- complete_streaming_response: (- Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse, InteractionsAPIResponse] | None- ) = self._get_assembled_streaming_response(- complete_streaming_response: Final[ModelResponse | TextCompletionResponse | ResponsesAPIResponse | None] = (- self._get_assembled_streaming_response(- result=result,- start_time=start_time,- end_time=end_time,- is_async=True,- streaming_chunks=self.streaming_chunks,- )++ complete_streaming_response: Final[++ ModelResponse | TextCompletionResponse | ResponsesAPIResponse | InteractionsAPIResponse | None++ ] = self._get_assembled_streaming_response(+ result=result,+ start_time=start_time,+ end_time=end_time,+ is_async=True,+ streaming_chunks=self.streaming_chunks,)if complete_streaming_response is not None:@@@ -3201,13 -3557,11 +3608,11 @@@start_time: datetime.datetime,end_time: datetime.datetime,is_async: bool,- streaming_chunks: List[Any],- ) -> Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse, InteractionsAPIResponse] | None:+ streaming_chunks: list[object],- ) -> ModelResponse | TextCompletionResponse | ResponsesAPIResponse | None:++ ) -> ModelResponse | TextCompletionResponse | ResponsesAPIResponse | InteractionsAPIResponse | None:if self.stream is not True:return None- if isinstance(result, ModelResponse):- return result- elif isinstance(result, TextCompletionResponse):+ if isinstance(result, ModelResponse) or isinstance(result, TextCompletionResponse):return resultelif isinstance(result,@@@ -3234,26 -3586,6 +3639,35 @@@else:return None+ @staticmethod+ def _assemble_completed_interaction_response(+ result: InteractionsAPIStreamingResponse,+ ) -> InteractionsAPIResponse | None:+ """+ The Interactions API streaming iterator hands the terminal event to the+ success handlers: the new schema (Api-Revision: 2026-05-20) emits+ ``interaction.completed`` carrying the full interaction object, the+ legacy schema (2026-05-07) emits a chunk with ``status="completed"``+ and usage on the chunk itself. Build the equivalent non-streaming+ response so cost calculation and spend tracking see one shape.+ """+ if result.event_type == "interaction.completed" and result.interaction is not None:+ return InteractionsAPIResponse(**result.interaction)+ if result.status == "completed":+ return InteractionsAPIResponse(- **result.model_dump(exclude={"event_type", "delta", "index", "step", "interaction_id", "interaction"})++ **result.model_dump(++ exclude={ # mutable-ok: pydantic types exclude as set[str], which a frozenset does not satisfy++ "event_type",++ "delta",++ "index",++ "step",++ "interaction_id",++ "interaction",++ }++ )+ )+ return None+def _handle_anthropic_messages_response_logging(self, result: Any) -> ModelResponse:"""Handles logging for Anthropic messages responses.diff --cc litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.pyindex 23fafc4132d,210ac72cd8a..df436ef7611--- a/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py+++ b/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py@@@ -1,7 -1,6 +1,9 @@@- from typing import Any, Mapping, Optional, Sequence, Union++from collections.abc import Mapping, Sequence++from types import MappingProxyType+ from typing import Anyfrom litellm.types.utils import (+ CompletionTokensDetailsWrapper,PromptTokensDetailsWrapper,TranscriptionUsageDurationObject,TranscriptionUsageTokensObject,@@@ -35,119 -34,3 +37,127 @@@ class TranscriptionUsageObjectTransform),)return None++- _INTERACTIONS_MODALITY_FIELDS: Mapping[str, str] = {- "text": "text_tokens",- "audio": "audio_tokens",- "image": "image_tokens",- "video": "video_tokens",- "document": "text_tokens",- }++_INTERACTIONS_MODALITY_FIELDS: Mapping[str, str] = MappingProxyType(++ {++ "text": "text_tokens",++ "audio": "audio_tokens",++ "image": "image_tokens",++ "video": "video_tokens",++ "document": "text_tokens",++ }++)+++def _modality_field(entry: Mapping[str, Any]) -> str | None:+ return _INTERACTIONS_MODALITY_FIELDS.get(str(entry.get("modality", "")).lower())++- def _token_count(value: Any) -> int:++def _token_count(value: object) -> int:+ return value if isinstance(value, int) else 0+++def _modality_token_sums(entries: Sequence[Mapping[str, Any]]) -> Mapping[str, int]:- fields = {field for entry in entries if (field := _modality_field(entry)) is not None}- return {- field: sum(_token_count(entry.get("tokens")) for entry in entries if _modality_field(entry) == field)- for field in fields- }++ fields = frozenset(field for entry in entries if (field := _modality_field(entry)) is not None)++ return MappingProxyType(++ {++ field: sum(_token_count(entry.get("tokens")) for entry in entries if _modality_field(entry) == field)++ for field in fields++ }++ )+++def _google_search_query_count(usage_object: Mapping[str, Any]) -> int:+ return sum(+ _token_count(entry.get("count"))+ for entry in tuple(usage_object.get("grounding_tool_count") or ())- if isinstance(entry, Mapping) and entry.get("type") == "google_search"++ if isinstance(entry, Mapping) and entry.get("type") == "google_search" # pyright: ignore[reportUnnecessaryIsInstance] # provider JSON, not the empty tuple inferred from `or ()`+ )+++def _subtract_cached_from_input(+ input_sums: Mapping[str, int],+ cached_sums: Mapping[str, int],+ total_cached_tokens: int,+) -> Mapping[str, int]:+ if cached_sums:- return {field: max(0, tokens - cached_sums.get(field, 0)) for field, tokens in input_sums.items()}++ return MappingProxyType(++ {field: max(0, tokens - cached_sums.get(field, 0)) for field, tokens in input_sums.items()}++ )+ if total_cached_tokens and "text_tokens" in input_sums:- return {- **input_sums,- "text_tokens": max(0, input_sums["text_tokens"] - total_cached_tokens),- }++ return MappingProxyType(++ {++ **input_sums,++ "text_tokens": max(0, input_sums["text_tokens"] - total_cached_tokens),++ }++ )+ return input_sums+++class InteractionsUsageObjectTransformation:+ """+ Maps the Google Interactions API usage block (total_input_tokens,+ output_tokens_by_modality, ...) into LiteLLM's chat-format ``Usage`` so the+ generic cost calculator and spend tracking can bill it.+ """++ @staticmethod- def is_interactions_usage_object(usage_object: Any) -> bool:++ def is_interactions_usage_object(usage_object: object) -> bool:+ if not isinstance(usage_object, dict):+ return False+ if "prompt_tokens" in usage_object or "input_tokens" in usage_object:+ return False+ return "total_input_tokens" in usage_object or "total_output_tokens" in usage_object++ @staticmethod+ def transform_interactions_usage_object(usage_object: Mapping[str, Any]) -> Usage:+ input_entries = tuple(usage_object.get("input_tokens_by_modality") or ()) + tuple(+ usage_object.get("tool_use_tokens_by_modality") or ()+ )+ cached_sums = _modality_token_sums(tuple(usage_object.get("cached_tokens_by_modality") or ()))+ output_sums = _modality_token_sums(tuple(usage_object.get("output_tokens_by_modality") or ()))++ total_cached_tokens = _token_count(usage_object.get("total_cached_tokens"))+ input_sums = _subtract_cached_from_input(+ input_sums=_modality_token_sums(input_entries),+ cached_sums=cached_sums,+ total_cached_tokens=total_cached_tokens,+ )++ reasoning_tokens = _token_count(usage_object.get("total_reasoning_tokens")) or _token_count(+ usage_object.get("total_thought_tokens")+ )+ prompt_tokens = _token_count(usage_object.get("total_input_tokens")) + _token_count(+ usage_object.get("total_tool_use_tokens")+ )+ completion_tokens = _token_count(usage_object.get("total_output_tokens")) + reasoning_tokens+ total_tokens = _token_count(usage_object.get("total_tokens")) or (prompt_tokens + completion_tokens)++ web_search_requests = _google_search_query_count(usage_object)+ prompt_tokens_details = (+ PromptTokensDetailsWrapper(+ cached_tokens=total_cached_tokens or None,+ web_search_requests=web_search_requests or None,+ **input_sums,+ )+ if input_sums or total_cached_tokens or web_search_requests+ else None+ )+ completion_tokens_details = (+ CompletionTokensDetailsWrapper(+ reasoning_tokens=reasoning_tokens or None,+ **output_sums,+ )+ if output_sums or reasoning_tokens+ else None+ )++ return Usage(+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ total_tokens=total_tokens,+ prompt_tokens_details=prompt_tokens_details,+ completion_tokens_details=completion_tokens_details,+ cache_read_input_tokens=total_cached_tokens or None,+ )diff --cc litellm/proxy/hooks/proxy_track_cost_callback.pyindex a645bb9929f,99d0c94d11b..55d3c6c6ed5--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@@ -1,588 -1,615 +1,635 @@@- import asyncio- import traceback- from datetime import datetime- from typing import Any, List, Optional, Union, cast-- import litellm- from litellm._logging import verbose_proxy_logger- from litellm.constants import BACKGROUND_INTERACTION_COST_POLLING_ENABLED- from litellm.integrations.custom_logger import CustomLogger- from litellm.litellm_core_utils.core_helpers import (- _get_parent_otel_span_from_kwargs,- get_litellm_metadata_from_kwargs,- )- from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup- from litellm.proxy._types import UserAPIKeyAuth- from litellm.proxy.auth.auth_checks import (- get_key_object,- get_team_object,- log_db_metrics,- )- from litellm.proxy.auth.route_checks import RouteChecks- from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup- from litellm.proxy.spend_tracking.spend_log_error_logger import (- should_suppress_spend_log_tracebacks,- spend_log_error,- )- from litellm.proxy.spend_tracking.spend_tracking_utils import (- _sanitize_error_information_for_spend_logs,- )- from litellm.proxy.utils import ProxyUpdateSpend- from litellm.types.utils import (- CallTypes,- StandardLoggingPayload,- StandardLoggingPayloadErrorInformation,- )- from litellm.utils import get_end_user_id_for_cost_tracking-- _PASS_THROUGH_CALL_TYPES: frozenset[str] = frozenset(- {- CallTypes.pass_through.value,- CallTypes.llm_passthrough_route.value,- CallTypes.allm_passthrough_route.value,- }- )--- class _ProxyDBLogger(CustomLogger):- async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):- await self._PROXY_track_cost_callback(kwargs, response_obj, start_time, end_time)-- async def async_post_call_failure_hook(- self,- request_data: dict,- original_exception: Exception,- user_api_key_dict: UserAPIKeyAuth,- traceback_str: Optional[str] = None,- ):- try:- await _release_budget_reservation(budget_reservation=user_api_key_dict.budget_reservation)- except Exception:- verbose_proxy_logger.exception("Failed to release budget reservation during failure handling")- try:- await _invalidate_budget_reservation_counters(budget_reservation=user_api_key_dict.budget_reservation)- if user_api_key_dict.budget_reservation is not None:- user_api_key_dict.budget_reservation["finalized"] = True- except Exception:- verbose_proxy_logger.exception(- "Failed to invalidate budget reservation counters after failure release failed"- )-- request_route = user_api_key_dict.request_route- if _ProxyDBLogger._should_track_errors_in_db() is False:- return- elif request_route is not None and not (- RouteChecks.is_llm_api_route(route=request_route) or RouteChecks.is_info_route(route=request_route)- ):- return-- from litellm.proxy.proxy_server import proxy_logging_obj-- _metadata = dict(- LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(user_api_key_dict=user_api_key_dict)- )- _metadata["user_api_key"] = user_api_key_dict.api_key- _metadata["status"] = "failure"- _error_information = StandardLoggingPayloadSetup.get_error_information(- original_exception=original_exception,- traceback_str=traceback_str,- )- if should_suppress_spend_log_tracebacks():- # Drop the traceback key entirely so the per-row Metadata pane in- # the UI (which renders the JSON blob verbatim) doesn't show a- # noisy ``"traceback": ""`` line. Downstream consumers all use- # ``.get("traceback")`` / truthy checks, and the TypedDict marks- # the field as optional, so omitting is type-safe.- _error_information.pop("traceback", None)- # Strip echoed request input + apply DB-size cap before storing in- # the spend-log metadata column (LIT-2992). Result is never None- # here because the input above is constructed non-None.- _error_information = cast(- StandardLoggingPayloadErrorInformation,- _sanitize_error_information_for_spend_logs(_error_information),- )- _metadata["error_information"] = _error_information-- _metadata = await _ProxyDBLogger._enrich_failure_metadata_with_key_info(- metadata=_metadata,- )-- existing_metadata: dict = request_data.get("metadata", None) or {}- existing_metadata.update(_metadata)-- if "litellm_params" not in request_data:- request_data["litellm_params"] = {}-- existing_litellm_params = request_data.get("litellm_params", {})- existing_litellm_metadata = existing_litellm_params.get("metadata", {}) or {}-- # Preserve tags from existing metadata- if existing_litellm_metadata.get("tags"):- existing_metadata["tags"] = existing_litellm_metadata.get("tags")-- request_data["litellm_params"]["proxy_server_request"] = (- request_data.get("proxy_server_request") or existing_litellm_params.get("proxy_server_request") or {}- )- request_data["litellm_params"]["metadata"] = existing_metadata-- # Preserve model name and custom_llm_provider- if "model" not in request_data:- request_data["model"] = existing_litellm_params.get("model") or request_data.get("model", "")- if "custom_llm_provider" not in request_data:- request_data["custom_llm_provider"] = existing_litellm_params.get(- "custom_llm_provider"- ) or request_data.get("custom_llm_provider", "")-- # Propagate standard_logging_object and litellm_trace_id from the- # Logging instance so that _get_session_id_for_spend_log uses the same- # trace_id that Langfuse received (via async_failure_handler).- # Without this, the DB session_id would be a random UUID that doesn't- # match the Langfuse trace_id, making failed requests unsearchable.- _litellm_logging_obj = request_data.get("litellm_logging_obj")- if _litellm_logging_obj is not None:- if not request_data.get("standard_logging_object"):- request_data["standard_logging_object"] = getattr(_litellm_logging_obj, "model_call_details", {}).get(- "standard_logging_object"- )- if request_data.get("litellm_trace_id") is None:- request_data["litellm_trace_id"] = getattr(_litellm_logging_obj, "litellm_trace_id", None)-- # Use the actual request start time from the logging object so that- # failed requests record the real duration instead of 0.- actual_start_time = datetime.now()- if _litellm_logging_obj is not None:- obj_start = getattr(_litellm_logging_obj, "start_time", None)- if obj_start is not None:- actual_start_time = obj_start-- # A stream that broke mid-flight still billed the provider for the- # chunks already delivered. ``post_call_failure_hook`` lifts that- # recovered cost onto request_data (the usage rides along in- # ``combined_usage_object`` for the token columns), so attribute the- # real partial spend to this failure row instead of zero.- recovered_response_cost = 0.0- if isinstance(request_data.get("combined_usage_object"), litellm.Usage):- recovered_response_cost = max(float(request_data.get("response_cost") or 0.0), 0.0)-- await proxy_logging_obj.db_spend_update_writer.update_database(- token=user_api_key_dict.api_key,- response_cost=recovered_response_cost,- user_id=user_api_key_dict.user_id,- end_user_id=user_api_key_dict.end_user_id,- team_id=user_api_key_dict.team_id,- kwargs=request_data,- completion_response=original_exception,- start_time=actual_start_time,- end_time=datetime.now(),- org_id=user_api_key_dict.org_id,- )-- @log_db_metrics- async def _PROXY_track_cost_callback(- self,- kwargs, # kwargs to completion- completion_response: Optional[Union[litellm.ModelResponse, Any]], # response from completion- start_time=None,- end_time=None, # start/end time for completion- ):- from litellm.proxy.proxy_server import (- increment_spend_counters,- proxy_logging_obj,- update_cache,- )-- verbose_proxy_logger.debug("INSIDE _PROXY_track_cost_callback")- try:- verbose_proxy_logger.debug(- f"kwargs stream: {kwargs.get('stream', None)} + complete streaming response: {kwargs.get('complete_streaming_response', None)}"- )- parent_otel_span = _get_parent_otel_span_from_kwargs(kwargs=kwargs)- litellm_params = kwargs.get("litellm_params", {}) or {}- end_user_id = get_end_user_id_for_cost_tracking(litellm_params)- metadata = get_litellm_metadata_from_kwargs(kwargs=kwargs)- # Only fetch key details when user_id wasn't already populated (e.g. direct MCP REST calls).- # Avoids a cache/DB lookup on every normal LLM request.- if metadata.get("user_api_key") and not metadata.get("user_api_key_user_id"):- metadata = await _ProxyDBLogger._enrich_failure_metadata_with_key_info(metadata=metadata)- _write_spend_metadata_to_kwargs(kwargs=kwargs, metadata=metadata)- budget_reservation = _get_budget_reservation_from_metadata(metadata=metadata)- user_id = cast(Optional[str], metadata.get("user_api_key_user_id", None))- team_id = cast(Optional[str], metadata.get("user_api_key_team_id", None))- org_id = cast(Optional[str], metadata.get("user_api_key_org_id", None))- key_alias = cast(Optional[str], metadata.get("user_api_key_alias", None))- end_user_max_budget = metadata.get("user_api_end_user_max_budget", None)- sl_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None)- response_cost = (- sl_object.get("response_cost", None) if sl_object is not None else kwargs.get("response_cost", None)- )- tags = _get_request_tags_for_cost_tracking(- sl_object=sl_object,- metadata=metadata,- )-- if response_cost is not None:- user_api_key = metadata.get("user_api_key", None)- if kwargs.get("cache_hit", False) is True:- response_cost = 0.0- verbose_proxy_logger.debug(f"Cache Hit: response_cost {response_cost}, for user_id {user_id}")-- verbose_proxy_logger.debug(- f"user_api_key {user_api_key}, user_id {user_id}, team_id {team_id}, end_user_id {end_user_id}"- )- call_type: Optional[str] = kwargs.get("call_type")- if _should_track_cost_callback(- user_api_key=user_api_key,- user_id=user_id,- team_id=team_id,- end_user_id=end_user_id,- call_type=call_type,- ):- ## UPDATE DATABASE- await _update_database_and_spend_counters(- proxy_logging_obj=proxy_logging_obj,- increment_spend_counters=increment_spend_counters,- user_api_key=user_api_key,- user_id=user_id,- end_user_id=end_user_id,- team_id=team_id,- org_id=org_id,- kwargs=kwargs,- completion_response=completion_response,- start_time=start_time,- end_time=end_time,- response_cost=response_cost,- budget_reservation=budget_reservation,- request_tags=tags,- )-- # update cache (fire-and-forget for backward compat:- # cached object fields, soft budget alerts, etc.)- asyncio.create_task(- update_cache(- token=user_api_key,- user_id=user_id,- end_user_id=end_user_id,- response_cost=response_cost,- team_id=team_id,- parent_otel_span=parent_otel_span,- tags=tags,- )- )-- await proxy_logging_obj.slack_alerting_instance.customer_spend_alert(- token=user_api_key,- key_alias=key_alias,- end_user_id=end_user_id,- response_cost=response_cost,- max_budget=end_user_max_budget,- )- elif budget_reservation is not None:- await _release_budget_reservation(budget_reservation=budget_reservation)- else:- if _is_unbilled_in_progress_interaction(completion_response):- if BACKGROUND_INTERACTION_COST_POLLING_ENABLED:- verbose_proxy_logger.debug(- "Cost tracking deferred for in-progress background interaction; "- "the budget reservation stays open until the poll task logs the final usage"- )- return- await _release_budget_reservation(budget_reservation=budget_reservation)- verbose_proxy_logger.debug(- "Background interaction cost polling is disabled; released the budget "- "reservation for an in-progress interaction that will not be billed"- )- return- await _release_budget_reservation(budget_reservation=budget_reservation)- # Non-model call types (health checks, afile_delete) have no model or standard_logging_object.- # Use .get() for "stream" to avoid KeyError on health checks.- # WS session wrappers (_aresponses_websocket, _arealtime) also reach here with- # result=None; their per-turn costs are tracked on the inner aresponses/realtime calls.- if sl_object is None and (- not kwargs.get("model") or kwargs.get("call_type") in ("_aresponses_websocket", "_arealtime")- ):- verbose_proxy_logger.warning(- "Cost tracking - skipping, no standard_logging_object for call_type=%s",- kwargs.get("call_type", "unknown"),- )- return- if kwargs.get("stream") is not True or (- kwargs.get("stream") is True and "complete_streaming_response" in kwargs- ):- if sl_object is not None:- cost_tracking_failure_debug_info: Union[dict, str] = (- sl_object["response_cost_failure_debug_info"] # type: ignore- or "response_cost_failure_debug_info is None in standard_logging_object"- )- else:- cost_tracking_failure_debug_info = "standard_logging_object not found"- model = kwargs.get("model")- raise Exception(- f"Cost tracking failed for model={model}.\nDebug info - {cost_tracking_failure_debug_info}\nAdd custom pricing - https://docs.litellm.ai/docs/proxy/custom_pricing"- )- except Exception as e:- error_msg = f"Error in tracking cost callback - {str(e)}\n Traceback:{traceback.format_exc()}"- model = kwargs.get("model", "")- metadata = get_litellm_metadata_from_kwargs(kwargs=kwargs)- litellm_metadata = kwargs.get("litellm_params", {}).get("litellm_metadata", {})- old_metadata = kwargs.get("litellm_params", {}).get("metadata", {})- call_type = kwargs.get("call_type", "")- error_msg += f"\n Args to _PROXY_track_cost_callback\n model: {model}\n chosen_metadata: {metadata}\n litellm_metadata: {litellm_metadata}\n old_metadata: {old_metadata}\n call_type: {call_type}\n"- asyncio.create_task(- proxy_logging_obj.failed_tracking_alert(- error_message=error_msg,- failing_model=model,- )- )-- spend_log_error("Error in tracking cost callback - %s", str(e), exc=e)-- @staticmethod- async def _enrich_failure_metadata_with_key_info(metadata: dict) -> dict:- """- Enriches failure spend log metadata by looking up the key object (and team object)- from cache/DB when key fields are missing.-- This handles two scenarios:- 1. Auth errors (401): UserAPIKeyAuth is created with only api_key set, all other- fields are null. We look up the full key object to fill in alias, user_id,- team_id, etc.- 2. Post-auth failures (provider errors, rate limits): key fields are populated- but team_alias is missing because LiteLLM_VerificationTokenView SQL view- doesn't include it. We look up the team object to fill in team_alias.- """- api_key_hash = metadata.get("user_api_key")- if not api_key_hash:- return metadata-- from litellm.proxy.proxy_server import (- prisma_client,- proxy_logging_obj,- user_api_key_cache,- )-- # Step 1: If key fields are missing, look up the full key object- if metadata.get("user_api_key_alias") is None:- try:- key_obj = await get_key_object(- hashed_token=api_key_hash,- prisma_client=prisma_client,- user_api_key_cache=user_api_key_cache,- proxy_logging_obj=proxy_logging_obj,- )- if metadata.get("user_api_key_alias") is None:- metadata["user_api_key_alias"] = key_obj.key_alias- if metadata.get("user_api_key_user_id") is None:- metadata["user_api_key_user_id"] = key_obj.user_id- if metadata.get("user_api_key_team_id") is None:- metadata["user_api_key_team_id"] = key_obj.team_id- if metadata.get("user_api_key_org_id") is None:- metadata["user_api_key_org_id"] = key_obj.org_id- except Exception:- verbose_proxy_logger.debug(- "Failed to enrich failure metadata with key info for api_key=%s",- api_key_hash,- )-- # Step 2: If team_id is known but team_alias is missing, look up the team object- team_id = metadata.get("user_api_key_team_id")- if team_id and metadata.get("user_api_key_team_alias") is None:- try:- team_obj = await get_team_object(- team_id=team_id,- prisma_client=prisma_client,- user_api_key_cache=user_api_key_cache,- proxy_logging_obj=proxy_logging_obj,- )- if team_obj.team_alias is not None:- metadata["user_api_key_team_alias"] = team_obj.team_alias- except Exception:- verbose_proxy_logger.debug(- "Failed to enrich failure metadata with team_alias for team_id=%s",- team_id,- )- return metadata-- @staticmethod- def _should_track_errors_in_db():- """- Returns True if errors should be tracked in the database-- By default, errors are tracked in the database-- If users want to disable error tracking, they can set the disable_error_logs flag in the general_settings- """- from litellm.proxy.proxy_server import general_settings-- if general_settings.get("disable_error_logs") is True:- return False- return--- def _write_spend_metadata_to_kwargs(kwargs: dict, metadata: dict) -> None:- patch = {k: v for k, v in metadata.items() if (k.startswith("user_api_key") or k == "tags") and v is not None}- if not patch:- return-- litellm_params = kwargs.setdefault("litellm_params", {})- for bucket_name in ("litellm_metadata", "metadata"):- bucket = litellm_params.get(bucket_name)- if isinstance(bucket, dict):- for key, value in patch.items():- if bucket.get(key) is None:- bucket[key] = value--- def _is_unbilled_in_progress_interaction(completion_response: Any) -> bool:- from litellm.types.interactions import InteractionsAPIResponse-- return isinstance(completion_response, InteractionsAPIResponse) and completion_response.usage is None--- def _should_track_cost_callback(- user_api_key: Optional[str],- user_id: Optional[str],- team_id: Optional[str],- end_user_id: Optional[str],- call_type: Optional[str] = None,- ) -> bool:- """- Determine if the cost callback should be tracked based on the kwargs-- Pass-through endpoints can be configured with ``auth=false``, which leaves- the request with no key/user/team/end-user to attribute spend to. Those- requests still forward real provider traffic that operators expect to see- in request/usage logs, so they are tracked even when unauthenticated.- """-- # don't run track cost callback if user opted into disabling spend- if ProxyUpdateSpend.disable_spend_updates() is True:- return False-- if user_api_key is not None or user_id is not None or team_id is not None or end_user_id is not None:- return True- return call_type in _PASS_THROUGH_CALL_TYPES--- def _get_budget_reservation_from_metadata(metadata: dict) -> Optional[dict]:- metadata_budget_reservation = metadata.get("user_api_key_budget_reservation")- if isinstance(metadata_budget_reservation, dict):- return metadata_budget_reservation-- user_api_key_auth_obj = metadata.get("user_api_key_auth")- if user_api_key_auth_obj is None:- return None- if isinstance(user_api_key_auth_obj, dict):- budget_reservation = user_api_key_auth_obj.get("budget_reservation")- return budget_reservation if isinstance(budget_reservation, dict) else None- return getattr(user_api_key_auth_obj, "budget_reservation", None)--- def _get_request_tags_for_cost_tracking(- sl_object: Optional[StandardLoggingPayload],- metadata: dict,- ) -> Optional[List[str]]:- if sl_object is not None:- request_tags = sl_object.get("request_tags", None)- if isinstance(request_tags, list):- return request_tags-- metadata_tags = metadata.get("tags", None)- if isinstance(metadata_tags, list):- return metadata_tags-- return None--- async def _update_database_and_spend_counters(- proxy_logging_obj: Any,- increment_spend_counters: Any,- user_api_key: Optional[str],- user_id: Optional[str],- end_user_id: Optional[str],- team_id: Optional[str],- org_id: Optional[str],- kwargs: dict,- completion_response: Optional[Union[litellm.ModelResponse, Any]],- start_time: Any,- end_time: Any,- response_cost: float,- budget_reservation: Optional[dict],- request_tags: Optional[List[str]] = None,- ) -> None:- try:- await proxy_logging_obj.db_spend_update_writer.update_database(- token=user_api_key,- response_cost=response_cost,- user_id=user_id,- end_user_id=end_user_id,- team_id=team_id,- kwargs=kwargs,- completion_response=completion_response,- start_time=start_time,- end_time=end_time,- org_id=org_id,- )- except Exception:- if budget_reservation is not None:- try:- await _release_budget_reservation(budget_reservation=budget_reservation)- except Exception:- verbose_proxy_logger.exception("Failed to release budget reservation after database update failed")- try:- await _invalidate_budget_reservation_counters(budget_reservation=budget_reservation)- except Exception:- verbose_proxy_logger.exception(- "Failed to invalidate budget reservation counters after release failed"- )- raise-- try:- await increment_spend_counters(- token=user_api_key,- team_id=team_id,- user_id=user_id,- response_cost=response_cost,- org_id=org_id,- budget_reservation=budget_reservation,- end_user_id=end_user_id,- tags=request_tags,- )- except Exception:- if budget_reservation is not None:- try:- await _invalidate_budget_reservation_counters(budget_reservation=budget_reservation)- except Exception:- verbose_proxy_logger.exception(- "Failed to invalidate budget reservation counters after spend counter update failed"- )- finally:- budget_reservation["finalized"] = True- raise--- async def _release_budget_reservation(budget_reservation: Optional[dict]) -> None:- if budget_reservation is None:- return-- from litellm.proxy.spend_tracking.budget_reservation import (- release_budget_reservation,- )-- await release_budget_reservation(- budget_reservation=budget_reservation,- )--- async def _invalidate_budget_reservation_counters(- budget_reservation: Optional[dict],- ) -> None:- if budget_reservation is None:- return-- from litellm.proxy.spend_tracking.budget_reservation import (- invalidate_budget_reservation_counters,- )-- await invalidate_budget_reservation_counters(- budget_reservation=budget_reservation,- )+ import asyncio+ import traceback+ from datetime import datetime+ from typing import Any, Final, cast++ import litellm+ from litellm._logging import verbose_proxy_logger++from litellm.constants import BACKGROUND_INTERACTION_COST_POLLING_ENABLED+ from litellm.integrations.custom_logger import CustomLogger+ from litellm.litellm_core_utils.core_helpers import (+ _get_parent_otel_span_from_kwargs,+ get_litellm_metadata_from_kwargs,+ )+ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup+ from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import guardrail_information_cost+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy.auth.auth_checks import (+ get_key_object,+ get_team_object,+ log_db_metrics,+ )+ from litellm.proxy.auth.route_checks import RouteChecks+ from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup+ from litellm.proxy.spend_tracking.spend_log_error_logger import (+ should_suppress_spend_log_tracebacks,+ spend_log_error,+ )+ from litellm.proxy.spend_tracking.spend_tracking_utils import (+ _sanitize_error_information_for_spend_logs,+ )+ from litellm.proxy.utils import ProxyUpdateSpend+ from litellm.types.utils import (+ CallTypes,+ StandardLoggingPayload,+ StandardLoggingPayloadErrorInformation,+ )+ from litellm.utils import get_end_user_id_for_cost_tracking++ _UNATTRIBUTED_TRACKABLE_CALL_TYPES: Final[frozenset[str]] = frozenset(+ {+ CallTypes.pass_through.value,+ CallTypes.llm_passthrough_route.value,+ CallTypes.allm_passthrough_route.value,+ # CheckBatchCost's synthetic logging_obj for a completed managed batch carries+ # whatever LiteLLM_ManagedObjectTable stored at create time, and all of it is+ # None for a batch created before those columns were persisted, or by the master+ # key. The batch already incurred real provider cost, so track it regardless.+ CallTypes.aretrieve_batch.value,+ }+ )++ # Both spellings, because call_type reaches the callback as str(...) of either the+ # enum member or its value.+ _CAPTURED_IDENTITY_CALL_TYPES: Final[frozenset[str]] = frozenset(+ (+ CallTypes.aretrieve_batch.value,+ str(CallTypes.aretrieve_batch),+ )+ )+++ class _ProxyDBLogger(CustomLogger):+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ await self._PROXY_track_cost_callback(kwargs, response_obj, start_time, end_time)++ async def async_post_call_failure_hook(+ self,+ request_data: dict,+ original_exception: Exception,+ user_api_key_dict: UserAPIKeyAuth,+ traceback_str: str | None = None,+ ):+ try:+ await _release_budget_reservation(budget_reservation=user_api_key_dict.budget_reservation)+ except Exception:+ verbose_proxy_logger.exception("Failed to release budget reservation during failure handling")+ try:+ await _invalidate_budget_reservation_counters(budget_reservation=user_api_key_dict.budget_reservation)+ if user_api_key_dict.budget_reservation is not None:+ user_api_key_dict.budget_reservation["finalized"] = True+ except Exception:+ verbose_proxy_logger.exception(+ "Failed to invalidate budget reservation counters after failure release failed"+ )++ request_route: Final = user_api_key_dict.request_route+ if (+ _ProxyDBLogger._should_track_errors_in_db() is False+ or request_route is not None+ and not (+ RouteChecks.is_llm_api_route(route=request_route) or RouteChecks.is_info_route(route=request_route)+ )+ ):+ return++ from litellm.proxy.proxy_server import proxy_logging_obj++ _metadata = dict(+ LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(user_api_key_dict=user_api_key_dict)+ )+ _metadata["user_api_key"] = user_api_key_dict.api_key+ _metadata["status"] = "failure"+ _error_information = StandardLoggingPayloadSetup.get_error_information(+ original_exception=original_exception,+ traceback_str=traceback_str,+ )+ if should_suppress_spend_log_tracebacks():+ # Drop the traceback key entirely so the per-row Metadata pane in+ # the UI (which renders the JSON blob verbatim) doesn't show a+ # noisy ``"traceback": ""`` line. Downstream consumers all use+ # ``.get("traceback")`` / truthy checks, and the TypedDict marks+ # the field as optional, so omitting is type-safe.+ _error_information.pop("traceback", None)+ # Strip echoed request input + apply DB-size cap before storing in+ # the spend-log metadata column (LIT-2992). Result is never None+ # here because the input above is constructed non-None.+ _error_information = cast(+ StandardLoggingPayloadErrorInformation,+ _sanitize_error_information_for_spend_logs(_error_information),+ )+ _metadata["error_information"] = _error_information++ _metadata = await _ProxyDBLogger._enrich_failure_metadata_with_key_info(+ metadata=_metadata,+ )++ existing_metadata: Final[dict] = request_data.get("metadata", None) or {}+ existing_metadata.update(_metadata)++ litellm_metadata_bucket: Final = request_data.get("litellm_metadata")+ if (+ isinstance(litellm_metadata_bucket, dict)+ and "standard_logging_guardrail_information" not in existing_metadata+ ):+ guardrail_info: Final = litellm_metadata_bucket.get("standard_logging_guardrail_information")+ if guardrail_info is not None:+ existing_metadata["standard_logging_guardrail_information"] = guardrail_info++ if "litellm_params" not in request_data:+ request_data["litellm_params"] = {}++ existing_litellm_params: Final = request_data.get("litellm_params", {})+ existing_litellm_metadata: Final = existing_litellm_params.get("metadata", {}) or {}++ # Preserve tags from existing metadata+ if existing_litellm_metadata.get("tags"):+ existing_metadata["tags"] = existing_litellm_metadata.get("tags")++ request_data["litellm_params"]["proxy_server_request"] = (+ request_data.get("proxy_server_request") or existing_litellm_params.get("proxy_server_request") or {}+ )+ request_data["litellm_params"]["metadata"] = existing_metadata++ # Preserve model name and custom_llm_provider+ if "model" not in request_data:+ request_data["model"] = existing_litellm_params.get("model") or request_data.get("model", "")+ if "custom_llm_provider" not in request_data:+ request_data["custom_llm_provider"] = existing_litellm_params.get(+ "custom_llm_provider"+ ) or request_data.get("custom_llm_provider", "")++ # Propagate standard_logging_object and litellm_trace_id from the+ # Logging instance so that _get_session_id_for_spend_log uses the same+ # trace_id that Langfuse received (via async_failure_handler).+ # Without this, the DB session_id would be a random UUID that doesn't+ # match the Langfuse trace_id, making failed requests unsearchable.+ _litellm_logging_obj: Final = request_data.get("litellm_logging_obj")+ if _litellm_logging_obj is not None:+ if not request_data.get("standard_logging_object"):+ request_data["standard_logging_object"] = getattr(_litellm_logging_obj, "model_call_details", {}).get(+ "standard_logging_object"+ )+ if request_data.get("litellm_trace_id") is None:+ request_data["litellm_trace_id"] = getattr(_litellm_logging_obj, "litellm_trace_id", None)++ # Use the actual request start time from the logging object so that+ # failed requests record the real duration instead of 0.+ actual_start_time = datetime.now()+ if _litellm_logging_obj is not None:+ obj_start: Final = getattr(_litellm_logging_obj, "start_time", None)+ if obj_start is not None:+ actual_start_time = obj_start++ # A stream that broke mid-flight still billed the provider for the+ # chunks already delivered. ``post_call_failure_hook`` lifts that+ # recovered cost onto request_data (the usage rides along in+ # ``combined_usage_object`` for the token columns), so attribute the+ # real partial spend to this failure row instead of zero.+ recovered_stream_cost: Final = (+ max(float(request_data.get("response_cost") or 0.0), 0.0)+ if isinstance(request_data.get("combined_usage_object"), litellm.Usage)+ else 0.0+ )+ recovered_response_cost: Final = recovered_stream_cost + guardrail_information_cost(+ existing_metadata.get("standard_logging_guardrail_information")+ )++ await proxy_logging_obj.db_spend_update_writer.update_database(+ token=user_api_key_dict.api_key,+ response_cost=recovered_response_cost,+ user_id=user_api_key_dict.user_id,+ end_user_id=user_api_key_dict.end_user_id,+ team_id=user_api_key_dict.team_id,+ kwargs=request_data,+ completion_response=original_exception,+ start_time=actual_start_time,+ end_time=datetime.now(),+ org_id=user_api_key_dict.org_id,+ )++ @log_db_metrics+ async def _PROXY_track_cost_callback(+ self,+ kwargs, # kwargs to completion+ completion_response: litellm.ModelResponse | Any | None, # response from completion+ start_time=None,+ end_time=None, # start/end time for completion+ ):+ from litellm.proxy.proxy_server import (+ increment_spend_counters,+ proxy_logging_obj,+ update_cache,+ )++ verbose_proxy_logger.debug("INSIDE _PROXY_track_cost_callback")+ try:+ verbose_proxy_logger.debug(+ "kwargs stream: %s + complete streaming response: %s",+ kwargs.get("stream", None),+ kwargs.get("complete_streaming_response", None),+ )+ parent_otel_span: Final = _get_parent_otel_span_from_kwargs(kwargs=kwargs)+ litellm_params: Final = kwargs.get("litellm_params", {}) or {}+ end_user_id: Final = get_end_user_id_for_cost_tracking(litellm_params)+ metadata = get_litellm_metadata_from_kwargs(kwargs=kwargs)+ # Only fetch key details when user_id wasn't already populated (e.g. direct MCP REST calls).+ # Avoids a cache/DB lookup on every normal LLM request.+ if metadata.get("user_api_key") and not metadata.get("user_api_key_user_id"):+ metadata = await _ProxyDBLogger._enrich_failure_metadata_with_key_info( # rebind-ok: enriched metadata replaces the original+ metadata=metadata,+ resolve_missing_key_identity=str(kwargs.get("call_type")) not in _CAPTURED_IDENTITY_CALL_TYPES,+ )+ _write_spend_metadata_to_kwargs(kwargs=kwargs, metadata=metadata)+ budget_reservation: Final = _get_budget_reservation_from_metadata(metadata=metadata)+ user_id: Final = cast(str | None, metadata.get("user_api_key_user_id", None))+ team_id: Final = cast(str | None, metadata.get("user_api_key_team_id", None))+ org_id: Final = cast(str | None, metadata.get("user_api_key_org_id", None))+ key_alias: Final = cast(str | None, metadata.get("user_api_key_alias", None))+ end_user_max_budget: Final = metadata.get("user_api_end_user_max_budget", None)+ sl_object: Final[StandardLoggingPayload | None] = kwargs.get("standard_logging_object", None)+ response_cost = (+ sl_object.get("response_cost", None) if sl_object is not None else kwargs.get("response_cost", None)+ )+ tags: Final = _get_request_tags_for_cost_tracking(+ sl_object=sl_object,+ metadata=metadata,+ )++ if response_cost is not None:+ user_api_key: Final = metadata.get("user_api_key", None)+ if kwargs.get("cache_hit", False) is True:+ response_cost = 0.0+ verbose_proxy_logger.debug("Cache Hit: response_cost %s, for user_id %s", response_cost, user_id)++ verbose_proxy_logger.debug(+ "user_api_key %s, user_id %s, team_id %s, end_user_id %s",+ user_api_key,+ user_id,+ team_id,+ end_user_id,+ )+ call_type: str | None = kwargs.get("call_type")+ if _should_track_cost_callback(+ user_api_key=user_api_key,+ user_id=user_id,+ team_id=team_id,+ end_user_id=end_user_id,+ call_type=call_type,+ ):+ ## UPDATE DATABASE+ await _update_database_and_spend_counters(+ proxy_logging_obj=proxy_logging_obj,+ increment_spend_counters=increment_spend_counters,+ user_api_key=user_api_key,+ user_id=user_id,+ end_user_id=end_user_id,+ team_id=team_id,+ org_id=org_id,+ kwargs=kwargs,+ completion_response=completion_response,+ start_time=start_time,+ end_time=end_time,+ response_cost=response_cost,+ budget_reservation=budget_reservation,+ request_tags=tags,+ )++ # update cache (fire-and-forget for backward compat:+ # cached object fields, soft budget alerts, etc.)+ asyncio.create_task(+ update_cache(+ token=user_api_key,+ user_id=user_id,+ end_user_id=end_user_id,+ response_cost=response_cost,+ team_id=team_id,+ parent_otel_span=parent_otel_span,+ tags=tags,+ )+ )++ await proxy_logging_obj.slack_alerting_instance.customer_spend_alert(+ token=user_api_key,+ key_alias=key_alias,+ end_user_id=end_user_id,+ response_cost=response_cost,+ max_budget=end_user_max_budget,+ )+ elif budget_reservation is not None:+ await _release_budget_reservation(budget_reservation=budget_reservation)+ else:++ if _is_unbilled_in_progress_interaction(completion_response):++ if BACKGROUND_INTERACTION_COST_POLLING_ENABLED:++ verbose_proxy_logger.debug(++ "Cost tracking deferred for in-progress background interaction; "++ "the budget reservation stays open until the poll task logs the final usage"++ )++ return++ await _release_budget_reservation(budget_reservation=budget_reservation)++ verbose_proxy_logger.debug(++ "Background interaction cost polling is disabled; released the budget "++ "reservation for an in-progress interaction that will not be billed"++ )++ return+ await _release_budget_reservation(budget_reservation=budget_reservation)+ # Non-model call types (health checks, afile_delete) have no model or standard_logging_object.+ # Use .get() for "stream" to avoid KeyError on health checks.+ # WS session wrappers (_aresponses_websocket, _arealtime) also reach here with+ # result=None; their per-turn costs are tracked on the inner aresponses/realtime calls.+ if sl_object is None and (+ not kwargs.get("model") or kwargs.get("call_type") in ("_aresponses_websocket", "_arealtime")+ ):+ verbose_proxy_logger.warning(+ "Cost tracking - skipping, no standard_logging_object for call_type=%s",+ kwargs.get("call_type", "unknown"),+ )+ return+ if kwargs.get("stream") is not True or (+ kwargs.get("stream") is True and "complete_streaming_response" in kwargs+ ):+ if sl_object is not None:+ cost_tracking_failure_debug_info: dict | str = (+ sl_object["response_cost_failure_debug_info"]+ or "response_cost_failure_debug_info is None in standard_logging_object"+ )+ else:+ cost_tracking_failure_debug_info = "standard_logging_object not found"+ model = kwargs.get("model")+ raise Exception(+ f"Cost tracking failed for model={model}.\nDebug info - {cost_tracking_failure_debug_info}\nAdd custom pricing - https://docs.litellm.ai/docs/proxy/custom_pricing"+ )+ except Exception as e:+ error_msg = f"Error in tracking cost callback - {e}\n Traceback:{traceback.format_exc()}"+ model = kwargs.get("model", "")+ metadata = get_litellm_metadata_from_kwargs(kwargs=kwargs)+ litellm_metadata: Final = kwargs.get("litellm_params", {}).get("litellm_metadata", {})+ old_metadata: Final = kwargs.get("litellm_params", {}).get("metadata", {})+ call_type = kwargs.get("call_type", "")+ error_msg += f"\n Args to _PROXY_track_cost_callback\n model: {model}\n chosen_metadata: {metadata}\n litellm_metadata: {litellm_metadata}\n old_metadata: {old_metadata}\n call_type: {call_type}\n"+ asyncio.create_task(+ proxy_logging_obj.failed_tracking_alert(+ error_message=error_msg,+ failing_model=model,+ )+ )++ spend_log_error("Error in tracking cost callback - %s", str(e), exc=e)++ @staticmethod+ async def _enrich_failure_metadata_with_key_info(metadata: dict, resolve_missing_key_identity: bool = True) -> dict:+ """+ Enriches failure spend log metadata by looking up the key object (and team object)+ from cache/DB when key fields are missing.++ This handles two scenarios:+ 1. Auth errors (401): UserAPIKeyAuth is created with only api_key set, all other+ fields are null. We look up the full key object to fill in alias, user_id,+ team_id, etc.+ 2. Post-auth failures (provider errors, rate limits): key fields are populated+ but team_alias is missing because LiteLLM_VerificationTokenView SQL view+ doesn't include it. We look up the team object to fill in team_alias.++ Scenario 1 reads the key's identity as it stands right now, so it is only correct+ for a log emitted within the request it describes. Callers that log after a delay,+ against an identity captured earlier, pass resolve_missing_key_identity=False and+ keep their own user_id, team_id and org_id.+ """+ api_key_hash: Final = metadata.get("user_api_key")+ if not api_key_hash:+ return metadata++ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ # Step 1: If key fields are missing, look up the full key object+ if resolve_missing_key_identity and metadata.get("user_api_key_alias") is None:+ try:+ key_obj: Final = await get_key_object(+ hashed_token=api_key_hash,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ if metadata.get("user_api_key_alias") is None:+ metadata["user_api_key_alias"] = key_obj.key_alias+ if metadata.get("user_api_key_user_id") is None:+ metadata["user_api_key_user_id"] = key_obj.user_id+ if metadata.get("user_api_key_team_id") is None:+ metadata["user_api_key_team_id"] = key_obj.team_id+ if metadata.get("user_api_key_org_id") is None:+ metadata["user_api_key_org_id"] = key_obj.org_id+ except Exception:+ verbose_proxy_logger.debug(+ "Failed to enrich failure metadata with key info for api_key=%s",+ api_key_hash,+ )++ # Step 2: If team_id is known but team_alias is missing, look up the team object+ team_id: Final = metadata.get("user_api_key_team_id")+ if team_id and metadata.get("user_api_key_team_alias") is None:+ try:+ team_obj: Final = await get_team_object(+ team_id=team_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ if team_obj.team_alias is not None:+ metadata["user_api_key_team_alias"] = team_obj.team_alias+ except Exception:+ verbose_proxy_logger.debug(+ "Failed to enrich failure metadata with team_alias for team_id=%s",+ team_id,+ )+ return metadata++ @staticmethod+ def _should_track_errors_in_db():+ """+ Returns True if errors should be tracked in the database++ By default, errors are tracked in the database++ If users want to disable error tracking, they can set the disable_error_logs flag in the general_settings+ """+ from litellm.proxy.proxy_server import general_settings++ if general_settings.get("disable_error_logs") is True:+ return False+ return+++ def _write_spend_metadata_to_kwargs(kwargs: dict, metadata: dict) -> None:+ patch = {k: v for k, v in metadata.items() if (k.startswith("user_api_key") or k == "tags") and v is not None}+ if not patch:+ return++ litellm_params: Final = kwargs.setdefault("litellm_params", {})+ for bucket_name in ("litellm_metadata", "metadata"):+ bucket = litellm_params.get(bucket_name)+ if isinstance(bucket, dict):+ for key, value in patch.items():+ if bucket.get(key) is None:+ bucket[key] = value++++def _is_unbilled_in_progress_interaction(completion_response: object) -> bool:++ from litellm.types.interactions import InteractionsAPIResponse++++ return isinstance(completion_response, InteractionsAPIResponse) and completion_response.usage is None+++++ def _should_track_cost_callback(+ user_api_key: str | None,+ user_id: str | None,+ team_id: str | None,+ end_user_id: str | None,+ call_type: str | None = None,+ ) -> bool:+ """+ Determine if the cost callback should be tracked based on the kwargs++ Pass-through endpoints can be configured with ``auth=false``, which leaves+ the request with no key/user/team/end-user to attribute spend to. Those+ requests still forward real provider traffic that operators expect to see+ in request/usage logs, so they are tracked even when unauthenticated.+ The same reasoning applies to a completed managed batch's cost event+ (see _UNATTRIBUTED_TRACKABLE_CALL_TYPES).+ """++ # don't run track cost callback if user opted into disabling spend+ if ProxyUpdateSpend.disable_spend_updates() is True:+ return False++ if user_api_key is not None or user_id is not None or team_id is not None or end_user_id is not None:+ return True+ return call_type in _UNATTRIBUTED_TRACKABLE_CALL_TYPES+++ def _get_budget_reservation_from_metadata(metadata: dict) -> dict | None:+ metadata_budget_reservation: Final = metadata.get("user_api_key_budget_reservation")+ if isinstance(metadata_budget_reservation, dict):+ return metadata_budget_reservation++ user_api_key_auth_obj: Final = metadata.get("user_api_key_auth")+ if user_api_key_auth_obj is None:+ return None+ if isinstance(user_api_key_auth_obj, dict):+ budget_reservation: Final = user_api_key_auth_obj.get("budget_reservation")+ return budget_reservation if isinstance(budget_reservation, dict) else None+ return getattr(user_api_key_auth_obj, "budget_reservation", None)+++ def _get_request_tags_for_cost_tracking(+ sl_object: StandardLoggingPayload | None,+ metadata: dict,+ ) -> list[str] | None:+ if sl_object is not None:+ request_tags: Final = sl_object.get("request_tags", None)+ if isinstance(request_tags, list):+ return request_tags++ metadata_tags: Final = metadata.get("tags", None)+ if isinstance(metadata_tags, list):+ return metadata_tags++ return None+++ async def _update_database_and_spend_counters(+ proxy_logging_obj: Any,+ increment_spend_counters: Any,+ user_api_key: str | None,+ user_id: str | None,+ end_user_id: str | None,+ team_id: str | None,+ org_id: str | None,+ kwargs: dict,+ completion_response: litellm.ModelResponse | Any | None,+ start_time: Any,+ end_time: Any,+ response_cost: float,+ budget_reservation: dict | None,+ request_tags: list[str] | None = None,+ ) -> None:+ try:+ await proxy_logging_obj.db_spend_update_writer.update_database(+ token=user_api_key,+ response_cost=response_cost,+ user_id=user_id,+ end_user_id=end_user_id,+ team_id=team_id,+ kwargs=kwargs,+ completion_response=completion_response,+ start_time=start_time,+ end_time=end_time,+ org_id=org_id,+ )+ except Exception:+ if budget_reservation is not None:+ try:+ await _release_budget_reservation(budget_reservation=budget_reservation)+ except Exception:+ verbose_proxy_logger.exception("Failed to release budget reservation after database update failed")+ try:+ await _invalidate_budget_reservation_counters(budget_reservation=budget_reservation)+ except Exception:+ verbose_proxy_logger.exception(+ "Failed to invalidate budget reservation counters after release failed"+ )+ raise++ try:+ await increment_spend_counters(+ token=user_api_key,+ team_id=team_id,+ user_id=user_id,+ response_cost=response_cost,+ org_id=org_id,+ budget_reservation=budget_reservation,+ end_user_id=end_user_id,+ tags=request_tags,+ )+ except Exception:+ if budget_reservation is not None:+ try:+ await _invalidate_budget_reservation_counters(budget_reservation=budget_reservation)+ except Exception:+ verbose_proxy_logger.exception(+ "Failed to invalidate budget reservation counters after spend counter update failed"+ )+ finally:+ budget_reservation["finalized"] = True+ raise+++ async def _release_budget_reservation(budget_reservation: dict | None) -> None:+ if budget_reservation is None:+ return++ from litellm.proxy.spend_tracking.budget_reservation import (+ release_budget_reservation,+ )++ await release_budget_reservation(+ budget_reservation=budget_reservation,+ )+++ async def _invalidate_budget_reservation_counters(+ budget_reservation: dict | None,+ ) -> None:+ if budget_reservation is None:+ return++ from litellm.proxy.spend_tracking.budget_reservation import (+ invalidate_budget_reservation_counters,+ )++ await invalidate_budget_reservation_counters(+ budget_reservation=budget_reservation,+ )diff --cc litellm/types/utils.pyindex 5e4d069b8a9,ac2ab1c8363..f276a90039e--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@@ -398,12 -435,11 +435,17 @@@ class CallTypes(str, Enum)vector_store_search = "vector_store_search"avector_store_search = "avector_store_search"+ ingest = "ingest"+ aingest = "aingest"+ query = "query"+ aquery = "aquery"++ #########################################################+ # Google Interactions API Call Types+ #########################################################+ create_interaction = "create_interaction"+ acreate_interaction = "acreate_interaction"+########################################################## Container Call Types#########################################################diff --cc tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex 4d8b19150f7,873da28fc34..8a682517f64--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@@ -3775,237 -4546,657 +4546,893 @@@ def test_zero_token_video_usage_preservassert payload["completion_tokens"] == 0+INTERACTIONS_USAGE_BLOCK = {+ "total_tokens": 175,+ "total_input_tokens": 100,+ "input_tokens_by_modality": [{"modality": "text", "tokens": 100}],+ "total_cached_tokens": 0,+ "total_output_tokens": 50,+ "output_tokens_by_modality": [{"modality": "text", "tokens": 50}],+ "total_tool_use_tokens": 0,+ "total_thought_tokens": 25,+}+++def _interactions_logging_obj(stream: bool, call_type: str = "acreate"):+ logging_obj = LitellmLogging(+ model="gemini-2.5-flash",+ messages=[],+ stream=stream,+ call_type=call_type,+ start_time=time.time(),+ litellm_call_id="interactions-call-id",+ function_id="interactions-fn-id",+ )+ logging_obj.update_environment_variables(+ litellm_params={},+ optional_params={},+ model="gemini-2.5-flash",+ custom_llm_provider="gemini",+ input="hi",+ )+ return logging_obj++[email protected]("call_type", ["create", "acreate", "create_interaction", "acreate_interaction"])+def test_interactions_response_is_recognized_for_logging(call_type):+ from litellm.types.interactions import InteractionsAPIResponse++ logging_obj = _interactions_logging_obj(stream=False, call_type=call_type)+ response = InteractionsAPIResponse(+ id="interactions/abc",+ model="gemini-2.5-flash",+ status="completed",+ usage=dict(INTERACTIONS_USAGE_BLOCK),+ )+ assert logging_obj._is_recognized_call_type_for_logging(logging_result=response) is True++[email protected]("call_type", ["acreate", "acreate_interaction"])+def test_in_progress_background_create_is_not_billed(call_type):+ import datetime as dt++ from litellm.types.interactions import InteractionsAPIResponse++ logging_obj = _interactions_logging_obj(stream=False, call_type=call_type)+ response = InteractionsAPIResponse(id="interactions/abc", model="gemini-2.5-flash", status="in_progress")++ assert logging_obj._is_recognized_call_type_for_logging(logging_result=response) is False++ logging_obj._success_handler_helper_fn(+ result=response,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ cache_hit=False,+ )++ assert logging_obj.model_call_details.get("response_cost") is None+ assert logging_obj.model_call_details.get("standard_logging_object") is None+++async def test_background_interaction_completion_rebills_after_in_progress_success():+ import datetime as dt++ from litellm.types.interactions import InteractionsAPIResponse++ logging_obj = _interactions_logging_obj(stream=False)+ in_progress = InteractionsAPIResponse(id="interactions/abc", model="gemini-2.5-flash", status="in_progress")+ await logging_obj.async_success_handler(+ result=in_progress,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ )++ assert logging_obj.model_call_details.get("response_cost") is None+ assert logging_obj.should_run_logging(event_type="async_success") is False++ completed = InteractionsAPIResponse(+ id="interactions/abc",+ model="gemini-2.5-flash",+ status="completed",+ steps=[],+ usage=dict(INTERACTIONS_USAGE_BLOCK),+ )+ await logging_obj.async_log_background_interaction_completion(result=completed)++ assert logging_obj.model_call_details["response_cost"] > 0+ assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175+++ "call_type",+ ["aget", "get", "aget_interaction", "adelete_interaction", "acancel_interaction"],+)+def test_interactions_get_poll_is_not_billed(call_type):+ import datetime as dt++ from litellm.types.interactions import InteractionsAPIResponse++ logging_obj = _interactions_logging_obj(stream=False, call_type=call_type)+ response = InteractionsAPIResponse(+ id="interactions/abc",+ model="gemini-2.5-flash",+ status="completed",+ steps=[],+ usage=dict(INTERACTIONS_USAGE_BLOCK),+ )++ assert logging_obj._is_recognized_call_type_for_logging(logging_result=response) is False++ logging_obj._success_handler_helper_fn(+ result=response,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ cache_hit=False,+ )++ assert logging_obj.model_call_details.get("response_cost") is None+ assert logging_obj.model_call_details.get("standard_logging_object") is None+++def test_non_streaming_interactions_success_sets_response_cost_and_usage():+ import datetime as dt++ from litellm.types.interactions import InteractionsAPIResponse++ logging_obj = _interactions_logging_obj(stream=False)+ response = InteractionsAPIResponse(+ id="interactions/abc",+ model="gemini-2.5-flash",+ status="completed",+ steps=[],+ usage=dict(INTERACTIONS_USAGE_BLOCK),+ )++ logging_obj._success_handler_helper_fn(+ result=response,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ cache_hit=False,+ )++ assert logging_obj.model_call_details["response_cost"] > 0+ standard_logging_object = logging_obj.model_call_details["standard_logging_object"]+ assert standard_logging_object["prompt_tokens"] == 100+ assert standard_logging_object["completion_tokens"] == 75+ assert standard_logging_object["total_tokens"] == 175+ assert standard_logging_object["response_cost"] == logging_obj.model_call_details["response_cost"]+++def test_assembled_streaming_response_from_completed_interaction_event():+ import datetime as dt++ from litellm.types.interactions import (+ InteractionsAPIResponse,+ InteractionsAPIStreamingResponse,+ )++ logging_obj = _interactions_logging_obj(stream=True)+ completed_event = InteractionsAPIStreamingResponse(+ event_type="interaction.completed",+ interaction={+ "id": "interactions/abc",+ "model": "gemini-2.5-flash",+ "status": "completed",+ "steps": [],+ "usage": dict(INTERACTIONS_USAGE_BLOCK),+ },+ )++ assembled = logging_obj._get_assembled_streaming_response(+ result=completed_event,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ is_async=True,+ streaming_chunks=[],+ )++ assert isinstance(assembled, InteractionsAPIResponse)+ assert assembled.usage == INTERACTIONS_USAGE_BLOCK++ in_progress_event = InteractionsAPIStreamingResponse(event_type="interaction.in_progress")+ assert (+ logging_obj._get_assembled_streaming_response(+ result=in_progress_event,+ start_time=dt.datetime.now(),+ end_time=dt.datetime.now(),+ is_async=True,+ streaming_chunks=[],+ )+ is None+ )+++def test_assembled_streaming_response_from_legacy_completed_chunk():+ from litellm.types.interactions import (+ InteractionsAPIResponse,+ InteractionsAPIStreamingResponse,+ )++ legacy_chunk = InteractionsAPIStreamingResponse(+ event_type="interaction.complete",+ id="interactions/legacy",+ model="gemini-2.5-flash",+ status="completed",+ outputs=[],+ usage=dict(INTERACTIONS_USAGE_BLOCK),+ )++ assembled = LitellmLogging._assemble_completed_interaction_response(legacy_chunk)++ assert isinstance(assembled, InteractionsAPIResponse)+ assert assembled.id == "interactions/legacy"+ assert assembled.usage == INTERACTIONS_USAGE_BLOCK+++def test_standard_logging_payload_maps_interactions_usage():+ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup++ usage = StandardLoggingPayloadSetup.get_usage_from_response_obj(+ response_obj={"usage": dict(INTERACTIONS_USAGE_BLOCK)}+ )++ assert usage.prompt_tokens == 100+ assert usage.completion_tokens == 75+ assert usage.total_tokens == 175+++++ def test_pre_call_does_not_pin_request_in_module_state(logging_obj):+ """+ pre_call/post_call must not stash their locals (full messages, the Logging+ object, complete_input_dict) into module-level state. That pinned the most+ recent request's entire payload in memory for the life of the worker,+ which with multi-hundred-KB requests is a permanent per-worker leak.+ """+ litellm.error_logs.clear()+ big_input = [{"role": "user", "content": "x" * 10_000}]++ logging_obj.pre_call(input=big_input, api_key="sk-test")+ logging_obj.post_call(original_response='{"ok": true}', input=big_input, api_key="sk-test")++ assert litellm.error_logs == {}+++ def test_handle_anthropic_messages_response_logging_preserves_fast_mode_speed():+ """/v1/messages non-streaming rebuilds usage by re-transforming the raw Anthropic+ response. Anthropic's fast-mode multiplier is applied off ``usage.speed``, which the+ response body never carries, so the request's optional params have to be passed in or+ fast-mode spend is logged at the standard rate."""+ import httpx++ logging_obj = LitellmLogging(+ model="claude-opus-4-8",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="anthropic_messages",+ start_time=time.time(),+ litellm_call_id="lit-5115",+ function_id="lit-5115",+ )+ logging_obj.optional_params = {"speed": "fast"}+ logging_obj.model_call_details["httpx_response"] = httpx.Response(+ status_code=200,+ json={+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": "claude-opus-4-8",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 100},+ },+ )++ result = logging_obj._handle_anthropic_messages_response_logging(result=None)++ assert getattr(result.usage, "speed", None) == "fast"+++ def test_handle_anthropic_messages_parsed_response_logging_preserves_fast_mode_speed():+ """The Rust messages bridge hands logging a parsed Anthropic response with no+ httpx_response in model_call_details, which routes through transform_parsed_response;+ the request's speed has to be threaded there too or rust-served fast-mode calls are+ logged at the standard rate."""+ logging_obj = LitellmLogging(+ model="claude-opus-4-8",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="anthropic_messages",+ start_time=time.time(),+ litellm_call_id="lit-5115-rust",+ function_id="lit-5115-rust",+ )+ logging_obj.optional_params = {"speed": "fast"}++ result = logging_obj._handle_anthropic_messages_response_logging(+ result={+ "id": "msg_2",+ "type": "message",+ "role": "assistant",+ "model": "claude-opus-4-8",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 100},+ }+ )++ assert getattr(result.usage, "speed", None) == "fast"+++ def test_logging_init_sets_trace_id():+ """Logging.__init__() must call set_trace_id with self.litellm_trace_id."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("")++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-001",+ function_id="fn-001",+ kwargs={},+ )+ assert trace_id_var.get() == log_obj.litellm_trace_id+++ def test_logging_init_skips_stamping_when_correlation_logging_unsupported():+ """supports_correlation_logging=False (what wrapper(), the sync entry+ point, always passes) must leave trace_id_var/session_id_var completely+ untouched, even though self.litellm_trace_id/litellm_session_id (the+ plain attributes used by StandardLoggingPayload) are still populated as+ usual - only the ambient contextvar stamping is gated."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("")+ session_id_var.set("")++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-sync-excluded",+ function_id="fn-sync-excluded",+ kwargs={"litellm_session_id": "should-not-be-stamped"},+ litellm_trace_id="should-not-be-stamped-either",+ supports_correlation_logging=False,+ )++ assert trace_id_var.get() == ""+ assert session_id_var.get() == ""+ # The plain attributes are unaffected - only the contextvar stamping is gated.+ assert log_obj.litellm_trace_id == "should-not-be-stamped-either"+ assert log_obj.litellm_session_id == "should-not-be-stamped"+++ def test_logging_init_sets_session_id_when_provided():+ """Logging.__init__() must call set_session_id when litellm_session_id is in kwargs."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ session_id_var.set("")++ Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-002",+ function_id="fn-002",+ kwargs={"litellm_session_id": "my-session-99"},+ )+ assert session_id_var.get() == "my-session-99"+++ def test_logging_init_resets_session_id_to_empty_when_absent():+ """When no session_id is in kwargs, Logging.__init__() must reset session_id_var to ""+ so a prior request's session_id does not leak into subsequent log records."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ session_id_var.set("preexisting-sid")++ Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-003",+ function_id="fn-003",+ kwargs={},+ )+ assert session_id_var.get() == ""+++ def test_restore_correlation_context_resets_to_pre_call_value():+ """_restore_correlation_context() must put trace_id_var/session_id_var back to+ whatever they were immediately before this Logging instance was constructed.+ This is the mechanism that prevents a nested call (e.g. a guardrail's own+ LLM-as-judge call sharing the same asyncio Task) from leaking its trace_id/+ session_id into the outer call's subsequent log lines."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("outer-trace")+ session_id_var.set("outer-session")+ try:+ inner = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="inner-call",+ function_id="fn-inner",+ kwargs={"litellm_session_id": "inner-session"},+ )+ assert trace_id_var.get() == inner.litellm_trace_id+ assert session_id_var.get() == "inner-session"++ inner._restore_correlation_context()++ assert trace_id_var.get() == "outer-trace"+ assert session_id_var.get() == "outer-session"+ finally:+ trace_id_var.set("")+ session_id_var.set("")+++ def test_restore_correlation_context_safe_to_call_repeatedly():+ """Calling _restore_correlation_context() more than once must not raise.++ It's deliberately NOT guarded against repeat calls: wrapper()'s finally+ block and a terminal handler (success_handler/failure_handler) can both+ end up calling it for the same instance, potentially from different+ asyncio Tasks - each call needs to take effect in its own Task's view of+ the contextvars, so repeat calls are expected, not just tolerated."""+ from litellm.litellm_core_utils.litellm_logging import Logging++ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=None,+ litellm_call_id="call-idempotent",+ function_id="fn-idempotent",+ kwargs={},+ )+ log_obj._restore_correlation_context()+ log_obj._restore_correlation_context() # must not raise+++ @pytest.mark.asyncio+ async def test_restore_correlation_context_works_across_asyncio_task_boundary():+ """_restore_correlation_context() must succeed even when it's called from a+ different asyncio Task than the one Logging.__init__() ran in - exactly what+ happens on litellm's real async success path, where async_success_handler is+ dispatched via asyncio.create_task / the global logging worker rather than+ awaited directly in the request's own task.++ A contextvars.Token can only be reset in the exact Context it was created in+ and raises ValueError otherwise (verified separately against raw contextvars,+ not just this codebase). The fix uses a plain set() of the captured pre-call+ value instead, which works regardless of which Task calls it. This test+ fails with a token-based implementation - the child task's reset() would+ raise, get silently swallowed, and leave the child's view unrestored - and+ passes with the value-based one.+ """+ from litellm.litellm_core_utils.litellm_logging import Logging++ trace_id_var.set("outer-trace-cross-task")+ session_id_var.set("outer-session-cross-task")+ try:+ # __init__ runs in THIS (outer) task's context.+ log_obj = Logging(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="acompletion",+ start_time=None,+ litellm_call_id="cross-task-call",+ function_id="fn-cross-task",+ kwargs={"litellm_session_id": "cross-task-session"},+ )+ assert trace_id_var.get() == log_obj.litellm_trace_id+ assert session_id_var.get() == "cross-task-session"++ async def restore_in_new_task():+ # Simulates async_success_handler running in a task spawned after+ # __init__ already ran elsewhere - a different Context object.+ log_obj._restore_correlation_context()+ return trace_id_var.get(), session_id_var.get()++ trace_in_child, session_in_child = await asyncio.create_task(restore_in_new_task())++ assert trace_in_child == "outer-trace-cross-task"+ assert session_in_child == "outer-session-cross-task"+ finally:+ trace_id_var.set("")+ session_id_var.set("")+++ def _build_success_payload(logging_obj, kwargs):+ import datetime++ from litellm.litellm_core_utils.litellm_logging import (+ get_standard_logging_object_payload,+ )++ now = datetime.datetime.now()+ return get_standard_logging_object_payload(+ kwargs=kwargs,+ init_response_obj={},+ start_time=now,+ end_time=now,+ logging_obj=logging_obj,+ status="success",+ )+++ def _guardrail_kwargs(response_cost):+ return {+ "litellm_call_id": "guardrail-cost-call",+ "model": "gpt-4o",+ "messages": [],+ "response_cost": response_cost,+ "litellm_params": {+ "metadata": {+ "standard_logging_guardrail_information": [+ {+ "guardrail_name": "bedrock-pre",+ "guardrail_status": "success",+ "guardrail_usage": {"topicPolicyUnits": 1, "contentPolicyUnits": 1},+ "guardrail_cost": 0.0003,+ },+ {"guardrail_name": "no-usage-guardrail", "guardrail_status": "success"},+ ]+ }+ },+ }+++ def test_payload_response_cost_includes_guardrail_cost(logging_obj):+ """LIT-5651: provider-billed guardrail cost must count in response_cost."""+ payload = _build_success_payload(logging_obj, _guardrail_kwargs(response_cost=0.0000429))++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"] is not None+ assert payload["cost_breakdown"]["guardrail_cost"] == pytest.approx(0.0003)+ assert payload["cost_breakdown"]["total_cost"] == pytest.approx(0.0003)+ assert payload["hidden_params"]["response_cost"] == pytest.approx(0.0000429)+++ def test_payload_guardrail_cost_merges_into_existing_cost_breakdown(logging_obj):+ logging_obj.set_cost_breakdown(+ input_cost=0.00003,+ output_cost=0.0000129,+ total_cost=0.0000429,+ cost_for_built_in_tools_cost_usd_dollar=0.0,+ )+ payload = _build_success_payload(logging_obj, _guardrail_kwargs(response_cost=0.0000429))++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"]["guardrail_cost"] == pytest.approx(0.0003)+ assert payload["cost_breakdown"]["total_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"]["input_cost"] == pytest.approx(0.00003)+ assert logging_obj.cost_breakdown["total_cost"] == pytest.approx(0.0000429)+++ def test_payload_without_guardrail_cost_is_unchanged(logging_obj):+ kwargs = {+ "litellm_call_id": "no-guardrail-call",+ "model": "gpt-4o",+ "messages": [],+ "response_cost": 0.0000429,+ "litellm_params": {"metadata": {}},+ }+ payload = _build_success_payload(logging_obj, kwargs)++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0000429)+ assert payload["cost_breakdown"] is None+++ _AWS_SECRET = "wJalrXUtnFEMIK7MDENGbPxRfiCYEXAMPLEKEY"+ _GEMINI_KEY = "AIzaSyC0000000000000000000000000000000"+++ def test_empty_api_base_does_not_dump_call_state(logging_obj):+ """Direct (non-HTTP) providers pass api_base='', which used to echo model_call_details."""+ logging_obj.model_call_details["litellm_params"] = {+ "api_key": "sk-proj-hunter2hunter2hunter2hunter2",+ "aws_secret_access_key": _AWS_SECRET,+ }++ curl_command = logging_obj._get_request_curl_command(+ api_base="",+ headers={},+ additional_args={},+ data={"model": "some-model"},+ )++ assert "litellm_call_id" not in curl_command+ assert _AWS_SECRET not in curl_command+ assert "hunter2" not in curl_command+++ def test_pre_call_redacts_and_masks_raw_request(logging_obj):+ """log_raw_request_response echoes the request body and api_base back to loggers/UI."""+ metadata = {"user_api_key_alias": "qa-key"}+ logging_obj.model_call_details["litellm_params"] = {"metadata": metadata}+ logging_obj.log_raw_request_response = True++ logging_obj.pre_call(+ input="hi",+ api_key="",+ additional_args={+ "api_base": f"https://generativelanguage.googleapis.com/v1beta/models/x:generateContent?key={_GEMINI_KEY}",+ "headers": {},+ "complete_input_dict": {"aws_secret_access_key": _AWS_SECRET},+ },+ )++ raw_request = metadata["raw_request"]+ assert _AWS_SECRET not in raw_request+ assert "REDACTED" in raw_request++ raw_api_base = logging_obj.model_call_details["raw_request_typed_dict"]["raw_request_api_base"]+ assert _GEMINI_KEY not in raw_api_base+ assert "key=*****" in raw_api_base+++ def _resolve(custom_llm_provider, litellm_params, optional_params, model):+ from litellm.litellm_core_utils.litellm_logging import (+ _resolve_vertex_location_for_cost,+ )++ return _resolve_vertex_location_for_cost(+ custom_llm_provider=custom_llm_provider,+ litellm_params=litellm_params,+ optional_params=optional_params,+ model=model,+ )+++ def test_resolve_vertex_location_for_cost():+ """Vertex requests resolve the serving location the way dispatch does; other providers get None."""+ assert _resolve("openai", {"vertex_location": "us-east5"}, None, "gpt-4o") is None+ assert _resolve(None, {}, None, "gemini-3.5-flash") is None+ assert _resolve("vertex_ai", {"vertex_location": "us-east5"}, None, "gemini-3.5-flash") == "us-east5"+ assert _resolve("vertex_ai", {"vertex_location": "global"}, None, "gemini-3.5-flash") == "global"+ assert (+ _resolve("vertex_ai_beta", {"vertex_ai_location": "europe-west1"}, None, "claude-haiku-4-5@20251001")+ == "europe-west1"+ )+++ def test_resolve_vertex_location_for_cost_reads_optional_params(monkeypatch):+ """+ On the proxy the logging object predates deployment selection, so the deployment's+ configured location only reaches it through optional_params. A configured global+ location must beat the environment fallback, or every proxy call gets the regional uplift.+ """+ monkeypatch.setenv("VERTEXAI_LOCATION", "us-east5")+ monkeypatch.setattr(litellm, "vertex_location", None)++ assert _resolve("vertex_ai", {}, {"vertex_location": "global"}, "gemini-3.5-flash") == "global"+ assert _resolve("vertex_ai", None, {"vertex_location": "europe-west1"}, "gemini-3.5-flash") == "europe-west1"+ assert (+ _resolve(+ "vertex_ai",+ {"vertex_location": "us-east5"},+ {"vertex_location": "global"},+ "gemini-3.5-flash",+ )+ == "global"+ )+ assert _resolve("vertex_ai", {"vertex_location": "global"}, {}, "gemini-3.5-flash") == "global"+ assert _resolve("vertex_ai", {}, {}, "gemini-3.5-flash") == "us-east5"+++ def test_resolve_vertex_location_for_cost_default_region(monkeypatch):+ """With no location configured anywhere, resolution lands on the dispatch default us-central1."""+ monkeypatch.delenv("VERTEXAI_LOCATION", raising=False)+ monkeypatch.delenv("VERTEX_LOCATION", raising=False)+ monkeypatch.setattr(litellm, "vertex_location", None)++ assert _resolve("vertex_ai", {}, None, "gemini-3.5-flash") == "us-central1"+ assert _resolve("vertex_ai", None, None, "gemini-3.5-flash") == "us-central1"+++ def test_response_cost_calculator_prices_proxy_vertex_calls_on_the_configured_location(monkeypatch):+ """+ Proxy-shaped logging objects (created before the router picks a deployment) carry the+ deployment's vertex_location only in optional_params. A global deployment must price at+ base rates even when the environment points at a regional location, and a regional one+ must price with the uplift.+ """+ from datetime import datetime++ from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map++ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")+ monkeypatch.setattr(litellm, "model_cost", get_model_cost_map(url=""))+ monkeypatch.setenv("VERTEXAI_LOCATION", "us-east5")+ monkeypatch.setattr(litellm, "vertex_location", None)++ def cost_at(location):+ logging_obj = LitellmLogging(+ model="gemini-3.5-flash",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=datetime.now(),+ litellm_call_id=f"vertex-loc-{location}",+ function_id="f",+ )+ logging_obj.update_environment_variables(+ model="gemini-3.5-flash",+ user="",+ optional_params={"vertex_location": location},+ litellm_params={"api_base": ""},+ custom_llm_provider="vertex_ai",+ )+ response = ModelResponse(+ id="resp-1",+ model="gemini-3.5-flash",+ choices=[{"message": {"role": "assistant", "content": "hello"}, "index": 0, "finish_reason": "stop"}],+ usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ )+ return logging_obj._response_cost_calculator(result=response)++ info = litellm.model_cost["vertex_ai/gemini-3.5-flash"]+ expected_global = 10 * info["input_cost_per_token"] + 5 * info["output_cost_per_token"]++ assert cost_at("global") == pytest.approx(expected_global)+ assert cost_at("us-east5") == pytest.approx(info["regional_endpoint_uplift_multiplier"] * expected_global)+++ def test_set_cost_breakdown_stores_vertex_location():+ """vertex_location is recorded in the pricing basis, None for non-vertex requests."""+ from datetime import datetime++ logging_obj = LitellmLogging(+ model="vertex_ai/claude-haiku-4-5@20251001",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=datetime.now(),+ litellm_call_id="vertex-location-set",+ function_id="f",+ )+ logging_obj.set_cost_breakdown(+ input_cost=0.001,+ output_cost=0.002,+ total_cost=0.003,+ cost_for_built_in_tools_cost_usd_dollar=0.0,+ vertex_location="us-east5",+ )+ assert logging_obj.cost_breakdown["vertex_location"] == "us-east5"++ no_location = LitellmLogging(+ model="gpt-4o",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="completion",+ start_time=datetime.now(),+ litellm_call_id="vertex-location-absent",+ function_id="f",+ )+ no_location.set_cost_breakdown(+ input_cost=0.001,+ output_cost=0.002,+ total_cost=0.003,+ cost_for_built_in_tools_cost_usd_dollar=0.0,+ )+ assert no_location.cost_breakdown.get("vertex_location") is None+++ def test_prompt_hooks_skip_prompt_managers_when_no_prompt_id(logging_obj, tmp_path, monkeypatch):+ """+ Regression for UI-injected `vector_store_ids: []` and always-on non-empty `vector_store_ids`+ with a registered prompt manager (e.g. dotprompt): requests without a prompt_id 500'd with+ "prompt_id is required for Prompt Management Base class" instead of completing normally.+ """+ from litellm.integrations.arize.arize_phoenix_prompt_manager import ArizePhoenixPromptManager+ from litellm.integrations.dotprompt.dotprompt_manager import DotpromptManager+ from litellm.integrations.vector_store_integrations.base_vector_store import BaseVectorStore+ from litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (+ VectorStorePreCallHook,+ )+ from litellm.types.vector_stores import LiteLLM_ManagedVectorStore+ from litellm.vector_stores.vector_store_registry import VectorStoreRegistry++ (tmp_path / "stem.prompt").write_text("---\nmodel: gemini-2.5-flash\n---\nyou are a stem tutor\n")+ dotprompt_manager = DotpromptManager(prompt_directory=str(tmp_path))+ arize_manager = ArizePhoenixPromptManager(api_key="fake-key", api_base="http://127.0.0.1:9")+ litellm.logging_callback_manager.add_litellm_callback(dotprompt_manager)+ litellm.logging_callback_manager.add_litellm_callback(arize_manager)+ monkeypatch.setattr(+ litellm,+ "vector_store_registry",+ VectorStoreRegistry(+ vector_stores=[LiteLLM_ManagedVectorStore(vector_store_id="vs_123", custom_llm_provider="openai")]+ ),+ )++ messages = [{"role": "user", "content": "hi"}]+ try:+ assert not logging_obj.should_run_prompt_management_hooks(+ prompt_id=None, non_default_params={"vector_store_ids": []}+ )++ assert logging_obj.get_chat_completion_prompt(+ model="gemini-2.5-flash",+ messages=messages,+ non_default_params={"vector_store_ids": []},+ prompt_variables=None,+ prompt_id=None,+ ) == ("gemini-2.5-flash", messages, {"vector_store_ids": []})++ assert dotprompt_manager.get_chat_completion_prompt(+ model="gemini-2.5-flash",+ messages=messages,+ non_default_params={},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ ) == ("gemini-2.5-flash", messages, {})++ assert not arize_manager.should_run_prompt_management(+ prompt_id=None, prompt_spec=None, dynamic_callback_params={}+ )++ assert logging_obj.should_run_prompt_management_hooks(+ prompt_id=None, non_default_params={"vector_store_ids": ["vs_123"]}+ )+ selected_logger = logging_obj.get_custom_logger_for_prompt_management(+ model="gemini-2.5-flash",+ non_default_params={"vector_store_ids": ["vs_123"]},+ prompt_id=None,+ dynamic_callback_params={},+ )+ assert isinstance(selected_logger, VectorStorePreCallHook)++ assert logging_obj._prompt_manager_runs_without_prompt_id(+ logger=BaseVectorStore(), prompt_spec=None, dynamic_callback_params=None+ )+ assert not logging_obj._prompt_manager_runs_without_prompt_id(+ logger=selected_logger, prompt_spec=None, dynamic_callback_params=None+ )+ assert not logging_obj._prompt_manager_runs_without_prompt_id(+ logger=dotprompt_manager, prompt_spec=None, dynamic_callback_params=None+ )+ assert not logging_obj._prompt_manager_runs_without_prompt_id(+ logger=arize_manager, prompt_spec=None, dynamic_callback_params=None+ )++ assert isinstance(+ logging_obj.get_custom_logger_for_prompt_management(+ model="gemini-2.5-flash",+ non_default_params={},+ prompt_id="stem",+ dynamic_callback_params={},+ ),+ DotpromptManager,+ )+ finally:+ for manager in (dotprompt_manager, arize_manager):+ litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, manager)+ litellm.logging_callback_manager.remove_callback_from_list_by_object(+ litellm._async_success_callback, manager+ )+ for hook in [cb for cb in litellm.callbacks if isinstance(cb, VectorStorePreCallHook)]:+ litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, hook)diff --cc tests/test_litellm/llms/azure/test_azure_common_utils.pyindex 413241adf37,f2c852e9509..f94995828ca--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py@@@ -446,6 -413,6 +413,7 @@@ def test_select_azure_base_url_called(s"avector_store_create","avector_store_search","acreate_skill",++ "acreate_interaction",]],)diff --cc tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.pyindex 725e7f22f7d,871f4b4bcd1..642db7e2d5d--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py@@@ -604,134 -731,6 +731,134 @@@ async def test_track_cost_callback_skipmock_proxy_logging.failed_tracking_alert.assert_not_called()- async def test_track_cost_callback_defers_in_progress_background_interaction():++async def test_track_cost_callback_defers_in_progress_background_interaction(): # test-quality-ok: writing no spend row and raising no alert is the whole observable contract of the deferral path+ """+ A background=true interaction create returns in_progress with no usage+ block, so its success event has a model but no standard_logging_object.+ The callback must skip quietly (billing happens later via the background+ poll task) instead of raising 'Cost tracking failed' and alerting.+ """+ from litellm.types.interactions import InteractionsAPIResponse++ logger = _ProxyDBLogger()++ kwargs = {+ "call_type": "acreate_interaction",+ "model": "gemini/gemini-3-flash-preview",+ "litellm_call_id": "test-call-id",+ "litellm_params": {},+ "stream": False,+ }+ in_progress_response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status="in_progress",+ )++ with patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ ) as mock_proxy_logging:+ mock_proxy_logging.failed_tracking_alert = AsyncMock()+ mock_proxy_logging.db_spend_update_writer = MagicMock()+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()++ await logger._PROXY_track_cost_callback(+ kwargs=kwargs,+ completion_response=in_progress_response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ mock_proxy_logging.db_spend_update_writer.update_database.assert_not_called()+ mock_proxy_logging.failed_tracking_alert.assert_not_called()+++def _in_progress_interaction_kwargs(reservation: dict) -> dict:+ return {+ "call_type": "acreate_interaction",+ "model": "gemini/gemini-3-flash-preview",+ "litellm_call_id": "test-call-id",+ "litellm_params": {"metadata": {"user_api_key_budget_reservation": reservation}},+ "stream": False,+ }+++async def test_track_cost_callback_keeps_reservation_open_for_in_progress_background_interaction():+ """+ The pre-call budget reservation must stay open while a background+ interaction is in flight, so concurrent creates cannot stack past the+ budget; the poll task's completion event reconciles it to the actual cost.+ """+ from litellm.types.interactions import InteractionsAPIResponse++ logger = _ProxyDBLogger()+ reservation = {"reserved_cost": 0.05, "entries": [], "finalized": False}+ in_progress_response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status="in_progress",+ )++ with patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ ) as mock_proxy_logging:+ mock_proxy_logging.failed_tracking_alert = AsyncMock()+ mock_proxy_logging.db_spend_update_writer = MagicMock()+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()++ await logger._PROXY_track_cost_callback(+ kwargs=_in_progress_interaction_kwargs(reservation),+ completion_response=in_progress_response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ assert reservation["finalized"] is False+ mock_proxy_logging.failed_tracking_alert.assert_not_called()+++async def test_track_cost_callback_releases_reservation_for_in_progress_interaction_when_polling_disabled(+ monkeypatch,+):+ """+ With the poll task kill switch off nothing will ever reconcile the+ reservation, so the callback must release it or the spend counters stay+ pinned at the estimated cost forever.+ """+ import litellm.proxy.hooks.proxy_track_cost_callback as callback_module+ from litellm.types.interactions import InteractionsAPIResponse++ monkeypatch.setattr(callback_module, "BACKGROUND_INTERACTION_COST_POLLING_ENABLED", False)++ logger = _ProxyDBLogger()+ reservation = {"reserved_cost": 0.05, "entries": [], "finalized": False}+ in_progress_response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status="in_progress",+ )++ with patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ ) as mock_proxy_logging:+ mock_proxy_logging.failed_tracking_alert = AsyncMock()+ mock_proxy_logging.db_spend_update_writer = MagicMock()+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()++ await logger._PROXY_track_cost_callback(+ kwargs=_in_progress_interaction_kwargs(reservation),+ completion_response=in_progress_response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ assert reservation["finalized"] is True+ mock_proxy_logging.failed_tracking_alert.assert_not_called()++@pytest.mark.asyncioasync def test_async_post_call_failure_hook_propagates_trace_id_from_logging_obj():"""diff --cc tests/test_litellm/test_cost_calculator.pyindex b144c614474,8dad4bef07b..1f1c9be973f--- a/tests/test_litellm/test_cost_calculator.py+++ b/tests/test_litellm/test_cost_calculator.py@@@ -3481,99 -3584,102 +3584,200 @@@ def test_batch_cost_calculator_cache_crassert prompt_cost == pytest.approx((1000 * 3e-6 + 8000 * 3e-7 + 2000 * 3e-6) / 2)+def test_completion_cost_bills_interactions_api_response():+ from litellm.types.interactions import InteractionsAPIResponse++ model_info = litellm.get_model_info(model="gemini-2.5-flash", custom_llm_provider="gemini")+ response = InteractionsAPIResponse(+ id="interactions/abc123",+ model="gemini-2.5-flash",+ status="completed",+ steps=[],+ usage={+ "total_tokens": 175,+ "total_input_tokens": 100,+ "input_tokens_by_modality": [{"modality": "text", "tokens": 100}],+ "total_cached_tokens": 0,+ "total_output_tokens": 50,+ "output_tokens_by_modality": [{"modality": "text", "tokens": 50}],+ "total_tool_use_tokens": 0,+ "total_thought_tokens": 25,+ },+ )++ cost = completion_cost(completion_response=response, custom_llm_provider="gemini")++ reasoning_rate = model_info.get("output_cost_per_reasoning_token") or model_info["output_cost_per_token"]+ expected = (+ 100 * model_info["input_cost_per_token"]+ + 50 * model_info["output_cost_per_token"]+ + 25 * reasoning_rate+ )+ assert cost == pytest.approx(expected)+ assert cost > 0+++def test_completion_cost_bills_interactions_google_search_per_query():+ from litellm.types.interactions import InteractionsAPIResponse++ model_info = litellm.get_model_info(model="gemini-3-flash-preview", custom_llm_provider="gemini")+ response = InteractionsAPIResponse(+ id="interactions/search123",+ model="gemini-3-flash-preview",+ status="completed",+ steps=[],+ usage={+ "total_tokens": 680,+ "total_input_tokens": 103,+ "input_tokens_by_modality": [{"modality": "text", "tokens": 103}],+ "total_cached_tokens": 0,+ "total_output_tokens": 226,+ "total_tool_use_tokens": 0,+ "total_thought_tokens": 351,+ "grounding_tool_count": [{"type": "google_search", "count": 3}],+ },+ )++ cost = completion_cost(completion_response=response, custom_llm_provider="gemini")++ per_query_cost = model_info["search_context_cost_per_query"]["search_context_size_medium"]+ reasoning_rate = model_info.get("output_cost_per_reasoning_token") or model_info["output_cost_per_token"]+ expected = (+ 103 * model_info["input_cost_per_token"]+ + 226 * model_info["output_cost_per_token"]+ + 351 * reasoning_rate+ + 3 * per_query_cost+ )+ assert model_info.get("web_search_billing_unit") == "per_query"+ assert cost == pytest.approx(expected)+ assert cost > 3 * per_query_cost+++def test_completion_cost_bills_interactions_video_output_at_video_rate():+ from litellm.types.interactions import InteractionsAPIResponse++ model_info = litellm.get_model_info(model="gemini-omni-flash-preview", custom_llm_provider="gemini")+ video_tokens = 5792 * 8+ response = InteractionsAPIResponse(+ id="interactions/video123",+ model="gemini-omni-flash-preview",+ status="completed",+ steps=[],+ usage={+ "total_tokens": 10 + video_tokens,+ "total_input_tokens": 10,+ "input_tokens_by_modality": [{"modality": "text", "tokens": 10}],+ "total_cached_tokens": 0,+ "total_output_tokens": video_tokens,+ "output_tokens_by_modality": [{"modality": "video", "tokens": video_tokens}],+ "total_tool_use_tokens": 0,+ "total_thought_tokens": 0,+ },+ )++ cost = completion_cost(completion_response=response, custom_llm_provider="gemini")++ expected = 10 * model_info["input_cost_per_token"] + video_tokens * model_info["output_cost_per_video_token"]+ assert model_info["output_cost_per_video_token"] != model_info["output_cost_per_token"]+ assert cost == pytest.approx(expected)+++++ @pytest.mark.parametrize(+ "batch_rate,expected_prompt,expected_completion",+ [+ (0.0, 0.0, 0.0),+ (1e-6, 1000 * 1e-6, 500 * 1e-6),+ (None, 1000 * 3e-6 / 2, 500 * 15e-6 / 2),+ ],+ ids=["explicit-zero", "explicit-nonzero", "unset"],+ )+ def test_batch_cost_calculator_honors_an_explicitly_zero_batch_rate(+ batch_rate: float | None,+ expected_prompt: float,+ expected_completion: float,+ ) -> None:+ """A batch rate configured as 0.0 means free, not unset.++ Gating the batch fields on truthiness read an explicit 0.0 as absent and+ charged half the standard rate for that token direction instead.+ """+ from litellm.cost_calculator import batch_cost_calculator++ base_model_info: ModelInfo = {+ "supported_openai_params": [],+ "input_cost_per_token": 3e-6,+ "output_cost_per_token": 15e-6,+ }+ model_info: ModelInfo = (+ base_model_info+ if batch_rate is None+ else {+ **base_model_info,+ "input_cost_per_token_batches": batch_rate,+ "output_cost_per_token_batches": batch_rate,+ }+ )++ prompt_cost, completion_cost_value = batch_cost_calculator(+ usage=Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500),+ model="claude-sonnet-4-5-20250929",+ custom_llm_provider="anthropic",+ model_info=model_info,+ )++ assert prompt_cost == pytest.approx(expected_prompt)+ assert completion_cost_value == pytest.approx(expected_completion)+++ def test_combine_usage_objects_sums_mirrored_cache_write_fields_once():+ """+ cache_write_tokens and cache_creation_tokens mirror each other on+ PromptTokensDetailsWrapper, so field-iterating aggregation must sum the pair+ once: a single 50-token usage stays 50 and two combine to 100, not double.+ """+ single = Usage(+ prompt_tokens=100,+ completion_tokens=10,+ total_tokens=110,+ prompt_tokens_details=PromptTokensDetailsWrapper(cache_write_tokens=50),+ )+ combined = BaseTokenUsageProcessor.combine_usage_objects([single])+ assert combined.prompt_tokens_details is not None+ assert combined.prompt_tokens_details.cache_write_tokens == 50+ assert combined.prompt_tokens_details.cache_creation_tokens == 50++ anthropic_style = Usage(+ prompt_tokens=100,+ completion_tokens=10,+ total_tokens=110,+ cache_creation_input_tokens=50,+ )+ combined_pair = BaseTokenUsageProcessor.combine_usage_objects([anthropic_style, anthropic_style])+ assert combined_pair.prompt_tokens_details is not None+ assert combined_pair.prompt_tokens_details.cache_write_tokens == 100+ assert combined_pair.prompt_tokens_details.cache_creation_tokens == 100+++ def test_completion_cost_prices_anthropic_shaped_cache_read_tokens(_local_model_cost_map):+ """Regression: an Anthropic /v1/messages response reports cache reads as top-level+ cache_read_input_tokens with input_tokens excluding them. Reading that usage as+ Responses API usage dropped the cache tokens and billed the whole prompt at the+ uncached input rate, overstating spend on cache hits."""++ response = {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": "gpt-5.6-sol",+ "stop_reason": "end_turn",+ "content": [{"type": "text", "text": "1"}],+ "usage": {"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 4014},+ }++ cost = litellm.completion_cost(+ completion_response=response,+ model="gpt-5.6-sol",+ custom_llm_provider="openai",+ )++ assert cost == pytest.approx(3 * 4e-6 + 4014 * 4e-7 + 5 * 2e-5, rel=1e-9)diff --cc ui/litellm-dashboard/src/lib/http/schema.d.tsindex 547e84a3cd2,cf55dc69e86..43b139a2549--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@@ -21685,7 -23142,7 +23142,7 @@@ export interface components* CallTypes* @enum {string}*/- CallTypes: "embedding" | "aembedding" | "completion" | "acompletion" | "atext_completion" | "text_completion" | "image_generation" | "aimage_generation" | "image_edit" | "aimage_edit" | "moderation" | "amoderation" | "atranscription" | "transcription" | "aspeech" | "speech" | "rerank" | "arerank" | "search" | "asearch" | "_arealtime" | "_aresponses_websocket" | "create_batch" | "acreate_batch" | "aretrieve_batch" | "retrieve_batch" | "acancel_batch" | "cancel_batch" | "pass_through_endpoint" | "anthropic_messages" | "get_assistants" | "aget_assistants" | "create_assistants" | "acreate_assistants" | "delete_assistant" | "adelete_assistant" | "acreate_thread" | "create_thread" | "aget_thread" | "get_thread" | "a_add_message" | "add_message" | "aget_messages" | "get_messages" | "arun_thread" | "run_thread" | "arun_thread_stream" | "run_thread_stream" | "afile_retrieve" | "file_retrieve" | "afile_delete" | "file_delete" | "afile_list" | "file_list" | "acreate_file" | "create_file" | "afile_content" | "file_content" | "create_fine_tuning_job" | "acreate_fine_tuning_job" | "create_video" | "acreate_video" | "avideo_retrieve" | "video_retrieve" | "avideo_content" | "video_content" | "video_remix" | "avideo_remix" | "video_list" | "avideo_list" | "video_retrieve_job" | "avideo_retrieve_job" | "video_delete" | "avideo_delete" | "video_create_character" | "avideo_create_character" | "video_get_character" | "avideo_get_character" | "video_edit" | "avideo_edit" | "video_extension" | "avideo_extension" | "vector_store_file_create" | "avector_store_file_create" | "vector_store_file_list" | "avector_store_file_list" | "vector_store_file_retrieve" | "avector_store_file_retrieve" | "vector_store_file_content" | "avector_store_file_content" | "vector_store_file_update" | "avector_store_file_update" | "vector_store_file_delete" | "avector_store_file_delete" | "vector_store_create" | "avector_store_create" | "vector_store_search" | "avector_store_search" | "create_interaction" | "acreate_interaction" | "create_container" | "acreate_container" | "list_containers" | "alist_containers" | "retrieve_container" | "aretrieve_container" | "delete_container" | "adelete_container" | "list_container_files" | "alist_container_files" | "upload_container_file" | "aupload_container_file" | "create_sandbox" | "acreate_sandbox" | "delete_sandbox" | "adelete_sandbox" | "run_code" | "arun_code" | "code_interpreter_tool" | "acode_interpreter_tool" | "acancel_fine_tuning_job" | "cancel_fine_tuning_job" | "alist_fine_tuning_jobs" | "list_fine_tuning_jobs" | "aretrieve_fine_tuning_job" | "retrieve_fine_tuning_job" | "responses" | "aresponses" | "alist_input_items" | "llm_passthrough_route" | "allm_passthrough_route" | "generate_content" | "agenerate_content" | "generate_content_stream" | "agenerate_content_stream" | "ocr" | "aocr" | "call_mcp_tool" | "list_mcp_tools" | "asend_message" | "send_message" | "acreate_skill";- CallTypes: "embedding" | "aembedding" | "completion" | "acompletion" | "atext_completion" | "text_completion" | "image_generation" | "aimage_generation" | "image_edit" | "aimage_edit" | "moderation" | "amoderation" | "atranscription" | "transcription" | "aspeech" | "speech" | "rerank" | "arerank" | "search" | "asearch" | "_arealtime" | "_aresponses_websocket" | "create_batch" | "acreate_batch" | "aretrieve_batch" | "retrieve_batch" | "acancel_batch" | "cancel_batch" | "pass_through_endpoint" | "anthropic_messages" | "aanthropic_messages" | "get_assistants" | "aget_assistants" | "create_assistants" | "acreate_assistants" | "delete_assistant" | "adelete_assistant" | "acreate_thread" | "create_thread" | "aget_thread" | "get_thread" | "a_add_message" | "add_message" | "aget_messages" | "get_messages" | "arun_thread" | "run_thread" | "arun_thread_stream" | "run_thread_stream" | "afile_retrieve" | "file_retrieve" | "afile_delete" | "file_delete" | "afile_list" | "file_list" | "acreate_file" | "create_file" | "afile_content" | "file_content" | "create_fine_tuning_job" | "acreate_fine_tuning_job" | "create_video" | "acreate_video" | "avideo_retrieve" | "video_retrieve" | "avideo_content" | "video_content" | "video_remix" | "avideo_remix" | "video_list" | "avideo_list" | "video_retrieve_job" | "avideo_retrieve_job" | "video_delete" | "avideo_delete" | "video_create_character" | "avideo_create_character" | "video_get_character" | "avideo_get_character" | "video_edit" | "avideo_edit" | "video_extension" | "avideo_extension" | "vector_store_file_create" | "avector_store_file_create" | "vector_store_file_list" | "avector_store_file_list" | "vector_store_file_retrieve" | "avector_store_file_retrieve" | "vector_store_file_content" | "avector_store_file_content" | "vector_store_file_update" | "avector_store_file_update" | "vector_store_file_delete" | "avector_store_file_delete" | "vector_store_create" | "avector_store_create" | "vector_store_search" | "avector_store_search" | "ingest" | "aingest" | "query" | "aquery" | "create_container" | "acreate_container" | "list_containers" | "alist_containers" | "retrieve_container" | "aretrieve_container" | "delete_container" | "adelete_container" | "list_container_files" | "alist_container_files" | "upload_container_file" | "aupload_container_file" | "create_sandbox" | "acreate_sandbox" | "delete_sandbox" | "adelete_sandbox" | "run_code" | "arun_code" | "code_interpreter_tool" | "acode_interpreter_tool" | "acancel_fine_tuning_job" | "cancel_fine_tuning_job" | "alist_fine_tuning_jobs" | "list_fine_tuning_jobs" | "aretrieve_fine_tuning_job" | "retrieve_fine_tuning_job" | "responses" | "aresponses" | "alist_input_items" | "llm_passthrough_route" | "allm_passthrough_route" | "generate_content" | "agenerate_content" | "generate_content_stream" | "agenerate_content_stream" | "ocr" | "aocr" | "call_mcp_tool" | "list_mcp_tools" | "asend_message" | "send_message" | "acreate_skill";++ CallTypes: "embedding" | "aembedding" | "completion" | "acompletion" | "atext_completion" | "text_completion" | "image_generation" | "aimage_generation" | "image_edit" | "aimage_edit" | "moderation" | "amoderation" | "atranscription" | "transcription" | "aspeech" | "speech" | "rerank" | "arerank" | "search" | "asearch" | "_arealtime" | "_aresponses_websocket" | "create_batch" | "acreate_batch" | "aretrieve_batch" | "retrieve_batch" | "acancel_batch" | "cancel_batch" | "pass_through_endpoint" | "anthropic_messages" | "aanthropic_messages" | "get_assistants" | "aget_assistants" | "create_assistants" | "acreate_assistants" | "delete_assistant" | "adelete_assistant" | "acreate_thread" | "create_thread" | "aget_thread" | "get_thread" | "a_add_message" | "add_message" | "aget_messages" | "get_messages" | "arun_thread" | "run_thread" | "arun_thread_stream" | "run_thread_stream" | "afile_retrieve" | "file_retrieve" | "afile_delete" | "file_delete" | "afile_list" | "file_list" | "acreate_file" | "create_file" | "afile_content" | "file_content" | "create_fine_tuning_job" | "acreate_fine_tuning_job" | "create_video" | "acreate_video" | "avideo_retrieve" | "video_retrieve" | "avideo_content" | "video_content" | "video_remix" | "avideo_remix" | "video_list" | "avideo_list" | "video_retrieve_job" | "avideo_retrieve_job" | "video_delete" | "avideo_delete" | "video_create_character" | "avideo_create_character" | "video_get_character" | "avideo_get_character" | "video_edit" | "avideo_edit" | "video_extension" | "avideo_extension" | "vector_store_file_create" | "avector_store_file_create" | "vector_store_file_list" | "avector_store_file_list" | "vector_store_file_retrieve" | "avector_store_file_retrieve" | "vector_store_file_content" | "avector_store_file_content" | "vector_store_file_update" | "avector_store_file_update" | "vector_store_file_delete" | "avector_store_file_delete" | "vector_store_create" | "avector_store_create" | "vector_store_search" | "avector_store_search" | "ingest" | "aingest" | "query" | "aquery" | "create_interaction" | "acreate_interaction" | "create_container" | "acreate_container" | "list_containers" | "alist_containers" | "retrieve_container" | "aretrieve_container" | "delete_container" | "adelete_container" | "list_container_files" | "alist_container_files" | "upload_container_file" | "aupload_container_file" | "create_sandbox" | "acreate_sandbox" | "delete_sandbox" | "adelete_sandbox" | "run_code" | "arun_code" | "code_interpreter_tool" | "acode_interpreter_tool" | "acancel_fine_tuning_job" | "cancel_fine_tuning_job" | "alist_fine_tuning_jobs" | "list_fine_tuning_jobs" | "aretrieve_fine_tuning_job" | "retrieve_fine_tuning_job" | "responses" | "aresponses" | "alist_input_items" | "llm_passthrough_route" | "allm_passthrough_route" | "generate_content" | "agenerate_content" | "generate_content_stream" | "agenerate_content_stream" | "ocr" | "aocr" | "call_mcp_tool" | "list_mcp_tools" | "asend_message" | "send_message" | "acreate_skill";/** CallbackDelete */CallbackDelete: {/** Callback Name */