mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* fix(router): keep both errors when a streamed cross-group fallback also fails On /v1/messages and /v1/responses streams, a recovery walk appended the fallback outcome to the MidStreamFallbackError envelope and the stream then raised the inner provider error without it. A fallback hop whose stream opened and then failed before any content never reached the walk, so the primary's error was dropped. The outcome now lands on the surfaced error, and a fallback hop's pre-content failure reads as the walk's own failure would. * fix(proxy): keep the router fallback outcome in Responses response.failed events The response.failed formatter preferred the upstream body message, so the primary error and fallback outcome the router put on the exception never reached the client. Use the exception message when it carries that outcome. * fix(router): only add the primary error to a fallback stream's failure before any content Count any chunk past message_start and pings, split or not, as content on /v1/messages, track forwarded output events on Responses, and switch the response.failed message only on a fallback-also-failed outcome. * fix(router): scope the streamed fallback outcome to pre-content messages and Responses failures Leave the router core and chat streams as they were. Carry the outcome the walk put on the stream's envelope onto the provider error only before any content, and read a fallback hop's /v1/messages stream as whole SSE frames so split or merged chunks are judged by event, not by chunk. * fix(router): keep a Responses stream's own error once it has sent output A primary Responses stream that already sent output no longer lets its fallback stream's failure read as the primary's. Keep CRLF line endings in a rewritten error frame, and read a bridge chunk's type through a typed mapping. * test(router): cover partial frames on a fallback stream's end and raise * fix(router): carry the primary error through a fallback stream's retry and redact the combined frame A fallback group's same-group stream retry keeps the fallback's error context, every fallback-level /v1/messages stream is read as whole frames, and the rewritten error frame goes through the client message redactor. * fix(router): treat a cut-off message_start on a fallback stream as before content * fix(router): redact the primary error and the fallback outcome separately before joining them A traceback in the primary's error made the client redactor drop the fallback outcome that followed it. Make the fallback-retry tests deterministic with a single-deployment fallback group. * test(router): cover a split error frame on a fallback group's retried stream --------- Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
3463 lines
127 KiB
Python
3463 lines
127 KiB
Python
"""Behavior pins for the proxy_server streaming helpers.
|
|
|
|
Pins covered:
|
|
- ``data_generator``
|
|
- ``async_assistants_data_generator``
|
|
- ``_get_client_requested_model_for_streaming``
|
|
- ``_restamp_streaming_chunk_model``
|
|
- ``_serialize_streaming_chunk``
|
|
- ``_apply_streaming_chunk_hooks``
|
|
- ``_format_streaming_sse_chunk``
|
|
- ``async_data_generator``
|
|
- ``select_data_generator``
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping
|
|
from datetime import datetime, timezone
|
|
from enum import Enum
|
|
from types import MappingProxyType
|
|
from typing import Final, Literal
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import HTTPException, Response
|
|
from fastapi.responses import JSONResponse, StreamingResponse
|
|
from openai import APIError as OpenAIAPIError
|
|
from pydantic import BaseModel, model_serializer
|
|
|
|
import litellm
|
|
import litellm.proxy.proxy_server as ps
|
|
from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
|
|
from litellm.proxy.common_request_processing import create_response
|
|
from litellm.proxy.common_utils.responses_stream_errors import ResponsesStreamErrorState
|
|
from litellm.proxy.proxy_server import (
|
|
_apply_streaming_chunk_hooks,
|
|
_format_fallback_metadata_sse_event,
|
|
_format_responses_sse_chunk,
|
|
_format_streaming_sse_chunk,
|
|
_get_client_requested_model_for_streaming,
|
|
_get_streaming_fallback_metadata,
|
|
_is_positive_int_like,
|
|
_restamp_streaming_chunk_model,
|
|
_serialize_streaming_chunk,
|
|
async_assistants_data_generator,
|
|
async_data_generator,
|
|
data_generator,
|
|
select_data_generator,
|
|
)
|
|
from litellm.types.llms.openai import (
|
|
ErrorEvent,
|
|
OutputTextDeltaEvent,
|
|
ResponseCompletedEvent,
|
|
ResponseCreatedEvent,
|
|
ResponseFailedEvent,
|
|
ResponseIncompleteEvent,
|
|
ResponsesAPIResponse,
|
|
ResponsesAPIStreamEvents,
|
|
)
|
|
from litellm.types.proxy.litellm_pre_call_utils import RedactedDict
|
|
from litellm.types.utils import (
|
|
ChatCompletionDeltaToolCall,
|
|
Delta,
|
|
Function,
|
|
ModelResponseStream,
|
|
StreamingChoices,
|
|
TextChoices,
|
|
TextCompletionResponse,
|
|
Usage,
|
|
)
|
|
from tests._support.clock_loops import AutojumpClockLoop
|
|
|
|
from .conftest import normalize, route_entry_points_to_stubs
|
|
|
|
|
|
def _user_auth() -> UserAPIKeyAuth:
|
|
return UserAPIKeyAuth(api_key="sk-test-key", user_id="u")
|
|
|
|
|
|
def _simple_chunk(model: str = "gpt-4", content: str = "hi") -> ModelResponseStream:
|
|
return ModelResponseStream(
|
|
id="chatcmpl-test",
|
|
choices=[
|
|
StreamingChoices(
|
|
finish_reason=None,
|
|
index=0,
|
|
delta=Delta(content=content, role="assistant"),
|
|
)
|
|
],
|
|
created=0,
|
|
model=model,
|
|
object="chat.completion.chunk",
|
|
)
|
|
|
|
|
|
def _sse_text(frame: str | bytes) -> str:
|
|
return frame.decode() if isinstance(frame, bytes) else frame
|
|
|
|
|
|
async def _async_iter(items):
|
|
for it in items:
|
|
yield it
|
|
|
|
|
|
async def _async_iter_raises(exc: Exception):
|
|
# yield once then raise — exercises the mid-stream failure branch
|
|
yield _simple_chunk(content="partial")
|
|
raise exc
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("terminal_type", ["response.completed", "response.failed", "response.incomplete", "error"])
|
|
async def test_responses_stream_dispatches_named_events_without_a_chat_done_sentinel(terminal_type: str) -> None:
|
|
response: Final = ResponsesAPIResponse(id="resp_framing", created_at=1, model="local-model", output=[])
|
|
created: Final = ResponseCreatedEvent.model_validate(
|
|
{"type": "response.created", "sequence_number": 0, "response": response}
|
|
)
|
|
delta: Final = OutputTextDeltaEvent.model_validate(
|
|
{
|
|
"type": "response.output_text.delta",
|
|
"sequence_number": 1,
|
|
"item_id": "msg_framing",
|
|
"output_index": 0,
|
|
"content_index": 0,
|
|
"delta": "hello",
|
|
}
|
|
)
|
|
terminal_models: Final = {
|
|
"response.completed": ResponseCompletedEvent,
|
|
"response.failed": ResponseFailedEvent,
|
|
"response.incomplete": ResponseIncompleteEvent,
|
|
"error": ErrorEvent,
|
|
}
|
|
terminal: Final = terminal_models[terminal_type].model_validate(
|
|
{"type": terminal_type, "sequence_number": 2, "response": response}
|
|
)
|
|
|
|
async def upstream() -> AsyncIterator[BaseModel]:
|
|
for event in (created, delta, terminal):
|
|
yield event
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
|
|
)
|
|
]
|
|
)
|
|
assert len(frames) == 3
|
|
for frame, event_type in zip(
|
|
frames, ("response.created", "response.output_text.delta", terminal_type), strict=True
|
|
):
|
|
assert frame.startswith(f"event: {event_type}\n")
|
|
payload: Final = json.loads(
|
|
next(line.removeprefix("data: ") for line in frame.splitlines() if line.startswith("data: "))
|
|
)
|
|
assert payload["type"] == event_type
|
|
assert json.loads(frames[1].split("data: ", 1)[1])["delta"] == "hello"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"as_chunk",
|
|
[lambda event: event, lambda event: event.model_dump()],
|
|
ids=["model", "dict"],
|
|
)
|
|
async def test_responses_stream_sends_no_failure_event_after_an_upstream_error_event(
|
|
as_chunk: Callable[[ErrorEvent], BaseModel | Mapping[str, object]],
|
|
) -> None:
|
|
response: Final = ResponsesAPIResponse(id="resp_error_then_raise", created_at=1, model="local-model", output=[])
|
|
created: Final = ResponseCreatedEvent.model_validate(
|
|
{"type": "response.created", "sequence_number": 0, "response": response}
|
|
)
|
|
error_event: Final = ErrorEvent.model_validate(
|
|
{"type": "error", "sequence_number": 1, "code": "server_error", "message": "upstream failed", "param": None}
|
|
)
|
|
|
|
async def upstream() -> AsyncIterator[BaseModel | Mapping[str, object]]:
|
|
yield created
|
|
yield as_chunk(error_event)
|
|
raise litellm.APIError(status_code=500, message="Stream close failed", llm_provider="openai", model="local-model")
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
|
|
)
|
|
]
|
|
)
|
|
|
|
assert tuple(frame.split("\n", 1)[0] for frame in frames) == ("event: response.created", "event: error")
|
|
assert json.loads(frames[-1].split("data: ", 1)[1])["message"] == "upstream failed"
|
|
|
|
|
|
async def _responses_frames(chunks: Iterable[object]) -> tuple[str, ...]:
|
|
async def upstream() -> AsyncIterator[object]:
|
|
for chunk in chunks:
|
|
yield chunk
|
|
|
|
return tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
|
|
)
|
|
]
|
|
)
|
|
|
|
|
|
_DUMPED_DELTA: Final = OutputTextDeltaEvent(
|
|
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,
|
|
item_id="msg_1",
|
|
output_index=0,
|
|
content_index=0,
|
|
delta="hi",
|
|
sequence_number=3,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_responses_stream_sends_a_hook_chunk_dumped_from_an_event_as_that_named_event() -> None:
|
|
frames: Final = await _responses_frames((_DUMPED_DELTA.model_dump(),))
|
|
|
|
assert len(frames) == 1
|
|
event_line, data_line = frames[0].strip().split("\n")
|
|
assert event_line == "event: response.output_text.delta"
|
|
assert json.loads(data_line.removeprefix("data: ")) == json.loads(_DUMPED_DELTA.model_dump_json())
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"chunk",
|
|
[{"type": 5}, {"type": "response.completed", "response": "hook-text"}],
|
|
ids=["non_string_type", "string_response"],
|
|
)
|
|
async def test_responses_stream_sends_a_hook_chunk_its_event_model_cannot_read_as_a_data_frame(
|
|
chunk: Mapping[str, object],
|
|
) -> None:
|
|
frames: Final = await _responses_frames((chunk,))
|
|
|
|
assert frames == (f"data: {json.dumps(chunk)}\n\n",)
|
|
|
|
|
|
class _TypeDroppedOnTheWire(BaseModel, frozen=True):
|
|
type: str = "response.completed"
|
|
sequence_number: int = 3
|
|
|
|
@model_serializer
|
|
def _without_type(self) -> Mapping[str, int]:
|
|
return {"sequence_number": self.sequence_number}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_responses_stream_names_a_model_chunk_from_the_json_it_sends() -> None:
|
|
frames: Final = await _responses_frames((_TypeDroppedOnTheWire(),))
|
|
|
|
assert len(frames) == 1
|
|
assert frames[0].startswith("data: ")
|
|
assert json.loads(frames[0].removeprefix("data: ")) == {"sequence_number": 3}
|
|
|
|
|
|
class _MaskedReprString(str):
|
|
def __repr__(self) -> str:
|
|
return "'***'"
|
|
|
|
|
|
class _MaskedReprModel(BaseModel, frozen=True):
|
|
token: str
|
|
|
|
def __repr__(self) -> str:
|
|
return "_MaskedReprModel(token=[secure])"
|
|
|
|
|
|
class _MaskedCount(int):
|
|
def __repr__(self) -> str:
|
|
return "_MaskedCount([secure])"
|
|
|
|
|
|
class _RigColor(Enum):
|
|
RED = "red"
|
|
|
|
|
|
def _self_referencing_chunk() -> Mapping[str, object]:
|
|
chunk: Final[dict[str, object]] = {"type": "response.output_text.delta"}
|
|
chunk["self"] = chunk # mutable-ok: a self-reference needs the dict to exist before it can hold itself
|
|
return chunk
|
|
|
|
|
|
def _chunk_holding_itself_twice() -> Mapping[str, object]:
|
|
chunk: Final[dict[str, object]] = {"type": "response.output_text.delta"}
|
|
chunk.update(left=chunk, right=chunk) # mutable-ok: a self-reference needs the dict to exist before it can hold itself
|
|
return chunk
|
|
|
|
|
|
_REDACTED_HEADERS: Final = RedactedDict({"authorization": "Bearer hook-canary"})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"chunk",
|
|
[
|
|
{"type": _MaskedReprString("hook-canary"), "delta": "hi"},
|
|
{"type": "response.output_text.delta", "headers": _REDACTED_HEADERS},
|
|
RedactedDict({"type": "response.output_text.delta", "authorization": "Bearer hook-canary"}),
|
|
MappingProxyType({"type": "response.output_text.delta"}),
|
|
{"type": "response.output_text.delta", "item": _MaskedReprModel(token="hook-canary")},
|
|
{"type": "response.output_text.delta", "count": _MaskedCount(7)},
|
|
{"type": "response.output_text.delta", "color": _RigColor.RED},
|
|
{"type": "response.output_text.delta", ("a", "b"): 1},
|
|
{"type": "response.output_text.delta", "score": float("nan")},
|
|
_self_referencing_chunk(),
|
|
_chunk_holding_itself_twice(),
|
|
],
|
|
ids=[
|
|
"masked_string",
|
|
"redacted_dict_value",
|
|
"redacted_dict_chunk",
|
|
"mapping_proxy_chunk",
|
|
"model_with_own_repr",
|
|
"int_subclass_with_own_repr",
|
|
"enum_without_a_json_value",
|
|
"tuple_key",
|
|
"nan",
|
|
"holds_itself",
|
|
"holds_itself_twice",
|
|
],
|
|
)
|
|
def test_responses_sse_chunk_that_json_cannot_show_as_printed_keeps_the_base_frame(chunk: Mapping[object, object]) -> None:
|
|
assert _format_responses_sse_chunk(chunk=chunk) == _format_streaming_sse_chunk(chunk=chunk)
|
|
|
|
|
|
def test_responses_sse_chunk_without_a_type_keeps_the_base_frame() -> None:
|
|
chunk: Final = {"note": "hook output without a type"}
|
|
|
|
assert _format_responses_sse_chunk(chunk=chunk) == _format_streaming_sse_chunk(chunk=chunk)
|
|
|
|
|
|
def test_responses_error_event_encodes_its_detail_the_way_the_chat_error_frame_does() -> None:
|
|
error: Final = {
|
|
"message": "blocked",
|
|
"provider_specific_fields": {"guardrail": "rig-guard", "at": datetime(2026, 10, 30, tzinfo=timezone.utc)},
|
|
}
|
|
|
|
frame: Final = ResponsesStreamErrorState().format_error(error)
|
|
|
|
assert json.loads(frame.split("data: ", 1)[1])["error"] == json.loads(json.dumps(error, default=str))
|
|
|
|
|
|
@pytest.mark.parametrize("status_code", ["abc", 1.5, True, None], ids=["string", "float", "bool", "null"])
|
|
def test_responses_hook_error_frame_keeps_its_message_whatever_status_code_it_carries(status_code: object) -> None:
|
|
hook_frame: Final = json.dumps(
|
|
{"error": {"message": "rig status", "type": "guardrail_scan_error", "status_code": status_code}}
|
|
)
|
|
|
|
frame: Final = ResponsesStreamErrorState().format_error_message(f"data: {hook_frame}\n\n")
|
|
|
|
assert frame.startswith("event: error\n")
|
|
assert json.loads(frame.split("data: ", 1)[1])["message"] == "rig status"
|
|
|
|
|
|
class _StatusCarryingError(Exception):
|
|
def __init__(self, status_code: object) -> None:
|
|
super().__init__("rig status")
|
|
self.status_code: Final = status_code
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("status_code", "code"),
|
|
[
|
|
(429, "rate_limit_exceeded"),
|
|
("429", "rate_limit_exceeded"),
|
|
(429.0, "rate_limit_exceeded"),
|
|
("abc", "server_error"),
|
|
(429.5, "server_error"),
|
|
],
|
|
ids=["int", "decimal_string", "integral_float", "word", "fractional_float"],
|
|
)
|
|
def test_responses_failure_event_reads_a_numeric_status_code_the_way_base_did(status_code: object, code: str) -> None:
|
|
frame: Final = ResponsesStreamErrorState().format_failure(_StatusCarryingError(status_code))
|
|
|
|
assert frame is not None
|
|
failure: Final = ResponseFailedEvent.model_validate_json(frame.split("data: ", 1)[1])
|
|
assert failure.response.error is not None
|
|
assert failure.response.error["code"] == code
|
|
|
|
|
|
def test_responses_failure_event_keeps_the_routers_fallback_outcome_over_the_upstream_message() -> None:
|
|
error: Final = litellm.InternalServerError(
|
|
message="FLASH-ERROR",
|
|
llm_provider="hosted_vllm",
|
|
model="qwen-flash",
|
|
body={"message": "FLASH-ERROR", "code": "500"},
|
|
)
|
|
error.message += "\n\nLiteLLM: model group 'p' failed with the error above. Fallback to q also failed: Q-ERROR"
|
|
|
|
frame: Final = ResponsesStreamErrorState().format_failure(error)
|
|
|
|
assert frame is not None
|
|
failure: Final = ResponseFailedEvent.model_validate_json(frame.split("data: ", 1)[1])
|
|
assert failure.response.error is not None
|
|
message: Final = failure.response.error["message"]
|
|
assert "FLASH-ERROR" in message
|
|
assert message.endswith("Fallback to q also failed: Q-ERROR")
|
|
|
|
|
|
def test_responses_failure_event_keeps_the_upstream_message_when_no_fallback_was_attempted() -> None:
|
|
error: Final = litellm.InternalServerError(
|
|
message="litellm wrapped FLASH-ERROR",
|
|
llm_provider="hosted_vllm",
|
|
model="qwen-flash",
|
|
body={"message": "FLASH-ERROR", "code": "500"},
|
|
)
|
|
error.message += "\n\nLiteLLM: model group 'p' failed with the error above. No fallback was attempted."
|
|
|
|
frame: Final = ResponsesStreamErrorState().format_failure(error)
|
|
|
|
assert frame is not None
|
|
failure: Final = ResponseFailedEvent.model_validate_json(frame.split("data: ", 1)[1])
|
|
assert failure.response.error is not None
|
|
assert failure.response.error["message"] == "FLASH-ERROR"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("guardrail_error", "error_object"),
|
|
[
|
|
(
|
|
{"message": "response withheld", "type": "guardrail_scan_error", "code": 500},
|
|
{"message": "response withheld", "type": "guardrail_scan_error", "code": 500},
|
|
),
|
|
("response withheld", {"message": "response withheld"}),
|
|
],
|
|
)
|
|
async def test_a_guardrail_error_string_mid_responses_stream_ends_it_as_a_named_error_event(
|
|
guardrail_error: Mapping[str, object] | str, error_object: Mapping[str, object]
|
|
) -> None:
|
|
response: Final = ResponsesAPIResponse(id="resp_hook_error", created_at=1, model="local-model", output=[])
|
|
created: Final = ResponseCreatedEvent.model_validate(
|
|
{"type": "response.created", "sequence_number": 0, "response": response}
|
|
)
|
|
|
|
async def upstream() -> AsyncIterator[object]:
|
|
yield created
|
|
yield f"data: {json.dumps({'error': guardrail_error})}\n\n"
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
|
|
)
|
|
]
|
|
)
|
|
event_line, data_line = frames[-1].strip().split("\n")
|
|
|
|
assert "data: [DONE]" not in "".join(frames)
|
|
assert event_line == "event: error"
|
|
assert json.loads(data_line.removeprefix("data: ")) == {
|
|
"type": "error",
|
|
"code": "server_error",
|
|
"message": "response withheld",
|
|
"param": None,
|
|
"sequence_number": 1,
|
|
"error": error_object,
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("binary", [False, True])
|
|
@pytest.mark.parametrize(
|
|
("event_type", "event_line"),
|
|
[
|
|
(None, ""),
|
|
("", ""),
|
|
("response.delta\ninjected", ""),
|
|
("response.delta\rinjected", ""),
|
|
("response.delta\r\ninjected", ""),
|
|
("response.vendor_delta", "event: response.vendor_delta\n"),
|
|
],
|
|
)
|
|
def test_responses_event_names_preserve_payload_without_injecting_sse_lines(
|
|
event_type: str | None, event_line: str, binary: bool
|
|
) -> None:
|
|
payload: Final = {"type": event_type, "sequence_number": 0}
|
|
data_line: Final = f"data: {json.dumps(payload)}\n\n"
|
|
frame: Final = data_line.encode("utf-8") if binary else data_line
|
|
expected: Final = (event_line + data_line).encode("utf-8") if binary else event_line + data_line
|
|
state: Final = ResponsesStreamErrorState()
|
|
state.observe_chunk(payload)
|
|
|
|
assert state.mark_emitted(frame) == expected
|
|
|
|
|
|
class _FakeStream:
|
|
def __init__(self, chunks, hidden_params=None):
|
|
self._chunks = chunks
|
|
self._hidden_params = hidden_params or {}
|
|
|
|
def __aiter__(self):
|
|
return _async_iter(self._chunks)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# data_generator
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_data_generator_yields_sse_lines_for_dict_chunks():
|
|
class DictChunk:
|
|
def __init__(self, payload):
|
|
self._payload = payload
|
|
|
|
def dict(self):
|
|
return self._payload
|
|
|
|
chunks = [
|
|
DictChunk({"id": "1", "object": "chat.completion.chunk", "model": "gpt-4"}),
|
|
DictChunk({"id": "2", "object": "chat.completion.chunk", "model": "gpt-4"}),
|
|
]
|
|
out = list(data_generator(chunks))
|
|
|
|
assert len(out) == 2
|
|
payloads = [json.loads(line.removeprefix("data: ").rstrip("\n\n")) for line in out]
|
|
assert normalize(payloads[0]) == {
|
|
"id": "<VOLATILE>",
|
|
"object": "chat.completion.chunk",
|
|
"model": "gpt-4",
|
|
}
|
|
assert payloads[1]["model"] == "gpt-4"
|
|
|
|
|
|
def test_data_generator_fallback_when_dict_raises_exception():
|
|
class BadChunk:
|
|
def dict(self):
|
|
raise RuntimeError("cannot serialize")
|
|
|
|
# When .dict() raises, the inner json.dumps(chunk) on a non-JSON-serializable
|
|
# instance also raises — the generator does not catch the second failure.
|
|
with pytest.raises((TypeError, RuntimeError)):
|
|
list(data_generator([BadChunk()]))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# async_assistants_data_generator
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class _FakeAssistantsStream:
|
|
"""Mimic the async-context-manager + async-iterable shape of the
|
|
assistants streaming object (e.g. AssistantEventHandler)."""
|
|
|
|
def __init__(self, chunks):
|
|
self._chunks = chunks
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, exc_type, exc, tb):
|
|
return False
|
|
|
|
def __aiter__(self):
|
|
async def _gen():
|
|
for c in self._chunks:
|
|
yield c
|
|
|
|
return _gen()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_assistants_data_generator_yields_sse_and_done(monkeypatch):
|
|
chunk = _simple_chunk(content="hello")
|
|
|
|
async def _passthrough_hook(*, user_api_key_dict, response, data, **kwargs):
|
|
return response
|
|
|
|
monkeypatch.setattr(
|
|
ps.proxy_logging_obj,
|
|
"async_post_call_streaming_hook",
|
|
_passthrough_hook,
|
|
)
|
|
|
|
stream = _FakeAssistantsStream([chunk])
|
|
out = []
|
|
async for line in async_assistants_data_generator(
|
|
response=stream,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
):
|
|
out.append(line)
|
|
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
body = json.loads(out[0].removeprefix("data: ").rstrip("\n\n"))
|
|
assert normalize(body) == {
|
|
"id": "<VOLATILE>",
|
|
"created": "<VOLATILE>",
|
|
"model": "gpt-4",
|
|
"object": "chat.completion.chunk",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"delta": {"content": "hello", "role": "assistant"},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_assistants_data_generator_hook_failure_yields_error_chunk(
|
|
monkeypatch,
|
|
):
|
|
async def _boom_hook(*args, **kwargs):
|
|
raise RuntimeError("hook exploded")
|
|
|
|
async def _noop_failure(*args, **kwargs):
|
|
return None
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _boom_hook)
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", _noop_failure)
|
|
|
|
stream = _FakeAssistantsStream([_simple_chunk()])
|
|
out = []
|
|
async for line in async_assistants_data_generator(
|
|
response=stream,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
):
|
|
out.append(line)
|
|
|
|
assert any("error" in line for line in out)
|
|
assert out[-1].startswith('data: {"error":')
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _get_client_requested_model_for_streaming
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_get_client_requested_model_for_streaming_prefers_client_requested():
|
|
request_data = {
|
|
"_litellm_client_requested_model": "gpt-4",
|
|
"model": "openai/internal-gpt-4",
|
|
"litellm_call_id": "abc",
|
|
}
|
|
result = _get_client_requested_model_for_streaming(request_data)
|
|
assert result == "gpt-4"
|
|
|
|
snapshot = {
|
|
"result": result,
|
|
"client_field_preserved": request_data["_litellm_client_requested_model"],
|
|
"model_field_preserved": request_data["model"],
|
|
}
|
|
assert normalize(snapshot) == {
|
|
"result": "gpt-4",
|
|
"client_field_preserved": "gpt-4",
|
|
"model_field_preserved": "openai/internal-gpt-4",
|
|
}
|
|
|
|
|
|
def test_get_client_requested_model_for_streaming_falls_back_to_model_field():
|
|
result = _get_client_requested_model_for_streaming({"model": "claude-sonnet"})
|
|
assert result == "claude-sonnet"
|
|
|
|
|
|
def test_get_client_requested_model_for_streaming_missing_returns_empty_invalid():
|
|
"""When neither key is set or values are non-strings, the helper returns ""
|
|
rather than raising — callers depend on this to skip restamping."""
|
|
assert _get_client_requested_model_for_streaming({}) == ""
|
|
assert _get_client_requested_model_for_streaming({"model": 123}) == ""
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _restamp_streaming_chunk_model
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_overrides_model_on_basemodel():
|
|
chunk = _simple_chunk(model="openai/internal-x")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="gpt-4",
|
|
request_data={"litellm_call_id": "id-1"},
|
|
model_mismatch_logged=False,
|
|
)
|
|
snapshot = {
|
|
"model": new_chunk.model,
|
|
"logged": logged,
|
|
"same_object": new_chunk is chunk,
|
|
"original_model": chunk.model,
|
|
}
|
|
assert snapshot == {"model": "gpt-4", "logged": True, "same_object": False, "original_model": "openai/internal-x"}
|
|
|
|
|
|
@pytest.mark.parametrize("return_raw_model_name", [False, True])
|
|
def test_restamp_streaming_chunk_model_respects_raw_model_name_toggle(return_raw_model_name):
|
|
chunk = _simple_chunk(model="gpt-4o-mini")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="auto_router/complexity_router",
|
|
request_data={"metadata": {RETURN_RAW_MODEL_NAME_METADATA_KEY: return_raw_model_name}},
|
|
model_mismatch_logged=False,
|
|
)
|
|
|
|
expected_model = "gpt-4o-mini" if return_raw_model_name else "auto_router/complexity_router"
|
|
assert new_chunk.model == expected_model
|
|
assert logged is (not return_raw_model_name)
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_overrides_model_on_dict():
|
|
chunk = {"model": "internal", "choices": []}
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="gpt-4",
|
|
request_data={},
|
|
model_mismatch_logged=True,
|
|
)
|
|
assert (new_chunk["model"], chunk["model"], logged) == ("gpt-4", "internal", True)
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_uses_fallback_model_from_metadata():
|
|
chunk = _simple_chunk(model="openai/internal-fallback")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="primary-model",
|
|
request_data={"litellm_call_id": "id-1"},
|
|
model_mismatch_logged=False,
|
|
fallback_was_attempted=True,
|
|
fallback_model_from_metadata="fallback-model",
|
|
)
|
|
assert new_chunk.model == "fallback-model"
|
|
assert logged is True
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_preserves_fallback_model_without_group():
|
|
chunk = _simple_chunk(model="openai/internal-fallback")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="primary-model",
|
|
request_data={},
|
|
model_mismatch_logged=False,
|
|
fallback_was_attempted=True,
|
|
fallback_model_from_metadata=None,
|
|
)
|
|
assert new_chunk.model == "openai/internal-fallback"
|
|
assert logged is False
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_invalid_chunk_type_unchanged():
|
|
"""For a non-BaseModel, non-dict chunk the helper returns it as-is
|
|
along with the original ``model_mismatch_logged`` flag."""
|
|
chunk = "raw string chunk"
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="gpt-4",
|
|
request_data={},
|
|
model_mismatch_logged=False,
|
|
)
|
|
assert new_chunk == "raw string chunk"
|
|
assert logged is False
|
|
|
|
|
|
def test_is_positive_int_like_invalid_and_edge_values():
|
|
assert _is_positive_int_like(None) is False
|
|
assert _is_positive_int_like("not-a-number") is False
|
|
assert _is_positive_int_like(0) is False
|
|
assert _is_positive_int_like(-1) is False
|
|
assert _is_positive_int_like("1") is True
|
|
assert _is_positive_int_like(2) is True
|
|
|
|
|
|
def test_get_streaming_fallback_metadata_reads_headers():
|
|
fallback_errors = [
|
|
{
|
|
"message": "litellm.RateLimitError: upstream limited request",
|
|
"type": "RateLimitError",
|
|
"param": None,
|
|
"code": "429",
|
|
}
|
|
]
|
|
stream = _FakeStream(
|
|
[],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": "1",
|
|
"x-litellm-model-group": "fallback-model",
|
|
"x-litellm-fallback-errors": json.dumps(fallback_errors),
|
|
}
|
|
},
|
|
)
|
|
assert _get_streaming_fallback_metadata(stream) == (
|
|
True,
|
|
"fallback-model",
|
|
fallback_errors,
|
|
)
|
|
|
|
|
|
def test_get_streaming_fallback_metadata_no_additional_headers():
|
|
stream = _FakeStream([], hidden_params={})
|
|
assert _get_streaming_fallback_metadata(stream) == (False, None, [])
|
|
|
|
|
|
def test_get_streaming_fallback_metadata_zero_fallback_count():
|
|
stream = _FakeStream(
|
|
[],
|
|
hidden_params={"additional_headers": {"x-litellm-attempted-fallbacks": 0}},
|
|
)
|
|
assert _get_streaming_fallback_metadata(stream) == (False, None, [])
|
|
|
|
|
|
def test_get_streaming_fallback_metadata_no_model_group_returns_none_model():
|
|
stream = _FakeStream(
|
|
[],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
}
|
|
},
|
|
)
|
|
was_attempted, fallback_model, errors = _get_streaming_fallback_metadata(stream)
|
|
assert was_attempted is True
|
|
assert fallback_model is None
|
|
assert errors == []
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_azure_router_preserves_model():
|
|
chunk = _simple_chunk(model="azure_ai/internal-deployment")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="azure_ai/model-router",
|
|
request_data={},
|
|
model_mismatch_logged=False,
|
|
)
|
|
assert new_chunk.model == "azure_ai/internal-deployment"
|
|
assert logged is False
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_fastest_response_preserves_model():
|
|
chunk = _simple_chunk(model="winning-model")
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="gpt-4,claude-3",
|
|
request_data={"fastest_response": True},
|
|
model_mismatch_logged=False,
|
|
)
|
|
assert new_chunk.model == "winning-model"
|
|
assert logged is False
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_restamps_a_frozen_chunk_through_a_copy():
|
|
from pydantic import ConfigDict
|
|
|
|
class FrozenChunk(_simple_chunk().__class__):
|
|
model_config = ConfigDict(frozen=True)
|
|
|
|
chunk = FrozenChunk(
|
|
id="chatcmpl-test",
|
|
choices=[],
|
|
created=0,
|
|
model="openai/internal-x",
|
|
object="chat.completion.chunk",
|
|
)
|
|
new_chunk, logged = _restamp_streaming_chunk_model(
|
|
chunk=chunk,
|
|
requested_model_from_client="gpt-4",
|
|
request_data={"litellm_call_id": "test-id"},
|
|
model_mismatch_logged=False,
|
|
)
|
|
assert (new_chunk.model, chunk.model, logged) == ("gpt-4", "openai/internal-x", True)
|
|
|
|
|
|
def test_restamp_streaming_chunk_model_records_the_client_model_on_the_logging_object():
|
|
import time
|
|
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
|
|
logging_obj = Logging(
|
|
model="openai/internal-x",
|
|
messages=[],
|
|
stream=True,
|
|
call_type="acompletion",
|
|
start_time=time.time(),
|
|
litellm_call_id="test-id",
|
|
function_id="test-id",
|
|
)
|
|
_restamp_streaming_chunk_model(
|
|
chunk=_simple_chunk(model="openai/internal-x"),
|
|
requested_model_from_client="gpt-4",
|
|
request_data={"litellm_call_id": "test-id", "litellm_logging_obj": logging_obj},
|
|
model_mismatch_logged=False,
|
|
)
|
|
assert logging_obj.client_facing_stream_model == "gpt-4"
|
|
|
|
|
|
def test_format_fallback_metadata_sse_event():
|
|
fallback_errors = [
|
|
{
|
|
"message": "litellm.RateLimitError: upstream limited request",
|
|
"type": "RateLimitError",
|
|
"param": None,
|
|
"code": "429",
|
|
}
|
|
]
|
|
|
|
event = _format_fallback_metadata_sse_event(
|
|
fallback_model="fallback-model",
|
|
fallback_errors=fallback_errors,
|
|
responses_stream=False,
|
|
return_raw_model_name=False,
|
|
)
|
|
|
|
assert isinstance(event, str)
|
|
assert event.startswith("data: ")
|
|
payload = json.loads(event.removeprefix("data: ").removesuffix("\n\n"))
|
|
assert payload["choices"] == []
|
|
assert payload["litellm_fallback"] == {
|
|
"fallback_model": "fallback-model",
|
|
"errors": fallback_errors,
|
|
}
|
|
assert payload["id"] == "litellm-fallback-metadata"
|
|
assert payload["object"] == "chat.completion.chunk"
|
|
assert payload["model"] == "fallback-model"
|
|
assert isinstance(payload["created"], int)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _serialize_streaming_chunk
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_serialize_streaming_chunk_simple_payload():
|
|
payload = json.loads(_serialize_streaming_chunk(_simple_chunk()))
|
|
assert normalize(payload) == {
|
|
"id": "<VOLATILE>",
|
|
"object": "chat.completion.chunk",
|
|
"created": "<VOLATILE>",
|
|
"model": "gpt-4",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"delta": {"role": "assistant", "content": "hi"},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("choice_extras", "serialized_extras"),
|
|
[
|
|
({"stop_reason": ",5", "token_ids": [20]}, {"stop_reason": ",5", "token_ids": [20]}),
|
|
({"finish_reason": "stop", "stop_reason": None}, {"finish_reason": "stop", "stop_reason": None}),
|
|
],
|
|
ids=["vllm-fields", "natural-stop"],
|
|
)
|
|
def test_serialize_streaming_chunk_keeps_the_vllm_choice_fields(
|
|
choice_extras: dict[str, object], serialized_extras: dict[str, object]
|
|
):
|
|
chunk: Final = ModelResponseStream(
|
|
id="chatcmpl-test",
|
|
choices=[StreamingChoices(index=0, delta=Delta(content="1,2,3,4", role="assistant"), **choice_extras)],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
)
|
|
|
|
assert json.loads(_serialize_streaming_chunk(chunk))["choices"] == [
|
|
{"index": 0, "delta": {"role": "assistant", "content": "1,2,3,4"}, **serialized_extras}
|
|
]
|
|
|
|
|
|
def _text_completion_chunk(choice_extras: Mapping[str, object]) -> TextCompletionResponse:
|
|
return TextCompletionResponse(
|
|
id="cmpl-1",
|
|
choices=[TextChoices(finish_reason="length", index=0, text="", **choice_extras)],
|
|
created=1,
|
|
model="Qwen/Qwen3-0.6B",
|
|
)
|
|
|
|
|
|
def _chat_chunk_with_fingerprint(choice_extras: Mapping[str, object]) -> ModelResponseStream:
|
|
return ModelResponseStream(
|
|
id="chatcmpl-1",
|
|
choices=[StreamingChoices(finish_reason="length", index=0, delta=Delta(content=None), **choice_extras)],
|
|
created=1,
|
|
model="Qwen/Qwen3-0.6B",
|
|
object="chat.completion.chunk",
|
|
system_fingerprint="fp_1",
|
|
)
|
|
|
|
|
|
_VLLM_SHAPED_CHUNKS: Final = pytest.mark.parametrize(
|
|
"build_chunk", [_text_completion_chunk, _chat_chunk_with_fingerprint], ids=["text-completion", "chat-fingerprint"]
|
|
)
|
|
|
|
|
|
@_VLLM_SHAPED_CHUNKS
|
|
@pytest.mark.parametrize(
|
|
"vllm_choice_fields",
|
|
[{"stop_reason": None}, {"stop_reason": None, "token_ids": [21]}, {"stop_reason": None, "token_ids": None}],
|
|
ids=["null-stop-reason", "null-stop-reason-with-token-ids", "null-stop-reason-and-token-ids"],
|
|
)
|
|
def test_serialize_streaming_chunk_keeps_null_vllm_choice_fields(
|
|
build_chunk: Callable[[Mapping[str, object]], TextCompletionResponse | ModelResponseStream],
|
|
vllm_choice_fields: dict[str, object],
|
|
) -> None:
|
|
chunk: Final = build_chunk(vllm_choice_fields)
|
|
plain_chunk: Final = json.loads(build_chunk({}).model_dump_json(exclude_none=True, exclude_unset=True))
|
|
|
|
assert json.loads(_serialize_streaming_chunk(chunk)) == {
|
|
**plain_chunk,
|
|
"choices": [{**plain_chunk["choices"][0], **vllm_choice_fields}],
|
|
}
|
|
|
|
|
|
@_VLLM_SHAPED_CHUNKS
|
|
@pytest.mark.parametrize("choice_extras", [{}, {"stop_reason": ",5", "token_ids": [20]}], ids=["no-vllm", "set-vllm"])
|
|
def test_serialize_streaming_chunk_without_null_vllm_fields_matches_model_dump_json(
|
|
build_chunk: Callable[[Mapping[str, object]], TextCompletionResponse | ModelResponseStream],
|
|
choice_extras: dict[str, object],
|
|
) -> None:
|
|
chunk: Final = build_chunk(choice_extras)
|
|
|
|
assert _serialize_streaming_chunk(chunk) == chunk.model_dump_json(exclude_none=True, exclude_unset=True).encode()
|
|
|
|
|
|
def test_serialize_streaming_chunk_keeps_streaming_a_null_stop_reason_chunk_with_a_value_json_cannot_encode() -> None:
|
|
chunk: Final = ModelResponseStream(
|
|
id="chatcmpl-vllm",
|
|
choices=[StreamingChoices(index=0, delta=Delta(content="a"), stop_reason=None, token_ids=[21])],
|
|
created=0,
|
|
model="Qwen/Qwen3-0.6B",
|
|
object="chat.completion.chunk",
|
|
)
|
|
setattr(chunk, "trace_chunk", hashlib.sha256(b"trace").digest())
|
|
|
|
payload: Final = json.loads(_serialize_streaming_chunk(chunk))
|
|
|
|
assert payload["choices"][0]["delta"] == {"content": "a"}
|
|
assert payload["choices"][0]["token_ids"] == [21]
|
|
assert "trace_chunk" not in payload
|
|
|
|
|
|
def test_serialize_streaming_chunk_invalid_input_raises_attribute_error():
|
|
"""The helper is typed as ``BaseModel`` — handing it a plain dict trips
|
|
the attribute-access path (no ``model_dump_json``)."""
|
|
with pytest.raises(AttributeError):
|
|
_serialize_streaming_chunk({"not": "a model"}) # type: ignore[arg-type]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _apply_streaming_chunk_hooks
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_apply_streaming_chunk_hooks_appends_to_str_so_far(monkeypatch):
|
|
chunk = _simple_chunk(content="abc")
|
|
|
|
async def _passthrough(*, user_api_key_dict, response, data, str_so_far=None):
|
|
return response
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _passthrough)
|
|
|
|
new_chunk, new_str = await _apply_streaming_chunk_hooks(
|
|
chunk=chunk,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
str_so_far="prior:",
|
|
)
|
|
|
|
observed = {
|
|
"chunk_is_basemodel": isinstance(new_chunk, ModelResponseStream),
|
|
"str_so_far": new_str,
|
|
"grew": len(new_str) > len("prior:"),
|
|
}
|
|
assert observed == {
|
|
"chunk_is_basemodel": True,
|
|
"str_so_far": "prior:abc",
|
|
"grew": True,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_apply_streaming_chunk_hooks_hook_raises_exception(monkeypatch):
|
|
async def _boom(*args, **kwargs):
|
|
raise RuntimeError("hook failed")
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _boom)
|
|
|
|
with pytest.raises(RuntimeError):
|
|
await _apply_streaming_chunk_hooks(
|
|
chunk=_simple_chunk(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
str_so_far="",
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _format_streaming_sse_chunk
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_format_streaming_sse_chunk_handles_bytes_and_str_shapes():
|
|
bytes_out = _format_streaming_sse_chunk(b'{"a":1}')
|
|
str_out = _format_streaming_sse_chunk('{"a":1}')
|
|
|
|
snapshot = {
|
|
"bytes_out": bytes_out,
|
|
"str_out": str_out,
|
|
"bytes_starts_with_data": bytes_out.startswith(b"data: "),
|
|
}
|
|
assert snapshot == {
|
|
"bytes_out": b'data: {"a":1}\n\n',
|
|
"str_out": 'data: {"a":1}\n\n',
|
|
"bytes_starts_with_data": True,
|
|
}
|
|
|
|
|
|
def test_format_streaming_sse_chunk_invalid_empty_string_still_wraps():
|
|
"""Edge case: empty string still gets the ``data: \\n\\n`` wrapping
|
|
— clients expect SSE shape even on empty payloads."""
|
|
result = _format_streaming_sse_chunk("")
|
|
assert result == "data: \n\n"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# async_data_generator
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _patch_logging_flags(monkeypatch, needs_wrap=False, needs_per_chunk=False):
|
|
monkeypatch.setattr(
|
|
ps.proxy_logging_obj,
|
|
"needs_iterator_wrap",
|
|
lambda: needs_wrap,
|
|
)
|
|
monkeypatch.setattr(
|
|
ps.proxy_logging_obj,
|
|
"needs_per_chunk_streaming_hook",
|
|
lambda: needs_per_chunk,
|
|
)
|
|
# ``_fire_deferred_stream_logging`` is a classmethod — patch the
|
|
# underlying function so the no-wrap branch is a no-op rather than
|
|
# touching real logging globals.
|
|
monkeypatch.setattr(
|
|
ps.ProxyLogging,
|
|
"fire_deferred_stream_logging",
|
|
staticmethod(lambda request_data: None),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_yields_sse_chunks_and_done(monkeypatch):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
response = _async_iter([_simple_chunk(content="hello")])
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
):
|
|
out.append(line)
|
|
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert normalize(payload) == {
|
|
"id": "<VOLATILE>",
|
|
"object": "chat.completion.chunk",
|
|
"created": "<VOLATILE>",
|
|
"model": "gpt-4",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"delta": {"role": "assistant", "content": "hello"},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(("provider_chunks", "released"), [(0, True), (1, False)], ids=["before_output", "after_output"])
|
|
async def test_async_data_generator_refunds_the_reservation_only_when_the_client_leaves_before_provider_output(
|
|
monkeypatch: pytest.MonkeyPatch, provider_chunks: int, released: bool
|
|
) -> None:
|
|
_patch_logging_flags(monkeypatch)
|
|
waiting_on_provider: Final = asyncio.Event()
|
|
|
|
async def provider() -> AsyncIterator[ModelResponseStream]:
|
|
for _ in range(provider_chunks):
|
|
yield _simple_chunk(content="partial")
|
|
waiting_on_provider.set()
|
|
await asyncio.Event().wait()
|
|
yield _simple_chunk(content="never sent")
|
|
|
|
auth: Final = UserAPIKeyAuth(
|
|
api_key="sk-test-key", budget_reservation={"reserved_cost": 0.01, "input_cost": 0.0, "entries": []}
|
|
)
|
|
generator: Final = async_data_generator(response=provider(), user_api_key_dict=auth, request_data={"model": "gpt-4"})
|
|
for _ in range(provider_chunks):
|
|
await generator.__anext__()
|
|
next_frame: Final = asyncio.ensure_future(generator.__anext__())
|
|
await waiting_on_provider.wait()
|
|
next_frame.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await next_frame
|
|
|
|
assert auth.budget_reservation is not None
|
|
assert (auth.budget_reservation.get("finalized") is True) is released
|
|
|
|
|
|
class _PartialBillingRecorder(CustomLogger):
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self.billed_texts: Final[list[str]] = [] # mutable-ok: collects the billing events the stream dispatches
|
|
self.billed: Final = asyncio.Event()
|
|
|
|
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
|
|
self.billed_texts.append(litellm.get_response_string(response_obj))
|
|
self.billed.set()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_stream_a_guardrail_buffered_leaves_its_reservation_to_the_partial_billing_when_the_client_leaves(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
_patch_logging_flags(monkeypatch, needs_wrap=True)
|
|
recorder: Final = _PartialBillingRecorder()
|
|
provider_stream: Final = await litellm.acompletion(
|
|
model="gpt-4o-mini",
|
|
messages=[{"role": "user", "content": "count"}],
|
|
mock_response="one two three four five six seven eight",
|
|
stream=True,
|
|
api_key="test-key",
|
|
)
|
|
provider_stream.logging_obj.dynamic_async_success_callbacks = [recorder]
|
|
guardrail_holding_chunks: Final = asyncio.Event()
|
|
|
|
async def buffering_guardrail(user_api_key_dict, response, request_data) -> AsyncIterator[object]:
|
|
held: Final = [await response.__anext__() for _ in range(3)]
|
|
guardrail_holding_chunks.set()
|
|
await asyncio.Event().wait()
|
|
for chunk in held:
|
|
yield chunk
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_iterator_hook", buffering_guardrail)
|
|
auth: Final = UserAPIKeyAuth(
|
|
api_key="sk-test-key", budget_reservation={"reserved_cost": 0.01, "input_cost": 0.004, "entries": []}
|
|
)
|
|
generator: Final = async_data_generator(
|
|
response=provider_stream,
|
|
user_api_key_dict=auth,
|
|
request_data={"model": "gpt-4o-mini", "litellm_logging_obj": provider_stream.logging_obj},
|
|
)
|
|
first_frame: Final = asyncio.ensure_future(generator.__anext__())
|
|
await guardrail_holding_chunks.wait()
|
|
first_frame.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await first_frame
|
|
await asyncio.wait_for(recorder.billed.wait(), timeout=5)
|
|
|
|
assert recorder.billed_texts == ["".join(chunk.choices[0].delta.content or "" for chunk in provider_stream.chunks)]
|
|
assert recorder.billed_texts[0]
|
|
assert auth.budget_reservation is not None
|
|
assert auth.budget_reservation.get("finalized") is not True
|
|
|
|
|
|
_AZURE_CONTENT_FILTER_RESULTS: Final = {
|
|
"hate": {"filtered": False, "severity": "safe"},
|
|
"protected_material_text": {"detected": False, "filtered": False},
|
|
}
|
|
|
|
|
|
def _azure_chunk(choice_fields: dict[str, object], chunk_fields: dict[str, object]) -> ModelResponseStream:
|
|
return ModelResponseStream(
|
|
id="chatcmpl-azure",
|
|
choices=[StreamingChoices(index=0, delta=Delta(content="Red"), **choice_fields)],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
**chunk_fields,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("chunk", "read_field", "sent"),
|
|
[
|
|
pytest.param(
|
|
_azure_chunk({"content_filter_results": _AZURE_CONTENT_FILTER_RESULTS}, {}),
|
|
lambda payload: payload["choices"][0]["content_filter_results"],
|
|
_AZURE_CONTENT_FILTER_RESULTS,
|
|
id="choice-content-filter-results",
|
|
),
|
|
pytest.param(
|
|
_azure_chunk({}, {"obfuscation": "Ab3"}),
|
|
lambda payload: payload["obfuscation"],
|
|
"Ab3",
|
|
id="chunk-obfuscation",
|
|
),
|
|
pytest.param(
|
|
ModelResponseStream(
|
|
id="chatcmpl-or",
|
|
choices=[
|
|
StreamingChoices(
|
|
index=0,
|
|
delta=Delta(content="Red", reasoning_details=[{"type": "reasoning.text", "text": "colors"}]),
|
|
)
|
|
],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
),
|
|
lambda payload: payload["choices"][0]["delta"]["reasoning_details"],
|
|
[{"type": "reasoning.text", "text": "colors"}],
|
|
id="delta-reasoning-details",
|
|
),
|
|
pytest.param(
|
|
ModelResponseStream(
|
|
id="chatcmpl-resp",
|
|
choices=[
|
|
StreamingChoices(
|
|
index=0,
|
|
delta=Delta(content="Red", reasoning_items=[{"type": "reasoning", "id": "rs_1", "summary": []}]),
|
|
)
|
|
],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
),
|
|
lambda payload: payload["choices"][0]["delta"]["reasoning_items"],
|
|
[{"type": "reasoning", "id": "rs_1", "summary": []}],
|
|
id="delta-reasoning-items",
|
|
),
|
|
],
|
|
)
|
|
async def test_async_data_generator_sse_frame_keeps_provider_fields_on_a_text_chunk(
|
|
monkeypatch, chunk: ModelResponseStream, read_field: Callable[[dict[str, object]], object], sent: object
|
|
):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
out = [
|
|
line
|
|
async for line in async_data_generator(
|
|
response=_async_iter([chunk]),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
)
|
|
]
|
|
|
|
assert read_field(json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))) == sent
|
|
|
|
|
|
def _circular_dict() -> dict[str, object]:
|
|
looped: Final[dict[str, object]] = {"keep": 1} # mutable-ok: a circular dict has to be inserted into itself
|
|
looped["self"] = looped
|
|
return looped
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"unencodable",
|
|
[
|
|
pytest.param(object(), id="unknown-type"),
|
|
pytest.param(hashlib.sha256(b"trace").digest(), id="invalid-utf8-bytes"),
|
|
],
|
|
)
|
|
async def test_async_data_generator_streams_a_text_chunk_a_hook_tagged_with_a_value_json_cannot_encode(
|
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, unencodable: object
|
|
) -> None:
|
|
_patch_logging_flags(monkeypatch)
|
|
chunk: Final = _azure_chunk({"content_filter_results": _AZURE_CONTENT_FILTER_RESULTS}, {"obfuscation": "Ab3"})
|
|
setattr(chunk, "trace_chunk", unencodable)
|
|
setattr(chunk.choices[0], "trace_choice", unencodable)
|
|
setattr(chunk.choices[0].delta, "trace_delta", unencodable)
|
|
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
|
|
out: Final = [
|
|
line
|
|
async for line in async_data_generator(
|
|
response=_async_iter([chunk]),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
)
|
|
]
|
|
|
|
payload: Final = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert payload["obfuscation"] == "Ab3"
|
|
assert payload["choices"][0]["content_filter_results"] == _AZURE_CONTENT_FILTER_RESULTS
|
|
assert payload["choices"][0]["delta"] == {"content": "Red"}
|
|
assert "trace_chunk" not in payload
|
|
assert "trace_choice" not in payload["choices"][0]
|
|
assert all(name in caplog.text for name in ("trace_chunk", "trace_choice", "trace_delta"))
|
|
|
|
|
|
def test_serialize_streaming_chunk_keeps_lone_surrogates_a_provider_split_across_frames(
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
tool_call: Final = ChatCompletionDeltaToolCall(
|
|
id="call_1", index=0, type="function", function=Function(name="get_weather", arguments='{"city": "Par\udc00is"}')
|
|
)
|
|
chunk: Final = ModelResponseStream(
|
|
id="chatcmpl-split",
|
|
choices=[StreamingChoices(index=0, delta=Delta(content="Hi \ud83d", tool_calls=[tool_call]))],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
)
|
|
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
|
|
delta: Final = json.loads(_serialize_streaming_chunk(chunk))["choices"][0]["delta"]
|
|
|
|
assert caplog.text == ""
|
|
assert delta["content"] == "Hi \ud83d"
|
|
assert delta["tool_calls"][0]["id"] == "call_1"
|
|
assert delta["tool_calls"][0]["function"] == {"name": "get_weather", "arguments": '{"city": "Par\udc00is"}'}
|
|
|
|
|
|
def test_serialize_streaming_chunk_drops_only_the_nested_value_json_cannot_encode() -> None:
|
|
digest: Final = hashlib.sha256(b"trace").digest()
|
|
chunk: Final = ModelResponseStream(
|
|
id="chatcmpl-nested",
|
|
choices=[
|
|
StreamingChoices(index=0, delta=Delta(content="a")),
|
|
StreamingChoices(
|
|
index=1, delta=Delta(content="b", provider_specific_fields={"citations": ["ok"], "raw": digest})
|
|
),
|
|
],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
usage=Usage(prompt_tokens=3, completion_tokens=2, total_tokens=5),
|
|
)
|
|
setattr(chunk.usage, "raw", digest)
|
|
setattr(chunk, "trace_chunk", _circular_dict())
|
|
|
|
payload: Final = json.loads(_serialize_streaming_chunk(chunk))
|
|
|
|
assert payload["choices"][0]["delta"] == {"content": "a"}
|
|
assert payload["choices"][1]["delta"] == {"content": "b", "provider_specific_fields": {"citations": ["ok"]}}
|
|
assert payload["usage"] == {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}
|
|
assert payload["trace_chunk"] == {"keep": 1}
|
|
|
|
|
|
def test_serialize_streaming_chunk_keeps_streaming_when_unencodable_values_sit_under_non_string_keys() -> None:
|
|
chunk: Final = ModelResponseStream(
|
|
id="chatcmpl-keys",
|
|
choices=[StreamingChoices(index=0, delta=Delta(content="still streaming"))],
|
|
created=0,
|
|
model="gpt-4",
|
|
object="chat.completion.chunk",
|
|
)
|
|
setattr(chunk, "by_index", {0: "kept", 1: object()})
|
|
setattr(chunk, "mixed_keys", {"name": "x", 2: object()})
|
|
setattr(chunk, "bytes_keys", {b"raw": object()})
|
|
setattr(chunk, "read_only_view", MappingProxyType({"name": object()}))
|
|
|
|
payload: Final = json.loads(_serialize_streaming_chunk(chunk))
|
|
|
|
assert payload["choices"][0]["delta"] == {"content": "still streaming"}
|
|
assert payload["by_index"] == {"0": "kept"}
|
|
assert "mixed_keys" not in payload
|
|
assert "bytes_keys" not in payload
|
|
assert "read_only_view" not in payload
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_uses_response_fallback_metadata(monkeypatch):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
response = _FakeStream(
|
|
[_simple_chunk(model="openai/internal-fallback", content="hello")],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
}
|
|
},
|
|
)
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "primary-model", "include_fallback_errors": True},
|
|
):
|
|
out.append(line)
|
|
|
|
payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert payload["model"] == "fallback-model"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_uses_chunk_fallback_metadata(monkeypatch):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
chunk = _simple_chunk(model="openai/internal-fallback", content="hello")
|
|
chunk._hidden_params = {
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
}
|
|
}
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_async_iter([chunk]),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "primary-model"},
|
|
):
|
|
out.append(line)
|
|
|
|
payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert payload["model"] == "fallback-model"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_switches_model_mid_stream_on_fallback(monkeypatch):
|
|
"""Pre-fallback chunks keep the client-requested model; once a chunk carries
|
|
fallback metadata the model latches to the fallback group for the rest of the
|
|
stream. This pins the client-visible mid-stream model change."""
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
primary_chunk = _simple_chunk(model="openai/internal-primary", content="hi")
|
|
fallback_chunk = _simple_chunk(model="openai/internal-fallback", content="there")
|
|
fallback_chunk._hidden_params = {
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
}
|
|
}
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_async_iter([primary_chunk, fallback_chunk]),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "primary-model"},
|
|
):
|
|
out.append(line)
|
|
|
|
first_payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
second_payload = json.loads(_sse_text(out[1]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert first_payload["model"] == "primary-model"
|
|
assert second_payload["model"] == "fallback-model"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_emits_fallback_error_metadata_event(monkeypatch):
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setitem(ps.general_settings, "expose_fallback_errors_to_caller", True)
|
|
|
|
fallback_errors = [
|
|
{
|
|
"message": "litellm.RateLimitError: upstream limited request",
|
|
"type": "RateLimitError",
|
|
"param": None,
|
|
"code": "429",
|
|
}
|
|
]
|
|
response = _FakeStream(
|
|
[_simple_chunk(model="openai/internal-fallback", content="hello")],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
"x-litellm-fallback-errors": json.dumps(fallback_errors),
|
|
}
|
|
},
|
|
)
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "primary-model", "include_fallback_errors": True},
|
|
):
|
|
out.append(line)
|
|
|
|
chunk_payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert chunk_payload["model"] == "fallback-model"
|
|
assert isinstance(out[1], str)
|
|
assert out[1].startswith("data: ")
|
|
metadata_payload = json.loads(out[1].removeprefix("data: ").removesuffix("\n\n"))
|
|
assert metadata_payload["choices"] == []
|
|
assert metadata_payload["litellm_fallback"] == {
|
|
"fallback_model": "fallback-model",
|
|
"errors": fallback_errors,
|
|
}
|
|
assert metadata_payload["id"] == "litellm-fallback-metadata"
|
|
assert metadata_payload["object"] == "chat.completion.chunk"
|
|
assert metadata_payload["model"] == "fallback-model"
|
|
assert isinstance(metadata_payload["created"], int)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chat_stream_sends_fallback_metadata_in_place_of_a_stripped_usage_artifact(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setitem(ps.general_settings, "expose_fallback_errors_to_caller", True)
|
|
fallback_errors: Final = [
|
|
{"message": "litellm.RateLimitError: upstream limited request", "type": "RateLimitError", "code": "429"}
|
|
]
|
|
usage_artifact: Final = ModelResponseStream(
|
|
id="chatcmpl-test", choices=[], created=0, model="openai/internal-fallback", object="chat.completion.chunk"
|
|
)
|
|
upstream: Final = _FakeStream(
|
|
[usage_artifact, _simple_chunk(model="openai/internal-fallback", content="hello")],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
"x-litellm-fallback-errors": json.dumps(fallback_errors),
|
|
}
|
|
},
|
|
)
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in async_data_generator(
|
|
response=upstream,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={
|
|
"model": "primary-model",
|
|
"include_fallback_errors": True,
|
|
"_litellm_strip_stream_usage": True,
|
|
},
|
|
)
|
|
]
|
|
)
|
|
payloads: Final = tuple(json.loads(frame.removeprefix("data: ")) for frame in frames[:-1])
|
|
|
|
assert frames[-1] == "data: [DONE]\n\n"
|
|
assert len(payloads) == 2
|
|
assert payloads[0]["object"] == "chat.completion.chunk"
|
|
assert payloads[0]["choices"] == []
|
|
assert payloads[0]["litellm_fallback"] == {"fallback_model": "fallback-model", "errors": fallback_errors}
|
|
assert payloads[1]["choices"][0]["delta"]["content"] == "hello"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("fallback_model", ["fallback-model", None])
|
|
@pytest.mark.parametrize("return_raw_model_name", [False, True])
|
|
async def test_responses_stream_sends_fallback_metadata_as_a_typed_event_without_an_event_line(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
fallback_model: str | None,
|
|
return_raw_model_name: bool,
|
|
) -> None:
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setitem(ps.general_settings, "expose_fallback_errors_to_caller", True)
|
|
fallback_errors: Final = [
|
|
{
|
|
"message": "litellm.AuthenticationError: Incorrect API key provided",
|
|
"type": "AuthenticationError",
|
|
"param": None,
|
|
"code": "401",
|
|
}
|
|
]
|
|
response: Final = ResponsesAPIResponse(id="resp_fallback", created_at=1, model="fallback-model", output=[])
|
|
upstream: Final = _FakeStream(
|
|
[
|
|
ResponseCreatedEvent.model_validate(
|
|
{"type": "response.created", "sequence_number": 0, "response": response}
|
|
),
|
|
ResponseCompletedEvent.model_validate(
|
|
{"type": "response.completed", "sequence_number": 1, "response": response}
|
|
),
|
|
],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
**({"x-litellm-model-group": fallback_model} if fallback_model else {}),
|
|
"x-litellm-fallback-errors": json.dumps(fallback_errors),
|
|
}
|
|
},
|
|
)
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in async_data_generator(
|
|
response=upstream,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={
|
|
"model": "primary-model",
|
|
"include_fallback_errors": True,
|
|
"metadata": {RETURN_RAW_MODEL_NAME_METADATA_KEY: return_raw_model_name},
|
|
},
|
|
responses_stream_errors=True,
|
|
)
|
|
]
|
|
)
|
|
event_frames: Final = tuple(frame for frame in frames if frame != "data: [DONE]\n\n")
|
|
payloads: Final = tuple(
|
|
json.loads(next(line.removeprefix("data: ") for line in frame.splitlines() if line.startswith("data: ")))
|
|
for frame in event_frames
|
|
)
|
|
|
|
assert tuple(payload.get("type") for payload in payloads) == (
|
|
"response.created",
|
|
"litellm.fallback_metadata",
|
|
"response.completed",
|
|
)
|
|
stamped_model: Final = None if return_raw_model_name else fallback_model
|
|
assert payloads[1] == {
|
|
"type": "litellm.fallback_metadata",
|
|
"id": "litellm-fallback-metadata",
|
|
**({"model": stamped_model} if stamped_model else {}),
|
|
"litellm_fallback": {"fallback_model": fallback_model, "errors": fallback_errors},
|
|
}
|
|
assert {payload.get("model") for payload in payloads} == {stamped_model}
|
|
assert event_frames[1] == f"data: {json.dumps(payloads[1])}\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_skips_fallback_error_event_without_opt_in(
|
|
monkeypatch,
|
|
):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
fallback_errors = [
|
|
{
|
|
"message": "litellm.RateLimitError: upstream limited request",
|
|
"type": "RateLimitError",
|
|
"param": None,
|
|
"code": "429",
|
|
}
|
|
]
|
|
response = _FakeStream(
|
|
[_simple_chunk(model="openai/internal-fallback", content="hello")],
|
|
hidden_params={
|
|
"additional_headers": {
|
|
"x-litellm-attempted-fallbacks": 1,
|
|
"x-litellm-model-group": "fallback-model",
|
|
"x-litellm-fallback-errors": json.dumps(fallback_errors),
|
|
}
|
|
},
|
|
)
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "primary-model"},
|
|
):
|
|
out.append(line)
|
|
|
|
payload = json.loads(_sse_text(out[0]).removeprefix("data: ").removesuffix("\n\n"))
|
|
assert payload["model"] == "fallback-model"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_mid_stream_exception_yields_error_payload(
|
|
monkeypatch,
|
|
):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
async def _noop_failure(*args, **kwargs):
|
|
return None
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", _noop_failure)
|
|
|
|
response = _async_iter_raises(RuntimeError("upstream blew up"))
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
):
|
|
out.append(line)
|
|
|
|
# First entry is the successful "partial" chunk (bytes), last is the error.
|
|
assert any(isinstance(item, str) and item.startswith('data: {"error":') for item in out)
|
|
|
|
|
|
_BLOCK_MESSAGE: Final = "Content blocked: keyword 'keeper' detected"
|
|
_BLOCK_ERROR: Final = {
|
|
"message": _BLOCK_MESSAGE,
|
|
"type": "invalid_request_error",
|
|
"param": None,
|
|
"code": "400",
|
|
"provider_specific_fields": {"error": _BLOCK_MESSAGE},
|
|
}
|
|
_UNSERIALIZABLE_SPAN: Final = object()
|
|
|
|
|
|
async def _blocked_after(chunks: int, detail: dict[str, object]) -> AsyncIterator[ModelResponseStream]:
|
|
for _ in range(chunks):
|
|
yield _simple_chunk(content="partial")
|
|
raise HTTPException(status_code=400, detail=detail)
|
|
|
|
|
|
async def _served(
|
|
upstream: AsyncIterator[ModelResponseStream], request_data: dict[str, object] | None = None
|
|
) -> tuple[int, str | None, tuple[str, ...]]:
|
|
response: Final = await create_response(
|
|
generator=async_data_generator(
|
|
response=upstream, user_api_key_dict=_user_auth(), request_data=dict(request_data or {})
|
|
),
|
|
media_type="text/event-stream",
|
|
headers={},
|
|
)
|
|
assert isinstance(response, StreamingResponse)
|
|
body: Final = "".join(
|
|
[part if isinstance(part, str) else bytes(part).decode() async for part in response.body_iterator]
|
|
)
|
|
return response.status_code, response.media_type, tuple(frame for frame in body.split("\n\n") if frame)
|
|
|
|
|
|
def _error_of(frame: str) -> dict[str, object]:
|
|
return json.loads(frame.removeprefix("data: "))["error"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"raised, expected_error",
|
|
[
|
|
pytest.param(
|
|
ProxyException(message="Budget has been exceeded", type="budget_exceeded", param=None, code=429),
|
|
{"message": "Budget has been exceeded", "type": "budget_exceeded", "param": None, "code": "429"},
|
|
id="proxy_exception_keeps_its_status",
|
|
),
|
|
pytest.param(
|
|
RuntimeError("upstream blew up"),
|
|
{"message": "upstream blew up", "type": "internal_server_error", "param": None, "code": "500"},
|
|
id="unexpected_failure",
|
|
),
|
|
],
|
|
)
|
|
async def test_a_mid_stream_failure_frame_carries_the_status_the_error_was_raised_with(
|
|
monkeypatch, raised: Exception, expected_error: dict[str, object]
|
|
):
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", AsyncMock(return_value=None))
|
|
|
|
frames: Final = [
|
|
frame
|
|
async for frame in async_data_generator(
|
|
response=_async_iter_raises(raised), user_api_key_dict=_user_auth(), request_data={}
|
|
)
|
|
]
|
|
|
|
error_frames: Final = [frame for frame in frames if isinstance(frame, str) and frame.startswith('data: {"error":')]
|
|
assert [_error_of(frame.removesuffix("\n\n")) for frame in error_frames] == [expected_error]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"detail,expected_message,expected_fields",
|
|
[
|
|
pytest.param(
|
|
{"error": _BLOCK_MESSAGE, "guardrail": "block-keeper-word"},
|
|
_BLOCK_MESSAGE,
|
|
{"error": _BLOCK_MESSAGE, "guardrail": "block-keeper-word"},
|
|
id="json_detail",
|
|
),
|
|
pytest.param(
|
|
{"error": _BLOCK_MESSAGE, "matched_span": _UNSERIALIZABLE_SPAN},
|
|
_BLOCK_MESSAGE,
|
|
{"error": _BLOCK_MESSAGE, "matched_span": str(_UNSERIALIZABLE_SPAN)},
|
|
id="non_json_detail",
|
|
),
|
|
pytest.param(
|
|
{"matched_span": _UNSERIALIZABLE_SPAN},
|
|
json.dumps({"matched_span": str(_UNSERIALIZABLE_SPAN)}),
|
|
{"matched_span": str(_UNSERIALIZABLE_SPAN)},
|
|
id="non_json_detail_without_message",
|
|
),
|
|
],
|
|
)
|
|
async def test_guardrail_block_after_the_first_chunk_ends_the_stream_with_an_error_event(
|
|
detail: dict[str, object], expected_message: str, expected_fields: dict[str, str]
|
|
) -> None:
|
|
status_code, _, frames = await _served(_blocked_after(1, detail))
|
|
|
|
assert status_code == 200
|
|
assert len(frames) == 3
|
|
assert json.loads(frames[0].removeprefix("data: "))["choices"][0]["delta"]["content"] == "partial"
|
|
assert _error_of(frames[1]) == {
|
|
"message": expected_message,
|
|
"type": "invalid_request_error",
|
|
"param": None,
|
|
"code": "400",
|
|
"provider_specific_fields": expected_fields,
|
|
}
|
|
assert frames[2] == "data: [DONE]"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_guardrail_block_mid_stream_on_a_gemini_stream_sends_no_openai_error_event() -> None:
|
|
response: Final = await create_response(
|
|
generator=async_data_generator(
|
|
response=_blocked_after(1, {"error": _BLOCK_MESSAGE}),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"_litellm_skip_openai_stream_done": True},
|
|
),
|
|
media_type="text/event-stream",
|
|
headers={},
|
|
)
|
|
assert isinstance(response, StreamingResponse)
|
|
parts: Final = aiter(response.body_iterator)
|
|
first: Final = await anext(parts)
|
|
|
|
with pytest.raises(HTTPException):
|
|
await anext(parts)
|
|
assert '"error"' not in (first if isinstance(first, str) else bytes(first).decode())
|
|
|
|
|
|
async def _upstream_fails_after(chunks: int) -> AsyncIterator[ModelResponseStream]:
|
|
for _ in range(chunks):
|
|
yield _simple_chunk(content="partial")
|
|
raise RuntimeError("upstream reset")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"request_data,closing_frames",
|
|
[
|
|
pytest.param({}, ("data: [DONE]",), id="openai_stream"),
|
|
pytest.param({"_litellm_skip_openai_stream_done": True}, (), id="gemini_stream"),
|
|
],
|
|
)
|
|
async def test_upstream_failure_mid_stream_ends_with_an_error_event(
|
|
request_data: dict[str, object], closing_frames: tuple[str, ...]
|
|
) -> None:
|
|
status_code, _, frames = await _served(_upstream_fails_after(1), request_data)
|
|
|
|
assert status_code == 200
|
|
assert _error_of(frames[1])["message"] == "upstream reset"
|
|
assert frames[2:] == closing_frames
|
|
|
|
|
|
class _ReplacesClientErrors(CustomLogger):
|
|
async def async_post_call_failure_hook(
|
|
self,
|
|
request_data: dict,
|
|
original_exception: Exception,
|
|
user_api_key_dict: UserAPIKeyAuth,
|
|
traceback_str: str | None = None,
|
|
) -> HTTPException:
|
|
return HTTPException(status_code=403, detail="Request blocked by policy")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"upstream,original_message,expected_status",
|
|
[
|
|
pytest.param(
|
|
lambda: _blocked_after(0, {"error": _BLOCK_MESSAGE}), _BLOCK_MESSAGE, 403, id="block_before_the_first_chunk"
|
|
),
|
|
pytest.param(lambda: _blocked_after(1, {"error": _BLOCK_MESSAGE}), _BLOCK_MESSAGE, 200, id="block_mid_stream"),
|
|
pytest.param(lambda: _upstream_fails_after(1), "upstream reset", 200, id="failure_mid_stream"),
|
|
],
|
|
)
|
|
async def test_stream_error_sends_the_failure_hook_replacement(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
upstream: Callable[[], AsyncIterator[ModelResponseStream]],
|
|
original_message: str,
|
|
expected_status: int,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
|
|
|
|
status_code, _, frames = await _served(upstream())
|
|
|
|
assert status_code == expected_status
|
|
assert original_message not in "".join(frames)
|
|
assert _error_of(frames[-2]) == {
|
|
"message": "Request blocked by policy",
|
|
"type": "permission_error",
|
|
"param": None,
|
|
"code": "403",
|
|
}
|
|
assert frames[-1] == "data: [DONE]"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_failure_before_the_first_chunk_answers_the_failure_hook_replacement_as_json(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
|
|
|
|
response: Final = await create_response(
|
|
generator=async_data_generator(
|
|
response=_upstream_fails_after(0), user_api_key_dict=_user_auth(), request_data={}
|
|
),
|
|
media_type="text/event-stream",
|
|
headers={},
|
|
)
|
|
|
|
assert isinstance(response, JSONResponse)
|
|
assert response.status_code == 403
|
|
assert json.loads(bytes(response.body))["error"]["message"] == "Request blocked by policy"
|
|
assert b"upstream reset" not in bytes(response.body)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_failure_before_the_first_chunk_on_a_bare_stream_still_ends_with_the_replacement_event(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame
|
|
async for frame in async_data_generator(
|
|
response=_upstream_fails_after(0), user_api_key_dict=_user_auth(), request_data={}
|
|
)
|
|
]
|
|
)
|
|
|
|
assert _error_of(frames[0].strip())["message"] == "Request blocked by policy"
|
|
assert frames[1:] == ("data: [DONE]\n\n",)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_responses_stream_failure_sends_the_failure_hook_replacement(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_ReplacesClientErrors()])
|
|
response: Final = ResponsesAPIResponse(id="resp_visible", created_at=1, model="gpt-6-astra", output=[])
|
|
|
|
async def upstream() -> AsyncIterator[BaseModel]:
|
|
yield ResponseCreatedEvent.model_validate({"type": "response.created", "sequence_number": 0, "response": response})
|
|
raise HTTPException(status_code=400, detail={"error": _BLOCK_MESSAGE})
|
|
|
|
frames: Final = tuple(
|
|
[
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(), user_api_key_dict=_user_auth(), request_data={}, responses_stream_errors=True
|
|
)
|
|
]
|
|
)
|
|
failure: Final = ResponseFailedEvent.model_validate_json(
|
|
next(line.removeprefix("data: ") for line in frames[-1].splitlines() if line.startswith("data: "))
|
|
)
|
|
|
|
assert _BLOCK_MESSAGE not in "".join(frames)
|
|
assert failure.response.error is not None
|
|
assert failure.response.error["code"] == "permission_error"
|
|
assert "Request blocked by policy" in failure.response.error["message"]
|
|
assert frames[-1].startswith("event: response.failed\n")
|
|
assert "data: [DONE]\n\n" not in frames
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"detail,expected_fields",
|
|
[
|
|
pytest.param({"error": _BLOCK_MESSAGE}, {"error": _BLOCK_MESSAGE}, id="json_detail"),
|
|
pytest.param(
|
|
{"error": _BLOCK_MESSAGE, "matched_span": _UNSERIALIZABLE_SPAN},
|
|
{"error": _BLOCK_MESSAGE, "matched_span": str(_UNSERIALIZABLE_SPAN)},
|
|
id="non_json_detail",
|
|
),
|
|
],
|
|
)
|
|
async def test_guardrail_block_before_the_first_chunk_keeps_its_http_status(
|
|
detail: dict[str, object], expected_fields: dict[str, str]
|
|
) -> None:
|
|
status_code, media_type, frames = await _served(_blocked_after(0, detail))
|
|
|
|
assert (status_code, media_type) == (400, "text/event-stream")
|
|
assert len(frames) == 2
|
|
assert _error_of(frames[0]) == {**_BLOCK_ERROR, "provider_specific_fields": expected_fields}
|
|
assert frames[1] == "data: [DONE]"
|
|
|
|
|
|
async def _blocked_after_a_stall() -> AsyncIterator[ModelResponseStream]:
|
|
await asyncio.sleep(1.5)
|
|
async for chunk in _blocked_after(0, {"error": _BLOCK_MESSAGE}):
|
|
yield chunk
|
|
|
|
|
|
def test_guardrail_block_after_a_keepalive_ping_ends_the_stream_with_an_error_event(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 1)
|
|
loop: Final = AutojumpClockLoop()
|
|
|
|
try:
|
|
status_code, _, frames = loop.run_until_complete(_served(_blocked_after_a_stall()))
|
|
finally:
|
|
loop.run_until_complete(loop.shutdown_asyncgens())
|
|
loop.close()
|
|
|
|
assert status_code == 200
|
|
assert frames[0] == ": ping"
|
|
assert _error_of(frames[-2]) == _BLOCK_ERROR
|
|
assert frames[-1] == "data: [DONE]"
|
|
|
|
class _BlocksKeeperPerChunk(CustomLogger):
|
|
async def async_post_call_streaming_hook(self, user_api_key_dict: UserAPIKeyAuth, response: str) -> None:
|
|
if "keeper" in response:
|
|
raise HTTPException(status_code=400, detail={"error": _BLOCK_MESSAGE})
|
|
|
|
|
|
async def _chunks(*contents: str) -> AsyncIterator[ModelResponseStream]:
|
|
for content in contents:
|
|
yield _simple_chunk(content=content)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"contents,expected_status,expected_frames",
|
|
[
|
|
pytest.param(("the keeper",), 400, 2, id="first_chunk"),
|
|
pytest.param(("partial", "the keeper"), 200, 3, id="second_chunk"),
|
|
],
|
|
)
|
|
async def test_per_chunk_guardrail_block_keeps_early_blocks_on_their_status_and_ends_later_ones_in_band(
|
|
monkeypatch: pytest.MonkeyPatch, contents: tuple[str, ...], expected_status: int, expected_frames: int
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "callbacks", [_BlocksKeeperPerChunk()])
|
|
|
|
status_code, media_type, frames = await _served(_chunks(*contents))
|
|
|
|
assert (status_code, media_type) == (expected_status, "text/event-stream")
|
|
assert len(frames) == expected_frames
|
|
assert _error_of(frames[-2]) == _BLOCK_ERROR
|
|
assert frames[-1] == "data: [DONE]"
|
|
|
|
|
|
_UPSTREAM_BODY: Final = {
|
|
"code": "cyber_policy",
|
|
"message": "Upstream rejected request: flagged for possible cybersecurity risk",
|
|
"type": None,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"terminal,upstream_error,expected_code",
|
|
[
|
|
("completed", None, None),
|
|
("serialization_failure", None, "server_error"),
|
|
("failure_after_completed", None, None),
|
|
pytest.param(
|
|
"upstream_failure",
|
|
litellm.AuthenticationError(
|
|
message="Upstream rejected request", llm_provider="openai", model="gpt-6-astra"
|
|
),
|
|
"authentication_error", id="authentication_error",
|
|
),
|
|
pytest.param(
|
|
"upstream_failure",
|
|
OpenAIAPIError(
|
|
message="Upstream rejected request",
|
|
request=httpx.Request("POST", "https://streaming.example/v1/responses"),
|
|
body={"code": {"reason": "overloaded"}, "type": {"unexpected": "object"}},
|
|
),
|
|
"server_error", id="structured_provider_error_fields",
|
|
),
|
|
pytest.param(
|
|
"upstream_failure",
|
|
litellm.InternalServerError(
|
|
message="Upstream rejected request", llm_provider="openai", model="gpt-6-astra", body=_UPSTREAM_BODY
|
|
),
|
|
"cyber_policy", id="upstream_body_code_and_message",
|
|
),
|
|
pytest.param(
|
|
"upstream_failure", RuntimeError("Upstream rejected request"), "server_error", id="builtin_exception"
|
|
),
|
|
*(
|
|
pytest.param(
|
|
"upstream_failure", HTTPException(status_code=status, detail="Upstream rejected request"),
|
|
code, id=f"http_{status}",
|
|
)
|
|
for status, code in (
|
|
(400, "invalid_request_error"), (403, "permission_error"), (404, "not_found_error"),
|
|
(408, "request_timeout"), (422, "invalid_request_error"), (500, "server_error"), (503, "server_error"),
|
|
)
|
|
),
|
|
],
|
|
)
|
|
async def test_responses_stream_keeps_tool_deltas_and_only_emits_a_valid_terminal(
|
|
terminal: Literal["completed", "serialization_failure", "failure_after_completed", "upstream_failure"],
|
|
upstream_error: Exception | None,
|
|
expected_code: str | None,
|
|
) -> None:
|
|
class ToolDelta(BaseModel):
|
|
type: Literal["response.function_call_arguments.delta"]
|
|
sequence_number: int
|
|
item_id: str
|
|
output_index: int
|
|
delta: str
|
|
|
|
class UnserializableTerminal(BaseModel):
|
|
type: Literal["response.completed"]
|
|
sequence_number: int
|
|
response: ResponsesAPIResponse
|
|
invalid: object
|
|
|
|
response: Final = ResponsesAPIResponse(id="resp_visible", created_at=1, model="gpt-6-astra", output=[])
|
|
created: Final = ResponseCreatedEvent.model_validate(
|
|
{"type": "response.created", "sequence_number": 0, "response": response}
|
|
)
|
|
completed: Final = ResponseCompletedEvent.model_validate(
|
|
{"type": "response.completed", "sequence_number": 2, "response": response}
|
|
)
|
|
tool_delta: Final = ToolDelta(
|
|
type="response.function_call_arguments.delta", sequence_number=1, item_id="fc_stream_error",
|
|
output_index=0, delta='{"path":"partial',
|
|
)
|
|
original_status: Final = (
|
|
upstream_error.status_code if isinstance(upstream_error, (HTTPException, litellm.AuthenticationError)) else None
|
|
)
|
|
|
|
async def upstream() -> AsyncIterator[BaseModel]:
|
|
yield created
|
|
yield tool_delta
|
|
if upstream_error is not None:
|
|
raise upstream_error
|
|
yield (
|
|
UnserializableTerminal(type="response.completed", sequence_number=2, response=response, invalid=object())
|
|
if terminal == "serialization_failure" else completed
|
|
)
|
|
if terminal == "failure_after_completed":
|
|
raise litellm.APIError(
|
|
status_code=500, message="Stream close failed", llm_provider="openai", model="gpt-6-astra"
|
|
)
|
|
|
|
frames: Final = [
|
|
frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={},
|
|
responses_stream_errors=True,
|
|
)
|
|
]
|
|
decoded: Final = tuple(frame.decode() if isinstance(frame, bytes) else frame for frame in frames)
|
|
event_frames: Final = tuple(frame for frame in decoded if frame != "data: [DONE]\n\n")
|
|
payloads: Final = tuple(
|
|
json.loads(next(line[6:] for line in frame.splitlines() if line.startswith("data: ")))
|
|
for frame in event_frames
|
|
)
|
|
|
|
assert len(decoded) == len(event_frames)
|
|
assert "data: [DONE]\n\n" not in decoded
|
|
assert payloads[0]["response"]["id"] == "resp_visible"
|
|
assert payloads[1] == tool_delta.model_dump()
|
|
assert len(payloads) == 3
|
|
if terminal in ("serialization_failure", "upstream_failure"):
|
|
failure: Final = ResponseFailedEvent.model_validate(payloads[-1])
|
|
assert event_frames[-1].startswith("event: response.failed\n")
|
|
assert failure.response.id == "resp_visible"
|
|
assert failure.response.status == "failed"
|
|
assert failure.response.error is not None
|
|
assert failure.response.error["code"] == expected_code
|
|
if upstream_error is None:
|
|
assert "serialize" in failure.response.error["message"].lower()
|
|
else:
|
|
assert "Upstream rejected request" in failure.response.error["message"]
|
|
if isinstance(upstream_error, litellm.InternalServerError):
|
|
assert failure.response.error["message"] == _UPSTREAM_BODY["message"]
|
|
if isinstance(upstream_error, (HTTPException, litellm.AuthenticationError)):
|
|
assert upstream_error.status_code == original_status
|
|
assert payloads[-1]["sequence_number"] > payloads[1]["sequence_number"]
|
|
else:
|
|
assert payloads[-1]["type"] == "response.completed"
|
|
assert payloads[-1]["sequence_number"] == 2
|
|
assert "error" not in payloads[-1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("raw_sse_stream", [False, True])
|
|
@pytest.mark.parametrize("newline", ["\n", "\r\n"])
|
|
@pytest.mark.parametrize(
|
|
"event_name,data,terminal",
|
|
[
|
|
(
|
|
"response.output_text.delta",
|
|
{"type": "response.output_text.delta", "sequence_number": 4, "delta": "hi"},
|
|
False,
|
|
),
|
|
(
|
|
"response.completed",
|
|
{"type": "response.completed", "sequence_number": 4, "response": {"id": "resp_raw", "model": "gpt-6"}},
|
|
True,
|
|
),
|
|
("error", {"error": {"message": "denied", "code": "529"}}, True),
|
|
("response.completed", {"sequence_number": 4, "note": "typeless"}, False),
|
|
("error", {"sequence_number": 4, "note": "no error object"}, False),
|
|
("error", {"sequence_number": 4, "error": "denied"}, False),
|
|
("error", {"sequence_number": 4, "error": ["denied"]}, False),
|
|
],
|
|
)
|
|
async def test_a_responses_stream_failing_after_a_pre_framed_event_adds_a_failure_only_without_a_terminal(
|
|
raw_sse_stream: bool, newline: str, event_name: str, data: Mapping[str, object], terminal: bool
|
|
) -> None:
|
|
pre_framed: Final = f"event: {event_name}{newline}data: {json.dumps(data)}{newline}{newline}"
|
|
|
|
async def upstream() -> AsyncIterator[bytes]:
|
|
yield pre_framed.encode()
|
|
raise litellm.APIError(status_code=500, message="Stream closed", llm_provider="openai", model="gpt-6")
|
|
|
|
frames: Final = [
|
|
frame.decode() if isinstance(frame, bytes) else frame
|
|
async for frame in select_data_generator(
|
|
response=upstream(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"_litellm_raw_sse_stream": True} if raw_sse_stream else {},
|
|
responses_stream_errors=True,
|
|
)
|
|
]
|
|
|
|
assert frames[0] == pre_framed
|
|
assert len(frames) == (1 if terminal else 2)
|
|
if not terminal:
|
|
failure: Final = ResponseFailedEvent.model_validate_json(frames[1].split("data: ", 1)[1])
|
|
assert frames[1].startswith("event: response.failed\n")
|
|
assert failure.sequence_number == 5
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"sequence_number",
|
|
["9" * 4300, "-7", str(2**63), str(2**63 - 1)],
|
|
ids=["4300_digits", "negative", "past_int64", "int64_max"],
|
|
)
|
|
def test_responses_error_event_after_an_out_of_range_pre_framed_sequence_number_stays_parseable(
|
|
sequence_number: str,
|
|
) -> None:
|
|
state: Final = ResponsesStreamErrorState()
|
|
state.observe_frames(
|
|
'data: {"type": "response.output_text.delta", "sequence_number": 4}\n\n'
|
|
f'data: {{"type": "response.output_text.delta", "sequence_number": {sequence_number}}}\n\n'
|
|
)
|
|
|
|
error_frame: Final = state.format_error_message('data: {"error": {"message": "scan failed"}}\n\n')
|
|
failure_frame: Final = state.format_failure(RuntimeError("stream closed"))
|
|
|
|
error_event: Final = json.loads(error_frame.split("data: ", 1)[1])
|
|
assert failure_frame is not None
|
|
assert error_event["message"] == "scan failed"
|
|
assert error_event["sequence_number"] == 5
|
|
assert json.loads(failure_frame.split("data: ", 1)[1])["sequence_number"] == 5
|
|
|
|
|
|
class _UnreadableErrorModel(BaseModel, frozen=True):
|
|
type: str = "response.output_text.delta"
|
|
sequence_number: int = 4
|
|
|
|
@property
|
|
def error(self) -> object:
|
|
raise RuntimeError("error is not readable")
|
|
|
|
|
|
class _UnreadableErrorMapping(Mapping[str, object]):
|
|
def __init__(self, data: Mapping[str, object]) -> None:
|
|
self.data: Final = data
|
|
|
|
def __getitem__(self, key: str) -> object:
|
|
if key == "error":
|
|
raise RuntimeError("error is not readable")
|
|
return self.data[key]
|
|
|
|
def __iter__(self) -> Iterator[str]:
|
|
return iter(self.data)
|
|
|
|
def __len__(self) -> int:
|
|
return len(self.data)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"chunk,next_sequence_number",
|
|
[
|
|
(_UnreadableErrorModel(), 5),
|
|
(_UnreadableErrorMapping({"type": "response.output_text.delta", "sequence_number": 4}), 5),
|
|
({"type": "response.output_text.delta", "sequence_number": 2**63}, 2**63 + 1),
|
|
],
|
|
ids=["unreadable_error_property", "unreadable_error_item", "past_int64"],
|
|
)
|
|
def test_responses_failure_after_a_hook_chunk_continues_its_sequence_number_like_base(
|
|
chunk: object, next_sequence_number: int
|
|
) -> None:
|
|
state: Final = ResponsesStreamErrorState()
|
|
state.observe_chunk(chunk)
|
|
state.mark_emitted(_format_responses_sse_chunk(chunk=chunk))
|
|
|
|
failure_frame: Final = state.format_failure(RuntimeError("stream closed"))
|
|
|
|
assert failure_frame is not None
|
|
assert json.loads(failure_frame.split("data: ", 1)[1])["sequence_number"] == next_sequence_number
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# select_data_generator
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_select_data_generator_returns_async_generator(monkeypatch):
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
response = _async_iter([_simple_chunk()])
|
|
gen = select_data_generator(
|
|
response=response,
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
)
|
|
|
|
# Drain to confirm it really is an async iterator emitting SSE shape.
|
|
collected = []
|
|
async for line in gen:
|
|
collected.append(line)
|
|
|
|
snapshot = {
|
|
"is_async_iterable": hasattr(gen, "__aiter__"),
|
|
"yielded_at_least_one": len(collected) >= 1,
|
|
"ends_with_done": collected[-1] == "data: [DONE]\n\n",
|
|
}
|
|
assert snapshot == {
|
|
"is_async_iterable": True,
|
|
"yielded_at_least_one": True,
|
|
"ends_with_done": True,
|
|
}
|
|
|
|
|
|
def test_select_data_generator_missing_required_kwarg_raises_type_error():
|
|
"""``select_data_generator`` requires all three keyword args — calling
|
|
without ``request_data`` raises TypeError at the wrapper, before any
|
|
streaming starts."""
|
|
with pytest.raises(TypeError):
|
|
select_data_generator(response=_async_iter([]), user_api_key_dict=_user_auth()) # type: ignore[call-arg]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SSE keepalive helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
from litellm.proxy.proxy_server import ( # noqa: E402
|
|
_iter_with_keepalive,
|
|
_keepalive_from_deployment_config,
|
|
_make_keepalive_resolver,
|
|
_resolve_keepalive_seconds,
|
|
)
|
|
from litellm.proxy.proxy_server import _KEEPALIVE_MAX_SECONDS, _KEEPALIVE_MIN_SECONDS # noqa: E402
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_hot_path_no_task_wrapping():
|
|
"""When keepalive_seconds <= 0, the generator is a transparent pass-through."""
|
|
chunks = [_simple_chunk(content="a"), _simple_chunk(content="b")]
|
|
out = []
|
|
async for item in _iter_with_keepalive(_async_iter(chunks), lambda _: 0, keepalive_seconds=0):
|
|
out.append(item)
|
|
|
|
assert out == chunks
|
|
assert ps._STREAM_KEEPALIVE not in out
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_emits_sentinel_when_stream_stalls():
|
|
"""With a short keepalive interval and a stalled upstream, _STREAM_KEEPALIVE
|
|
sentinels appear before the delayed chunk arrives. The resolver returns a
|
|
constant interval, since this test pins the timing mechanics, not
|
|
re-resolution."""
|
|
import asyncio
|
|
|
|
async def _slow_stream():
|
|
yield _simple_chunk(content="first")
|
|
await asyncio.sleep(0.3)
|
|
yield _simple_chunk(content="second")
|
|
|
|
items = []
|
|
async for item in _iter_with_keepalive(_slow_stream(), lambda _: 0.05, keepalive_seconds=0.05):
|
|
items.append(item)
|
|
|
|
sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
|
|
real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
|
|
|
|
assert len(sentinels) >= 2, f"expected >= 2 sentinels during 0.3s stall; got {len(sentinels)}"
|
|
assert len(real_chunks) == 2
|
|
assert real_chunks[0].choices[0].delta.content == "first"
|
|
assert real_chunks[1].choices[0].delta.content == "second"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_cancel_on_early_close():
|
|
"""Closing the generator early cancels the in-flight task without raising."""
|
|
import asyncio
|
|
|
|
async def _infinite_stream():
|
|
while True:
|
|
await asyncio.sleep(10)
|
|
yield _simple_chunk()
|
|
|
|
gen = _iter_with_keepalive(_infinite_stream(), lambda _: 0.05, keepalive_seconds=0.05)
|
|
# Advance once to get the sentinel; then close before the real chunk.
|
|
first = await gen.__anext__()
|
|
assert first is ps._STREAM_KEEPALIVE
|
|
# aclose must not raise, and must drain the cancelled task cleanly.
|
|
await gen.aclose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_disables_after_fallback_lowers_interval():
|
|
"""Greptile P1: a mid-stream router fallback can hand off to a deployment
|
|
with a different (or disabled) keepalive policy partway through the same
|
|
stream. The interval must be re-resolved against each chunk's own identity,
|
|
not the one picked before iteration started, or heartbeats keep using the
|
|
pre-fallback deployment's policy for the rest of the stream."""
|
|
import asyncio
|
|
|
|
async def _slow_stream():
|
|
yield _simple_chunk(content="first")
|
|
await asyncio.sleep(0.3)
|
|
yield _simple_chunk(content="second")
|
|
|
|
def _resolver(item):
|
|
# First chunk resolves under the enabled interval used to start the
|
|
# wrapper; every chunk after that resolves as if a fallback disabled it.
|
|
return 0.0 if item.choices[0].delta.content == "first" else 999.0
|
|
|
|
items = []
|
|
async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=0.05):
|
|
items.append(item)
|
|
|
|
sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
|
|
real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
|
|
|
|
assert sentinels == [], f"expected no sentinels once the resolver disables keepalive; got {len(sentinels)}"
|
|
assert len(real_chunks) == 2
|
|
assert real_chunks[0].choices[0].delta.content == "first"
|
|
assert real_chunks[1].choices[0].delta.content == "second"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_enables_after_fallback_raises_interval():
|
|
"""Symmetric case: a mid-stream fallback to a deployment with a *shorter*
|
|
keepalive interval must take effect immediately, not stay pinned to the
|
|
longer interval the stream started with. The interval used to wait for a
|
|
chunk is resolved from the *previous* chunk (the only one seen so far when
|
|
that wait begins), so the stall has to follow the fallback chunk rather
|
|
than precede it: waiting for "third" is where the shorter interval bites."""
|
|
import asyncio
|
|
|
|
async def _slow_stream():
|
|
yield _simple_chunk(content="first")
|
|
yield _simple_chunk(content="second")
|
|
await asyncio.sleep(0.3)
|
|
yield _simple_chunk(content="third")
|
|
|
|
def _resolver(item):
|
|
# "first" resolves under an interval too long to fire before "second"
|
|
# arrives; "second" (the fallback chunk) resolves as if the fallback
|
|
# deployment enabled a much shorter interval for everything after it.
|
|
return 999.0 if item.choices[0].delta.content == "first" else 0.05
|
|
|
|
items = []
|
|
async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=999.0):
|
|
items.append(item)
|
|
|
|
sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
|
|
real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
|
|
|
|
assert len(sentinels) >= 2, (
|
|
f"expected >= 2 sentinels once the resolver enables a short interval; got {len(sentinels)}"
|
|
)
|
|
assert len(real_chunks) == 3
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_iter_with_keepalive_activates_from_a_fully_disabled_start():
|
|
"""Greptile P1: a stream can start on a deployment with keepalive off
|
|
(keepalive_seconds passed in as 0, not merely a long interval) and fall back
|
|
mid-stream to one that enables it. The 0-second start must not be treated as
|
|
a one-time decision to skip heartbeats for the rest of the stream: no task
|
|
is created while inactive, but every chunk still re-resolves so the fallback
|
|
chunk can switch the stream into task-wrapped mode."""
|
|
import asyncio
|
|
|
|
async def _slow_stream():
|
|
yield _simple_chunk(content="first")
|
|
yield _simple_chunk(content="second")
|
|
await asyncio.sleep(0.3)
|
|
yield _simple_chunk(content="third")
|
|
|
|
def _resolver(item):
|
|
# "first" resolves to stay off; "second" (the fallback chunk) resolves
|
|
# as if the fallback deployment newly enabled a short interval.
|
|
return 0.0 if item.choices[0].delta.content == "first" else 0.05
|
|
|
|
items = []
|
|
async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=0):
|
|
items.append(item)
|
|
|
|
sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
|
|
real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
|
|
|
|
assert len(sentinels) >= 2, (
|
|
f"expected >= 2 sentinels once the resolver activates from a disabled start; got {len(sentinels)}"
|
|
)
|
|
assert len(real_chunks) == 3
|
|
|
|
|
|
def test_resolve_keepalive_seconds_client_value_ignored_without_override_permission(monkeypatch):
|
|
"""keepalive_seconds is operator-only by default: a deployment that hasn't set
|
|
allow_client_keepalive_override must not let a client's request-level value
|
|
change its behavior at all, since that would let any authenticated client
|
|
unilaterally enable heartbeats (and the LB-idle-timeout evasion that comes
|
|
with them) for a deployment that never opted in."""
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 15.0
|
|
deployment.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-locked"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 1}, response=response)
|
|
assert result == 15.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_request_value_wins_when_override_allowed(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = None
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-opt-in"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 30}, response=response)
|
|
assert result == 30.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_explicit_zero_disables_when_override_allowed(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 20.0
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-opt-in"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 0}, response=response)
|
|
assert result == 0.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_clamps_below_minimum(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = None
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-opt-in"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 0.001}, response=response)
|
|
assert result == _KEEPALIVE_MIN_SECONDS
|
|
|
|
|
|
def test_resolve_keepalive_seconds_clamps_above_maximum(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = None
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-opt-in"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 9999}, response=response)
|
|
assert result == _KEEPALIVE_MAX_SECONDS
|
|
|
|
|
|
def test_resolve_keepalive_seconds_non_numeric_returns_zero(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = None
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-opt-in"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": "not-a-number"}, response=response)
|
|
assert result == 0.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_absent_returns_zero(monkeypatch):
|
|
monkeypatch.setattr(ps, "llm_router", None)
|
|
result = _resolve_keepalive_seconds({}, response=None)
|
|
assert result == 0.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_deployment_disable_cannot_be_overridden_by_request(monkeypatch):
|
|
"""A deployment that explicitly sets keepalive_seconds: 0 is a hard operator
|
|
disable: an authenticated client must not be able to re-enable heartbeats for
|
|
that deployment by passing a positive value in the request body, since that
|
|
would let a client evade the deployment's idle-timeout behavior at will. This
|
|
holds even if the deployment also grants override permission, since an
|
|
explicit disable is a stronger, unconditional signal than an override grant."""
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 0
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-disabled"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 250}, response=response)
|
|
assert result == 0.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_global_default_applies_when_unconfigured(monkeypatch):
|
|
"""litellm_settings.sse_keepalive_ping_interval_seconds is the operator's
|
|
global default: it applies when neither the serving deployment nor the
|
|
request supplies keepalive_seconds, including proxies with no router at
|
|
all."""
|
|
import litellm
|
|
|
|
monkeypatch.setattr(ps, "llm_router", None)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)
|
|
|
|
result = _resolve_keepalive_seconds({}, response=None)
|
|
assert result == 15.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_global_default_is_clamped(monkeypatch):
|
|
import litellm
|
|
|
|
monkeypatch.setattr(ps, "llm_router", None)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 900.0)
|
|
|
|
result = _resolve_keepalive_seconds({}, response=None)
|
|
assert result == _KEEPALIVE_MAX_SECONDS
|
|
|
|
|
|
def test_resolve_keepalive_seconds_deployment_zero_beats_global_default(monkeypatch):
|
|
"""A deployment's explicit keepalive_seconds: 0 is a hard operator disable
|
|
that must also win over the global default interval, or the global setting
|
|
would silently re-enable heartbeats (and the LB-idle-timeout evasion that
|
|
comes with them) for a deployment the operator opted out of."""
|
|
from unittest.mock import MagicMock
|
|
|
|
import litellm
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 0
|
|
deployment.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-disabled"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model"}, response=response)
|
|
assert result == 0.0
|
|
|
|
|
|
def test_resolve_keepalive_seconds_deployment_value_beats_global_default(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
import litellm
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 30.0
|
|
deployment.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-tuned"}
|
|
|
|
result = _resolve_keepalive_seconds({"model": "my-model"}, response=response)
|
|
assert result == 30.0
|
|
|
|
|
|
def test_keepalive_from_deployment_config_reads_by_model_id(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 45.0
|
|
deployment.litellm_params.allow_client_keepalive_override = True
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "deploy-abc"}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "my-model"}, response)
|
|
assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=45.0, allow_client_override=True)
|
|
router.get_deployment.assert_called_once_with(model_id="deploy-abc")
|
|
|
|
|
|
def test_keepalive_from_deployment_config_stale_model_id_does_not_fall_through(monkeypatch):
|
|
"""A populated model_id names the specific deployment that served the stream.
|
|
If that ID no longer resolves (e.g. removed by a config reload mid-stream),
|
|
that's a stale identity, not an absent one: it must not fall through to the
|
|
model_name fallback, since a currently-live sibling deployment's config was
|
|
never what actually served this stream, even if that sibling's config is
|
|
unambiguous on its own."""
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [
|
|
{"litellm_params": {"keepalive_seconds": 20.0}},
|
|
]
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {"model_id": "stale-deploy-id"}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
|
|
assert result is None
|
|
router.get_model_list.assert_not_called()
|
|
|
|
|
|
def test_keepalive_from_deployment_config_fallback_by_name(monkeypatch):
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [
|
|
{"litellm_params": {"keepalive_seconds": 20.0}},
|
|
]
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
|
|
assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=20.0, allow_client_override=False)
|
|
router.registry.return_value.deployments.assert_called_once_with(model_name="slow-model")
|
|
|
|
|
|
def test_keepalive_from_deployment_config_fallback_by_name_agreeing_deployments(monkeypatch):
|
|
"""Multiple deployments under the same model_name with the same keepalive_seconds
|
|
is unambiguous, so the shared value is used even without a model_id."""
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [
|
|
{"litellm_params": {"keepalive_seconds": 20.0, "allow_client_keepalive_override": True}},
|
|
{"litellm_params": {"keepalive_seconds": 20.0, "allow_client_keepalive_override": True}},
|
|
]
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
|
|
assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=20.0, allow_client_override=True)
|
|
|
|
|
|
def test_keepalive_from_deployment_config_fallback_by_name_conflicting_deployments(monkeypatch):
|
|
"""Without a model_id, if deployments under the same model_name disagree on
|
|
keepalive_seconds, we can't tell which one served the stream: don't guess and
|
|
apply the wrong deployment's interval (or override an explicit disable)."""
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [
|
|
{"litellm_params": {"keepalive_seconds": 20.0}},
|
|
{"litellm_params": {"keepalive_seconds": 0}},
|
|
]
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
|
|
assert result is None
|
|
|
|
|
|
def test_keepalive_from_deployment_config_fallback_by_name_configured_plus_unset(monkeypatch):
|
|
"""A deployment that leaves keepalive_seconds unset entirely (not explicitly 0)
|
|
must not inherit a sibling deployment's configured interval: without a model_id
|
|
we can't tell which deployment served the stream, so mixing a configured
|
|
deployment with an unconfigured one is just as ambiguous as two conflicting
|
|
configured values."""
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [
|
|
{"litellm_params": {"keepalive_seconds": 20.0}},
|
|
{"litellm_params": {}},
|
|
]
|
|
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
response = MagicMock()
|
|
response._hidden_params = {}
|
|
|
|
result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
|
|
assert result is None
|
|
|
|
|
|
def test_keepalive_from_deployment_config_no_router_returns_none(monkeypatch):
|
|
monkeypatch.setattr(ps, "llm_router", None)
|
|
result = _keepalive_from_deployment_config({"model": "gpt-4"}, None)
|
|
assert result is None
|
|
|
|
|
|
def test_make_keepalive_resolver_caches_by_model_id(monkeypatch):
|
|
"""The steady-state case (no fallback): every chunk shares the same
|
|
model_id, so the deployment lookup must happen once, not once per chunk."""
|
|
from unittest.mock import MagicMock
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = 5.0
|
|
deployment.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
resolve = _make_keepalive_resolver({"model": "my-model"})
|
|
|
|
first = _simple_chunk(content="a")
|
|
first._hidden_params = {"model_id": "deploy-steady"}
|
|
second = _simple_chunk(content="b")
|
|
second._hidden_params = {"model_id": "deploy-steady"}
|
|
|
|
assert resolve(first) == 5.0
|
|
assert resolve(second) == 5.0
|
|
router.get_deployment.assert_called_once_with(model_id="deploy-steady")
|
|
|
|
|
|
def test_make_keepalive_resolver_reresolves_on_model_id_change(monkeypatch):
|
|
"""A mid-stream fallback changes model_id: the cache must miss and
|
|
re-resolve against the new deployment, not keep serving the stale value."""
|
|
from unittest.mock import MagicMock
|
|
|
|
before = MagicMock()
|
|
before.litellm_params.keepalive_seconds = 5.0
|
|
before.litellm_params.allow_client_keepalive_override = False
|
|
|
|
after = MagicMock()
|
|
after.litellm_params.keepalive_seconds = 30.0
|
|
after.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.side_effect = lambda model_id: {"deploy-a": before, "deploy-b": after}[model_id]
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
resolve = _make_keepalive_resolver({"model": "my-model"})
|
|
|
|
chunk_a = _simple_chunk(content="a")
|
|
chunk_a._hidden_params = {"model_id": "deploy-a"}
|
|
chunk_b = _simple_chunk(content="b")
|
|
chunk_b._hidden_params = {"model_id": "deploy-b"}
|
|
|
|
assert resolve(chunk_a) == 5.0
|
|
assert resolve(chunk_b) == 30.0
|
|
assert router.get_deployment.call_count == 2
|
|
|
|
|
|
def test_make_keepalive_resolver_missing_model_id_never_cached(monkeypatch):
|
|
"""Without a model_id there's no reliable cache key (see the model_name
|
|
fallback in _keepalive_from_deployment_config), so every chunk must
|
|
re-resolve fresh rather than reuse a stale guess."""
|
|
from unittest.mock import MagicMock
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [{"litellm_params": {"keepalive_seconds": 12.0}}]
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
resolve = _make_keepalive_resolver({"model": "slow-model"})
|
|
|
|
chunk_a = _simple_chunk(content="a")
|
|
chunk_a._hidden_params = {}
|
|
chunk_b = _simple_chunk(content="b")
|
|
chunk_b._hidden_params = {}
|
|
|
|
assert resolve(chunk_a) == 12.0
|
|
assert resolve(chunk_b) == 12.0
|
|
assert router.get_model_list.call_count == 2
|
|
|
|
|
|
def test_make_keepalive_resolver_expires_cache_after_ttl(monkeypatch):
|
|
"""An operator's live config change (revoking override, disabling
|
|
keepalive, removing the deployment) must be observed within
|
|
_KEEPALIVE_CACHE_TTL_SECONDS, not frozen for the rest of an
|
|
already-in-flight stream just because the model_id hasn't changed."""
|
|
from unittest.mock import MagicMock
|
|
|
|
before = MagicMock()
|
|
before.litellm_params.keepalive_seconds = 20.0
|
|
before.litellm_params.allow_client_keepalive_override = False
|
|
|
|
after = MagicMock()
|
|
after.litellm_params.keepalive_seconds = 0
|
|
after.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = before
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
clock = {"t": 0.0}
|
|
monkeypatch.setattr(ps.time, "monotonic", lambda: clock["t"])
|
|
|
|
resolve = _make_keepalive_resolver({"model": "my-model"})
|
|
|
|
chunk = _simple_chunk(content="a")
|
|
chunk._hidden_params = {"model_id": "deploy-live"}
|
|
|
|
assert resolve(chunk) == 20.0
|
|
assert router.get_deployment.call_count == 1
|
|
|
|
# Still within the TTL: same model_id, cached value reused even though
|
|
# the router's live config has since changed underneath it.
|
|
router.get_deployment.return_value = after
|
|
clock["t"] = ps._KEEPALIVE_CACHE_TTL_SECONDS - 0.01
|
|
assert resolve(chunk) == 20.0
|
|
assert router.get_deployment.call_count == 1
|
|
|
|
# Past the TTL: the config-reload disable is now observed.
|
|
clock["t"] = ps._KEEPALIVE_CACHE_TTL_SECONDS + 0.01
|
|
assert resolve(chunk) == 0.0
|
|
assert router.get_deployment.call_count == 2
|
|
|
|
|
|
def test_keepalive_seconds_in_all_litellm_params():
|
|
from litellm.types.utils import all_litellm_params
|
|
|
|
assert "keepalive_seconds" in all_litellm_params
|
|
|
|
|
|
def test_allow_client_keepalive_override_in_all_litellm_params():
|
|
"""allow_client_keepalive_override is a deployment-only control flag: if it's
|
|
missing from all_litellm_params, it leaks straight through into the actual
|
|
provider API call as an unrecognized field and gets rejected (confirmed live
|
|
against the real Anthropic API, which returns 'Extra inputs are not
|
|
permitted')."""
|
|
from litellm.types.utils import all_litellm_params
|
|
|
|
assert "allow_client_keepalive_override" in all_litellm_params
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_emits_ping_heartbeat(monkeypatch):
|
|
"""When keepalive_seconds is set on a deployment that allows client override,
|
|
': ping' frames appear during upstream stalls."""
|
|
import asyncio
|
|
from unittest.mock import MagicMock
|
|
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setattr(ps, "_KEEPALIVE_MIN_SECONDS", 0.05)
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = None
|
|
router.get_model_list.return_value = [{"litellm_params": {"allow_client_keepalive_override": True}}]
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
async def _slow_response():
|
|
yield _simple_chunk(content="hello")
|
|
await asyncio.sleep(0.4)
|
|
yield _simple_chunk(content="world")
|
|
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_slow_response(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4", "keepalive_seconds": 0.05},
|
|
):
|
|
out.append(line)
|
|
|
|
pings = [item for item in out if item == ": ping\n\n"]
|
|
assert len(pings) >= 2, f"expected >= 2 ping frames; got {len(pings)}"
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_emits_ping_heartbeat_from_global_default_without_router(monkeypatch):
|
|
"""The global sse_keepalive_ping_interval_seconds must produce ': ping'
|
|
frames even on a proxy with no router, where the wrap was previously
|
|
skipped entirely because no deployment could ever resolve a non-zero
|
|
interval."""
|
|
import asyncio
|
|
|
|
import litellm
|
|
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setattr(ps, "_KEEPALIVE_MIN_SECONDS", 0.05)
|
|
monkeypatch.setattr(ps, "llm_router", None)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 0.05)
|
|
|
|
async def _slow_response():
|
|
yield _simple_chunk(content="hello")
|
|
await asyncio.sleep(0.4)
|
|
yield _simple_chunk(content="world")
|
|
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_slow_response(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
):
|
|
out.append(line)
|
|
|
|
pings = [item for item in out if item == ": ping\n\n"]
|
|
assert len(pings) >= 2, f"expected >= 2 ping frames; got {len(pings)}"
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_no_keepalive_no_pings(monkeypatch):
|
|
"""Without keepalive_seconds, no ': ping' frames are emitted."""
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_async_iter([_simple_chunk(content="hello")]),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
):
|
|
out.append(line)
|
|
|
|
assert ": ping\n\n" not in out
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_resolves_deployment_once_per_steady_stream(monkeypatch):
|
|
"""Regression test for the per-chunk resolver cost: a stream where every
|
|
real chunk comes from the same deployment (the common, no-fallback case)
|
|
must only pay for one `llm_router.get_deployment()` call, not one per
|
|
chunk. Before caching, this asserted 1 but got len(chunks) since the
|
|
resolver re-ran the full deployment lookup after every single chunk.
|
|
|
|
The very first resolve happens on the raw `response` object before any
|
|
chunk is yielded; a bare async generator (unlike the real
|
|
CustomStreamWrapper this stands in for) can't carry `_hidden_params`, so
|
|
that one call goes through the model_name fallback instead of
|
|
`get_deployment` — hence it's asserted separately.
|
|
"""
|
|
from unittest.mock import MagicMock
|
|
|
|
_patch_logging_flags(monkeypatch)
|
|
|
|
deployment = MagicMock()
|
|
deployment.litellm_params.keepalive_seconds = None
|
|
deployment.litellm_params.allow_client_keepalive_override = False
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_deployment.return_value = deployment
|
|
router.get_model_list.return_value = [{"litellm_params": {}}]
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
async def _steady_response():
|
|
for content in ("a", "b", "c", "d", "e"):
|
|
chunk = _simple_chunk(content=content)
|
|
chunk._hidden_params = {"model_id": "deploy-steady"}
|
|
yield chunk
|
|
|
|
out = []
|
|
async for line in async_data_generator(
|
|
response=_steady_response(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
):
|
|
out.append(line)
|
|
|
|
assert router.get_deployment.call_count == 1
|
|
assert router.get_model_list.call_count == 1
|
|
assert out[-1] == "data: [DONE]\n\n"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# run_thread: SSE keepalives during the time-to-first-token
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class _SlowAssistantsStream(_FakeAssistantsStream):
|
|
"""The assistants run only contacts the upstream when the stream is entered,
|
|
and `create_response` buffers that first chunk, so the whole
|
|
time-to-first-token is spent before a byte can be written."""
|
|
|
|
def __init__(self, chunks, delay):
|
|
super().__init__(chunks)
|
|
self._delay = delay
|
|
|
|
async def __aenter__(self):
|
|
await asyncio.sleep(self._delay)
|
|
return self
|
|
|
|
|
|
async def _run_thread_streaming(monkeypatch, interval, delay=0.3, fails_with=None):
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", interval)
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_model_list.return_value = []
|
|
if fails_with is None:
|
|
router.arun_thread = AsyncMock(return_value=_SlowAssistantsStream([_simple_chunk(content="hi")], delay))
|
|
else:
|
|
|
|
async def _fails_after_the_first_ping(**kwargs):
|
|
await asyncio.sleep(delay)
|
|
raise fails_with
|
|
|
|
router.arun_thread = _fails_after_the_first_ping
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
async def _passthrough_hook(*, user_api_key_dict, response, data, **kwargs):
|
|
return response
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _passthrough_hook)
|
|
|
|
async def _add_data(data, **kwargs):
|
|
return data
|
|
|
|
monkeypatch.setattr(ps, "add_litellm_data_to_request", _add_data)
|
|
|
|
request = MagicMock()
|
|
request.body = AsyncMock(return_value=b'{"assistant_id": "asst_1", "stream": true}')
|
|
request.is_disconnected = AsyncMock(return_value=False)
|
|
|
|
return await ps.run_thread(
|
|
request=request,
|
|
thread_id="thr_1",
|
|
fastapi_response=Response(),
|
|
user_api_key_dict=_user_auth(),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_thread_pings_while_the_assistants_run_is_still_silent(monkeypatch):
|
|
"""Regression for LIT-5737. A streaming assistants run wrote zero bytes for the
|
|
whole time-to-first-token, so an idle-timeout hop drops a healthy connection."""
|
|
response = await _run_thread_streaming(monkeypatch, interval=0.05)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
assert response.headers["x-accel-buffering"] == "no"
|
|
chunks = [chunk async for chunk in response.body_iterator]
|
|
|
|
assert chunks[0] == b": ping\n\n"
|
|
assert chunks.count(b": ping\n\n") >= 3
|
|
assert chunks[-1] == b"data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_thread_audits_a_failure_that_arrives_after_the_first_ping(monkeypatch):
|
|
"""Once a ping is on the wire the run can no longer raise, so the handler's own
|
|
`except` never runs. The failure still has to reach post_call_failure_hook or it
|
|
goes unaudited, and it has to reach the client as an SSE frame."""
|
|
audited = []
|
|
|
|
async def _record_failure(*, user_api_key_dict, original_exception, request_data, **kwargs):
|
|
audited.append(original_exception)
|
|
return None
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", _record_failure)
|
|
|
|
boom = RuntimeError("upstream died after the wire was already open")
|
|
response = await _run_thread_streaming(monkeypatch, interval=0.05, fails_with=boom)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
chunks = [chunk async for chunk in response.body_iterator]
|
|
|
|
assert chunks[0] == b": ping\n\n"
|
|
# The hook is the only thing that still sees the real exception; the client
|
|
# gets the sanitized frame, under the 200 the ping already committed.
|
|
assert audited == [boom]
|
|
assert b"upstream died after the wire was already open" not in chunks[-2]
|
|
assert json.loads(chunks[-2].removeprefix(b"data: "))["error"]["code"] == "500"
|
|
assert chunks[-1] == b"data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_thread_stream_is_untouched_while_keepalives_are_unconfigured(monkeypatch):
|
|
"""Off until an operator sets an interval, so the default run is unchanged."""
|
|
response = await _run_thread_streaming(monkeypatch, interval=None, delay=0.15)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
chunks = [chunk async for chunk in response.body_iterator]
|
|
|
|
assert not any(chunk.startswith(": ping") for chunk in chunks)
|
|
assert chunks[-1] == "data: [DONE]\n\n"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# async_queue_request: SSE keepalives during the time-to-first-token
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
async def _queue_streaming(monkeypatch, interval, delay=0.3, fails_with=None):
|
|
_patch_logging_flags(monkeypatch)
|
|
monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", interval)
|
|
|
|
router = route_entry_points_to_stubs(MagicMock())
|
|
router.get_model_list.return_value = []
|
|
router.split_request_priority.return_value = (0, {})
|
|
|
|
async def _schedule_after_the_scheduler_queue_drains(**kwargs):
|
|
await asyncio.sleep(delay)
|
|
if fails_with is not None:
|
|
raise fails_with
|
|
return _async_iter([_simple_chunk(content="queued reply")])
|
|
|
|
router.schedule_acompletion = _schedule_after_the_scheduler_queue_drains
|
|
monkeypatch.setattr(ps, "llm_router", router)
|
|
|
|
request = MagicMock()
|
|
request.url = "http://testserver/queue/chat/completions"
|
|
request.method = "POST"
|
|
request.headers = {}
|
|
request.json = AsyncMock(
|
|
return_value={
|
|
"model": "gpt-4",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"priority": 0,
|
|
"stream": True,
|
|
}
|
|
)
|
|
request.is_disconnected = AsyncMock(return_value=False)
|
|
|
|
return await ps.async_queue_request(
|
|
request=request,
|
|
fastapi_response=Response(),
|
|
user_api_key_dict=_user_auth(),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_queue_request_pings_while_the_scheduler_is_still_waiting(monkeypatch):
|
|
response = await _queue_streaming(monkeypatch, interval=0.05)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
assert response.headers["x-accel-buffering"] == "no"
|
|
chunks = [chunk async for chunk in response.body_iterator]
|
|
|
|
assert chunks[0] == b": ping\n\n"
|
|
assert chunks.count(b": ping\n\n") >= 3
|
|
assert b'"content":"queued reply"' in chunks[-2]
|
|
assert chunks[-1] == b"data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_queue_request_audits_a_failure_that_arrives_after_the_first_ping(monkeypatch):
|
|
audited = []
|
|
|
|
async def _record_failure(*, user_api_key_dict, original_exception, request_data, **kwargs):
|
|
audited.append(original_exception)
|
|
return None
|
|
|
|
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", _record_failure)
|
|
|
|
boom = RuntimeError("scheduler died after the wire was already open")
|
|
response = await _queue_streaming(monkeypatch, interval=0.05, fails_with=boom)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
chunks = [chunk async for chunk in response.body_iterator]
|
|
|
|
assert chunks[0] == b": ping\n\n"
|
|
assert audited == [boom]
|
|
assert json.loads(chunks[-2].removeprefix(b"data: "))["error"]["code"] == "500"
|
|
assert chunks[-1] == b"data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_queue_request_stream_is_untouched_while_keepalives_are_unconfigured(monkeypatch):
|
|
response = await _queue_streaming(monkeypatch, interval=None, delay=0.15)
|
|
|
|
assert isinstance(response, StreamingResponse)
|
|
chunks = [chunk if isinstance(chunk, bytes) else chunk.encode() async for chunk in response.body_iterator]
|
|
|
|
assert not any(chunk.startswith(b": ping") for chunk in chunks)
|
|
assert chunks[-1] == b"data: [DONE]\n\n"
|
|
|
|
|
|
def test_serialize_streaming_chunk_keeps_served_service_tier():
|
|
chunk = _simple_chunk()
|
|
chunk.service_tier = "priority"
|
|
|
|
assert json.loads(_serialize_streaming_chunk(chunk))["service_tier"] == "priority"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_data_generator_lets_other_tasks_run_during_a_stream_that_never_waits(monkeypatch):
|
|
"""A stream whose chunks are already buffered never suspends on its own, so
|
|
the generator has to hand the loop back itself once it has held the loop
|
|
long enough: another task must get to run before the stream is over, and
|
|
not before the hold budget is used up."""
|
|
_patch_logging_flags(monkeypatch)
|
|
order: list[str] = [] # mutable-ok: records the interleaving of the two tasks
|
|
clock: list[float] = [0.0] # mutable-ok: fake monotonic clock, advanced 20 ms per chunk
|
|
monkeypatch.setattr(ps.time, "monotonic", lambda: clock[0])
|
|
|
|
async def chunks():
|
|
for index in range(6):
|
|
clock[0] += 0.02
|
|
order.append(f"chunk{index}")
|
|
yield _simple_chunk(content=str(index))
|
|
|
|
async def other_task():
|
|
order.append("other")
|
|
|
|
other = asyncio.ensure_future(other_task())
|
|
async for _ in async_data_generator(
|
|
response=chunks(),
|
|
user_api_key_dict=_user_auth(),
|
|
request_data={"model": "gpt-4"},
|
|
):
|
|
pass
|
|
await other
|
|
|
|
assert "other" in order[:-1], order
|
|
assert order.index("other") >= 3, order
|