Skip to content

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

17.7 KB
Raw Blame
import asyncio
from typing import Any, AsyncIterator, Dict, Final, List

import pytest


import datetime

import litellm
from litellm._internal_context import in_post_response_phase
from litellm.caching.caching import Cache, LiteLLMCacheType
from litellm.caching.caching_handler import LLMCachingHandler
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.llms.anthropic.pass_through.messages import handler
from litellm.llms.anthropic.pass_through.messages.response_cache import (
    AnthropicMessagesStreamCacheWriter,
    CachedAnthropicMessagesStreamIterator,
)

STREAM_EVENTS: List[bytes] = [
    b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_stream_1", "type": "message", '
    b'"role": "assistant", "model": "claude-sonnet-4-5", "content": [], "stop_reason": null, '
    b'"usage": {"input_tokens": 10, "output_tokens": 0}}}\n\n',
    b'event: content_block_start\ndata: {"type": "content_block_start", "index": 0, '
    b'"content_block": {"type": "text", "text": ""}}\n\n',
    b'event: content_block_delta\ndata: {"type": "content_block_delta", "index": 0, '
    b'"delta": {"type": "text_delta", "text": "ALPHA"}}\n\n',
    b'event: content_block_stop\ndata: {"type": "content_block_stop", "index": 0}\n\n',
    b'event: message_delta\ndata: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, '
    b'"usage": {"output_tokens": 3}}\n\n',
    b'event: message_stop\ndata: {"type": "message_stop"}\n\n',
]


def _anthropic_response(message_id: str, text: str) -> Dict[str, Any]:
    return {
        "id": message_id,
        "type": "message",
        "role": "assistant",
        "model": "claude-sonnet-4-5",
        "content": [{"type": "text", "text": text}],
        "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": 3},
    }


class _CountingHandler:
    """Stands in for the provider dispatch so cache hits are observable as skipped calls."""

    def __init__(self, results: List[Any]) -> None:
        self.results = results
        self.calls: List[Dict[str, Any]] = []

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.calls.append(kwargs)
        return self.results[min(len(self.calls) - 1, len(self.results) - 1)]


async def _byte_stream(chunks: List[bytes]) -> AsyncIterator[bytes]:
    for chunk in chunks:
        yield chunk


async def _collect(stream: AsyncIterator[bytes]) -> List[bytes]:
    return [chunk async for chunk in stream]


@pytest.fixture(autouse=True)
async def _drain_logging_worker():
    yield
    await GLOBAL_LOGGING_WORKER.flush()


@pytest.fixture
def local_cache():
    previous_cache = litellm.cache
    litellm.cache = Cache(type=LiteLLMCacheType.LOCAL)
    yield litellm.cache
    litellm.cache = previous_cache


@pytest.fixture
def request_kwargs() -> Dict[str, Any]:
    return {
        "model": "anthropic/claude-sonnet-4-5",
        "custom_llm_provider": "anthropic",
        "api_key": "fake-key",
        "max_tokens": 64,
        "messages": [{"role": "user", "content": "which greek letter?"}],
    }


@pytest.mark.asyncio
async def test_non_streaming_request_is_served_from_cache(local_cache, request_kwargs, monkeypatch):
    fake_handler = _CountingHandler([_anthropic_response("msg_1", "ALPHA"), _anthropic_response("msg_2", "BETA")])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    first = await litellm.anthropic_messages(**request_kwargs)
    await asyncio.sleep(0)
    second = await litellm.anthropic_messages(**request_kwargs)

    assert len(fake_handler.calls) == 1
    assert first == second
    assert second["content"][0]["text"] == "ALPHA"


@pytest.mark.asyncio
async def test_cache_key_separates_different_system_prompts(local_cache, request_kwargs, monkeypatch):
    """`system` has no OpenAI equivalent; if it is dropped from the cache key the
    second request is answered with the first system prompt's response."""
    fake_handler = _CountingHandler([_anthropic_response("msg_1", "ALPHA"), _anthropic_response("msg_2", "BETA")])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    first = await litellm.anthropic_messages(**request_kwargs, system="Always answer ALPHA")
    await asyncio.sleep(0)
    second = await litellm.anthropic_messages(**request_kwargs, system="Always answer BETA")

    assert len(fake_handler.calls) == 2
    assert first["content"][0]["text"] == "ALPHA"
    assert second["content"][0]["text"] == "BETA"


@pytest.mark.parametrize("anthropic_param", [{"top_k": 5}, {"stop_sequences": ["STOP"]}])
@pytest.mark.asyncio
async def test_cache_key_separates_anthropic_native_params(local_cache, request_kwargs, monkeypatch, anthropic_param):
    fake_handler = _CountingHandler([_anthropic_response("msg_1", "ALPHA"), _anthropic_response("msg_2", "BETA")])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    await litellm.anthropic_messages(**request_kwargs)
    await asyncio.sleep(0)
    await litellm.anthropic_messages(**request_kwargs, **anthropic_param)

    assert len(fake_handler.calls) == 2


@pytest.mark.asyncio
async def test_streaming_request_is_replayed_from_cache(local_cache, request_kwargs, monkeypatch):
    fake_handler = _CountingHandler([_byte_stream(STREAM_EVENTS), _byte_stream([b"event: never_used\n\n"])])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    first = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    await asyncio.sleep(0)
    second_stream = await litellm.anthropic_messages(**request_kwargs, stream=True)
    second = await _collect(second_stream)

    assert len(fake_handler.calls) == 1
    assert first == STREAM_EVENTS
    assert second == STREAM_EVENTS
    assert second_stream._hidden_params["cache_hit"] is True


@pytest.mark.asyncio
async def test_streaming_cache_is_not_shared_with_non_streaming(local_cache, request_kwargs, monkeypatch):
    fake_handler = _CountingHandler([_byte_stream(STREAM_EVENTS), _anthropic_response("msg_2", "ALPHA")])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    non_streaming = await litellm.anthropic_messages(**request_kwargs)

    assert len(fake_handler.calls) == 2
    assert non_streaming["content"][0]["text"] == "ALPHA"


@pytest.mark.asyncio
async def test_stream_without_content_blocks_is_not_cached(local_cache, request_kwargs, monkeypatch):
    empty_events = [STREAM_EVENTS[0], STREAM_EVENTS[4], STREAM_EVENTS[5]]
    fake_handler = _CountingHandler(
        [_byte_stream(empty_events), _byte_stream(STREAM_EVENTS), _byte_stream([b"event: never_used\n\n"])]
    )
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    empty = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    await asyncio.sleep(0)
    refilled = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    await asyncio.sleep(0)
    replayed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert empty == empty_events
    assert refilled == STREAM_EVENTS
    assert replayed == STREAM_EVENTS
    assert len(fake_handler.calls) == 2


@pytest.mark.asyncio
async def test_failed_stream_is_not_cached(local_cache, request_kwargs, monkeypatch):
    error_events = STREAM_EVENTS[:3] + [
        b'event: error\ndata: {"type": "error", "error": {"type": "overloaded_error", "message": "overloaded"}}\n\n'
    ]
    fake_handler = _CountingHandler([_byte_stream(error_events), _byte_stream(STREAM_EVENTS)])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    failed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    replayed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert failed == error_events
    assert len(fake_handler.calls) == 2
    assert replayed == STREAM_EVENTS


@pytest.mark.asyncio
async def test_multibyte_utf8_split_across_chunks_streams_and_caches(local_cache, request_kwargs, monkeypatch):
    """aiter_bytes() can split a multi-byte character across chunks; per-chunk
    strict decoding raised UnicodeDecodeError mid-stream and broke the client."""
    multibyte_delta = (
        'event: content_block_delta\ndata: {"type": "content_block_delta", "index": 0, '
        '"delta": {"type": "text_delta", "text": "ALPHA €"}}\n\n'
    ).encode("utf-8")
    split_at = multibyte_delta.index("€".encode("utf-8")) + 1
    chunks = STREAM_EVENTS[:2] + [multibyte_delta[:split_at], multibyte_delta[split_at:]] + STREAM_EVENTS[3:]
    fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream([b"event: never_used\n\n"])])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    first = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    await asyncio.sleep(0)
    second = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert len(fake_handler.calls) == 1
    assert first == chunks
    assert b"".join(second) == b"".join(chunks)


@pytest.mark.asyncio
async def test_message_stop_split_across_chunks_still_caches(local_cache, request_kwargs, monkeypatch):
    """The terminal `event: message_stop` line can arrive split across two
    chunks; per-chunk line matching missed it, so the stream was never stored."""
    stop_event = STREAM_EVENTS[-1]
    chunks = STREAM_EVENTS[:-1] + [stop_event[:10], stop_event[10:]]
    fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream([b"event: never_used\n\n"])])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    first = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    await asyncio.sleep(0)
    second = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert len(fake_handler.calls) == 1
    assert first == chunks
    assert b"".join(second) == b"".join(chunks)


@pytest.mark.asyncio
async def test_error_event_split_across_chunks_is_not_cached(local_cache, request_kwargs, monkeypatch):
    error_event = (
        b'event: error\ndata: {"type": "error", "error": {"type": "overloaded_error", "message": "overloaded"}}\n\n'
    )
    chunks = STREAM_EVENTS[:4] + [error_event[:8], error_event[8:]] + STREAM_EVENTS[4:]
    fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream(STREAM_EVENTS)])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    failed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))
    replayed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert failed == chunks
    assert len(fake_handler.calls) == 2
    assert replayed == STREAM_EVENTS


@pytest.mark.asyncio
async def test_abandoned_stream_is_not_cached(local_cache, request_kwargs, monkeypatch):
    fake_handler = _CountingHandler([_byte_stream(STREAM_EVENTS), _byte_stream(STREAM_EVENTS)])
    monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)

    partial_stream = await litellm.anthropic_messages(**request_kwargs, stream=True)
    await partial_stream.__anext__()
    await partial_stream.aclose()

    replayed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))

    assert len(fake_handler.calls) == 2
    assert replayed == STREAM_EVENTS


@pytest.mark.asyncio
async def test_cached_stream_replay_logs_once_when_polled_after_exhaustion():
    from unittest.mock import AsyncMock, MagicMock, patch

    from litellm.llms.anthropic.pass_through.messages.response_cache import (
        CachedAnthropicMessagesStreamIterator,
    )
    from litellm.proxy.pass_through_endpoints.streaming_handler import (
        PassThroughStreamingHandler,
    )

    logging_obj = MagicMock()
    logging_obj.model_call_details = {}
    iterator = CachedAnthropicMessagesStreamIterator(
        events=[event.decode("utf-8") for event in STREAM_EVENTS],
        litellm_logging_obj=logging_obj,
        request_body={"model": "claude-sonnet-4-5"},
    )

    with patch.object(
        PassThroughStreamingHandler,
        "route_streaming_logging_to_handler",
        new=AsyncMock(),
    ) as mock_route:
        assert await _collect(iterator) == STREAM_EVENTS
        for _ in range(2):
            with pytest.raises(StopAsyncIteration):
                await iterator.__anext__()
        await asyncio.sleep(0)

    mock_route.assert_called_once()


class _ReplayRecorder(CustomLogger):
    def __init__(self) -> None:
        super().__init__()
        self.logged: list[object] = []

    async def async_log_success_event(
        self,
        kwargs: dict[str, object],
        response_obj: object,
        start_time: datetime.datetime,
        end_time: datetime.datetime,
    ) -> None:
        self.logged.append(kwargs.get("completion_start_time"))


@pytest.mark.asyncio
async def test_cached_stream_replay_logs_when_its_first_event_was_replayed():
    recorder: Final = _ReplayRecorder()
    logging_obj: Final = LiteLLMLoggingObj(
        model="claude-sonnet-4-5",
        messages=[{"role": "user", "content": "which greek letter?"}],
        stream=True,
        call_type="anthropic_messages",
        start_time=datetime.datetime(2026, 10, 20, 12, 0, 0),
        litellm_call_id="cached-replay",
        function_id="cached-replay",
        dynamic_async_success_callbacks=[recorder],
    )
    logging_obj.update_environment_variables(
        model="claude-sonnet-4-5",
        user="",
        optional_params={},
        litellm_params={"custom_llm_provider": "anthropic"},
        custom_llm_provider="anthropic",
    )
    iterator: Final = CachedAnthropicMessagesStreamIterator(
        events=[event.decode("utf-8") for event in STREAM_EVENTS],
        litellm_logging_obj=logging_obj,
        request_body={"model": "claude-sonnet-4-5", "stream": True},
    )

    _ = await iterator.__anext__()
    first_event_at: Final = iterator.completion_start_time
    _ = await _collect(iterator)
    await GLOBAL_LOGGING_WORKER.flush()

    assert first_event_at is not None
    assert recorder.logged == [first_event_at]


class _HeldBackStream:
    has_buffered_provider_output = True

    def __aiter__(self) -> "_HeldBackStream":
        return self

    async def __anext__(self) -> bytes:
        raise StopAsyncIteration


class _AttributedStream:
    """Stream stub carrying the billing attributes the disconnect helper reads."""

    def __init__(self, chunks: list) -> None:
        self.chunks = [object()]
        self.messages = [{"role": "user", "content": "hi"}]
        self.model = "gpt-4o-mini"
        self._pending = list(chunks)

    def __aiter__(self) -> "_AttributedStream":
        return self

    async def __anext__(self) -> bytes:
        if not self._pending:
            raise StopAsyncIteration
        return self._pending.pop(0)


@pytest.mark.asyncio
async def test_cache_writer_exposes_inner_stream_billing_attributes(request_kwargs):
    caching_handler = LLMCachingHandler(
        original_function=handler.anthropic_messages,
        request_kwargs=dict(request_kwargs),
        start_time=datetime.datetime.now(),
    )
    inner = _AttributedStream(STREAM_EVENTS)
    writer = AnthropicMessagesStreamCacheWriter(stream=inner, caching_handler=caching_handler)

    assert writer.chunks is inner.chunks
    assert writer.messages is inner.messages
    assert writer.model == "gpt-4o-mini"
    assert await _collect(writer) == STREAM_EVENTS


@pytest.mark.asyncio
async def test_stream_cache_write_runs_in_post_response_phase(request_kwargs, monkeypatch):
    """Every event, message_stop included, is already with the client when the stream write
    runs, so it must not hold the stream open and the redis span it logs must detach from the
    request trace like the chat completions write does. The marker must not leak into the consumer."""
    phases: list[bool] = []
    write_started = asyncio.Event()
    release_write = asyncio.Event()

    class _PhaseRecordingCache:
        supported_call_types = ["anthropic_messages"]
        cache = None

        async def async_add_cache(self, result, dynamic_cache_object=None, **kwargs):
            phases.append(in_post_response_phase())
            write_started.set()
            await release_write.wait()

    monkeypatch.setattr(litellm, "cache", _PhaseRecordingCache())
    caching_handler = LLMCachingHandler(
        original_function=handler.anthropic_messages,
        request_kwargs=dict(request_kwargs),
        start_time=datetime.datetime.now(),
    )
    writer = AnthropicMessagesStreamCacheWriter(stream=_byte_stream(STREAM_EVENTS), caching_handler=caching_handler)

    collected = await asyncio.wait_for(_collect(writer), timeout=1)
    assert collected == STREAM_EVENTS, "the stream must close without waiting for the write"
    assert in_post_response_phase() is False, "the phase must not leak into the stream consumer"
    await asyncio.wait_for(write_started.wait(), timeout=1)
    release_write.set()
    assert phases == [True], "async_add_cache must observe the post-response phase"


def test_cache_writer_forwards_has_buffered_provider_output(request_kwargs):
    caching_handler = LLMCachingHandler(
        original_function=handler.anthropic_messages,
        request_kwargs=dict(request_kwargs),
        start_time=datetime.datetime.now(),
    )
    held_back = AnthropicMessagesStreamCacheWriter(stream=_HeldBackStream(), caching_handler=caching_handler)
    assert held_back.has_buffered_provider_output is True
    replayable = AnthropicMessagesStreamCacheWriter(
        stream=_byte_stream(STREAM_EVENTS), caching_handler=caching_handler
    )
    assert replayable.has_buffered_provider_output is False