Skip to content

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

feat(router): mid-stream fallback continuation for chat completions (#41127)

Ayush Shekhar7930c0e43407
diff --git a/litellm/__init__.py b/litellm/__init__.py
index af812dade3c..88e56c14187 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -207,7 +207,7 @@ _async_failure_callback: List[Union[str, Callable[..., object], "CustomLogger"]]
[]
) # internal variable - async custom callbacks are routed here.
pre_call_rules: List[Callable] = []
-post_call_rules: List[Callable] = []
+post_call_rules: List[Callable[..., object]] = []
turn_off_message_logging: Optional[bool] = False
standard_logging_payload_excluded_fields: Optional[List[str]] = (
None # Fields to exclude from StandardLoggingPayload before callbacks receive it
diff --git a/litellm/constants.py b/litellm/constants.py
index eb03d034c7e..39363cc02e4 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -57,6 +57,7 @@ RUNTIME_UPDATABLE_ROUTER_SETTINGS: Final[frozenset[str]] = frozenset(
"model_group_retry_policy",
"model_group_alias",
"enable_weighted_failover",
+ "enable_mid_stream_fallback_continuation",
"enable_tag_filtering",
"tag_routing_prefix",
"optional_pre_call_checks",
@@ -146,6 +147,7 @@ HF_CONFIG_FETCH_TIMEOUT_SECONDS: Final = 10.0
# Streams exceeding this duration are terminated with a Timeout error.
# None (default) = no limit. Set env var to a number of seconds to enable globally.
LITELLM_MAX_STREAMING_DURATION_SECONDS: Final = get_env_float_or_none("LITELLM_MAX_STREAMING_DURATION_SECONDS")
+MID_STREAM_FAILURE_LOG_WAIT_SECONDS: Final = 1.0
# Maximum number of base64 characters to keep in logging payloads.
# Data URIs exceeding this are replaced with a size placeholder.
diff --git a/litellm/exceptions.py b/litellm/exceptions.py
index 31388b00554..b3a0802db13 100644
--- a/litellm/exceptions.py
+++ b/litellm/exceptions.py
@@ -1217,6 +1217,7 @@ class MidStreamFallbackError(ServiceUnavailableError):
num_retries: int | None = None,
generated_content: str = "",
is_pre_first_chunk: bool = False,
+ emitted_disqualifying_content: bool = False,
):
original_status: Final = getattr(original_exception, "status_code", None)
self.status_code = int(original_status) if original_status is not None else 503
@@ -1229,6 +1230,7 @@ class MidStreamFallbackError(ServiceUnavailableError):
self.num_retries = num_retries
self.generated_content = generated_content
self.is_pre_first_chunk = is_pre_first_chunk
+ self.emitted_disqualifying_content = emitted_disqualifying_content
# Create a response if one wasn't provided
if response is None:
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index e766a2be9c3..fa009ca6327 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -2295,6 +2295,36 @@ class Logging(LiteLLMLoggingBaseClass):
self.model_call_details["combined_usage_object"] = usage
self.model_call_details["response_cost"] = response_cost
+ def record_continued_partial(self, usage: Usage, response_cost: float, response_id: str) -> None:
+ """Bill what a cut stream already consumed on this continuation's success log, under the id the caller saw."""
+ self.model_call_details["continued_partial_usage"] = usage
+ self.model_call_details["continued_partial_cost"] = response_cost
+ self.model_call_details["continued_response_id"] = response_id
+
+ def _add_continued_partial_spend(self, response: object) -> None:
+ partial_usage: Final = self.model_call_details.get("continued_partial_usage")
+ partial_cost: Final = self.model_call_details.get("continued_partial_cost")
+ own_usage: Final = getattr(response, "usage", None)
+ own_cost: Final = self.model_call_details.get("response_cost")
+ if not (isinstance(partial_usage, Usage) and isinstance(partial_cost, float) and isinstance(own_usage, Usage)):
+ return
+ from litellm.cost_calculator import BaseTokenUsageProcessor
+
+ self.model_call_details["combined_usage_object"] = BaseTokenUsageProcessor.combine_usage_objects(
+ usage_objects=[own_usage, partial_usage]
+ )
+ if not isinstance(own_cost, (int, float)):
+ return
+ self.model_call_details["response_cost"] = own_cost + partial_cost
+ if self.cost_breakdown is not None:
+ self.cost_breakdown = self.cost_breakdown | CostBreakdown(
+ total_cost=own_cost + partial_cost,
+ additional_costs={
+ **self.cost_breakdown.get("additional_costs", {}),
+ "mid_stream_partial_cost": partial_cost,
+ },
+ )
+
def record_assembled_response_for_failure(self, assembled: ModelResponse) -> None:
"""Bill a fully streamed response on the failure log when a post-call hook rejects it."""
usage: Final = getattr(assembled, "usage", None)
@@ -2590,6 +2620,15 @@ class Logging(LiteLLMLoggingBaseClass):
return response
return response.model_copy(update={"model": model})
+ def _with_continued_response_id(
+ self,
+ response: ModelResponse | TextCompletionResponse | ResponsesAPIResponse | InteractionsAPIResponse,
+ ) -> ModelResponse | TextCompletionResponse | ResponsesAPIResponse | InteractionsAPIResponse:
+ response_id: Final = self.model_call_details.get("continued_response_id")
+ if not isinstance(response_id, str) or getattr(response, "id", None) == response_id:
+ return response
+ return response.model_copy(update={"id": response_id})
+
def _success_handler_helper_fn(
self,
result: object = None,
@@ -2908,8 +2947,11 @@ class Logging(LiteLLMLoggingBaseClass):
self.model_call_details["response_cost"] = self.response_cost_calculator(
result=complete_streaming_response
)
+ self._add_continued_partial_spend(complete_streaming_response)
self._merge_hidden_params_from_response_into_metadata(complete_streaming_response)
- logged_streaming_response: Final = self._with_client_facing_stream_model(complete_streaming_response)
+ logged_streaming_response: Final = self._with_continued_response_id(
+ self._with_client_facing_stream_model(complete_streaming_response)
+ )
self.model_call_details["complete_streaming_response"] = logged_streaming_response
## STANDARDIZED LOGGING PAYLOAD
self.model_call_details["standard_logging_object"] = self._build_standard_logging_payload(
@@ -3445,12 +3487,15 @@ class Logging(LiteLLMLoggingBaseClass):
self.model,
)
self.model_call_details["response_cost"] = None
+ self._add_continued_partial_spend(complete_streaming_response)
self._merge_hidden_params_from_response_into_metadata(complete_streaming_response)
await self._prepare_baseline_cache_estimate(complete_streaming_response)
- logged_streaming_response: Final = self._with_client_facing_stream_model(complete_streaming_response)
+ logged_streaming_response: Final = self._with_continued_response_id(
+ self._with_client_facing_stream_model(complete_streaming_response)
+ )
self.model_call_details["async_complete_streaming_response"] = logged_streaming_response
## STANDARDIZED LOGGING PAYLOAD
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index 81fc865a5bc..044123d8729 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -1894,6 +1894,11 @@ def strip_litellm_internal_message_fields(message: AllMessageValues) -> AllMessa
return _message_without_fields(message, LITELLM_INTERNAL_MESSAGE_FIELDS)
+def strip_prefill_prefix_field(message: AllMessageValues) -> AllMessageValues:
+ """Drop the ``prefix`` flag Mistral and DeepSeek read off a prefill, for endpoints that reject unknown keys."""
+ return _message_without_fields(message, frozenset({"prefix"}))
+
+
def filter_value_from_dict(dictionary: dict, key: str, depth: int = 0) -> Any:
"""
Filters a value from a dictionary
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index 07534e70a27..87e76fe39f7 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -4303,6 +4303,24 @@ def _with_text_when_document_only(message: BedrockMessageBlock) -> BedrockMessag
return BedrockMessageBlock(role="user", content=[*blocks[:cut], placeholder, *blocks[cut:]])
+def _rstrip_text_block(block: BedrockContentBlock) -> BedrockContentBlock:
+ return BedrockContentBlock(text=block["text"].rstrip()) if "text" in block else block
+
+
+def _assistant_turn_rstripped(message: BedrockMessageBlock) -> BedrockMessageBlock:
+ """Claude on Converse rejects a final assistant turn that ends in whitespace, as the Anthropic path strips it."""
+ if message["role"] != "assistant":
+ return message
+ blocks: Final = message["content"]
+ last_text_index: Final = max((index for index, block in enumerate(blocks) if "text" in block), default=None)
+ return BedrockMessageBlock(
+ role="assistant",
+ content=[
+ _rstrip_text_block(block) if index == last_text_index else block for index, block in enumerate(blocks)
+ ],
+ )
+
+
def _ensure_document_messages_have_text(
contents: list[BedrockMessageBlock],
) -> list[BedrockMessageBlock]:
@@ -4894,7 +4912,12 @@ class BedrockConverseMessagesProcessor:
llm_provider=llm_provider,
)
- return _ensure_document_messages_have_text(_rename_duplicate_bedrock_document_names(contents))
+ converse_messages: Final = _ensure_document_messages_have_text(
+ _rename_duplicate_bedrock_document_names(contents)
+ )
+ if not (to_claude and converse_messages):
+ return converse_messages
+ return [*converse_messages[:-1], _assistant_turn_rstripped(converse_messages[-1])]
@staticmethod
def translate_thinking_blocks_to_reasoning_content_blocks(
@@ -5303,7 +5326,10 @@ def _bedrock_converse_messages_pt(
llm_provider=llm_provider,
)
- return _ensure_document_messages_have_text(_rename_duplicate_bedrock_document_names(contents))
+ converse_messages: Final = _ensure_document_messages_have_text(_rename_duplicate_bedrock_document_names(contents))
+ if not (to_claude and converse_messages):
+ return converse_messages
+ return [*converse_messages[:-1], _assistant_turn_rstripped(converse_messages[-1])]
def make_valid_bedrock_tool_name(input_tool_name: str) -> str:
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 46ad1b70abe..95d062a190c 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -242,6 +242,7 @@ class CustomStreamWrapper:
self.completion_stream = completion_stream
self.sent_first_chunk = False
self.sent_last_chunk = False
+ self._failure_logging: asyncio.Task[None] | None = None
self._closed = False
self._stream_created_time: float = time.time()
@@ -269,6 +270,7 @@ class CustomStreamWrapper:
self.holding_chunk = ""
self.complete_response = ""
self.response_uptil_now = ""
+ self._emitted_disqualifying_content = False
_model_info: Final[dict] = litellm_params.model_info or {}
_api_base: Final = get_api_base(
@@ -1129,6 +1131,7 @@ class CustomStreamWrapper:
if self.merge_reasoning_content_in_choices is True:
reasoning_content: Final = getattr(model_response.choices[0].delta, "reasoning_content", None)
if reasoning_content:
+ self._emitted_disqualifying_content = True
if self.sent_first_thinking_block is False:
# Ensure content is not None before concatenation
if model_response.choices[0].delta.content is None:
@@ -1865,9 +1868,7 @@ class CustomStreamWrapper:
if response.choices:
choice = response.choices[0]
if isinstance(choice, StreamingChoices):
- self.response_uptil_now += choice.delta.get("content", "") or ""
- else:
- self.response_uptil_now += ""
+ self._accumulate_streamed_delta(choice.delta)
self.rules.post_call_rules(input=self.response_uptil_now, model=self.model)
# HANDLE STREAM OPTIONS
self.chunks.append(response)
@@ -2084,9 +2085,7 @@ class CustomStreamWrapper:
if processed_chunk.choices:
choice = processed_chunk.choices[0]
if isinstance(choice, StreamingChoices):
- self.response_uptil_now += choice.delta.get("content", "") or ""
- else:
- self.response_uptil_now += ""
+ self._accumulate_streamed_delta(choice.delta)
self.rules.post_call_rules(input=self.response_uptil_now, model=self.model)
# Add mcp_list_tools to first chunk if present
if not self.sent_first_chunk and processed_chunk.choices:
@@ -2156,9 +2155,7 @@ class CustomStreamWrapper:
choice = processed_chunk.choices[0]
if isinstance(choice, StreamingChoices):
- self.response_uptil_now += choice.delta.get("content", "") or ""
- else:
- self.response_uptil_now += ""
+ self._accumulate_streamed_delta(choice.delta)
self.rules.post_call_rules(input=self.response_uptil_now, model=self.model)
# RETURN RESULT
self.chunks.append(processed_chunk)
@@ -2172,7 +2169,7 @@ class CustomStreamWrapper:
if self.logging_obj is not None:
self._record_partial_usage_for_failure()
## LOGGING
- asyncio.create_task(
+ self._failure_logging = asyncio.create_task(
self.logging_obj.dispatch_failure_handlers(e, traceback_exception, prefer_async_handlers=True)
)
await self.aclose()
@@ -2305,11 +2302,17 @@ class CustomStreamWrapper:
if self.logging_obj is not None:
self._record_partial_usage_for_failure()
## LOGGING
- asyncio.create_task(
+ self._failure_logging = asyncio.create_task(
self.logging_obj.dispatch_failure_handlers(e, traceback_exception, prefer_async_handlers=True)
)
self._handle_stream_fallback_error(e)
+ async def wait_for_failure_logging(self, timeout: float) -> None:
+ """Let this stream's failure log read its own deployment before a fallback reuses the logging object."""
+ if self._failure_logging is None:
+ return
+ await asyncio.wait((self._failure_logging,), timeout=timeout)
+
def _record_partial_usage_for_failure(self) -> None:
"""
A stream that breaks mid-flight still billed the provider for the chunks
@@ -2346,6 +2349,35 @@ class CustomStreamWrapper:
recover_error,
)
+ # Delta fields a text-only prefill continuation cannot carry, so a stream
+ # that emitted any of them is not eligible for mid-stream continuation.
+ _CONTINUATION_DISQUALIFYING_DELTA_FIELDS: Final = (
+ "tool_calls",
+ "function_call",
+ "reasoning_content",
+ "thinking_blocks",
+ "reasoning_items",
+ "audio",
+ "images",
+ "annotations",
+ )
+
+ @classmethod
+ def _delta_disqualifies_continuation(cls, delta: object) -> bool:
+ get: Final = getattr(delta, "get", None)
+ if not callable(get):
+ return False
+ return any(get(field) for field in cls._CONTINUATION_DISQUALIFYING_DELTA_FIELDS)
+
+ def _accumulate_streamed_delta(self, delta: object) -> None:
+ # Shared by the sync, async, and non-aiohttp iteration sites so answer
+ # text and the disqualifying-content latch stay in step across all three.
+ get: Final = getattr(delta, "get", None)
+ content: Final = get("content") if callable(get) else None
+ self.response_uptil_now += content if isinstance(content, str) else ""
+ if not self._emitted_disqualifying_content and self._delta_disqualifies_continuation(delta):
+ self._emitted_disqualifying_content = True
+
def _handle_stream_fallback_error(self, e: Exception) -> "NoReturn":
"""
Common error handling for both __next__ and __anext__.
@@ -2377,6 +2409,7 @@ class CustomStreamWrapper:
original_exception=e.original_exception,
generated_content=self.response_uptil_now,
is_pre_first_chunk=not self.sent_first_chunk,
+ emitted_disqualifying_content=self._emitted_disqualifying_content or e.emitted_disqualifying_content,
)
# Map to OpenAI exception format. Some providers' mappers (e.g.
@@ -2437,6 +2470,7 @@ class CustomStreamWrapper:
original_exception=mapped_exception,
generated_content=self.response_uptil_now,
is_pre_first_chunk=not self.sent_first_chunk,
+ emitted_disqualifying_content=self._emitted_disqualifying_content,
)
@staticmethod
diff --git a/litellm/llms/databricks/chat/transformation.py b/litellm/llms/databricks/chat/transformation.py
index 2145c19a71a..74bdd2cd733 100644
--- a/litellm/llms/databricks/chat/transformation.py
+++ b/litellm/llms/databricks/chat/transformation.py
@@ -20,6 +20,7 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import (
merge_consecutive_system_messages,
strip_litellm_internal_message_fields,
strip_name_from_message,
+ strip_prefill_prefix_field,
)
from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator
from litellm.llms.base_llm.base_utils import (
@@ -487,6 +488,7 @@ class DatabricksConfig(DatabricksBase, OpenAILikeChatConfig, AnthropicConfig):
Databricks does not support:
- 'name' in user message.
- litellm's internal `thinking_blocks` / `reasoning_content` on assistant messages.
+ - the `prefix` prefill flag Mistral and DeepSeek read, which Claude does not need to continue an assistant turn.
- non-Claude json_object "json" checks read only string content, so a single text block is sent as a string.
"""
new_messages = []
@@ -496,7 +498,7 @@ class DatabricksConfig(DatabricksBase, OpenAILikeChatConfig, AnthropicConfig):
else:
_message = message
_message = strip_name_from_message(_message, allowed_name_roles=["user"])
- _message = strip_litellm_internal_message_fields(_message)
+ _message = strip_prefill_prefix_field(strip_litellm_internal_message_fields(_message))
# Move message-level cache_control into a content block when content is a string.
if "cache_control" in _message and isinstance(_message.get("content"), str):
_message = self._move_cache_control_into_string_content_block(_message)
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index b744032fb6c..5fff760d85a 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -2773,7 +2773,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2808,7 +2808,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2843,7 +2843,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2878,7 +2878,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2913,7 +2913,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2948,7 +2948,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -3743,7 +3743,7 @@
"max_tokens": 128000,
"mode": "chat",
"output_cost_per_token": 1.5e-05,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -15494,7 +15494,7 @@
},
"supports_adaptive_thinking": true,
"supports_legacy_thinking": true,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -20832,7 +20832,7 @@
"output_cost_per_token": 2.5000010000000002e-05,
"output_dbu_cost_per_token": 0.000357143,
"source": "https://www.databricks.com/product/pricing/proprietary-foundation-model-serving",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_legacy_thinking": true,
"supports_prompt_caching": true,
@@ -21047,7 +21047,7 @@
"output_cost_per_token": 1.5000020000000002e-05,
"output_dbu_cost_per_token": 0.000214286,
"source": "https://www.databricks.com/product/pricing/proprietary-foundation-model-serving",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_legacy_thinking": true,
"supports_prompt_caching": true,
@@ -49176,7 +49176,7 @@
"max_tokens": 64000,
"mode": "chat",
"output_cost_per_token": 2.5e-05,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_prompt_caching": true,
@@ -51006,7 +51006,7 @@
"mode": "chat",
"output_cost_per_token": 1.5e-05,
"output_cost_per_token_batches": 7.5e-06,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -51179,7 +51179,7 @@
"supported_regions": [
"global"
],
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
@@ -51200,7 +51200,7 @@
"supported_regions": [
"us-central1"
],
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
@@ -58822,7 +58822,7 @@
"mode": "chat",
"output_cost_per_token": 1.5e-05,
"output_cost_per_token_batches": 7.5e-06,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -72334,7 +72334,7 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py
index fe55092591e..9ebea589cc9 100644
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@ -573,11 +573,11 @@ def get_logging_payload(
elif isinstance(_usage, dict):
usage = _usage
- # A request that failed mid-stream has no usable response_obj usage, but the
- # streaming handler may have recovered the usage from the chunks already
- # delivered. Honor that override so the partial usage lands in spend tracking.
+ # A request that failed mid-stream has no usable response_obj usage, and a stream
+ # continued on a fallback only has the fallback's. combined_usage_object holds the
+ # usage of every call the client's answer took, so it wins in both cases.
_combined_usage: Final = kwargs.get("combined_usage_object")
- if not usage and isinstance(_combined_usage, litellm.Usage):
+ if (not usage or "continued_partial_usage" in kwargs) and isinstance(_combined_usage, litellm.Usage):
usage = _combined_usage.model_dump()
id = get_spend_logs_id(call_type or "acompletion", response_obj_dict, kwargs, metadata)
diff --git a/litellm/router.py b/litellm/router.py
index 151a8a75dc3..3c969610e83 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -38,7 +38,7 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from functools import lru_cache, partial
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, Generic, Literal, Optional, TypeAlias, TypeVar, Union, cast
+from typing import TYPE_CHECKING, Any, Final, Generic, Literal, NoReturn, Optional, TypeAlias, TypeVar, Union, cast
import anyio
import httpx
@@ -68,6 +68,7 @@ from litellm.constants import (
DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER,
DEFAULT_MAX_LRU_CACHE_SIZE,
INTERNAL_CALL_ORIGIN_METADATA_KEY,
+ MID_STREAM_FAILURE_LOG_WAIT_SECONDS,
OUTPUT_TOKEN_CEILING_PARAMS,
PROMPT_CACHE_PIN_CACHE_MAX_SIZE,
ROUTER_USAGE_COUNTED_TOKENS_METADATA_KEY,
@@ -75,7 +76,7 @@ from litellm.constants import (
RUNTIME_UPDATABLE_ROUTER_SETTINGS,
SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,
)
-from litellm.integrations.custom_guardrail import is_guardrail_intervention
+from litellm.integrations.custom_guardrail import CustomGuardrail, is_guardrail_intervention
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.otel.routing import routing_decision_attributes
from litellm.integrations.otel.runtime import phase_attributes, phase_event, phase_span
@@ -194,6 +195,7 @@ from litellm.router_utils.clientside_credential_handler import (
is_clientside_credential,
)
from litellm.router_utils.common_utils import (
+ MID_STREAM_CONTINUATION_KWARG,
filter_team_based_models,
filter_web_search_deployments,
format_fallback_outcome_message,
@@ -233,7 +235,10 @@ from litellm.router_utils.fallback_event_handlers import (
check_non_standard_fallback_format,
clear_pre_routing_selection,
committed_retry_budget_for_request,
+ continuation_fallback_targets,
fallback_lookup_groups,
+ fallback_target_name,
+ fallback_target_overrides_request_params,
fallbacks_disabled_for_request,
get_fallback_model_group_for_lookup_groups,
get_pre_routing_selection,
@@ -258,6 +263,17 @@ from litellm.router_utils.handle_error import (
send_llm_exception_alert,
)
from litellm.router_utils.health_state_cache import DeploymentHealthCache
+from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_MARKER,
+ ContinuationOutput,
+ ContinuationPrefillDeploymentCheck,
+ ContinuedPartial,
+ constrains_continuation,
+ continuation_deployments,
+ continuation_output_ceilings,
+ continued_text,
+ deployment_can_continue,
+)
from litellm.router_utils.pre_call_checks.deployment_affinity_check import (
DeploymentAffinityCheck,
warn_on_unknown_model_group_affinity_flags,
@@ -303,6 +319,8 @@ from litellm.router_utils.routing_groups import (
)
from litellm.router_utils.routing_read_batch import ROUTER_USAGE_TARGET, RoutingPrefetch, RoutingReadBatch
from litellm.scheduler import FlowItem, Scheduler
+from litellm.secret_managers.main import str_to_bool
+from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.litellm_params import RoutingStrategyName
from litellm.types.llms.openai import (
AllMessageValues,
@@ -371,6 +389,7 @@ from litellm.utils import (
EmbeddingResponse,
ModelResponse,
Rules,
+ TextCompletionResponse,
function_setup,
get_llm_provider,
get_non_default_completion_params,
@@ -527,6 +546,15 @@ _ROUTING_KWARGS_ADAPTER: Final[TypeAdapter[Mapping[str, object] | None]] = TypeA
_FALLBACK_HOP_ADAPTER: Final = TypeAdapter(Mapping[str, object])
_OPAQUE_VALUE_ADAPTER: Final = TypeAdapter(object)
_DEPLOYMENT_SELECTED_EVENT: Final = "litellm.request.deployment_selected"
+_CONTENT_BLOCKS_ADAPTER: Final = TypeAdapter(list[dict[str, object]])
+
+
+def _extend_trailing_text_block(blocks: Sequence[Mapping[str, object]], text: str) -> Sequence[Mapping[str, object]]:
+ """Continue the last text block in place so the prefill reads as the text the caller already received."""
+ last: Final = blocks[-1] if blocks else None
+ if last is not None and last.get("type") == "text" and isinstance(last_text := last.get("text"), str):
+ return [*blocks[:-1], {**last, "text": f"{last_text}{text}"}]
+ return [*blocks, {"type": "text", "text": text}]
def _is_fallback_hop(request_kwargs: Mapping[str, object]) -> bool:
@@ -1119,6 +1147,7 @@ class Router:
health_check_ignore_transient_errors: bool = False,
background_health_check_model_groups: Sequence[str] | None = None,
enable_weighted_failover: bool = False,
+ enable_mid_stream_fallback_continuation: bool = False,
fallback_access_check: FallbackAccessCheck | None = None,
fallback_budget_check: FallbackBudgetCheck | None = None,
auto_router_capability_limit: AutoRouterCapabilityLimit | None = None,
@@ -1160,6 +1189,7 @@ class Router:
deployment_affinity_ttl_seconds (int): TTL for user-key -> deployment affinity mapping. Defaults to 3600.
ignore_invalid_deployments (bool): Ignores invalid deployments, and continues with other deployments. Default is to raise an error.
enable_weighted_failover (bool): When True and the routing strategy is "simple-shuffle", a retryable failure on one deployment causes the request to re-pick (weighted) across the other deployments in the same model group before any cross-group fallback runs. Bounded by `max_fallbacks`. Async-only: currently honored by `router.acompletion()` and other async entrypoints. The sync `router.completion()` path falls back to the regular fallback flow. Defaults to False.
+ enable_mid_stream_fallback_continuation (bool): When True, a chat-completions stream that breaks after plain assistant text has been delivered continues on a fallback deployment via assistant prefill instead of surfacing the error. Only deployments whose model supports assistant prefill are eligible, so the partial text is continued, not regenerated; if none is, the original error is surfaced. Streams that emitted tool calls, thinking blocks, audio/images, or constrained (JSON / forced tool_choice) output are never continued. Async-only. Defaults to False.
fallback_access_check (Optional[FallbackAccessCheck]): Awaited before each cross-model-group fallback attempt on the async path; a fallback target it rejects is skipped. Defaults to None (every configured fallback is attempted).
fallback_budget_check (Optional[FallbackBudgetCheck]): Awaited before each cross-model-group fallback attempt on the async path; a fallback target it rejects as over budget is skipped. Defaults to None (budget is not re-checked on fallback).
Returns:
@@ -1355,6 +1385,7 @@ class Router:
self.fallback_on_unsupported_params = fallback_on_unsupported_params
self.enable_health_check_routing = enable_health_check_routing
self.enable_weighted_failover = enable_weighted_failover
+ self.enable_mid_stream_fallback_continuation = self._is_flag_enabled(enable_mid_stream_fallback_continuation)
self.health_check_ignore_transient_errors = health_check_ignore_transient_errors
self.background_health_check_model_groups: frozenset[str] | None = (
frozenset(background_health_check_model_groups)
@@ -1549,6 +1580,14 @@ class Router:
default_pre_call_checks: Final[OptionalPreCallChecks] = []
self.add_optional_pre_call_checks(default_pre_call_checks)
+ if self.enable_mid_stream_fallback_continuation:
+ self._register_continuation_prefill_check()
+
+ @staticmethod
+ def _register_continuation_prefill_check() -> None:
+ # Process-global on purpose: Router.discard() must not drop a filter another router still needs.
+ litellm.logging_callback_manager.add_litellm_callback(ContinuationPrefillDeploymentCheck())
+
def discard(self):
"""
Pseudo-destructor to be invoked to clean up global data structures when router is no longer used.
@@ -3143,15 +3182,53 @@ class Router:
usage: Final = cast(Usage | None, getattr(fallback_item, "usage", None))
usage_objects: Final = [usage] if usage is not None else []
- if (
- complete_response_object_usage is not None
- and hasattr(complete_response_object_usage, "usage")
- and complete_response_object_usage.usage is not None
- ):
+ if complete_response_object_usage is not None:
usage_objects.append(complete_response_object_usage)
combined_usage: Final = BaseTokenUsageProcessor.combine_usage_objects(usage_objects=usage_objects)
setattr(fallback_item, "usage", combined_usage)
+ @staticmethod
+ def _price_cut_partial(
+ cut_stream: CustomStreamWrapper,
+ partial_response: ModelResponse | TextCompletionResponse | None,
+ ) -> "ContinuedPartial | None":
+ """Price the cut stream's partial, plus any partial it inherited, before a fallback can reuse its logging."""
+ from litellm.cost_calculator import BaseTokenUsageProcessor
+
+ cut_logging: Final = cut_stream.logging_obj
+ partial_usage: Final = getattr(partial_response, "usage", None)
+ if partial_response is None or not isinstance(partial_usage, Usage):
+ return None
+ inherited_usage: Final = cut_logging.model_call_details.get("continued_partial_usage")
+ inherited_cost: Final = cut_logging.model_call_details.get("continued_partial_cost")
+ inherited_id: Final = cut_logging.model_call_details.get("continued_response_id")
+ priced_partial: Final = partial_response.model_copy(
+ update={"model": cut_stream.model} if cut_stream.model else {}
+ )
+ priced_partial._hidden_params = { # pyright: ignore[reportPrivateUsage] # no public accessor
+ key: value for key, value in get_hidden_params_dict(partial_response).items() if key != "response_cost"
+ }
+ return ContinuedPartial(
+ usage=BaseTokenUsageProcessor.combine_usage_objects(
+ usage_objects=[partial_usage, inherited_usage]
+ if isinstance(inherited_usage, Usage)
+ else [partial_usage]
+ ),
+ response_cost=(cut_logging.response_cost_calculator(result=priced_partial) or 0.0)
+ + (inherited_cost if isinstance(inherited_cost, float) else 0.0),
+ response_id=inherited_id if isinstance(inherited_id, str) else partial_response.id,
+ )
+
+ @staticmethod
+ def _carry_partial_spend_to_fallback(fallback_response: object, cut_partial: "ContinuedPartial | None") -> None:
+ """Bill what the cut legs consumed on the continuation's success log."""
+ fallback_logging: Final = getattr(fallback_response, "logging_obj", None)
+ if cut_partial is None or not isinstance(fallback_logging, LiteLLMLogging):
+ return
+ fallback_logging.record_continued_partial(
+ usage=cut_partial.usage, response_cost=cut_partial.response_cost, response_id=cut_partial.response_id
+ )
+
@staticmethod
def _prepare_fallback_hidden_params(
fallback_response: object,
@@ -3201,7 +3278,7 @@ class Router:
self,
model_response: CustomStreamWrapper,
messages: list[dict[str, str]],
- initial_kwargs: dict,
+ initial_kwargs: dict[str, Any],
deployment_slot: contextlib.AsyncExitStack | None = None,
first_chunk: _FirstChunk[AsyncIterator[object]] | None = None,
) -> CustomStreamWrapper:
@@ -3264,16 +3341,22 @@ class Router:
with anyio.CancelScope(shield=True):
await close_model_response()
await held_slot.aclose()
- if not e.is_pre_first_chunk and (
- e.generated_content or _stream_chunks_have_generated_content(model_response.chunks)
- ):
- if e.original_exception is not None:
- raise e.original_exception from e
- raise
+ committed: Final = bool(
+ not e.is_pre_first_chunk
+ and (e.generated_content or _stream_chunks_have_generated_content(model_response.chunks))
+ )
+ cut_hidden_params: Final = get_hidden_params(model_response) or {}
+ continue_after_content: Final = committed and self._mid_stream_continuation_eligible(
+ e=e, request_kwargs=initial_kwargs, cut_deployment_id=cut_hidden_params.get("model_id")
+ )
+ if committed and not continue_after_content:
+ self._raise_original_mid_stream_error(e)
from litellm.main import stream_chunk_builder
- complete_response_object: Final = stream_chunk_builder(chunks=model_response.chunks)
+ complete_response_object: Final = stream_chunk_builder(
+ chunks=model_response.chunks, messages=messages if continue_after_content else None
+ )
complete_response_object_usage: Final = cast(
Usage | None,
getattr(complete_response_object, "usage", None),
@@ -3289,7 +3372,41 @@ class Router:
"content_policy_fallbacks", self.content_policy_fallbacks
)
initial_kwargs["original_function"] = self._acompletion
- initial_kwargs["messages"] = messages
+ continuation_messages: Final = (
+ self._build_completion_continuation_input(messages, e.generated_content)
+ if continue_after_content
+ else None
+ )
+ continuation_output: Final = (
+ ContinuationOutput(
+ e.generated_content,
+ continuation_messages[-1],
+ model_group,
+ complete_response_object,
+ checks_post_call_rules=initial_kwargs.get(MID_STREAM_CONTINUATION_KWARG)
+ is not MID_STREAM_CONTINUATION_MARKER,
+ )
+ if continuation_messages is not None
+ else None
+ )
+ cut_partial: Final = (
+ Router._price_cut_partial(model_response, complete_response_object)
+ if continuation_output is not None
+ else None
+ )
+ if continue_after_content:
+ emitted_tokens: Final = int(
+ getattr(complete_response_object_usage, "completion_tokens", 0) or 0
+ )
+ reduced_ceilings: Final = continuation_output_ceilings(initial_kwargs, emitted_tokens)
+ if reduced_ceilings is None or continuation_messages is None:
+ self._raise_original_mid_stream_error(e)
+ await model_response.wait_for_failure_logging(timeout=MID_STREAM_FAILURE_LOG_WAIT_SECONDS)
+ initial_kwargs.update(reduced_ceilings)
+ initial_kwargs["messages"] = continuation_messages
+ initial_kwargs[MID_STREAM_CONTINUATION_KWARG] = MID_STREAM_CONTINUATION_MARKER
+ else:
+ initial_kwargs["messages"] = messages
self._update_kwargs_before_fallbacks(model=model_group, kwargs=initial_kwargs)
fallback_response = await self.async_function_with_fallbacks_common_utils(
e=e,
@@ -3305,11 +3422,17 @@ class Router:
# If fallback returns a streaming response, iterate over it
if hasattr(fallback_response, "__aiter__"):
+ Router._carry_partial_spend_to_fallback(fallback_response, cut_partial)
prepared_fallback_hidden_params = Router._adopt_fallback_response_headers(
wrapper_ref, fallback_response
)
fallback_headers_are_settled = False
- async for fallback_item in fallback_response:
+ fallback_items: Final = (
+ continuation_output.splice(fallback_response)
+ if continuation_output is not None
+ else fallback_response
+ )
+ async for fallback_item in fallback_items:
if not fallback_headers_are_settled:
fallback_headers_are_settled = True
# a fallback that failed over again only repoints itself once it yields
@@ -3322,7 +3445,10 @@ class Router:
and isinstance(fallback_item, ModelResponseStream)
and hasattr(fallback_item, "usage")
):
- self._combine_fallback_usage(fallback_item, complete_response_object_usage)
+ self._combine_fallback_usage(
+ fallback_item,
+ complete_response_object_usage if continuation_output is not None else None,
+ )
yield fallback_item
else:
# If fallback returns a non-streaming response, yield None
@@ -3479,6 +3605,97 @@ class Router:
total_tokens=(partial_usage.total_tokens or 0) + (fb.total_tokens or 0),
)
+ @staticmethod
+ def _raise_original_mid_stream_error(e: "MidStreamFallbackError") -> NoReturn:
+ """Surface the provider error the stream wrapper carried instead of the internal MidStreamFallbackError."""
+ if e.original_exception is not None:
+ raise e.original_exception from e
+ raise e
+
+ def _params_sent_to_deployment(
+ self, request_kwargs: Mapping[str, object], deployment: Deployment | None
+ ) -> Mapping[str, object]:
+ """The request as the deployment received it, merged in the order _update_kwargs_with_deployment applies."""
+ deployment_params: Final = deployment.litellm_params.model_dump(exclude_none=True) if deployment else {}
+ defaults: Final = {key: value for key, value in self.default_litellm_params.items() if value is not None}
+ deployment_tool_choice: Final = (
+ {"tool_choice": deployment_params["tool_choice"]}
+ if deployment_params.get("tool_choice") is not None
+ else {}
+ )
+ return MappingProxyType({**deployment_params, **defaults, **deployment_tool_choice, **request_kwargs})
+
+ def _names_deployment_that_cannot_continue(self, target: object) -> bool:
+ name: Final = fallback_target_name(target)
+ if name is None or name in self.model_names or not self.has_model_id(name):
+ return False
+ deployment: Final = self.get_deployment(model_id=name)
+ return deployment is not None and not deployment_can_continue(deployment.model_dump(exclude_none=True))
+
+ def _mid_stream_continuation_eligible(
+ self,
+ e: "MidStreamFallbackError",
+ request_kwargs: Mapping[str, object],
+ cut_deployment_id: object = None,
+ ) -> bool:
+ """Whether a stream that broke after plain assistant text may continue via prefill."""
+ if not self.enable_mid_stream_fallback_continuation:
+ return False
+ if not e.generated_content or e.emitted_disqualifying_content:
+ return False
+ if isinstance(e.original_exception, litellm.ContentPolicyViolationError):
+ return False
+ cut_deployment: Final = (
+ self.get_deployment(model_id=cut_deployment_id) if isinstance(cut_deployment_id, str) else None
+ )
+ if isinstance(cut_deployment_id, str) and cut_deployment is None:
+ return False
+ if constrains_continuation(self._params_sent_to_deployment(request_kwargs, cut_deployment)):
+ return False
+ requested_group: Final = request_kwargs.get("model")
+ lookup_groups: Final = fallback_lookup_groups(
+ request_kwargs, requested_group if isinstance(requested_group, str) else None
+ )
+ targets: Final = continuation_fallback_targets(request_kwargs.get("fallbacks", self.fallbacks), lookup_groups)
+ if any(fallback_target_overrides_request_params(target) for target in targets):
+ return False
+ if any(self._names_deployment_that_cannot_continue(target) for target in targets):
+ return False
+ return not any(
+ isinstance(callback, CustomGuardrail)
+ and callback._event_hook_is_event_type( # pyright: ignore[reportPrivateUsage] # the only check of a guardrail's hooks
+ GuardrailEventHooks.post_call
+ )
+ for callback in litellm.callbacks
+ )
+
+ @staticmethod
+ def _build_completion_continuation_input(
+ messages: Sequence[Mapping[str, object]],
+ generated_content: str,
+ ) -> Sequence[Mapping[str, object]] | None:
+ """Append the partial output as an assistant prefill, or extend a trailing `prefix: True` assistant turn in
+ place so the request never ends in two assistant messages. None when the request ends in a plain assistant
+ turn, in a prefill turn whose content has a shape this cannot extend, or when the cut came mid-echo of the
+ prefill."""
+ last: Final = messages[-1] if messages else None
+ if last is None or last.get("role") != "assistant":
+ return [*messages, {"role": "assistant", "content": generated_content, "prefix": True}]
+ if last.get("prefix") is not True:
+ return None
+ new_text: Final = continued_text(last, generated_content)
+ if new_text is None:
+ return None
+ content: Final = last.get("content")
+ if content is None or isinstance(content, str):
+ return [*messages[:-1], {**last, "content": f"{content or ''}{new_text}", "prefix": True}]
+ try:
+ blocks: Final = _CONTENT_BLOCKS_ADAPTER.validate_python(content)
+ except ValidationError:
+ return None
+ extended: Final = _extend_trailing_text_block(blocks, new_text)
+ return [*messages[:-1], {**last, "content": extended, "prefix": True}]
+
@staticmethod
def _build_responses_continuation_input(
input_val: Union[str, "ResponseInputParam"] | None,
@@ -3880,13 +4097,6 @@ class Router:
raise e.original_exception from e
raise
- from litellm.main import stream_chunk_builder
-
- complete_response_object: Final = stream_chunk_builder(chunks=model_response.chunks)
- complete_response_object_usage: Final = cast(
- Usage | None,
- getattr(complete_response_object, "usage", None),
- )
try:
model_group: Final = cast(str, initial_kwargs.get("model"))
fallbacks: Final[list | None] = initial_kwargs.get("fallbacks", router_self.fallbacks)
@@ -3932,7 +4142,7 @@ class Router:
and isinstance(fallback_item, ModelResponseStream)
and hasattr(fallback_item, "usage")
):
- router_self._combine_fallback_usage(fallback_item, complete_response_object_usage)
+ router_self._combine_fallback_usage(fallback_item, None)
yield fallback_item
else:
yield None
@@ -13004,6 +13214,7 @@ class Router:
"retry_policy",
"model_group_alias",
"enable_weighted_failover",
+ "enable_mid_stream_fallback_continuation",
"enable_tag_filtering",
"tag_routing_prefix",
"fallback_on_unsupported_params",
@@ -13060,12 +13271,10 @@ class Router:
rebuild_routing_groups = True
elif var == "optional_pre_call_checks":
self.set_optional_pre_call_checks(kwargs[var])
+ elif var == "enable_mid_stream_fallback_continuation":
+ self._set_mid_stream_fallback_continuation(kwargs[var])
elif var == "retry_policy":
- value = kwargs[var]
- if isinstance(value, dict):
- value = RetryPolicy(**value)
- if value is None or isinstance(value, RetryPolicy):
- setattr(self, var, value)
+ self._set_retry_policy(kwargs[var])
else:
value = kwargs[var]
# only run routing strategy init if it has changed
@@ -13092,6 +13301,20 @@ class Router:
self._routing_groups_input = routing_groups_input
verbose_router_logger.debug("Updated Router settings: %s", self.get_settings())
+ @staticmethod
+ def _is_flag_enabled(value: object) -> bool:
+ return value is True or (isinstance(value, str) and str_to_bool(value) is True)
+
+ def _set_mid_stream_fallback_continuation(self, enabled: object) -> None:
+ self.enable_mid_stream_fallback_continuation = self._is_flag_enabled(enabled)
+ if self.enable_mid_stream_fallback_continuation:
+ self._register_continuation_prefill_check()
+
+ def _set_retry_policy(self, value: object) -> None:
+ policy: Final = RetryPolicy.model_validate(value) if isinstance(value, dict) else value
+ if policy is None or isinstance(policy, RetryPolicy):
+ self.retry_policy = policy
+
def _get_client(self, deployment, kwargs, client_type=None):
"""
Returns the appropriate client based on the given deployment, kwargs, and client_type.
@@ -15119,9 +15342,8 @@ class Router:
request_kwargs=request_kwargs,
)
strategy, strategy_selector = self._get_routing_context(model, request_kwargs)
- pick_attributes: Final = _deployment_pick_attributes(
- model, _ROUTING_KWARGS_ADAPTER.validate_python(request_kwargs)
- )
+ routing_kwargs: Final = _ROUTING_KWARGS_ADAPTER.validate_python(request_kwargs)
+ pick_attributes: Final = _deployment_pick_attributes(model, routing_kwargs)
if isinstance(healthy_deployments, dict):
if (healthy_deployments.get("model_info") or {}).get("blocked") is True:
@@ -15159,7 +15381,9 @@ class Router:
)
healthy_deployments = _pre_cooldown_deployments
- healthy_deployments = self._filter_blocked_deployments(healthy_deployments)
+ healthy_deployments = continuation_deployments(
+ self._filter_blocked_deployments(healthy_deployments), routing_kwargs
+ )
# filter pre-call checks
if self.enable_pre_call_checks and (messages is not None or input is not None):
diff --git a/litellm/router_utils/common_utils.py b/litellm/router_utils/common_utils.py
index e12304c6ed1..c4e4d9ccc0b 100644
--- a/litellm/router_utils/common_utils.py
+++ b/litellm/router_utils/common_utils.py
@@ -27,7 +27,8 @@ from litellm.types.utils import LlmProviders, ProviderSpecificModelInfo
_V = TypeVar("_V")
-ROUTER_ONLY_CALL_KWARGS: Final = frozenset({"silent_model", "include_fallback_errors"})
+MID_STREAM_CONTINUATION_KWARG: Final = "_mid_stream_continuation"
+ROUTER_ONLY_CALL_KWARGS: Final = frozenset({"silent_model", "include_fallback_errors", MID_STREAM_CONTINUATION_KWARG})
_OBJECT_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[object, object]]] = TypeAdapter(Mapping[object, object])
diff --git a/litellm/router_utils/fallback_event_handlers.py b/litellm/router_utils/fallback_event_handlers.py
index 1f37c6c8cb1..06bd3329cc1 100644
--- a/litellm/router_utils/fallback_event_handlers.py
+++ b/litellm/router_utils/fallback_event_handlers.py
@@ -615,6 +615,32 @@ def get_fallback_model_group(
return fallback_model_group, generic_fallback_idx
+def _resolved_fallback_chain(entries: Sequence[object], lookup_groups: tuple[str, ...]) -> Sequence[object]:
+ group_entries: Final[Sequence[Mapping[str, list[str]]]] = tuple( # mutable-ok: mirrors the fallbacks config shape
+ entry for entry in entries if isinstance(entry, Mapping) and entry
+ )
+ chain, _ = get_fallback_model_group_for_lookup_groups(fallbacks=group_entries, lookup_groups=lookup_groups)
+ return chain if isinstance(chain, list) else ()
+
+
+def continuation_fallback_targets(fallbacks: object, lookup_groups: tuple[str, ...]) -> Sequence[object]:
+ entries: Final[Sequence[object]] = fallbacks if isinstance(fallbacks, list) else ()
+ return (
+ entries
+ if check_non_standard_fallback_format(fallbacks=entries)
+ else _resolved_fallback_chain(entries, lookup_groups)
+ )
+
+
+def fallback_target_overrides_request_params(target: object) -> bool:
+ return isinstance(target, Mapping) and "model" in target and len(target) > 1
+
+
+def fallback_target_name(target: object) -> str | None:
+ name: Final = target.get("model") if isinstance(target, Mapping) else target
+ return name if isinstance(name, str) else None
+
+
PROVIDER_SCOPED_RESOURCE_KEYS: Final = ("input_file_id", "training_file", "batch_id", "file_id", "fine_tuning_job_id")
PROVIDER_SCOPED_RESOURCE_FUNCTION_NAMES: Final = frozenset(
{
diff --git a/litellm/router_utils/pre_call_checks/continuation_prefill_check.py b/litellm/router_utils/pre_call_checks/continuation_prefill_check.py
new file mode 100644
index 00000000000..8f211ef67db
--- /dev/null
+++ b/litellm/router_utils/pre_call_checks/continuation_prefill_check.py
@@ -0,0 +1,264 @@
+"""Keeps a mid-stream continuation on deployments whose model supports assistant prefill and whose own params leave
+the output unconstrained."""
+
+from collections.abc import AsyncIterable, AsyncIterator, Mapping, Sequence
+from dataclasses import dataclass
+from itertools import accumulate
+from os.path import commonprefix
+from types import MappingProxyType
+from typing import Final
+
+from pydantic import TypeAdapter, ValidationError
+
+import litellm
+from litellm.integrations.custom_logger import CustomLogger, Span
+from litellm.litellm_core_utils.rules import Rules
+from litellm.router_utils.common_utils import MID_STREAM_CONTINUATION_KWARG
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import ModelResponse, ModelResponseStream, Usage
+from litellm.utils import supports_assistant_prefill
+
+
+class _ContinuationMarker:
+ """Only the router constructs one, so a JSON request body cannot forge the continuation flag."""
+
+
+MID_STREAM_CONTINUATION_MARKER: Final = _ContinuationMarker()
+
+_STR_KEYED_DICT_ADAPTER: Final = TypeAdapter(dict[str, object])
+_NO_FIELDS: Final[Mapping[str, object]] = MappingProxyType({})
+_UNCONSTRAINED_RESPONSE_FORMAT: Final[Mapping[str, str]] = MappingProxyType({"type": "text"})
+_OUTPUT_CEILING_KEYS: Final = ("max_tokens", "max_completion_tokens")
+
+
+def _str_keyed(value: object) -> Mapping[str, object]:
+ try:
+ return _STR_KEYED_DICT_ADAPTER.validate_python(value)
+ except ValidationError:
+ return _NO_FIELDS
+
+
+def deployment_supports_prefill(deployment: object) -> bool:
+ deployment_map: Final = _str_keyed(deployment)
+ model_info: Final = _str_keyed(deployment_map.get("model_info"))
+ declared: Final = model_info.get("supports_assistant_prefill")
+ if isinstance(declared, bool):
+ return declared
+ litellm_params: Final = _str_keyed(deployment_map.get("litellm_params"))
+ candidates: Final = (model_info.get("base_model"), litellm_params.get("base_model"), litellm_params.get("model"))
+ model: Final = next((candidate for candidate in candidates if isinstance(candidate, str) and candidate), None)
+ return model is not None and supports_assistant_prefill(model=model)
+
+
+def constrains_continuation(params: Mapping[str, object]) -> bool:
+ sent: Final = {**params, **_str_keyed(params.get("extra_body"))}
+ choice_count: Final = sent.get("n")
+ response_format: Final = sent.get("response_format")
+ tool_choice: Final = sent.get("tool_choice")
+ return (
+ (isinstance(choice_count, int) and choice_count > 1)
+ or (response_format is not None and response_format != _UNCONSTRAINED_RESPONSE_FORMAT)
+ or tool_choice == "required"
+ or isinstance(tool_choice, Mapping)
+ or sent.get("merge_reasoning_content_in_choices") is True
+ )
+
+
+def deployment_can_continue(deployment: object) -> bool:
+ litellm_params: Final = _str_keyed(_str_keyed(deployment).get("litellm_params"))
+ return deployment_supports_prefill(deployment) and not constrains_continuation(litellm_params)
+
+
+def continuation_deployments(
+ healthy_deployments: list[dict[str, object]], # mutable-ok: router deployment-list contract
+ request_kwargs: Mapping[str, object] | None,
+) -> list[dict[str, object]]: # mutable-ok: returns a mutable deployment list
+ marker: Final = (request_kwargs or {}).get(MID_STREAM_CONTINUATION_KWARG)
+ if not isinstance(marker, _ContinuationMarker):
+ return healthy_deployments
+ return [deployment for deployment in healthy_deployments if deployment_can_continue(deployment)]
+
+
+class ContinuationPrefillDeploymentCheck(CustomLogger):
+ async def async_filter_deployments(
+ self,
+ model: str,
+ healthy_deployments: list[dict[str, object]], # mutable-ok: CustomLogger deployment-list contract
+ messages: Sequence[AllMessageValues] | None,
+ request_kwargs: Mapping[str, object] | None = None,
+ parent_otel_span: Span | None = None,
+ ) -> list[dict[str, object]]: # mutable-ok: returns a mutable deployment list
+ return continuation_deployments(healthy_deployments, request_kwargs)
+
+
+def _delta_text(chunk: ModelResponseStream) -> str:
+ if not chunk.choices:
+ return ""
+ content: Final = chunk.choices[0].delta.content
+ return content if isinstance(content, str) else ""
+
+
+_CONTENT_BLOCKS_ADAPTER: Final = TypeAdapter(list[dict[str, object]])
+
+
+def _prefill_text(prefill_message: Mapping[str, object]) -> str:
+ content: Final = prefill_message.get("content")
+ if isinstance(content, str):
+ return content
+ try:
+ blocks: Final = _CONTENT_BLOCKS_ADAPTER.validate_python(content)
+ except ValidationError:
+ return ""
+ return "".join(
+ text for block in blocks if block.get("type") == "text" and isinstance(text := block.get("text"), str)
+ )
+
+
+def _resendable_whitespace(prefill: str) -> str:
+ return prefill[len(prefill.rstrip()) :] if prefill.strip() else ""
+
+
+def continued_text(prefill_message: Mapping[str, object], generated_content: str) -> str | None:
+ prefill: Final = _prefill_text(prefill_message)
+ if generated_content and len(generated_content) < len(prefill) and prefill.startswith(generated_content):
+ return None
+ echo: Final = len(prefill) if prefill and generated_content.startswith(prefill) else 0
+ after_echo: Final = generated_content[echo:]
+ return after_echo[len(commonprefix((after_echo, _resendable_whitespace(prefill)))) :]
+
+
+def _reduced_ceilings(params: Mapping[str, object], emitted_tokens: int) -> Mapping[str, int]:
+ return MappingProxyType(
+ {key: value - emitted_tokens for key in _OUTPUT_CEILING_KEYS if isinstance(value := params.get(key), int)}
+ )
+
+
+def continuation_output_ceilings(
+ request_kwargs: Mapping[str, object], emitted_tokens: int
+) -> Mapping[str, object] | None:
+ """The caller's output ceilings, top-level and in extra_body, minus the tokens already emitted, or None once
+ nothing is left."""
+ extra_body: Final = _str_keyed(request_kwargs.get("extra_body"))
+ top_level: Final = _reduced_ceilings(request_kwargs, emitted_tokens)
+ in_extra_body: Final = _reduced_ceilings(extra_body, emitted_tokens)
+ if any(ceiling <= 0 for ceiling in (*top_level.values(), *in_extra_body.values())):
+ return None
+ if not in_extra_body:
+ return top_level
+ return MappingProxyType({**top_level, "extra_body": {**extra_body, **in_extra_body}})
+
+
+def _with_first_delta(chunk: ModelResponseStream, update: Mapping[str, object]) -> ModelResponseStream:
+ choice: Final = chunk.choices[0]
+ delta: Final = choice.delta.model_copy(update=update)
+ return chunk.model_copy(update={"choices": [choice.model_copy(update={"delta": delta}), *chunk.choices[1:]]})
+
+
+def _without_leading_text(chunk: ModelResponseStream, count: int) -> ModelResponseStream:
+ if count <= 0:
+ return chunk
+ return _with_first_delta(chunk, {"content": _delta_text(chunk)[count:]})
+
+
+def _without_role(chunk: ModelResponseStream) -> ModelResponseStream:
+ if not chunk.choices or chunk.choices[0].delta.role is None:
+ return chunk
+ return _with_first_delta(chunk, {"role": None})
+
+
+def _stream_identity(primary_response: object) -> Mapping[str, object]:
+ if not isinstance(primary_response, ModelResponse):
+ return _NO_FIELDS
+ return MappingProxyType({"id": primary_response.id, "created": primary_response.created})
+
+
+def _drop_leading_text(chunks: tuple[ModelResponseStream, ...], count: int) -> tuple[ModelResponseStream, ...]:
+ lengths: Final = tuple(len(_delta_text(chunk)) for chunk in chunks)
+ offsets: Final = tuple(accumulate(lengths, initial=0))[:-1]
+ return tuple(
+ _without_leading_text(chunk, min(length, count - offset))
+ for chunk, offset, length in zip(chunks, offsets, lengths, strict=True)
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class ContinuedPartial:
+ usage: Usage
+ response_cost: float
+ response_id: str
+
+
+class ContinuationOutput:
+ """Splices a fallback's continuation onto the stream the client already received. Drops a leading echo of the
+ prefill, since some providers (Mistral) return the prefix inside the completion, and the prefill's trailing
+ whitespace sent again by a provider that strips it (Anthropic), keeps the primary's chunk id, created time and single role delta, and
+ runs litellm.post_call_rules over the joined text, since each stream wrapper only sees its own fragment. A
+ continuation nested in another leaves the rules to the outermost one, the only one holding the whole text."""
+
+ def __init__(
+ self,
+ emitted_text: str,
+ prefill_message: Mapping[str, object],
+ model: str,
+ primary_response: object,
+ checks_post_call_rules: bool = True,
+ ) -> None:
+ self._text = emitted_text
+ self._checks_post_call_rules: Final = checks_post_call_rules
+ self._prefill_text: Final = _prefill_text(prefill_message)
+ self._model: Final = model
+ self._identity: Final = _stream_identity(primary_response)
+ self._rules: Final = Rules()
+ self._held: tuple[ModelResponseStream, ...] = ()
+ self._echo_settled = not self._prefill_text
+ self._seam = _resendable_whitespace(self._prefill_text)
+
+ async def splice(self, stream: AsyncIterable[object]) -> AsyncIterator[object]:
+ async for item in stream:
+ if not isinstance(item, ModelResponseStream):
+ yield item
+ continue
+ for released in self._observed(self._past_seam(self._released(item))):
+ yield self._in_primary_stream(released)
+ for released in self._observed(self._past_seam(self._flushed())):
+ yield self._in_primary_stream(released)
+
+ def _in_primary_stream(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ return _without_role(chunk.model_copy(update=self._identity) if self._identity else chunk)
+
+ def _flushed(self) -> tuple[ModelResponseStream, ...]:
+ held: Final = self._held
+ self._held = ()
+ self._echo_settled = True
+ return held
+
+ def _released(self, chunk: ModelResponseStream) -> tuple[ModelResponseStream, ...]:
+ if self._echo_settled:
+ return (chunk,)
+ held: Final = (*self._held, chunk)
+ text: Final = "".join(_delta_text(held_chunk) for held_chunk in held)
+ if len(text) < len(self._prefill_text) and self._prefill_text.startswith(text):
+ self._held = held
+ return ()
+ self._held = ()
+ self._echo_settled = True
+ if not text.startswith(self._prefill_text):
+ return held
+ return _drop_leading_text(held, len(self._prefill_text))
+
+ def _past_seam(self, chunks: tuple[ModelResponseStream, ...]) -> tuple[ModelResponseStream, ...]:
+ return tuple(self._without_seam(chunk) for chunk in chunks)
+
+ def _without_seam(self, chunk: ModelResponseStream) -> ModelResponseStream:
+ text: Final = _delta_text(chunk)
+ matched: Final = len(commonprefix((text, self._seam)))
+ self._seam = self._seam[matched:] if matched == len(text) else ""
+ return _without_leading_text(chunk, matched)
+
+ def _observed(self, chunks: tuple[ModelResponseStream, ...]) -> tuple[ModelResponseStream, ...]:
+ if not self._checks_post_call_rules or not litellm.post_call_rules:
+ return chunks
+ for chunk in chunks:
+ self._text += _delta_text(chunk)
+ self._rules.post_call_rules(input=self._text, model=self._model)
+ return chunks
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 0bcb732a0f5..7df8cc7452f 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -4045,7 +4045,9 @@ class CustomPricingLiteLLMParams(MirroredPricingParams):
DEPLOYMENT_SCOPED_PRICING_FIELDS: Final[frozenset[str]] = frozenset({"off_peak_pricing"})
-DEPLOYMENT_SCOPED_CAPABILITY_FIELDS: Final[frozenset[str]] = frozenset({"supports_regex_lookaround"})
+DEPLOYMENT_SCOPED_CAPABILITY_FIELDS: Final[frozenset[str]] = frozenset(
+ {"supports_regex_lookaround", "supports_assistant_prefill"}
+)
SHARED_BACKEND_MODEL_INFO_FIELDS: Final[frozenset[str]] = (
frozenset(ModelInfoBase.__required_keys__ | ModelInfoBase.__optional_keys__)
diff --git a/litellm/utils.py b/litellm/utils.py
index 65408663f6f..ea36a68ad5a 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -3060,6 +3060,20 @@ def supports_prompt_cache_breakpoint(model: str, custom_llm_provider: str | None
)
+def supports_assistant_prefill(model: str, custom_llm_provider: str | None = None) -> bool:
+ """
+ Whether the model can continue a prefilled assistant message (Anthropic's
+ ``prefix: True`` trick and equivalents). Missing metadata reads as False,
+ so a mid-stream fallback continuation is only routed to a model known to
+ support it.
+ """
+ return _supports_factory(
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ key="supports_assistant_prefill",
+ )
+
+
def supports_thinking_cache_preservation(model: str, custom_llm_provider: str | None = None) -> bool:
return supports_factory(
model=model,
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index b744032fb6c..5fff760d85a 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -2773,7 +2773,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2808,7 +2808,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2843,7 +2843,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2878,7 +2878,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2913,7 +2913,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -2948,7 +2948,7 @@
"search_context_size_low": 0.01,
"search_context_size_medium": 0.01
},
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -3743,7 +3743,7 @@
"max_tokens": 128000,
"mode": "chat",
"output_cost_per_token": 1.5e-05,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -15494,7 +15494,7 @@
},
"supports_adaptive_thinking": true,
"supports_legacy_thinking": true,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -20832,7 +20832,7 @@
"output_cost_per_token": 2.5000010000000002e-05,
"output_dbu_cost_per_token": 0.000357143,
"source": "https://www.databricks.com/product/pricing/proprietary-foundation-model-serving",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_legacy_thinking": true,
"supports_prompt_caching": true,
@@ -21047,7 +21047,7 @@
"output_cost_per_token": 1.5000020000000002e-05,
"output_dbu_cost_per_token": 0.000214286,
"source": "https://www.databricks.com/product/pricing/proprietary-foundation-model-serving",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_legacy_thinking": true,
"supports_prompt_caching": true,
@@ -49176,7 +49176,7 @@
"max_tokens": 64000,
"mode": "chat",
"output_cost_per_token": 2.5e-05,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_prompt_caching": true,
@@ -51006,7 +51006,7 @@
"mode": "chat",
"output_cost_per_token": 1.5e-05,
"output_cost_per_token_batches": 7.5e-06,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -51179,7 +51179,7 @@
"supported_regions": [
"global"
],
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
@@ -51200,7 +51200,7 @@
"supported_regions": [
"us-central1"
],
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_function_calling": true,
"supports_prompt_caching": true,
"supports_reasoning": true,
@@ -58822,7 +58822,7 @@
"mode": "chat",
"output_cost_per_token": 1.5e-05,
"output_cost_per_token_batches": 7.5e-06,
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
@@ -72334,7 +72334,7 @@
"max_output_tokens": 64000,
"max_tokens": 64000,
"mode": "chat",
- "supports_assistant_prefill": true,
+ "supports_assistant_prefill": false,
"supports_computer_use": true,
"supports_function_calling": true,
"supports_pdf_input": true,
diff --git a/tests/code_coverage_tests/router_code_coverage.py b/tests/code_coverage_tests/router_code_coverage.py
index a3ed70f4a56..6762e4cd35c 100644
--- a/tests/code_coverage_tests/router_code_coverage.py
+++ b/tests/code_coverage_tests/router_code_coverage.py
@@ -114,6 +114,12 @@ ignored_function_names = [
"_deployment_that_just_failed", # Tested through the same-boundary hop test in test_router_order_fallback.py
"_collect_ptu_share_teams", # Cached behind team_ptu_ceiling, tested through the live model list test in test_router.py
"_resolve_team_ptu_ceiling", # Cached behind team_ptu_ceiling, tested through the live model list test in test_router.py
+ "_register_continuation_prefill_check", # Tested through the continuation tests in test_router.py
+ "_set_mid_stream_fallback_continuation", # Tested through the update_settings continuation test in test_router.py
+ "_is_flag_enabled", # Tested through the string-flag continuation tests in test_router.py
+ "_params_sent_to_deployment", # Tested through the configured-constraint continuation tests in test_router.py
+ "_names_deployment_that_cannot_continue", # Tested through the deployment-id continuation tests in test_router.py
+ "_set_retry_policy", # Tested through update_settings in test_router_retry_policy_update.py
"_resolve_pre_call_check_input_tokens", # Tested through the token-count failure pre-call check tests in test_router.py
"_params_neither_dropped_nor_allowed", # Tested through the allowed-or-dropped param pre-call check tests in test_router.py
"_deployment_rejects_params", # Tested through the unsupported-param pre-call check tests in test_router.py
diff --git a/tests/integration/streaming/test_mid_stream_fallback_continuation.py b/tests/integration/streaming/test_mid_stream_fallback_continuation.py
new file mode 100644
index 00000000000..8ec52f26dde
--- /dev/null
+++ b/tests/integration/streaming/test_mid_stream_fallback_continuation.py
@@ -0,0 +1,749 @@
+from __future__ import annotations
+
+import functools
+import hashlib
+import itertools
+import json
+import math
+import operator
+import threading
+import uuid
+from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence
+from contextlib import ExitStack, contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+
+import openai
+import pytest
+import yaml
+from integration._support.client import JSON_OBJECT, Gateway, eventually, gateway_from_environment, object_value
+from integration._support.database import read_rows, scratch_database
+from integration._support.process import graceful_stop_seconds, owned_proxy
+from integration._support.wire import Reply, Request, Wire, wire_server
+from openai.types.chat import ChatCompletionChunk
+from pydantic import JsonValue, TypeAdapter
+
+pytestmark: Final = pytest.mark.timeout(4 * graceful_stop_seconds() + 120)
+
+SETTING: Final = "enable_mid_stream_fallback_continuation"
+PARTIAL: Final = ("Alpha beta", " gamma")
+JOINED_PARTIAL: Final = "".join(PARTIAL)
+RELAY_TEXT: Final = " delta"
+BACKUP_TEXT: Final = " omega."
+PLAIN_TEXT: Final = "plain answer"
+TOOL_PREAMBLE: Final = "Let me check"
+BACKUP_USAGE: Final = (40, 6)
+MAX_TOKENS: Final = 200
+PRIMARY_PRICES: Final = (0.001, 0.002)
+BACKUP_PRICES: Final = (0.003, 0.005)
+SHARED_BACKEND: Final = "openai/gpt-4o-mini"
+SEPARATE_BACKEND: Final = "openai/gpt-4o"
+WEATHER_TOOL: Final[Mapping[str, JsonValue]] = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+ },
+}
+TOOL_CALL_DELTA: Final[Mapping[str, JsonValue]] = {
+ "index": 0,
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": ""},
+}
+NOTHING_SEEN: Final[tuple[ChatCompletionChunk, ...]] = ()
+ALLOW_EVERYTHING: Final = "def apply_guardrail(inputs, request_data, input_type):\n return allow()\n"
+EVENT_BATCH: Final = TypeAdapter(list[dict[str, JsonValue]])
+
+
+def cut_gate(marker: str, hop: str, attempt: int) -> threading.Event:
+ return threading.Event()
+
+
+def attempts(marker: str, hop: str) -> Iterator[int]:
+ return itertools.count()
+
+
+def frame(identity: str, delta: Mapping[str, JsonValue], finish: str | None = None) -> bytes:
+ body: Final = {
+ "id": identity,
+ "object": "chat.completion.chunk",
+ "created": 1700000000,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "delta": dict(delta), "finish_reason": finish}],
+ }
+ return b"data: " + json.dumps(body).encode() + b"\n\n"
+
+
+def complete_stream(identity: str, text: str, usage: tuple[int, int]) -> Reply:
+ usage_frame: Final[dict[str, JsonValue]] = {
+ "id": identity,
+ "object": "chat.completion.chunk",
+ "created": 1700000000,
+ "model": "gpt-4o-mini",
+ "choices": [],
+ "usage": {"prompt_tokens": usage[0], "completion_tokens": usage[1], "total_tokens": sum(usage)},
+ }
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(
+ frame(identity, {"role": "assistant", "content": text}),
+ frame(identity, {}, finish="stop"),
+ b"data: " + json.dumps(usage_frame).encode() + b"\n\n",
+ b"data: [DONE]\n\n",
+ ),
+ )
+
+
+def cut_after_caller_sees(marker: str, hop: str, *frames: bytes) -> Reply:
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(b"".join(frames), b"data: never sent\n\n"),
+ abort_after=1,
+ gate_after_first=cut_gate(marker, hop, next(attempts(marker, hop))),
+ )
+
+
+def first_user_text(request: Request) -> str:
+ messages: Final = JSON_OBJECT.validate_json(request.body)["messages"]
+ assert isinstance(messages, list), messages
+ first: Final = object_value(messages[0])["content"]
+ assert isinstance(first, str), first
+ return first
+
+
+def marker_of(request: Request) -> str:
+ return first_user_text(request).split()[-1]
+
+
+def is_chat(request: Request) -> bool:
+ return request.target.endswith("/chat/completions")
+
+
+def model_list() -> Reply:
+ return Reply(body=b'{"object": "list", "data": []}')
+
+
+def primary(request: Request) -> Reply:
+ if not is_chat(request):
+ return model_list()
+ scenario: Final = first_user_text(request).split()[0]
+ marker: Final = marker_of(request)
+ identity: Final = f"chatcmpl-{marker}-primary"
+ if scenario == "reject":
+ return Reply(status=500, body=b'{"error": {"message": "primary is down", "type": "server_error"}}')
+ if scenario == "tool-cut":
+ return cut_after_caller_sees(
+ marker,
+ "primary",
+ frame(identity, {"role": "assistant", "content": TOOL_PREAMBLE}),
+ frame(identity, {"tool_calls": [dict(TOOL_CALL_DELTA)]}),
+ )
+ return cut_after_caller_sees(
+ marker,
+ "primary",
+ frame(identity, {"role": "assistant", "content": PARTIAL[0]}),
+ frame(identity, {"content": PARTIAL[1]}),
+ )
+
+
+def relay(request: Request) -> Reply:
+ if not is_chat(request):
+ return model_list()
+ marker: Final = marker_of(request)
+ return cut_after_caller_sees(
+ marker, "relay", frame(f"chatcmpl-{marker}-relay", {"role": "assistant", "content": RELAY_TEXT})
+ )
+
+
+def backup(request: Request) -> Reply:
+ if not is_chat(request):
+ return model_list()
+ return complete_stream(f"chatcmpl-{marker_of(request)}-backup", BACKUP_TEXT, BACKUP_USAGE)
+
+
+def no_prefill(request: Request) -> Reply:
+ if not is_chat(request):
+ return model_list()
+ return complete_stream(f"chatcmpl-{marker_of(request)}-plain", PLAIN_TEXT, (9, 2))
+
+
+def accept_events(request: Request) -> Reply:
+ return Reply()
+
+
+def registered_guardrail(name: str, mode: str) -> dict[str, JsonValue]:
+ return {
+ "guardrail_name": name,
+ "litellm_params": {
+ "guardrail": "custom_code",
+ "mode": mode,
+ "default_on": False,
+ "custom_code": ALLOW_EVERYTHING,
+ },
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ gateway: Gateway
+ database_url: str
+ primary: Wire
+ relay: Wire
+ backup: Wire
+ no_prefill: Wire
+ events: Wire
+
+
+def joined_text(chunks: Iterable[ChatCompletionChunk]) -> str:
+ return "".join(choice.delta.content or "" for chunk in chunks for choice in chunk.choices)
+
+
+def has_tool_call(chunks: Iterable[ChatCompletionChunk]) -> bool:
+ return any(choice.delta.tool_calls for chunk in chunks for choice in chunk.choices)
+
+
+@dataclass(frozen=True, slots=True)
+class Release:
+ gate: threading.Event
+ ready: Callable[[tuple[ChatCompletionChunk, ...]], bool]
+
+
+def after_text(marker: str, hop: str, text: str, attempt: int = 0) -> Release:
+ return Release(cut_gate(marker, hop, attempt), lambda seen: joined_text(seen) == text)
+
+
+@dataclass(frozen=True, slots=True)
+class Streamed:
+ chunks: tuple[ChatCompletionChunk, ...]
+ error: openai.APIError | None
+
+ @property
+ def text(self) -> str:
+ return joined_text(self.chunks)
+
+ @property
+ def ids(self) -> frozenset[str]:
+ return frozenset(chunk.id for chunk in self.chunks)
+
+ @property
+ def role_deltas(self) -> int:
+ return sum(1 for chunk in self.chunks for choice in chunk.choices if choice.delta.role is not None)
+
+ @property
+ def finish_reasons(self) -> tuple[str, ...]:
+ return tuple(choice.finish_reason for chunk in self.chunks for choice in chunk.choices if choice.finish_reason)
+
+ @property
+ def usage(self) -> tuple[int, int]:
+ reported: Final = tuple(chunk.usage for chunk in self.chunks if chunk.usage is not None)
+ assert reported, self.chunks
+ return (reported[-1].prompt_tokens, reported[-1].completion_tokens)
+
+
+def deployment(
+ name: str,
+ wire: Wire,
+ prices: tuple[float, float],
+ *,
+ backend: str = SHARED_BACKEND,
+ prefill: bool | None = None,
+) -> dict[str, JsonValue]:
+ return {
+ "model_name": name,
+ "litellm_params": {
+ "model": backend,
+ "api_base": wire.url + "/v1",
+ "api_key": "synthetic-continuation-key",
+ "input_cost_per_token": prices[0],
+ "output_cost_per_token": prices[1],
+ },
+ **({"model_info": {"supports_assistant_prefill": prefill}} if prefill is not None else {}),
+ }
+
+
+def write_config(
+ directory: Path,
+ model_entries: Sequence[Mapping[str, JsonValue]],
+ fallbacks: Sequence[Mapping[str, JsonValue]],
+ router_settings: Mapping[str, JsonValue],
+ guardrails: Sequence[Mapping[str, JsonValue]],
+) -> Path:
+ base: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ config: Final = {
+ **base,
+ "model_list": [dict(entry) for entry in model_entries],
+ "litellm_settings": {
+ **object_value(base["litellm_settings"]),
+ "callbacks": ["generic_api"],
+ "DEFAULT_FLUSH_INTERVAL_SECONDS": 1,
+ },
+ "guardrails": [dict(entry) for entry in guardrails],
+ "router_settings": {
+ **object_value(base["router_settings"]),
+ "num_retries": 0,
+ "fallbacks": [dict(entry) for entry in fallbacks],
+ **router_settings,
+ },
+ }
+ path: Final = directory / f"continuation-{uuid.uuid4().hex[:8]}.yaml"
+ path.write_text(yaml.safe_dump(config))
+ return path
+
+
+@contextmanager
+def booted_rig(
+ directory: Path,
+ fallbacks: Sequence[Mapping[str, JsonValue]],
+ router_settings: Mapping[str, JsonValue],
+ workers: int,
+ guardrails: Sequence[Mapping[str, JsonValue]] = (),
+) -> Generator[Rig]:
+ with ExitStack() as stack:
+ shared: Final = stack.enter_context(gateway_from_environment())
+ database_url: Final = stack.enter_context(scratch_database())
+ wires: Final = tuple(
+ stack.enter_context(wire_server(respond)) for respond in (primary, relay, backup, no_prefill, accept_events)
+ )
+ primary_wire, relay_wire, backup_wire, no_prefill_wire, events_wire = wires
+ config: Final = write_config(
+ directory,
+ (
+ *(
+ deployment(name, primary_wire, PRIMARY_PRICES)
+ for name in ("primary", "primary-skip", "primary-none", "primary-relay", "primary-shared")
+ ),
+ deployment("relay", relay_wire, PRIMARY_PRICES, prefill=True),
+ deployment("backup", backup_wire, BACKUP_PRICES, prefill=True),
+ deployment("no-prefill", no_prefill_wire, PRIMARY_PRICES, backend=SEPARATE_BACKEND),
+ deployment("no-prefill-shared", no_prefill_wire, PRIMARY_PRICES),
+ ),
+ fallbacks,
+ router_settings,
+ guardrails,
+ )
+ gateway: Final = stack.enter_context(
+ owned_proxy(
+ shared,
+ directory,
+ {"DATABASE_URL": database_url, "GENERIC_LOGGER_ENDPOINT": events_wire.url},
+ config=config,
+ remove_environment=("DATABASE_URL_READ_REPLICA",),
+ workers=workers,
+ )
+ )
+ yield Rig(gateway, database_url, primary_wire, relay_wire, backup_wire, no_prefill_wire, events_wire)
+
+
[email protected](scope="module")
+def configured(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ fallbacks: Final[tuple[Mapping[str, JsonValue], ...]] = (
+ {"primary": ["backup"]},
+ {"primary-skip": ["no-prefill", "backup"]},
+ {"primary-none": ["no-prefill"]},
+ {"primary-relay": ["relay"]},
+ {"relay": ["backup"]},
+ {"primary-shared": ["no-prefill-shared"]},
+ )
+ with booted_rig(
+ tmp_path_factory.mktemp("continuation-configured"),
+ fallbacks,
+ {SETTING: True},
+ 2,
+ (registered_guardrail("input-check", "pre_call"),),
+ ) as rig:
+ yield rig
+
+
[email protected](scope="module")
+def output_guarded(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ with booted_rig(
+ tmp_path_factory.mktemp("continuation-output-guarded"),
+ ({"primary": ["backup"]},),
+ {SETTING: True},
+ 2,
+ (registered_guardrail("output-check", "post_call"),),
+ ) as rig:
+ yield rig
+
+
[email protected](scope="module")
+def unset(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ with booted_rig(
+ tmp_path_factory.mktemp("continuation-unset"), ({"primary": ["no-prefill", "backup"]},), {}, 1
+ ) as rig:
+ yield rig
+
+
+def new_key(rig: Rig) -> str:
+ key: Final = rig.gateway.post("/key/generate", {})["key"]
+ assert isinstance(key, str), key
+ return key
+
+
+def appended(seen: tuple[ChatCompletionChunk, ...], chunk: ChatCompletionChunk) -> tuple[ChatCompletionChunk, ...]:
+ return (*seen, chunk)
+
+
+def observed(
+ response: Iterable[ChatCompletionChunk], releases: Sequence[Release]
+) -> Iterator[ChatCompletionChunk | openai.APIError]:
+ try:
+ for seen in itertools.accumulate(response, appended, initial=NOTHING_SEEN):
+ for release in releases:
+ if release.ready(seen):
+ release.gate.set()
+ yield from seen[-1:]
+ except openai.APIError as error:
+ yield error
+
+
+def stream(
+ rig: Rig,
+ key: str,
+ model: str,
+ prompt: str,
+ releases: Sequence[Release] = (),
+ extra: Mapping[str, JsonValue] | None = None,
+) -> Streamed:
+ base_url: Final = f"{rig.gateway.client.base_url}".rstrip("/") + "/v1"
+ try:
+ with openai.OpenAI(base_url=base_url, api_key=key, max_retries=0, timeout=60) as client:
+ response: Final = client.chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": prompt}],
+ stream=True,
+ stream_options={"include_usage": True},
+ max_tokens=MAX_TOKENS,
+ extra_body=dict(extra or {}),
+ )
+ outcome: Final = tuple(observed(response, releases))
+ finally:
+ for release in releases:
+ release.gate.set()
+ errors: Final = tuple(item for item in outcome if isinstance(item, openai.APIError))
+ return Streamed(
+ tuple(item for item in outcome if isinstance(item, ChatCompletionChunk)), errors[0] if errors else None
+ )
+
+
+def chat_bodies(wire: Wire, marker: str) -> tuple[dict[str, JsonValue], ...]:
+ return tuple(
+ JSON_OBJECT.validate_json(request.body)
+ for request in wire.drain()
+ if is_chat(request) and marker_of(request) == marker
+ )
+
+
+def spend_rows(rig: Rig, key: str) -> list[dict[str, JsonValue]]:
+ return eventually(
+ lambda: read_rows(
+ 'SELECT request_id, status, spend, prompt_tokens, completion_tokens, metadata FROM "LiteLLM_SpendLogs" '
+ "WHERE api_key=%s",
+ (hashlib.sha256(key.encode()).hexdigest(),),
+ database_url=rig.database_url,
+ ),
+ lambda rows: len(rows) >= 1,
+ seconds=70,
+ )
+
+
+def amount(value: JsonValue) -> float:
+ assert isinstance(value, (int, float)), value
+ return float(value)
+
+
+def key_spend(rig: Rig, key: str) -> float:
+ return amount(object_value(rig.gateway.get("/key/info", {"key": key})["info"])["spend"])
+
+
+def close(observed_value: float, expected: float) -> bool:
+ return math.isclose(observed_value, expected, rel_tol=1e-9, abs_tol=1e-12)
+
+
+def cost(tokens: tuple[int, int], prices: tuple[float, float]) -> float:
+ return tokens[0] * prices[0] + tokens[1] * prices[1]
+
+
+def prefill_turn(text: str) -> dict[str, JsonValue]:
+ return {"role": "assistant", "content": text, "prefix": True}
+
+
+@dataclass(frozen=True, slots=True)
+class Billed:
+ rows: list[dict[str, JsonValue]]
+ partial: tuple[int, int]
+
+
+def billed_once(rig: Rig, key: str, received: Streamed) -> Billed:
+ rows: Final = spend_rows(rig, key)
+ assert [row["status"] for row in rows] == ["success"], rows
+ row_tokens: Final = (rows[0]["prompt_tokens"], rows[0]["completion_tokens"])
+ assert isinstance(row_tokens[0], int) and isinstance(row_tokens[1], int), rows
+ assert received.usage == row_tokens, (received.usage, row_tokens)
+ partial: Final = (row_tokens[0] - BACKUP_USAGE[0], row_tokens[1] - BACKUP_USAGE[1])
+ assert partial[0] > 0 and partial[1] > 0, (row_tokens, BACKUP_USAGE)
+ return Billed(rows, partial)
+
+
+def assert_spend_prices_every_token(rig: Rig, key: str, billed: Billed) -> None:
+ partial_cost: Final = cost(billed.partial, PRIMARY_PRICES)
+ breakdown: Final = object_value(object_value(billed.rows[0]["metadata"])["cost_breakdown"])
+ spend: Final = amount(billed.rows[0]["spend"])
+ reported_partial_cost: Final = amount(object_value(breakdown["additional_costs"])["mid_stream_partial_cost"])
+ assert close(spend, cost(BACKUP_USAGE, BACKUP_PRICES) + partial_cost) and close(
+ reported_partial_cost, partial_cost
+ ), f"partial={billed.partial} spend={spend} breakdown={json.dumps(breakdown)}"
+ eventually(lambda: key_spend(rig, key), lambda value: close(value, spend), seconds=70)
+ assert spend_rows(rig, key) == billed.rows
+
+
+def test_text_cut_continues_on_the_prefill_fallback_and_bills_both_calls_once(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ key: Final = new_key(configured)
+ prompt: Final = f"text-cut {marker}"
+ received: Final = stream(configured, key, "primary", prompt, (after_text(marker, "primary", JOINED_PARTIAL),))
+ assert received.error is None, received.error
+ assert received.text == JOINED_PARTIAL + BACKUP_TEXT, received.chunks
+ assert received.ids == {f"chatcmpl-{marker}-primary"}, received.ids
+ assert received.role_deltas == 1, received.chunks
+ assert received.finish_reasons == ("stop",), received.chunks
+ assert len(chat_bodies(configured.primary, marker)) == 1
+ continued: Final = chat_bodies(configured.backup, marker)
+ assert len(continued) == 1, continued
+ assert continued[0]["messages"] == [{"role": "user", "content": prompt}, prefill_turn(JOINED_PARTIAL)]
+ assert "_mid_stream_continuation" not in continued[0], continued[0]
+ billed: Final = billed_once(configured, key, received)
+ assert continued[0]["max_tokens"] == MAX_TOKENS - billed.partial[1], (continued[0], billed.partial)
+ assert_spend_prices_every_token(configured, key, billed)
+
+
+def test_spend_row_of_a_continued_stream_carries_the_id_the_caller_received(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ key: Final = new_key(configured)
+ received: Final = stream(
+ configured, key, "primary", f"text-cut {marker}", (after_text(marker, "primary", JOINED_PARTIAL),)
+ )
+ assert received.error is None, received.error
+ assert [row["request_id"] for row in spend_rows(configured, key)] == [received.chunks[0].id]
+
+
+def test_tool_call_before_the_cut_keeps_the_original_error(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ configured,
+ new_key(configured),
+ "primary",
+ f"tool-cut {marker}",
+ (Release(cut_gate(marker, "primary", 0), has_tool_call),),
+ {"tools": [dict(WEATHER_TOOL)]},
+ )
+ assert received.error is not None, received.chunks
+ assert (received.text, has_tool_call(received.chunks)) == (TOOL_PREAMBLE, True), received.chunks
+ assert len(chat_bodies(configured.primary, marker)) == 1
+ assert chat_bodies(configured.backup, marker) == ()
+
+
+def test_continuation_skips_a_fallback_without_prefill_support(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ prompt: Final = f"text-cut {marker}"
+ received: Final = stream(
+ configured, new_key(configured), "primary-skip", prompt, (after_text(marker, "primary", JOINED_PARTIAL),)
+ )
+ assert received.error is None, received.error
+ assert received.text == JOINED_PARTIAL + BACKUP_TEXT, received.chunks
+ assert chat_bodies(configured.no_prefill, marker) == ()
+ assert [body["messages"] for body in chat_bodies(configured.backup, marker)] == [
+ [{"role": "user", "content": prompt}, prefill_turn(JOINED_PARTIAL)]
+ ]
+
+
+def test_no_prefill_capable_fallback_keeps_the_original_error(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ configured,
+ new_key(configured),
+ "primary-none",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL),),
+ )
+ assert received.error is not None, received.chunks
+ assert "No deployments available" not in str(received.error), received.error
+ assert received.text == JOINED_PARTIAL, received.chunks
+ assert len(chat_bodies(configured.primary, marker)) == 1
+ assert chat_bodies(configured.no_prefill, marker) == ()
+
+
+def test_undeclared_fallback_sharing_a_backend_with_a_prefill_deployment_keeps_the_original_error(
+ configured: Rig,
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ configured,
+ new_key(configured),
+ "primary-shared",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL),),
+ )
+ assert (received.error is not None, received.text) == (True, JOINED_PARTIAL), received.chunks
+ assert chat_bodies(configured.no_prefill, marker) == ()
+
+
+def test_failure_before_content_still_falls_back_to_a_fallback_without_prefill_support(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ prompt: Final = f"reject {marker}"
+ received: Final = stream(configured, new_key(configured), "primary-none", prompt)
+ assert received.error is None, received.error
+ assert received.text == PLAIN_TEXT, received.chunks
+ assert [body["messages"] for body in chat_bodies(configured.no_prefill, marker)] == [
+ [{"role": "user", "content": prompt}]
+ ]
+
+
+def stream_with_two_cuts(rig: Rig, key: str, marker: str) -> Streamed:
+ return stream(
+ rig,
+ key,
+ "primary-relay",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL), after_text(marker, "relay", JOINED_PARTIAL + RELAY_TEXT)),
+ )
+
+
+def test_second_cut_continues_with_both_partials_in_one_prefill(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ key: Final = new_key(configured)
+ received: Final = stream_with_two_cuts(configured, key, marker)
+ assert received.error is None, received.error
+ assert received.text == JOINED_PARTIAL + RELAY_TEXT + BACKUP_TEXT, received.chunks
+ assert received.role_deltas == 1, received.chunks
+ user_turn: Final = {"role": "user", "content": f"text-cut {marker}"}
+ relayed: Final = chat_bodies(configured.relay, marker)
+ continued: Final = chat_bodies(configured.backup, marker)
+ assert [body["messages"] for body in relayed] == [[user_turn, prefill_turn(JOINED_PARTIAL)]]
+ assert [body["messages"] for body in continued] == [[user_turn, prefill_turn(JOINED_PARTIAL + RELAY_TEXT)]]
+ partial: Final = billed_once(configured, key, received).partial
+ relay_ceiling: Final = relayed[0]["max_tokens"]
+ assert isinstance(relay_ceiling, int), relayed[0]
+ assert 0 < MAX_TOKENS - relay_ceiling < partial[1], (relayed[0], partial)
+ assert continued[0]["max_tokens"] == MAX_TOKENS - partial[1], (continued[0], partial)
+
+
+def test_second_cut_bills_every_call_on_one_row(configured: Rig) -> None:
+ key: Final = new_key(configured)
+ received: Final = stream_with_two_cuts(configured, key, uuid.uuid4().hex)
+ assert received.error is None, received.error
+ assert_spend_prices_every_token(configured, key, billed_once(configured, key, received))
+
+
+def test_repeating_a_continued_request_never_returns_only_the_continuation(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ key: Final = new_key(configured)
+ prompt: Final = f"text-cut {marker}"
+ answers: Final = tuple(
+ stream(configured, key, "primary", prompt, (after_text(marker, "primary", JOINED_PARTIAL, attempt),))
+ for attempt in range(2)
+ )
+ assert tuple((answer.error, answer.text) for answer in answers) == ((None, JOINED_PARTIAL + BACKUP_TEXT),) * 2
+
+
+def test_without_the_setting_a_text_cut_keeps_the_original_error(unset: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ unset, new_key(unset), "primary", f"text-cut {marker}", (after_text(marker, "primary", JOINED_PARTIAL),)
+ )
+ assert received.error is not None, received.chunks
+ assert received.text == JOINED_PARTIAL, received.chunks
+ assert len(chat_bodies(unset.primary, marker)) == 1
+ assert chat_bodies(unset.no_prefill, marker) == ()
+ assert chat_bodies(unset.backup, marker) == ()
+
+
+def router_setting(rig: Rig) -> JsonValue:
+ return object_value(rig.gateway.get("/router/settings")["current_values"]).get(SETTING)
+
+
+def test_turning_the_setting_on_at_runtime_continues_on_a_prefill_fallback(unset: Rig) -> None:
+ rig: Final = unset
+ rig.gateway.post("/config/update", {"router_settings": {SETTING: True}})
+ try:
+ assert router_setting(rig) is True
+ marker: Final = uuid.uuid4().hex
+ prompt: Final = f"text-cut {marker}"
+ received: Final = stream(rig, new_key(rig), "primary", prompt, (after_text(marker, "primary", JOINED_PARTIAL),))
+ assert received.error is None, received.error
+ assert received.text == JOINED_PARTIAL + BACKUP_TEXT, received.chunks
+ assert chat_bodies(rig.no_prefill, marker) == ()
+ assert [body["messages"] for body in chat_bodies(rig.backup, marker)] == [
+ [{"role": "user", "content": prompt}, prefill_turn(JOINED_PARTIAL)]
+ ]
+ finally:
+ rig.gateway.post("/config/update", {"router_settings": {SETTING: False}})
+
+
+def test_a_registered_output_guardrail_keeps_the_original_error(output_guarded: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ output_guarded,
+ new_key(output_guarded),
+ "primary",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL),),
+ )
+ assert (received.error is not None, received.text) == (True, JOINED_PARTIAL), received.chunks
+ assert len(chat_bodies(output_guarded.primary, marker)) == 1
+ assert chat_bodies(output_guarded.backup, marker) == ()
+
+
+def test_a_request_fallback_bringing_its_own_messages_keeps_the_original_error(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ configured,
+ new_key(configured),
+ "primary",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL),),
+ {"fallbacks": [{"model": "backup", "messages": [{"role": "user", "content": f"start over {marker}"}]}]},
+ )
+ assert (received.error is not None, received.text) == (True, JOINED_PARTIAL), received.chunks
+ assert len(chat_bodies(configured.primary, marker)) == 1
+ assert chat_bodies(configured.backup, marker) == ()
+
+
+def carries_tag(event: Mapping[str, JsonValue], marker: str) -> bool:
+ tags: Final = event.get("request_tags")
+ return isinstance(tags, list) and marker in tags
+
+
+def tagged_events(batches: Iterable[Request], marker: str) -> tuple[dict[str, JsonValue], ...]:
+ events: Final = itertools.chain.from_iterable(EVENT_BATCH.validate_json(batch.body) for batch in batches)
+ return tuple(event for event in events if carries_tag(event, marker))
+
+
+def logged_events(sink: Wire, marker: str) -> Iterator[tuple[dict[str, JsonValue], ...]]:
+ return itertools.accumulate((tagged_events(sink.drain(), marker) for _ in itertools.count()), operator.add)
+
+
+def test_the_cut_call_logs_its_failure_under_its_own_deployment_and_price(configured: Rig) -> None:
+ marker: Final = uuid.uuid4().hex
+ received: Final = stream(
+ configured,
+ new_key(configured),
+ "primary",
+ f"text-cut {marker}",
+ (after_text(marker, "primary", JOINED_PARTIAL),),
+ {"metadata": {"tags": [marker]}},
+ )
+ assert received.error is None, received.error
+ polls: Final = logged_events(configured.events, marker)
+ events: Final = eventually(lambda: next(polls), lambda logged: len(logged) >= 2, seconds=30)
+ assert sorted(str(event["status"]) for event in events) == ["failure", "success"], events
+ failure: Final = next(event for event in events if event["status"] == "failure")
+ assert failure["model_group"] == "primary", failure
+ assert str(failure["api_base"]).startswith(configured.primary.url), failure
+ tokens: Final = (failure["prompt_tokens"], failure["completion_tokens"])
+ assert isinstance(tokens[0], int) and isinstance(tokens[1], int) and tokens[0] > 0 and tokens[1] > 0, failure
+ assert close(amount(failure["response_cost"]), cost((tokens[0], tokens[1]), PRIMARY_PRICES)), failure
diff --git a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
index c878f0e149d..bf977325a85 100644
--- a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
+++ b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
@@ -642,6 +642,64 @@ async def test_bedrock_converse_replays_reasoning_to_claude_only_as_base64_of_cl
assert assistant_content == [*sent, {"text": "hello"}]
[email protected]("use_async", [False, True])
+ "model, final_text",
+ [("us.anthropic.claude-sonnet-4-6", "Leaves fall"), ("us.amazon.nova-pro-v1:0", "Leaves fall \n")],
+ ids=["claude", "nova"],
+)
+async def test_bedrock_converse_strips_trailing_whitespace_from_a_final_assistant_turn_for_claude_only(
+ use_async: bool, model: str, final_text: str
+):
+ """Claude on Converse 400s on a final assistant turn ending in whitespace, which a cut stream's prefill often has."""
+ messages: Final = [
+ {"role": "user", "content": "Write a haiku."},
+ {"role": "assistant", "content": "Sure. "},
+ {"role": "user", "content": "About autumn."},
+ {"role": "assistant", "content": "Leaves fall \n"},
+ ]
+
+ result: Final = (
+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
+ messages=messages, model=model, llm_provider="bedrock"
+ )
+ if use_async
+ else _bedrock_converse_messages_pt(messages=messages, model=model, llm_provider="bedrock")
+ )
+
+ assert [m["content"] for m in result if m["role"] == "assistant"] == [
+ [{"text": "Sure. "}],
+ [{"text": final_text}],
+ ]
+
+
[email protected]("use_async", [False, True])
+async def test_bedrock_converse_keeps_whitespace_between_text_blocks_of_a_final_claude_assistant_turn(
+ use_async: bool,
+):
+ messages: Final = [
+ {"role": "user", "content": "Write a haiku."},
+ {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "Leaves fall "}, {"type": "text", "text": "softly \n"}],
+ },
+ ]
+
+ result: Final = (
+ await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async(
+ messages=messages, model="us.anthropic.claude-sonnet-4-6", llm_provider="bedrock"
+ )
+ if use_async
+ else _bedrock_converse_messages_pt(
+ messages=messages, model="us.anthropic.claude-sonnet-4-6", llm_provider="bedrock"
+ )
+ )
+
+ assert result[-1]["content"] == [{"text": "Leaves fall "}, {"text": "softly"}]
+
+
def test_translate_thinking_blocks_keeps_dropping_redacted_data_when_called_the_old_way():
"""Outside callers that only pass the thinking blocks keep the old behavior, with no redactedContent sent."""
assert BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks(
diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.py
index 4347a6639bd..fa649b48a51 100644
--- a/tests/unit/litellm_core_utils/test_streaming_handler.py
+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py
@@ -1019,6 +1019,87 @@ async def test_bridged_stream_mid_stream_fallback_error_is_rebuilt_around_the_pr
assert excinfo.value.generated_content == ""
[email protected]("merge_reasoning", [True, False], ids=["merged_into_content", "kept_as_reasoning"])
+async def test_mid_stream_break_after_reasoning_disqualifies_continuation(logging_obj: Logging, merge_reasoning: bool):
+ import httpx
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ class _ReasoningThenCut:
+ def __init__(self) -> None:
+ self.chunks = iter(
+ (
+ ModelResponseStream(choices=[{"index": 0, "delta": {"reasoning_content": "Let me think"}}]),
+ ModelResponseStream(choices=[{"index": 0, "delta": {"content": "The answer"}}]),
+ )
+ )
+
+ def __aiter__(self) -> "_ReasoningThenCut":
+ return self
+
+ async def __anext__(self) -> ModelResponseStream:
+ next_chunk: Final = next(self.chunks, None)
+ if next_chunk is None:
+ raise httpx.ReadTimeout("connection dropped")
+ return next_chunk
+
+ response: Final = CustomStreamWrapper(
+ completion_stream=_ReasoningThenCut(), model="deepseek-reasoner", logging_obj=logging_obj
+ )
+ response.merge_reasoning_content_in_choices = merge_reasoning
+
+ with pytest.raises(MidStreamFallbackError) as excinfo:
+ async for _ in response:
+ pass
+
+ assert excinfo.value.is_pre_first_chunk is False
+ assert excinfo.value.emitted_disqualifying_content is True
+
+
+ "outer_delta,inner_flag,expected",
+ [
+ ({"tool_calls": [{"index": 0}]}, False, True),
+ ({"content": "Let me check."}, True, True),
+ ({"content": "Let me check."}, False, False),
+ ],
+ ids=["bridge_wrapper_sent_a_tool_call", "inner_stream_sent_a_tool_call", "plain_text_only"],
+)
+async def test_bridged_stream_rebuild_keeps_the_continuation_disqualifier(
+ logging_obj: Logging, outer_delta: dict[str, object], inner_flag: bool, expected: bool
+):
+ from litellm.exceptions import InternalServerError, MidStreamFallbackError
+
+ provider_error: Final = InternalServerError(message="upstream 500", llm_provider="azure", model="gpt-6.1-sol")
+ inner_error: Final = MidStreamFallbackError(
+ message=str(provider_error),
+ model="gpt-6.1-sol",
+ llm_provider="azure",
+ original_exception=provider_error,
+ is_pre_first_chunk=False,
+ emitted_disqualifying_content=inner_flag,
+ )
+
+ async def _raise_inner_error(**kwargs: object) -> NoReturn:
+ raise inner_error
+
+ response: Final = CustomStreamWrapper(
+ completion_stream=None,
+ model="gpt-6.1-sol",
+ logging_obj=logging_obj,
+ custom_llm_provider="azure",
+ make_call=_raise_inner_error,
+ )
+ response._accumulate_streamed_delta(outer_delta)
+
+ with pytest.raises(MidStreamFallbackError) as excinfo:
+ await response.__anext__()
+
+ assert excinfo.value.emitted_disqualifying_content is expected
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("sync_mode", [True, False])
async def test_streaming_rate_limit_midstream_fallback_keeps_provider_headers(logging_obj: Logging, sync_mode: bool):
@@ -6230,6 +6311,59 @@ class TestStableStreamingResponseId:
assert wrapper.model_response_creator().id == "chatcmpl-from-provider"
+class TestContinuationDisqualifiers:
+ """The mid-stream continuation eligibility hinges on classifying which deltas
+ carry output a text-only prefill cannot represent."""
+
+ @pytest.mark.parametrize(
+ "field",
+ [
+ "tool_calls",
+ "function_call",
+ "reasoning_content",
+ "thinking_blocks",
+ "reasoning_items",
+ "audio",
+ "images",
+ "annotations",
+ ],
+ )
+ def test_disqualifying_fields_flagged(self, field):
+ # reasoning_content included: it reaches the caller as visible reasoning a
+ # text-only prefill cannot carry, so a reasoning fallback would re-derive it
+ assert CustomStreamWrapper._delta_disqualifies_continuation({field: [{"x": 1}]}) is True
+
+ @pytest.mark.parametrize("delta", [{"content": "hi"}, {}, {"role": "assistant"}])
+ def test_plain_text_not_flagged(self, delta):
+ assert CustomStreamWrapper._delta_disqualifies_continuation(delta) is False
+
+ def test_non_mapping_delta_is_safe(self):
+ assert CustomStreamWrapper._delta_disqualifies_continuation(object()) is False
+
+ def test_accumulate_grows_text_and_leaves_flag_clear_for_plain_text(self):
+ wrapper = object.__new__(CustomStreamWrapper)
+ wrapper.response_uptil_now = ""
+ wrapper._emitted_disqualifying_content = False
+
+ wrapper._accumulate_streamed_delta({"content": "Hel"})
+ wrapper._accumulate_streamed_delta({"content": "lo"})
+
+ assert wrapper.response_uptil_now == "Hello"
+ assert wrapper._emitted_disqualifying_content is False
+
+ def test_accumulate_latches_flag_on_disqualifying_delta(self):
+ wrapper = object.__new__(CustomStreamWrapper)
+ wrapper.response_uptil_now = ""
+ wrapper._emitted_disqualifying_content = False
+
+ wrapper._accumulate_streamed_delta({"content": "Hi"})
+ wrapper._accumulate_streamed_delta({"tool_calls": [{"index": 0}]})
+ wrapper._accumulate_streamed_delta({"content": "there"})
+
+ assert wrapper.response_uptil_now == "Hithere"
+ assert wrapper._emitted_disqualifying_content is True
+
+
@pytest.mark.asyncio
async def test_async_stream_without_usage_counts_tokens_off_the_event_loop():
from tests.large_text import text
diff --git a/tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py b/tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py
index 650517c92ca..1e353a7a82a 100644
--- a/tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py
+++ b/tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py
@@ -461,6 +461,21 @@ def test_transform_messages_sanitizes_empty_content():
assert result[1]["content"] == "Hi"
+def test_transform_messages_drops_the_prefill_prefix_flag():
+ """Databricks rejects unknown message keys, so a continuation prefill reaches Claude without ``prefix``."""
+ messages = [
+ {"role": "user", "content": "How do transformers work?"},
+ {"role": "assistant", "content": "Transformers use", "prefix": True},
+ ]
+
+ result = DatabricksConfig().transform_messages(
+ messages=messages, model="databricks-claude-sonnet-4-6", is_async=False
+ )
+
+ assert result[-1] == {"role": "assistant", "content": "Transformers use"}
+ assert messages[-1]["prefix"] is True
+
+
def test_transform_request_preserves_unity_model_service_name():
config = DatabricksConfig()
result = config.transform_request(
diff --git a/tests/unit/router_utils/pre_call_checks/test_continuation_prefill_check.py b/tests/unit/router_utils/pre_call_checks/test_continuation_prefill_check.py
new file mode 100644
index 00000000000..8fa1c799863
--- /dev/null
+++ b/tests/unit/router_utils/pre_call_checks/test_continuation_prefill_check.py
@@ -0,0 +1,288 @@
+import pytest
+
+import litellm
+from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_KWARG,
+ MID_STREAM_CONTINUATION_MARKER,
+ ContinuationOutput,
+ ContinuationPrefillDeploymentCheck,
+ continuation_output_ceilings,
+ deployment_supports_prefill,
+)
+
+PREFILL_MODEL = "anthropic/prefill-capable-test-model"
+NON_PREFILL_MODEL = "openai/prefill-unknown-test-model"
+UNMAPPED_MODEL = "openai/unmapped-test-model"
+
+
[email protected](autouse=True)
+def _synthetic_cost_map_entries() -> None:
+ litellm.register_model(
+ {
+ PREFILL_MODEL: {"litellm_provider": "anthropic", "mode": "chat", "supports_assistant_prefill": True},
+ NON_PREFILL_MODEL: {"litellm_provider": "openai", "mode": "chat"},
+ },
+ persist_across_reloads=False,
+ )
+ litellm.get_model_info.cache_clear()
+
+
+def _deployment(model: str, dep_id: str) -> dict[str, object]:
+ return {"litellm_params": {"model": model}, "model_info": {"id": dep_id}}
+
+
+def test_deployment_supports_prefill_reads_capability():
+ assert deployment_supports_prefill(_deployment(PREFILL_MODEL, "a")) is True
+ assert deployment_supports_prefill(_deployment(NON_PREFILL_MODEL, "b")) is False
+ assert deployment_supports_prefill({"litellm_params": {"model": PREFILL_MODEL}}) is True
+ assert deployment_supports_prefill({"litellm_params": {"model": PREFILL_MODEL}, "model_info": "bogus"}) is True
+
+
+def test_deployment_model_info_override_wins_over_cost_map():
+ # model_info True opts in a model that is not in the cost map
+ assert (
+ deployment_supports_prefill(
+ {"litellm_params": {"model": "vendor/custom-model"}, "model_info": {"supports_assistant_prefill": True}}
+ )
+ is True
+ )
+ # model_info False opts out a model the cost map would otherwise allow
+ assert (
+ deployment_supports_prefill(
+ {"litellm_params": {"model": PREFILL_MODEL}, "model_info": {"supports_assistant_prefill": False}}
+ )
+ is False
+ )
+ # model_info without the key falls through to the cost map
+ assert deployment_supports_prefill(_deployment(PREFILL_MODEL, "z")) is True
+
+
+ "deployment,expected",
+ [
+ ({"litellm_params": {"model": "bedrock/arn:custom-import", "base_model": PREFILL_MODEL}}, True),
+ ({"litellm_params": {"model": "azure/my-deployment"}, "model_info": {"base_model": PREFILL_MODEL}}, True),
+ (
+ {
+ "litellm_params": {"model": "azure/my-deployment", "base_model": NON_PREFILL_MODEL},
+ "model_info": {"base_model": PREFILL_MODEL},
+ },
+ True,
+ ),
+ (
+ {
+ "litellm_params": {"model": PREFILL_MODEL, "base_model": NON_PREFILL_MODEL},
+ "model_info": {"base_model": NON_PREFILL_MODEL},
+ },
+ False,
+ ),
+ ],
+ ids=[
+ "litellm_params_base_model",
+ "model_info_base_model",
+ "model_info_base_model_wins",
+ "base_model_wins_over_model",
+ ],
+)
+def test_deployment_supports_prefill_reads_the_cost_map_key_of_the_base_model(deployment, expected):
+ assert deployment_supports_prefill(deployment) is expected
+
+
+def test_deployment_supports_prefill_rejects_malformed_deployments():
+ assert deployment_supports_prefill({}) is False
+ assert deployment_supports_prefill({"litellm_params": {}}) is False
+ assert deployment_supports_prefill("not-a-dict") is False
+
+
+async def test_filter_is_noop_without_continuation_marker():
+ """A normal (non-continuation) request must be passed through untouched, even
+ if some deployments cannot prefill."""
+ check = ContinuationPrefillDeploymentCheck()
+ deployments = [_deployment(PREFILL_MODEL, "a"), _deployment(NON_PREFILL_MODEL, "b")]
+
+ for request_kwargs in ({}, None, {MID_STREAM_CONTINUATION_KWARG: False}):
+ result = await check.async_filter_deployments(
+ model="group", healthy_deployments=deployments, messages=None, request_kwargs=request_kwargs
+ )
+ assert result == deployments
+
+
+async def test_filter_ignores_forged_client_flag():
+ """A client cannot steer routing: a plain truthy value under the marker key
+ (which the proxy could forward from the request body) is not the internal
+ sentinel, so the filter leaves the deployment list untouched."""
+ check = ContinuationPrefillDeploymentCheck()
+ deployments = [_deployment(PREFILL_MODEL, "a"), _deployment(NON_PREFILL_MODEL, "b")]
+
+ for forged in (True, "true", 1, {"any": "json"}):
+ result = await check.async_filter_deployments(
+ model="group",
+ healthy_deployments=deployments,
+ messages=None,
+ request_kwargs={MID_STREAM_CONTINUATION_KWARG: forged},
+ )
+ assert result == deployments
+
+
+async def test_filter_keeps_only_prefill_capable_on_continuation():
+ check = ContinuationPrefillDeploymentCheck()
+ deployments = [_deployment(PREFILL_MODEL, "a"), _deployment(NON_PREFILL_MODEL, "b")]
+
+ result = await check.async_filter_deployments(
+ model="group",
+ healthy_deployments=deployments,
+ messages=None,
+ request_kwargs={MID_STREAM_CONTINUATION_KWARG: MID_STREAM_CONTINUATION_MARKER},
+ )
+ assert [d["model_info"]["id"] for d in result] == ["a"]
+
+
+async def test_filter_empties_group_when_no_prefill_capable_deployment():
+ """No prefill-capable deployment -> empty result, so the router advances the
+ fallback chain and ultimately surfaces the original error."""
+ check = ContinuationPrefillDeploymentCheck()
+ deployments = [_deployment(NON_PREFILL_MODEL, "b"), _deployment(UNMAPPED_MODEL, "c")]
+
+ result = await check.async_filter_deployments(
+ model="group",
+ healthy_deployments=deployments,
+ messages=None,
+ request_kwargs={MID_STREAM_CONTINUATION_KWARG: MID_STREAM_CONTINUATION_MARKER},
+ )
+ assert result == []
+
+
+async def test_filter_drops_deployments_whose_own_params_constrain_the_continuation():
+ check = ContinuationPrefillDeploymentCheck()
+ plain = _deployment(PREFILL_MODEL, "plain")
+ constrained = [
+ {"litellm_params": {"model": PREFILL_MODEL, **params}, "model_info": {"id": dep_id}}
+ for dep_id, params in (
+ ("json", {"response_format": {"type": "json_object"}}),
+ ("two_choices", {"extra_body": {"n": 2}}),
+ ("forced_tool", {"tool_choice": {"type": "function", "function": {"name": "f"}}}),
+ ("merged_reasoning", {"merge_reasoning_content_in_choices": True}),
+ )
+ ]
+
+ result = await check.async_filter_deployments(
+ model="group",
+ healthy_deployments=[plain, *constrained],
+ messages=None,
+ request_kwargs={MID_STREAM_CONTINUATION_KWARG: MID_STREAM_CONTINUATION_MARKER},
+ )
+ assert [d["model_info"]["id"] for d in result] == ["plain"]
+
+
+def _text_chunk(text: str) -> litellm.ModelResponseStream:
+ return litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": text}}])
+
+
+ "prefill_content,fallback_texts,expected_texts",
+ [
+ ("Hello", ("", "Hel", "lo wor", "ld"), ("", "", " wor", "ld")),
+ ("Hello", ("Hello",), ("",)),
+ ("Hello", (" world",), (" world",)),
+ ("Hello", ("Hel", "p me"), ("Hel", "p me")),
+ ("Hello", ("Hel",), ("Hel",)),
+ ([{"type": "text", "text": "Sure: "}, {"type": "text", "text": "Hello"}], ("Sure: Hello", " world"), ("", " world")),
+ ],
+ ids=[
+ "echo_split_across_chunks_is_dropped",
+ "exact_echo_then_end_is_dropped",
+ "continuation_without_echo_passes_through",
+ "near_echo_is_kept_in_order",
+ "stream_ending_mid_match_is_kept",
+ "content_block_prefill_echo_is_dropped",
+ ],
+)
+async def test_continuation_output_drops_only_a_full_echo_of_the_prefill(
+ prefill_content, fallback_texts, expected_texts
+):
+ output = ContinuationOutput(
+ "Hello", {"role": "assistant", "content": prefill_content, "prefix": True}, "group", ()
+ )
+
+ async def fallback_stream():
+ for text in fallback_texts:
+ yield _text_chunk(text)
+
+ released = [chunk async for chunk in output.splice(fallback_stream())]
+
+ assert tuple(chunk.choices[0].delta.content for chunk in released) == expected_texts
+
+
+ "prefill,fallback_texts,expected_texts",
+ [
+ ("Transformers use ", ("self-attention",), ("self-attention",)),
+ ("Hello ", ("Hello ", " world"), ("", "world")),
+ ("Hello \n", ("\nworld",), ("\nworld",)),
+ ("A.\n\n", ("\n Hi", "\nthere"), (" Hi", "\nthere")),
+ ("\n\n", ("\nHi",), ("\nHi",)),
+ ("\nHello\n", ("\n",), ("",)),
+ ],
+ ids=[
+ "continuation_without_whitespace_passes_through",
+ "echo_then_re_emitted_space_are_both_dropped",
+ "different_whitespace_is_kept",
+ "seam_ends_at_the_first_divergence",
+ "whitespace_only_prefill_has_no_seam",
+ "re_emitted_whitespace_at_stream_end_is_dropped",
+ ],
+)
+async def test_continuation_output_drops_only_whitespace_the_client_already_has(
+ prefill, fallback_texts, expected_texts
+):
+ output = ContinuationOutput(prefill, {"role": "assistant", "content": prefill, "prefix": True}, "group", ())
+
+ async def fallback_stream():
+ for text in fallback_texts:
+ yield _text_chunk(text)
+
+ released = [chunk async for chunk in output.splice(fallback_stream())]
+
+ assert tuple(chunk.choices[0].delta.content for chunk in released) == expected_texts
+
+
+ "request_kwargs,expected",
+ [
+ ({"max_tokens": 100}, {"max_tokens": 70}),
+ ({"max_tokens": 100, "max_completion_tokens": 40}, {"max_tokens": 70, "max_completion_tokens": 10}),
+ ({}, {}),
+ (
+ {"max_tokens": 100, "extra_body": {"max_tokens": 50, "top_k": 3}},
+ {"max_tokens": 70, "extra_body": {"max_tokens": 20, "top_k": 3}},
+ ),
+ ({"extra_body": {"max_completion_tokens": 45}}, {"extra_body": {"max_completion_tokens": 15}}),
+ ({"extra_body": {"top_k": 3}}, {}),
+ ],
+ ids=["max_tokens", "both_ceilings", "no_ceiling", "extra_body_max_tokens", "extra_body_only", "extra_body_no_ceiling"],
+)
+def test_continuation_output_ceilings_take_the_emitted_tokens_off_every_ceiling_the_request_sends(
+ request_kwargs, expected
+):
+ assert continuation_output_ceilings(request_kwargs, 30) == expected
+
+
+ "request_kwargs",
+ [
+ {"max_tokens": 30},
+ {"max_tokens": 20},
+ {"max_tokens": 100, "max_completion_tokens": 30},
+ {"max_tokens": 100, "extra_body": {"max_tokens": 30}},
+ ],
+ ids=["max_tokens_met", "max_tokens_exceeded", "one_of_two_met", "extra_body_met"],
+)
+def test_continuation_output_ceilings_decline_once_a_ceiling_has_no_tokens_left(request_kwargs):
+ assert continuation_output_ceilings(request_kwargs, 30) is None
diff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.py
index 3bd051d71d4..6bc52ab3dfc 100644
--- a/tests/unit/test_router/test_router.py
+++ b/tests/unit/test_router/test_router.py
@@ -1,4 +1,5 @@
import ast, asyncio, importlib, time
+import contextlib
import copy
import functools
import gc
@@ -12,7 +13,7 @@ import warnings
from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from types import SimpleNamespace
+from types import MappingProxyType, SimpleNamespace
from typing import TYPE_CHECKING, Final, Literal, cast
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -2934,6 +2935,1216 @@ async def test_acompletion_streaming_iterator():
print("\n=== All tests passed! ===")
+def _make_midstream_source(error, chunks=None, first_chunk=None):
+ from unittest.mock import MagicMock
+
+ opening_chunk = (
+ first_chunk if first_chunk is not None else MagicMock(choices=[MagicMock(delta=MagicMock(content="Hello"))])
+ )
+
+ class _Source:
+ def __init__(self):
+ self.index = 0
+ self.chunks = chunks if chunks is not None else []
+ self.model = "gpt-4"
+ self.custom_llm_provider = "openai"
+ self.logging_obj = MagicMock()
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ if self.index == 0:
+ self.index += 1
+ return opening_chunk
+ raise error
+
+ async def wait_for_failure_logging(self, timeout):
+ return None
+
+ return _Source()
+
+
+class _FakeFallbackStream:
+ def __init__(self, item):
+ self._item = item
+ self._done = False
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ if self._done:
+ raise StopAsyncIteration
+ self._done = True
+ return self._item
+
+
+async def test_acompletion_streaming_iterator_continues_after_content_when_eligible():
+ """Flag on + plain-text break: the router re-enters the fallback chain with an
+ assistant-prefill continuation and the mid-stream marker, then streams the
+ fallback's output instead of re-raising."""
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+ from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_KWARG,
+ MID_STREAM_CONTINUATION_MARKER,
+ )
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+
+ error = MidStreamFallbackError(
+ message="Connection lost",
+ model="gpt-4",
+ llm_provider="openai",
+ generated_content="Hello",
+ is_pre_first_chunk=False,
+ emitted_disqualifying_content=False,
+ )
+ source = _make_midstream_source(error)
+ fallback_chunk = litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": "world"}}])
+ initial_kwargs = {"model": "gpt-4", "stream": True}
+
+ with patch.object(
+ router,
+ "async_function_with_fallbacks_common_utils",
+ new=AsyncMock(return_value=_FakeFallbackStream(fallback_chunk)),
+ ) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=source, messages=[{"role": "user", "content": "Hi"}], initial_kwargs=initial_kwargs
+ )
+ collected = [chunk async for chunk in result]
+
+ mock_fallback.assert_awaited_once()
+ passed_kwargs = mock_fallback.await_args.kwargs["kwargs"]
+ assert passed_kwargs[MID_STREAM_CONTINUATION_KWARG] is MID_STREAM_CONTINUATION_MARKER
+ assert passed_kwargs["messages"][-1] == {"role": "assistant", "content": "Hello", "prefix": True}
+ assert fallback_chunk in collected
+
+
+ "continuation_text,joined_output_trips_rule",
+ [("6789", True), ("6788", False)],
+ ids=["rule_trips_only_on_the_joined_text", "clean_continuation_streams"],
+)
+async def test_acompletion_streaming_iterator_continuation_runs_post_call_rules_on_the_joined_text(
+ monkeypatch, continuation_text, joined_output_trips_rule
+):
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ monkeypatch.setattr(litellm, "post_call_rules", [lambda output: "123-45-6789" not in output])
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content="123-45-",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ fallback_chunk = litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": continuation_text}}])
+
+ with patch.object(
+ router,
+ "async_function_with_fallbacks_common_utils",
+ new=AsyncMock(return_value=_FakeFallbackStream(fallback_chunk)),
+ ):
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error),
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ if joined_output_trips_rule:
+ with pytest.raises(litellm.APIResponseValidationError):
+ async for _ in result:
+ pass
+ else:
+ assert fallback_chunk in [chunk async for chunk in result]
+
+
+async def test_a_second_cut_runs_post_call_rules_only_on_the_text_the_caller_received(monkeypatch):
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+ from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_KWARG,
+ MID_STREAM_CONTINUATION_MARKER,
+ )
+
+ checked_texts = []
+ monkeypatch.setattr(litellm, "post_call_rules", [lambda output: checked_texts.append(output) is None])
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+
+ def cut(generated_content):
+ return MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content=generated_content,
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+
+ messages = [{"role": "user", "content": "Hi"}]
+ middle_leg = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(
+ cut(" there"),
+ first_chunk=litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": " there"}}]),
+ ),
+ messages=[*messages, {"role": "assistant", "content": "Hello", "prefix": True}],
+ initial_kwargs={"model": "gpt-4", "stream": True, MID_STREAM_CONTINUATION_KWARG: MID_STREAM_CONTINUATION_MARKER},
+ )
+ backup_leg = _FakeFallbackStream(
+ litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": " friend"}}])
+ )
+
+ with patch.object(
+ router, "async_function_with_fallbacks_common_utils", new=AsyncMock(side_effect=[middle_leg, backup_leg])
+ ):
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(cut("Hello")),
+ messages=messages,
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ _ = [chunk async for chunk in result]
+
+ assert checked_texts == ["Hello there", "Hello there friend"]
+
+
+ "fallback_texts",
+ [("Hel", "lo", " world"), (" world",)],
+ ids=["fallback_echoes_the_prefill", "fallback_continues_after_the_prefill"],
+)
+async def test_acompletion_streaming_iterator_continuation_never_repeats_the_partial_output(fallback_texts):
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "mistral/mistral-small-latest", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+
+ async def fallback_stream():
+ for text in fallback_texts:
+ yield litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": text}}])
+
+ with patch.object(
+ router, "async_function_with_fallbacks_common_utils", new=AsyncMock(return_value=fallback_stream())
+ ):
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error),
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ collected = [chunk async for chunk in result]
+
+ continuation = [chunk for chunk in collected if isinstance(chunk, litellm.ModelResponseStream)]
+ assert "".join(chunk.choices[0].delta.content for chunk in continuation) == " world"
+
+
+async def test_acompletion_streaming_iterator_continuation_stays_in_the_primary_stream():
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ primary_chunk = litellm.ModelResponseStream(
+ id="chatcmpl-primary", created=111, choices=[{"index": 0, "delta": {"role": "assistant", "content": "Hello"}}]
+ )
+
+ async def fallback_stream():
+ yield litellm.ModelResponseStream(
+ id="msg-fallback", created=222, choices=[{"index": 0, "delta": {"role": "assistant", "content": " wor"}}]
+ )
+ yield litellm.ModelResponseStream(
+ id="msg-fallback", created=222, choices=[{"index": 0, "delta": {"content": "ld"}}]
+ )
+
+ with patch.object(
+ router, "async_function_with_fallbacks_common_utils", new=AsyncMock(return_value=fallback_stream())
+ ):
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error, chunks=[primary_chunk]),
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ collected = [chunk async for chunk in result]
+
+ continuation = [chunk for chunk in collected if isinstance(chunk, litellm.ModelResponseStream)]
+ assert [(chunk.id, chunk.created, chunk.choices[0].delta.role) for chunk in continuation] == [
+ ("chatcmpl-primary", 111, None),
+ ("chatcmpl-primary", 111, None),
+ ]
+ assert "".join(chunk.choices[0].delta.content for chunk in continuation) == " world"
+
+
+def _continuation_router():
+ return litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+
+
+def _usage_chunk(prompt_tokens, completion_tokens):
+ from litellm.types.utils import Usage
+
+ return litellm.ModelResponseStream(
+ model="gpt-4",
+ choices=[],
+ usage=Usage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=prompt_tokens + completion_tokens,
+ ),
+ )
+
+
+async def _drain_with_fallback(router, error, primary_chunks, messages, fallback_items):
+ from unittest.mock import AsyncMock, patch
+
+ async def fallback_stream():
+ for item in fallback_items:
+ yield item
+
+ with patch.object(
+ router, "async_function_with_fallbacks_common_utils", new=AsyncMock(return_value=fallback_stream())
+ ) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error, chunks=primary_chunks),
+ messages=messages,
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ collected = [chunk async for chunk in result]
+ streamed = [chunk for chunk in collected if isinstance(chunk, litellm.ModelResponseStream)]
+ return mock_fallback.await_args.kwargs["kwargs"], streamed
+
+
[email protected]("primary_reports_usage", [True, False], ids=["usage_reported", "usage_not_reported"])
+async def test_acompletion_streaming_iterator_continuation_usage_sums_both_legs(primary_reports_usage):
+ from litellm.exceptions import MidStreamFallbackError
+
+ messages = [{"role": "user", "content": "Explain transformers in one paragraph."}]
+ partial = "Transformers use "
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content=partial,
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ content_chunk = litellm.ModelResponseStream(
+ model="gpt-4", choices=[{"index": 0, "delta": {"role": "assistant", "content": partial}}]
+ )
+ primary_chunks = [content_chunk, _usage_chunk(21, 3)] if primary_reports_usage else [content_chunk]
+ primary_usage = litellm.stream_chunk_builder(chunks=list(primary_chunks), messages=messages).usage
+
+ _, streamed = await _drain_with_fallback(
+ _continuation_router(), error, primary_chunks, messages, [_usage_chunk(91, 5)]
+ )
+
+ assert primary_usage.prompt_tokens > 0
+ assert streamed[-1].usage.prompt_tokens == primary_usage.prompt_tokens + 91
+ assert streamed[-1].usage.completion_tokens == primary_usage.completion_tokens + 5
+
+
+class _CutSSE(httpx.AsyncByteStream):
+ def __init__(self, content: str) -> None:
+ self._content: Final = content
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ yield f'data: {json.dumps({"id": "cut", "object": "chat.completion.chunk", "created": 1700000000, "model": "m", "choices": [{"index": 0, "delta": {"role": "assistant", "content": self._content}, "finish_reason": None}]})}\n\n'.encode()
+ raise httpx.RemoteProtocolError("peer closed connection without sending complete message body")
+
+
+_BACKUP_SSE: Final = "".join(
+ f"data: {json.dumps(chunk)}\n\n"
+ for chunk in (
+ {"id": "b", "object": "chat.completion.chunk", "created": 1700000000, "model": "mistral-large-latest",
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": " self-attention."}, "finish_reason": None}]},
+ {"id": "b", "object": "chat.completion.chunk", "created": 1700000000, "model": "mistral-large-latest",
+ "choices": [{"index": 0, "delta": {"content": ""}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 91, "completion_tokens": 5, "total_tokens": 96}},
+ )
+) + "data: [DONE]\n\n"
+
+
+class _SpendRecorder(CustomLogger):
+ def __init__(self) -> None:
+ super().__init__()
+ self.successes: Final[list[dict[str, object]]] = []
+ self.failures: Final[list[dict[str, object]]] = []
+ self.spend_rows: Final[list[dict[str, object]]] = []
+ self.succeeded: Final = asyncio.Event()
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None:
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+
+ self.successes.append(kwargs["standard_logging_object"])
+ self.spend_rows.append(get_logging_payload(kwargs, response_obj, start_time, end_time))
+ self.succeeded.set()
+
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time) -> None:
+ self.failures.append(kwargs["standard_logging_object"])
+
+
+class _SlowFailureRecorder(_SpendRecorder):
+ def __init__(self) -> None:
+ super().__init__()
+ self.failed_deployment_ids: Final[list[str]] = []
+
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time) -> None:
+ await asyncio.sleep(0.05)
+ self.failed_deployment_ids.append(kwargs["litellm_params"]["metadata"]["model_info"]["id"])
+ await super().async_log_failure_event(kwargs, response_obj, start_time, end_time)
+
+
[email protected]("cut_groups", [("primary",), ("primary", "middle")], ids=["one_break", "two_breaks"])
+async def test_continued_stream_success_log_bills_every_cut_leg(
+ monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter, cut_groups: tuple[str, ...]
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ recorder: Final = _SpendRecorder()
+ monkeypatch.setattr(litellm, "callbacks", [recorder])
+ respx_mock.post("https://api.openai.com/v1/chat/completions").mock(
+ return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_CutSSE("Transformers use"))
+ )
+ respx_mock.post(host="api.deepseek.com").mock(
+ return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_CutSSE(" learned"))
+ )
+ respx_mock.post(host="api.mistral.ai").mock(
+ return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, text=_BACKUP_SSE)
+ )
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "openai/gpt-4o",
+ "api_key": "k1",
+ "input_cost_per_token": 0.001,
+ "output_cost_per_token": 0.002,
+ },
+ },
+ {
+ "model_name": "middle",
+ "litellm_params": {
+ "model": "deepseek/deepseek-chat",
+ "api_key": "k2",
+ "input_cost_per_token": 0.003,
+ "output_cost_per_token": 0.004,
+ },
+ },
+ {"model_name": "backup", "litellm_params": {"model": "mistral/mistral-large-latest", "api_key": "k3"}},
+ ],
+ fallbacks=[{"primary": ["middle" if "middle" in cut_groups else "backup"]}, {"middle": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+
+ response: Final = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "How do transformers work?"}],
+ stream=True,
+ stream_options={"include_usage": True},
+ )
+ chunks: Final = [chunk async for chunk in response]
+ await asyncio.wait_for(recorder.succeeded.wait(), timeout=10)
+ await asyncio.sleep(0.5)
+
+ backup_prompt_cost, backup_completion_cost = litellm.cost_per_token(
+ model="mistral/mistral-large-latest", prompt_tokens=91, completion_tokens=5
+ )
+ success: Final = recorder.successes[-1]
+ assert len(recorder.failures) == len(cut_groups)
+ assert [failure["response_cost"] for failure in recorder.failures] == pytest.approx(
+ [
+ failure["prompt_tokens"] * input_price + failure["completion_tokens"] * output_price
+ for failure, (input_price, output_price) in zip(recorder.failures, ((0.001, 0.002), (0.003, 0.004)))
+ ]
+ )
+ assert success["response_cost"] == pytest.approx(
+ sum(failure["response_cost"] for failure in recorder.failures) + backup_prompt_cost + backup_completion_cost
+ )
+ assert success["prompt_tokens"] == sum(failure["prompt_tokens"] for failure in recorder.failures) + 91
+ assert success["completion_tokens"] == sum(failure["completion_tokens"] for failure in recorder.failures) + 5
+ assert success["cost_breakdown"]["total_cost"] == pytest.approx(success["response_cost"])
+ spend_row: Final = recorder.spend_rows[-1]
+ assert (spend_row["spend"], spend_row["prompt_tokens"], spend_row["completion_tokens"]) == (
+ success["response_cost"],
+ success["prompt_tokens"],
+ success["completion_tokens"],
+ )
+ client_usage: Final = next(chunk.usage for chunk in reversed(chunks) if getattr(chunk, "usage", None))
+ assert (client_usage.prompt_tokens, client_usage.completion_tokens) == (
+ success["prompt_tokens"],
+ success["completion_tokens"],
+ )
+ assert {chunk.id for chunk in chunks} == {spend_row["request_id"]}
+
+
+async def test_continued_stream_sharing_the_proxy_logging_object_bills_the_cut_to_its_own_deployment(
+ monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ recorder: Final = _SlowFailureRecorder()
+ monkeypatch.setattr(litellm, "callbacks", [recorder])
+ respx_mock.post("https://api.openai.com/v1/chat/completions").mock(
+ return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_CutSSE("Transformers use"))
+ )
+ respx_mock.post(host="api.mistral.ai").mock(
+ return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, text=_BACKUP_SSE)
+ )
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "openai/gpt-4o",
+ "api_key": "k1",
+ "input_cost_per_token": 0.001,
+ "output_cost_per_token": 0.002,
+ },
+ "model_info": {"id": "primary-deployment"},
+ },
+ {"model_name": "backup", "litellm_params": {"model": "mistral/mistral-large-latest", "api_key": "k3"}},
+ ],
+ fallbacks=[{"primary": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ messages: Final = [{"role": "user", "content": "How do transformers work?"}]
+ shared_logging, _ = litellm.utils.function_setup(
+ original_function="acompletion",
+ rules_obj=litellm.utils.Rules(),
+ start_time=datetime.now(),
+ model="primary",
+ messages=messages,
+ stream=True,
+ litellm_call_id="shared-call",
+ )
+
+ response: Final = await router.acompletion(
+ model="primary",
+ messages=messages,
+ stream=True,
+ stream_options={"include_usage": True},
+ litellm_call_id="shared-call",
+ litellm_logging_obj=shared_logging,
+ )
+ _ = [chunk async for chunk in response]
+ await asyncio.wait_for(recorder.succeeded.wait(), timeout=10)
+ await asyncio.sleep(0.5)
+
+ backup_prompt_cost, backup_completion_cost = litellm.cost_per_token(
+ model="mistral/mistral-large-latest", prompt_tokens=91, completion_tokens=5
+ )
+ (failure,) = recorder.failures
+ assert (failure["model_group"], failure["model_id"]) == ("primary", "primary-deployment")
+ assert recorder.failed_deployment_ids == ["primary-deployment"]
+ assert failure["response_cost"] == pytest.approx(
+ failure["prompt_tokens"] * 0.001 + failure["completion_tokens"] * 0.002
+ )
+ assert recorder.successes[-1]["response_cost"] == pytest.approx(
+ failure["response_cost"] + backup_prompt_cost + backup_completion_cost
+ )
+
+
+def test_carry_partial_spend_to_fallback_adds_the_partial_the_cut_stream_inherited():
+ from litellm.types.utils import Usage
+
+ cut_logging: Final = LiteLLMLogging(
+ model="deepseek/deepseek-chat", messages=[], stream=True, call_type="acompletion",
+ start_time=datetime.now(), litellm_call_id="cut", function_id="cut",
+ )
+ cut_logging.model_call_details["response_cost"] = 0.5
+ cut_logging.update_environment_variables(
+ litellm_params={"custom_llm_provider": "deepseek"}, optional_params={}, model="deepseek/deepseek-chat"
+ )
+ cut_logging.record_continued_partial(
+ usage=Usage(prompt_tokens=40, completion_tokens=7, total_tokens=47),
+ response_cost=0.001,
+ response_id="chatcmpl-primary",
+ )
+ fallback_logging: Final = LiteLLMLogging(
+ model="mistral-large-latest", messages=[], stream=True, call_type="acompletion",
+ start_time=datetime.now(), litellm_call_id="fallback", function_id="fallback",
+ )
+
+ Router._carry_partial_spend_to_fallback(
+ SimpleNamespace(logging_obj=fallback_logging),
+ Router._price_cut_partial(
+ cast(CustomStreamWrapper, SimpleNamespace(logging_obj=cut_logging, model="deepseek/deepseek-chat")),
+ litellm.ModelResponse(
+ id="chatcmpl-relay", usage=Usage(prompt_tokens=60, completion_tokens=3, total_tokens=63)
+ ),
+ ),
+ )
+
+ relay_prompt_cost, relay_completion_cost = litellm.cost_per_token(
+ model="deepseek/deepseek-chat", prompt_tokens=60, completion_tokens=3
+ )
+ carried_usage: Final = fallback_logging.model_call_details["continued_partial_usage"]
+ assert (carried_usage.prompt_tokens, carried_usage.completion_tokens) == (100, 10)
+ assert fallback_logging.model_call_details["continued_partial_cost"] == pytest.approx(
+ relay_prompt_cost + relay_completion_cost + 0.001
+ )
+ assert fallback_logging.model_call_details["continued_response_id"] == "chatcmpl-primary"
+
+
+async def test_acompletion_streaming_iterator_plain_fallback_keeps_the_fallback_usage():
+ from litellm.exceptions import MidStreamFallbackError
+
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="anthropic", generated_content="",
+ is_pre_first_chunk=True,
+ )
+ role_chunk = litellm.ModelResponseStream(
+ model="gpt-4", choices=[{"index": 0, "delta": {"role": "assistant", "content": ""}}]
+ )
+
+ _, streamed = await _drain_with_fallback(
+ _continuation_router(),
+ error,
+ [role_chunk, _usage_chunk(21, 0)],
+ [{"role": "user", "content": "Hi"}],
+ [_usage_chunk(91, 5)],
+ )
+
+ assert (streamed[-1].usage.prompt_tokens, streamed[-1].usage.completion_tokens) == (91, 5)
+
+
+ "partial,fallback_texts,expected_answer",
+ [
+ ("Transformers use ", (" self", "-attention"), "Transformers use self-attention"),
+ ("def f():\n ", ("\n", " return 1"), "def f():\n return 1"),
+ ("First.\n", ("\n\nSecond",), "First.\n\nSecond"),
+ ],
+ ids=["space", "indentation", "paragraph_break"],
+)
+async def test_acompletion_streaming_iterator_continuation_does_not_double_trailing_whitespace(
+ partial, fallback_texts, expected_answer
+):
+ from litellm.exceptions import MidStreamFallbackError
+
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content=partial,
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ fallback_items = [
+ litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": text}}]) for text in fallback_texts
+ ]
+
+ passed_kwargs, streamed = await _drain_with_fallback(
+ _continuation_router(), error, [], [{"role": "user", "content": "Hi"}], fallback_items
+ )
+
+ assert passed_kwargs["messages"][-1]["content"] == partial
+ assert partial + "".join(chunk.choices[0].delta.content for chunk in streamed) == expected_answer
+
+
[email protected]("enabled", [True, "true", " True "])
+async def test_update_settings_turns_on_mid_stream_continuation(monkeypatch, enabled):
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+ from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_KWARG,
+ MID_STREAM_CONTINUATION_MARKER,
+ ContinuationPrefillDeploymentCheck,
+ )
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ )
+ router.update_settings(enable_mid_stream_fallback_continuation=enabled)
+
+ error = MidStreamFallbackError(
+ message="Connection lost", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ fallback_chunk = litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": " world"}}])
+ with patch.object(
+ router,
+ "async_function_with_fallbacks_common_utils",
+ new=AsyncMock(return_value=_FakeFallbackStream(fallback_chunk)),
+ ) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error),
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ collected = [chunk async for chunk in result]
+
+ assert mock_fallback.await_args.kwargs["kwargs"][MID_STREAM_CONTINUATION_KWARG] is MID_STREAM_CONTINUATION_MARKER
+ assert fallback_chunk in collected
+ assert any(isinstance(callback, ContinuationPrefillDeploymentCheck) for callback in litellm.callbacks)
+
+
+ "error_kwargs,request_kwargs",
+ [
+ ({"emitted_disqualifying_content": True}, {}),
+ ({"emitted_disqualifying_content": False}, {"response_format": {"type": "json_object"}}),
+ ({"emitted_disqualifying_content": False}, {"tool_choice": "required"}),
+ ({"emitted_disqualifying_content": False}, {"merge_reasoning_content_in_choices": True}),
+ ({"emitted_disqualifying_content": False}, {"n": 2}),
+ ],
+ ids=["tool_or_thinking_emitted", "json_mode", "forced_tool_choice", "merged_reasoning", "multiple_choices"],
+)
+async def test_acompletion_streaming_iterator_declines_ineligible_after_content(error_kwargs, request_kwargs):
+ """Flag on but the break is not continuation-safe: the router re-raises and
+ never enters the fallback chain, so no duplicated/rejected request is sent."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error = MidStreamFallbackError(
+ message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, **error_kwargs,
+ )
+ source = _make_midstream_source(error)
+ initial_kwargs = {"model": "gpt-4", "stream": True, **request_kwargs}
+
+ with patch.object(router, "async_function_with_fallbacks_common_utils", new=AsyncMock()) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=source, messages=[{"role": "user", "content": "Hi"}], initial_kwargs=initial_kwargs
+ )
+ with pytest.raises(MidStreamFallbackError):
+ async for _ in result:
+ pass
+
+ mock_fallback.assert_not_awaited()
+
+
+async def test_acompletion_streaming_iterator_raises_content_filter_instead_of_continuing():
+ """A content filter that stops a stream mid-answer reaches the client as ContentPolicyViolationError,
+ never as a continuation that lets a backup finish the filtered answer."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "azure/gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ content_filter = litellm.ContentPolicyViolationError(message="filtered", model="gpt-4", llm_provider="azure")
+ error = MidStreamFallbackError(
+ message="filtered", model="gpt-4", llm_provider="azure", generated_content="Step one is to obtain the",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False, original_exception=content_filter,
+ )
+
+ with patch.object(router, "async_function_with_fallbacks_common_utils", new=AsyncMock()) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error),
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ with pytest.raises(litellm.ContentPolicyViolationError):
+ async for _ in result:
+ pass
+
+ mock_fallback.assert_not_awaited()
+
+
+async def _continues_after_content(
+ initial_kwargs: dict[str, object],
+ primary_params: Mapping[str, object] = MappingProxyType({}),
+ default_litellm_params: dict[str, object] | None = None,
+ cut_model_id: str = "primary-deployment",
+) -> bool:
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "gpt-4", "api_key": "k1", **primary_params},
+ "model_info": {"id": "primary-deployment"},
+ },
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ {
+ "model_name": "openai-backup",
+ "litellm_params": {"model": "gpt-4o", "api_key": "k3"},
+ "model_info": {"id": "no-prefill-deployment", "supports_assistant_prefill": False},
+ },
+ {
+ "model_name": "claude-backup",
+ "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k4"},
+ "model_info": {"id": "prefill-deployment", "supports_assistant_prefill": True},
+ },
+ {
+ "model_name": "json-claude-backup",
+ "litellm_params": {
+ "model": "anthropic/claude-3-opus-20240229",
+ "api_key": "k5",
+ "response_format": {"type": "json_object"},
+ },
+ "model_info": {"id": "json-prefill-deployment", "supports_assistant_prefill": True},
+ },
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ default_litellm_params=default_litellm_params,
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error: Final = MidStreamFallbackError(
+ message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ fallback_chunk: Final = litellm.ModelResponseStream(choices=[{"index": 0, "delta": {"content": " world"}}])
+ cut_stream: Final = _make_midstream_source(error)
+ cut_stream._hidden_params = {"model_id": cut_model_id}
+ with patch.object(
+ router,
+ "async_function_with_fallbacks_common_utils",
+ new=AsyncMock(return_value=_FakeFallbackStream(fallback_chunk)),
+ ) as mock_fallback:
+ result: Final = await router._acompletion_streaming_iterator(
+ model_response=cut_stream,
+ messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True, **initial_kwargs},
+ )
+ with contextlib.suppress(MidStreamFallbackError):
+ _ = [chunk async for chunk in result]
+ return mock_fallback.await_count == 1
+
+
+ "event_hook,continues",
+ [("post_call", False), (None, False), ("pre_call", True)],
+ ids=["post_call_guardrail", "every_hook_guardrail", "input_only_guardrail"],
+)
+async def test_mid_stream_continuation_declines_while_an_output_guardrail_is_registered(
+ monkeypatch: pytest.MonkeyPatch, event_hook: str | None, continues: bool
+) -> None:
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ guardrail: Final = CustomGuardrail(
+ guardrail_name="output-check", event_hook=GuardrailEventHooks(event_hook) if event_hook else None
+ )
+ monkeypatch.setattr(litellm, "callbacks", [guardrail])
+
+ assert await _continues_after_content({}) is continues
+
+
+ "fallbacks,continues",
+ [
+ ([{"model": "backup", "messages": [{"role": "user", "content": "Say hi"}]}], False),
+ ([{"model": "backup", "stream": False}], False),
+ ([{"model": "backup", "max_tokens": 300}], False),
+ ([{"model": "backup"}], True),
+ ([{"gpt-4": [{"model": "backup", "stream": False}]}], False),
+ ([{"*": [{"model": "backup", "max_tokens": 300}]}], False),
+ ([{"gpt-4": [{"model": "backup"}, "backup"]}], True),
+ ([{"gpt-4": ["backup"]}, {"other-group": [{"model": "backup", "stream": False}]}], True),
+ ([{}], True),
+ ([{"gpt-4": 5}], True),
+ ],
+ ids=[
+ "entry_with_its_own_messages",
+ "entry_turning_off_streaming",
+ "entry_with_its_own_max_tokens",
+ "entry_with_model_only",
+ "group_target_turning_off_streaming",
+ "generic_group_target_with_its_own_max_tokens",
+ "group_targets_with_model_only",
+ "override_only_in_another_groups_chain",
+ "empty_entry",
+ "non_list_chain",
+ ],
+)
+async def test_mid_stream_continuation_declines_a_request_fallback_that_overrides_request_params(
+ fallbacks: list[object], continues: bool
+) -> None:
+ assert await _continues_after_content({"fallbacks": fallbacks}) is continues
+
+
+ "fallbacks,continues",
+ [
+ ([{"gpt-4": ["no-prefill-deployment"]}], False),
+ ([{"gpt-4": ["backup", "no-prefill-deployment"]}], False),
+ ([{"model": "no-prefill-deployment"}], False),
+ ([{"gpt-4": ["prefill-deployment"]}], True),
+ ([{"gpt-4": ["openai-backup"]}], True),
+ ([{"gpt-4": ["json-prefill-deployment"]}], False),
+ ],
+ ids=[
+ "deployment_id_without_prefill",
+ "deployment_id_without_prefill_later_in_chain",
+ "flat_entry_naming_a_deployment_id_without_prefill",
+ "deployment_id_with_prefill",
+ "group_without_prefill_left_to_the_deployment_filter",
+ "deployment_id_with_its_own_response_format",
+ ],
+)
+async def test_mid_stream_continuation_declines_a_fallback_naming_a_deployment_that_cannot_continue(
+ fallbacks: list[object], continues: bool
+) -> None:
+ assert await _continues_after_content({"fallbacks": fallbacks}) is continues
+
+
+ "primary_params,default_litellm_params,continues",
+ [
+ ({"response_format": {"type": "json_object"}}, None, False),
+ ({"n": 2}, None, False),
+ ({"tool_choice": "required"}, None, False),
+ ({"merge_reasoning_content_in_choices": True}, None, False),
+ ({}, {"response_format": {"type": "json_object"}}, False),
+ ({"response_format": {"type": "text"}}, None, True),
+ ({"temperature": 0.2}, None, True),
+ ({"tool_choice": "required"}, {"tool_choice": "auto"}, False),
+ ({"response_format": {"type": "json_object"}}, {"response_format": {"type": "text"}}, True),
+ ({"extra_body": {"n": 2}}, None, False),
+ ],
+ ids=[
+ "deployment_response_format",
+ "deployment_n",
+ "deployment_tool_choice",
+ "deployment_merged_reasoning",
+ "router_default_response_format",
+ "deployment_plain_text_format",
+ "deployment_unrelated_param",
+ "deployment_tool_choice_over_router_default",
+ "router_default_format_over_deployment",
+ "deployment_extra_body_n",
+ ],
+)
+async def test_mid_stream_continuation_reads_constraints_configured_on_the_cut_deployment(
+ primary_params: Mapping[str, object], default_litellm_params: dict[str, object] | None, continues: bool
+) -> None:
+ assert await _continues_after_content({}, primary_params, default_litellm_params) is continues
+
+
+ "extra_body,continues",
+ [({"response_format": {"type": "json_object"}}, False), ({"n": 2}, False), ({"top_k": 5}, True)],
+ ids=["json_format_in_extra_body", "n_in_extra_body", "unrelated_extra_body_key"],
+)
+async def test_mid_stream_continuation_reads_constraints_the_request_sends_in_extra_body(
+ extra_body: dict[str, object], continues: bool
+) -> None:
+ assert await _continues_after_content({"extra_body": extra_body}) is continues
+
+
+async def test_mid_stream_continuation_declines_when_the_cut_deployment_is_not_in_the_router() -> None:
+ assert await _continues_after_content({}, cut_model_id="per-request-credential-deployment") is False
+
+
+ "routing_strategy",
+ [
+ "simple-shuffle",
+ "usage-based-routing",
+ "usage-based-routing-v2",
+ "least-busy",
+ "latency-based-routing",
+ "cost-based-routing",
+ ],
+)
+async def test_continuation_routes_only_to_deployments_that_can_continue_under_every_routing_strategy(
+ routing_strategy: str,
+) -> None:
+ from litellm.router_utils.pre_call_checks.continuation_prefill_check import (
+ MID_STREAM_CONTINUATION_KWARG,
+ MID_STREAM_CONTINUATION_MARKER,
+ )
+ from litellm.types.router import RouterRateLimitError
+
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "backup",
+ "litellm_params": {"model": "gpt-4o", "api_key": "k1"},
+ "model_info": {"id": "no-prefill-deployment", "supports_assistant_prefill": False},
+ },
+ ],
+ routing_strategy=routing_strategy,
+ enable_mid_stream_fallback_continuation=True,
+ )
+ messages: Final = [{"role": "user", "content": "Hi"}]
+ plain_pick: Final = await router.async_get_available_deployment(
+ model="backup", messages=messages, request_kwargs={}
+ )
+ assert plain_pick["model_info"]["id"] == "no-prefill-deployment"
+ with pytest.raises(RouterRateLimitError):
+ await router.async_get_available_deployment(
+ model="backup",
+ messages=messages,
+ request_kwargs={MID_STREAM_CONTINUATION_KWARG: MID_STREAM_CONTINUATION_MARKER},
+ )
+
+
+ "flag_kwargs", [{}, {"enable_mid_stream_fallback_continuation": "false"}], ids=["default", "string_false"]
+)
+async def test_acompletion_streaming_iterator_flag_off_declines_after_content(flag_kwargs):
+ """Regression guard for the opt-in default: with the flag off, a post-content
+ break re-raises and never falls back, exactly as before this feature."""
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ **flag_kwargs,
+ )
+ error = MidStreamFallbackError(
+ message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ source = _make_midstream_source(error)
+
+ with patch.object(router, "async_function_with_fallbacks_common_utils", new=AsyncMock()) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=source, messages=[{"role": "user", "content": "Hi"}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ with pytest.raises(MidStreamFallbackError):
+ async for _ in result:
+ pass
+
+ mock_fallback.assert_not_awaited()
+
+
+def test_build_completion_continuation_input_appends_assistant_prefill():
+ messages = [{"role": "user", "content": "hi"}]
+ built = litellm.Router._build_completion_continuation_input(messages, "partial answer")
+ assert built[:-1] == messages
+ assert built[-1] == {"role": "assistant", "content": "partial answer", "prefix": True}
+
+
+ "prefill_content,second_partial,expected_content",
+ [
+ ("part one ", " part two ", "part one part two "),
+ ("part one ", "part two ", "part one part two "),
+ ("First.\n\n", "Second", "First.\n\nSecond"),
+ ([{"type": "text", "text": "part one "}], " part two ", [{"type": "text", "text": "part one part two "}]),
+ ],
+ ids=["separator_sent_again", "separator_not_sent_again", "paragraph_break_not_sent_again", "content_blocks"],
+)
+def test_build_completion_continuation_input_folds_into_existing_prefill(
+ prefill_content, second_partial, expected_content
+):
+ """A nested break must not leave two trailing assistant turns: the new partial folds into the prior prefill,
+ which keeps reading as the text the caller already received."""
+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": prefill_content, "prefix": True}]
+ built = litellm.Router._build_completion_continuation_input(messages, second_partial)
+ assert built == [messages[0], {"role": "assistant", "content": expected_content, "prefix": True}]
+
+
+ "prefill_content,expected_content",
+ [
+ ("Hello", "Hello world"),
+ ([{"type": "text", "text": "Hello"}], [{"type": "text", "text": "Hello world"}]),
+ ],
+ ids=["string_prefill", "content_block_prefill"],
+)
+def test_build_completion_continuation_input_does_not_double_an_echoed_prefill(prefill_content, expected_content):
+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": prefill_content, "prefix": True}]
+ built = litellm.Router._build_completion_continuation_input(messages, "Hello world")
+ assert built is not None
+ assert built[-1] == {"role": "assistant", "content": expected_content, "prefix": True}
+
+
+ "cut_partial,expected_content",
+ [("Hel", None), ("Hello", "Hello"), ("Hello wor", "Hello wor")],
+ ids=["cut_mid_echo", "cut_after_a_full_echo", "cut_after_new_text"],
+)
+def test_build_completion_continuation_input_declines_a_cut_in_the_middle_of_a_prefill_echo(
+ cut_partial, expected_content
+):
+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "Hello", "prefix": True}]
+ built = litellm.Router._build_completion_continuation_input(messages, cut_partial)
+ expected = None if expected_content is None else [messages[0], {**messages[1], "content": expected_content}]
+ assert built == expected
+
+
+ "assistant_content", ["Earlier answer.", [{"type": "text", "text": "Earlier answer."}]], ids=["string", "blocks"]
+)
+def test_build_completion_continuation_input_declines_a_trailing_plain_assistant_turn(assistant_content):
+ """The caller's own assistant turn is history, not a prefill, so the partial is never fused into it."""
+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": assistant_content}]
+ assert litellm.Router._build_completion_continuation_input(messages, "The capital of France is") is None
+
+
+async def test_acompletion_streaming_iterator_declines_when_request_ends_in_plain_assistant_turn():
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k1"}},
+ {"model_name": "backup", "litellm_params": {"model": "anthropic/claude-3-opus-20240229", "api_key": "k2"}},
+ ],
+ fallbacks=[{"gpt-4": ["backup"]}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ error = MidStreamFallbackError(
+ message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+
+ with patch.object(router, "async_function_with_fallbacks_common_utils", new=AsyncMock()) as mock_fallback:
+ result = await router._acompletion_streaming_iterator(
+ model_response=_make_midstream_source(error),
+ messages=[{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Earlier answer."}],
+ initial_kwargs={"model": "gpt-4", "stream": True},
+ )
+ with pytest.raises(MidStreamFallbackError):
+ async for _ in result:
+ pass
+
+ mock_fallback.assert_not_awaited()
+
+
+def test_build_completion_continuation_input_keeps_structured_assistant_content():
+ """Content blocks on a trailing assistant turn stay blocks: the partial continues the last text
+ block in place (a block boundary would let a provider drop the space between "Sure, " and "here"),
+ lands as a new text block only after a non-text block, and a content shape that cannot be extended declines."""
+ from litellm.router import _extend_trailing_text_block
+
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": [{"type": "text", "text": "Sure, "}], "prefix": True},
+ ]
+ built = litellm.Router._build_completion_continuation_input(messages, "here it is")
+ assert built is not None
+ assert [m["role"] for m in built] == ["user", "assistant"]
+ assert built[-1] == {"role": "assistant", "content": [{"type": "text", "text": "Sure, here it is"}], "prefix": True}
+ image_block = {"type": "image_url", "image_url": {"url": "https://example.test/a.png"}}
+ assert _extend_trailing_text_block([image_block], "here it is") == [image_block, {"type": "text", "text": "here it is"}]
+ assert _extend_trailing_text_block([], "here it is") == [{"type": "text", "text": "here it is"}]
+ assert (
+ litellm.Router._build_completion_continuation_input([{"role": "assistant", "content": 42, "prefix": True}], "x")
+ is None
+ )
+
+
+def test_mid_stream_continuation_eligible_allows_text_response_format():
+ """response_format={"type": "text"} is the unconstrained default and must stay
+ eligible, unlike json_object / json_schema."""
+ from litellm.exceptions import MidStreamFallbackError
+
+ router = litellm.Router(
+ model_list=[{"model_name": "gpt-4", "litellm_params": {"model": "gpt-4", "api_key": "k"}}],
+ enable_mid_stream_fallback_continuation=True,
+ )
+ e = MidStreamFallbackError(
+ message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello",
+ is_pre_first_chunk=False, emitted_disqualifying_content=False,
+ )
+ assert router._mid_stream_continuation_eligible(e=e, request_kwargs={"response_format": {"type": "text"}}) is True
+ assert router._mid_stream_continuation_eligible(e=e, request_kwargs={"response_format": {"type": "json_object"}}) is False
+
+
+def test_raise_original_mid_stream_error_surfaces_the_provider_exception():
+ from litellm.exceptions import MidStreamFallbackError, RateLimitError
+
+ provider_error = RateLimitError(message="rate limited", llm_provider="openai", model="gpt-4")
+ wrapped = MidStreamFallbackError(
+ message="rate limited", model="gpt-4", llm_provider="openai",
+ original_exception=provider_error, generated_content="Hello",
+ )
+ with pytest.raises(RateLimitError) as raised:
+ litellm.Router._raise_original_mid_stream_error(wrapped)
+ assert raised.value is provider_error
+ assert raised.value.__cause__ is wrapped
+
+ bare = MidStreamFallbackError(message="boom", model="gpt-4", llm_provider="openai", generated_content="Hello")
+ with pytest.raises(MidStreamFallbackError) as bare_raised:
+ litellm.Router._raise_original_mid_stream_error(bare)
+ assert bare_raised.value is bare
+
+
@pytest.mark.asyncio
async def test_acompletion_streaming_iterator_reraises_original_exception_when_available():
"""Async: when the mid-stream MidStreamFallbackError wraps a real provider
@@ -8694,6 +9905,11 @@ def test_combine_fallback_usage():
assert chunk.usage.completion_tokens == 5
assert chunk.usage.total_tokens == 15
+ Router._combine_fallback_usage(chunk, Usage(prompt_tokens=0, completion_tokens=4, total_tokens=4))
+ assert chunk.usage.prompt_tokens == 10
+ assert chunk.usage.completion_tokens == 9
+ assert chunk.usage.total_tokens == 19
+
@pytest.mark.asyncio
async def test_acompletion_streaming_iterator_does_not_log_success_on_terminal_failure():
diff --git a/tests/unit/test_router_model_cost_isolation.py b/tests/unit/test_router_model_cost_isolation.py
index d343f464a77..d8625ff9da3 100644
--- a/tests/unit/test_router_model_cost_isolation.py
+++ b/tests/unit/test_router_model_cost_isolation.py
@@ -544,13 +544,14 @@ def test_should_not_pollute_shared_key_with_custom_nonzero_pricing():
)
-def test_regex_lookaround_flag_stays_on_the_deployment_that_set_it() -> None:
- """A deployment's ``supports_regex_lookaround`` override must not land on the shared
[email protected]("flag", ["supports_regex_lookaround", "supports_assistant_prefill"])
+def test_capability_flag_stays_on_the_deployment_that_set_it(flag: str) -> None:
+ """A deployment's capability override must not land on the shared
``{provider}/{model}`` key, or every sibling deployment of that model would inherit it."""
backend_model = "bedrock/us.xai.grok-4.6"
deploy_id = "grok-deploy-keep-regex"
- builtin_flag = litellm.get_model_info(model=backend_model).get("supports_regex_lookaround")
+ builtin_flag = litellm.get_model_info(model=backend_model).get(flag)
model_keys = {
deploy_id: litellm.model_cost.get(deploy_id),
backend_model: copy.deepcopy(litellm.model_cost.get(backend_model)),
@@ -561,13 +562,13 @@ def test_regex_lookaround_flag_stays_on_the_deployment_that_set_it() -> None:
{
"model_name": "grok-keep-regex",
"litellm_params": {"model": backend_model},
- "model_info": {"id": deploy_id, "supports_regex_lookaround": not builtin_flag},
+ "model_info": {"id": deploy_id, flag: not builtin_flag},
}
],
)
- assert litellm.model_cost[deploy_id]["supports_regex_lookaround"] is (not builtin_flag)
- assert litellm.get_model_info(model=backend_model).get("supports_regex_lookaround") is builtin_flag
+ assert litellm.model_cost[deploy_id][flag] is (not builtin_flag)
+ assert litellm.get_model_info(model=backend_model).get(flag) is builtin_flag
finally:
_restore_model_cost_entries(model_keys)