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
fix(anthropic): preserve speed=fast in usage for /v1/messages and pass-through
Devin AI81a80b8c632a
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex c2dc7189934..15330a2a910 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -3278,7 +3278,7 @@ class Logging(LiteLLMLoggingBaseClass):model=self.model,messages=[],logging_obj=self,- optional_params={},+ optional_params=self.optional_params or {},api_key="",request_data={},encoding=litellm.encoding,diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.pyindex d52d9849310..5ceb64547a0 100644--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py@@ -569,6 +569,8 @@ class ChunkProcessor:# lost and 1h cache writes get billed at the 5m rate.cache_creation_token_details: Optional[CacheCreationTokenDetails] = Nonecost: Optional[float] = None+ inference_geo: Optional[str] = None+ speed: Optional[str] = Nonefor chunk in chunks:usage_chunk = self._extract_usage_chunk(chunk)@@ -627,6 +629,13 @@ class ChunkProcessor:if usage_chunk_dict["cost"] is not None:cost = usage_chunk_dict["cost"]+ chunk_inference_geo = getattr(usage_chunk, "inference_geo", None)+ if isinstance(chunk_inference_geo, str):+ inference_geo = chunk_inference_geo+ chunk_speed = getattr(usage_chunk, "speed", None)+ if isinstance(chunk_speed, str):+ speed = chunk_speed+prompt_tokens_details = self._attach_cache_creation_token_details(prompt_tokens_details, cache_creation_token_details)@@ -647,6 +656,8 @@ class ChunkProcessor:completion_tokens_details=completion_tokens_details,prompt_tokens_details=prompt_tokens_details,cost=cost,+ inference_geo=inference_geo,+ speed=speed,)@staticmethod@@ -806,6 +817,11 @@ class ChunkProcessor:if cost is not None:setattr(returned_usage, "cost", cost)+ if calculated_usage_per_chunk["inference_geo"] is not None:+ setattr(returned_usage, "inference_geo", calculated_usage_per_chunk["inference_geo"])+ if calculated_usage_per_chunk["speed"] is not None:+ setattr(returned_usage, "speed", calculated_usage_per_chunk["speed"])+# Return a new usage object with the new valuesreturned_usage = Usage(**returned_usage.model_dump())diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.pyindex 50e90699194..112780581de 100644--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py@@ -80,7 +80,9 @@ class AnthropicPassthroughLoggingHandler:model=model,messages=[],logging_obj=logging_obj,- optional_params={},+ optional_params=AnthropicPassthroughLoggingHandler._cost_relevant_request_params(+ request_body or kwargs.get("request_body")+ ),api_key="",request_data={},encoding=litellm.encoding,@@ -102,6 +104,15 @@ class AnthropicPassthroughLoggingHandler:"kwargs": kwargs,}+ @staticmethod+ def _cost_relevant_request_params(request_body: Optional[dict]) -> dict:+ """+ Request params that change how the response is priced, and so must reach the+ usage-building paths. Anthropic's ``speed=fast`` multiplies non-cache token cost.+ """+ speed = (request_body or {}).get("speed")+ return {"speed": speed} if isinstance(speed, str) else {}+@staticmethoddef _get_user_from_metadata(passthrough_logging_payload: PassthroughStandardLoggingPayload,@@ -315,6 +326,7 @@ class AnthropicPassthroughLoggingHandler:- Logs in litellm callbacks"""+ speed = AnthropicPassthroughLoggingHandler._cost_relevant_request_params(request_body).get("speed")model = request_body.get("model", "")# Check if it's available in the logging objectif (@@ -334,6 +346,7 @@ class AnthropicPassthroughLoggingHandler:all_chunks=all_chunks,litellm_logging_obj=litellm_logging_obj,model=model,+ speed=speed,)except Exception as e:# stream_chunk_builder re-raises assembly failures (as litellm.APIError)@@ -355,6 +368,7 @@ class AnthropicPassthroughLoggingHandler:complete_streaming_response = AnthropicPassthroughLoggingHandler._build_usage_only_response_from_chunks(all_chunks=all_chunks,model=model,+ speed=speed,)except Exception as e:verbose_proxy_logger.warning(@@ -419,6 +433,7 @@ class AnthropicPassthroughLoggingHandler:all_chunks: Sequence[Union[str, bytes]],litellm_logging_obj: LiteLLMLoggingObj,model: str,+ speed: Optional[str] = None,) -> Optional[Union[ModelResponse, TextCompletionResponse]]:"""Builds complete response from raw Anthropic chunks.@@ -443,11 +458,13 @@ class AnthropicPassthroughLoggingHandler:all_chunks=collapsed,litellm_logging_obj=litellm_logging_obj,model=model,+ speed=speed,)return AnthropicPassthroughLoggingHandler._build_complete_streaming_response_legacy(all_chunks=all_chunks,litellm_logging_obj=litellm_logging_obj,model=model,+ speed=speed,)# Anthropic SSE block/delta types that the fast path is NOT allowed to@@ -575,6 +592,7 @@ class AnthropicPassthroughLoggingHandler:all_chunks: Sequence[Union[str, bytes]],litellm_logging_obj: LiteLLMLoggingObj,model: str,+ speed: Optional[str] = None,) -> Optional[Union[ModelResponse, TextCompletionResponse]]:"""Original reconstruction: convert every SSE event to a generic chunk@@ -590,6 +608,7 @@ class AnthropicPassthroughLoggingHandler:anthropic_model_response_iterator = AnthropicModelResponseIterator(streaming_response=None,sync_stream=False,+ speed=speed,)all_openai_chunks = []@@ -649,6 +668,7 @@ class AnthropicPassthroughLoggingHandler:def _build_usage_only_response_from_chunks(all_chunks: Sequence[Union[str, bytes]],model: str,+ speed: Optional[str] = None,) -> Optional[ModelResponse]:"""Build a usage-bearing ModelResponse from Anthropic SSE token-usage events, for@@ -742,7 +762,7 @@ class AnthropicPassthroughLoggingHandler:usage_object["server_tool_use"] = _server_tool_useif inference_geo is not None:usage_object["inference_geo"] = inference_geo- usage_obj = AnthropicConfig().calculate_usage(usage_object=usage_object, reasoning_content=None)+ usage_obj = AnthropicConfig().calculate_usage(usage_object=usage_object, reasoning_content=None, speed=speed)return ModelResponse(model=resolved_model,choices=[diff --git a/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.pyindex c9f9d4e6baa..4ff47171e32 100644--- a/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py@@ -15,3 +15,5 @@ class UsagePerChunk(TypedDict):completion_tokens_details: Optional[CompletionTokensDetails]prompt_tokens_details: Optional[PromptTokensDetailsWrapper]cost: Optional[float]+ inference_geo: Optional[str]+ speed: Optional[str]diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex eaa4bd3e3fc..1cd4174c57c 100644--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@ -4153,3 +4153,38 @@ def test_pre_call_does_not_pin_request_in_module_state(logging_obj):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 result.usage.speed == "fast" # type: ignore[attr-defined]diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.pyindex be8c5a05601..72bbad7ae49 100644--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py@@ -992,3 +992,42 @@ def test_cost_field_in_usage_chunks():assert usage.cost == 0.00025assert usage.prompt_tokens == 10assert usage.completion_tokens == 5+++def test_anthropic_speed_and_geo_survive_stream_assembly():+ """Anthropic prices fast mode and non-global regions with a multiplier read off+ ``usage.speed`` / ``usage.inference_geo``. Dropping them while reassembling a stream+ bills streamed fast-mode calls at the standard rate."""+ from litellm.llms.anthropic.cost_calculation import cost_per_token++ def _usage(**extra):+ usage = Usage(completion_tokens=100, prompt_tokens=1000, total_tokens=1100)+ for key, value in extra.items():+ setattr(usage, key, value)+ return usage++ def _chunk(usage):+ return ModelResponseStream(+ id="chatcmpl-1",+ created=1745513206,+ model="claude-opus-4-8",+ choices=[StreamingChoices(finish_reason="stop", index=0, delta=Delta(content="Hi"))],+ usage=usage,+ )++ fast_chunk = _chunk(_usage(speed="fast", inference_geo="global"))+ fast_usage = ChunkProcessor(chunks=[fast_chunk]).calculate_usage(+ chunks=[fast_chunk], model="claude-opus-4-8", completion_output="Hi"+ )+ standard_chunk = _chunk(_usage(inference_geo="global"))+ standard_usage = ChunkProcessor(chunks=[standard_chunk]).calculate_usage(+ chunks=[standard_chunk], model="claude-opus-4-8", completion_output="Hi"+ )++ assert fast_usage.speed == "fast"+ assert fast_usage.inference_geo == "global"+ assert getattr(standard_usage, "speed", None) is None++ fast_cost = sum(cost_per_token(model="claude-opus-4-8", usage=fast_usage))+ standard_cost = sum(cost_per_token(model="claude-opus-4-8", usage=standard_usage))+ assert fast_cost == pytest.approx(standard_cost * 2.0)diff --git a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.pyindex 947a7a64beb..ffbdb3485ae 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py@@ -2192,3 +2192,116 @@ class TestAnthropicResponseCostRecordedOnModelCallDetails:logging_obj.model_call_details["response_cost"] == kwargs["response_cost"])assert logging_obj.model_call_details["response_cost"] > 0+++class TestAnthropicPassthroughFastMode:+ """Anthropic charges a provider-specific multiplier for ``speed=fast``, and the+ multiplier is applied off ``usage.speed``. The pass-through handler only sees the+ speed in the request body, so it has to thread it into every usage-building path or+ fast-mode pass-through spend is under-reported."""++ MODEL = "claude-opus-4-8"+ STREAM_CHUNKS = [+ 'event: message_start',+ 'data: {"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant",'+ ' "model": "claude-opus-4-8", "content": [], "stop_reason": null,'+ ' "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 0}}}',+ 'event: content_block_start',+ 'data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}',+ 'event: content_block_delta',+ 'data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "ok"}}',+ 'event: content_block_stop',+ 'data: {"type": "content_block_stop", "index": 0}',+ 'event: message_delta',+ 'data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"},'+ ' "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 100}}',+ 'event: message_stop',+ 'data: {"type": "message_stop"}',+ ]++ def _logging_obj(self) -> LiteLLMLoggingObj:+ return LiteLLMLoggingObj(+ model=self.MODEL,+ messages=[],+ stream=True,+ call_type="pass_through_endpoint",+ start_time=datetime.now(),+ litellm_call_id="fast-mode",+ function_id="fast-mode",+ )++ def _cost(self, response) -> float:+ import litellm++ return litellm.completion_cost(completion_response=response, model=f"anthropic/{self.MODEL}")++ def _expected_fast_cost(self, standard_cost: float) -> float:+ import litellm++ model_info = litellm.get_model_info(model=self.MODEL, custom_llm_provider="anthropic")+ cache_read_cost = 200 * (model_info.get("cache_read_input_token_cost") or 0.0)+ return (standard_cost - cache_read_cost) * 2.0 + cache_read_cost++ def test_non_streaming_applies_fast_multiplier(self):+ import httpx++ response_body = {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": self.MODEL,+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 1000, "cache_read_input_tokens": 200, "output_tokens": 100},+ }++ def _handle(request_body):+ logging_obj = self._logging_obj()+ logging_obj.model_call_details["stream"] = False+ return AnthropicPassthroughLoggingHandler.anthropic_passthrough_handler(+ httpx_response=httpx.Response(status_code=200, json=response_body),+ response_body=response_body,+ logging_obj=logging_obj,+ url_route="https://api.anthropic.com/v1/messages",+ result="",+ start_time=datetime.now(),+ end_time=datetime.now(),+ cache_hit=False,+ request_body=request_body,+ )++ fast = _handle({"model": self.MODEL, "speed": "fast"})+ standard = _handle({"model": self.MODEL})++ assert fast["result"].usage.speed == "fast"+ assert self._cost(fast["result"]) == pytest.approx(self._expected_fast_cost(self._cost(standard["result"])))++ def test_streaming_reconstruction_applies_fast_multiplier(self):+ fast = AnthropicPassthroughLoggingHandler._build_complete_streaming_response(+ all_chunks=self.STREAM_CHUNKS,+ litellm_logging_obj=self._logging_obj(),+ model=self.MODEL,+ speed="fast",+ )+ standard = AnthropicPassthroughLoggingHandler._build_complete_streaming_response(+ all_chunks=self.STREAM_CHUNKS,+ litellm_logging_obj=self._logging_obj(),+ model=self.MODEL,+ )++ assert fast.usage.speed == "fast"+ assert self._cost(fast) == pytest.approx(self._expected_fast_cost(self._cost(standard)))++ def test_usage_only_fallback_applies_fast_multiplier(self):+ fast = AnthropicPassthroughLoggingHandler._build_usage_only_response_from_chunks(+ all_chunks=self.STREAM_CHUNKS,+ model=self.MODEL,+ speed="fast",+ )+ standard = AnthropicPassthroughLoggingHandler._build_usage_only_response_from_chunks(+ all_chunks=self.STREAM_CHUNKS,+ model=self.MODEL,+ )++ assert fast.usage.speed == "fast"+ assert self._cost(fast) == pytest.approx(self._expected_fast_cost(self._cost(standard)))