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]

fix(responses): make previous_response_id resolve on the bridged path

mateo-berri70e4273ba1f5
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index c616d9e8723..9978fa04f40 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -6005,6 +6005,16 @@ async def enqueue_spend_logs(
)
+async def peek_spend_logs(prisma_client: PrismaClient) -> tuple[SpendLogsPayload, ...]:
+ """Snapshot the spend logs still waiting for the next flush, leaving the queue intact.
+
+ Reads that need a just-finished request use this, since the batch writer only
+ reaches the DB every ``PROXY_BATCH_WRITE_AT`` seconds.
+ """
+ async with prisma_client._spend_log_transactions_lock:
+ return tuple(prisma_client.spend_log_transactions)
+
+
async def dequeue_spend_logs(prisma_client: PrismaClient, limit: int) -> list[dict[str, object]]:
"""Take up to ``limit`` of the oldest queued spend logs off the queue.
diff --git a/litellm/responses/litellm_completion_transformation/session_handler.py b/litellm/responses/litellm_completion_transformation/session_handler.py
index dcff26c5b0c..935c78bc9a1 100644
--- a/litellm/responses/litellm_completion_transformation/session_handler.py
+++ b/litellm/responses/litellm_completion_transformation/session_handler.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, Final, cast
import litellm
@@ -104,10 +105,10 @@ class ResponsesSessionHandler:
if proxy_server_request_dict:
_response_input_param: Final = proxy_server_request_dict.get("input", None)
_messages = proxy_server_request_dict.get("messages", None)
- if isinstance(_response_input_param, str):
+ if isinstance(_response_input_param, (str, list)):
response_input_param = _response_input_param
elif isinstance(_response_input_param, dict):
- response_input_param = cast(ResponseInputParam, _response_input_param)
+ response_input_param = cast(ResponseInputParam, [_response_input_param])
if response_input_param:
chat_completion_messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(
@@ -131,8 +132,8 @@ class ResponsesSessionHandler:
############################################################
# Add Output messages for this Spend Log
############################################################
- _response_output: Final = spend_log.get("response", "{}")
- if isinstance(_response_output, dict) and _response_output and _response_output != {}:
+ _response_output: Final = ResponsesSessionHandler._get_response_dict_from_spend_log(spend_log)
+ if _response_output:
# transform `ChatCompletion Response` to `ResponsesAPIResponse`
model_response: Final = ModelResponse(**_response_output)
for choice in model_response.choices:
@@ -140,6 +141,23 @@ class ResponsesSessionHandler:
chat_completion_message_history.append(getattr(choice, "message"))
return chat_completion_message_history
+ @staticmethod
+ def _get_response_dict_from_spend_log(spend_log: SpendLogsPayload) -> Mapping[str, Any] | None:
+ """
+ Spend logs read from the DB hold `response` as a dict, ones still queued in memory
+ hold it as a JSON string.
+ """
+ _response_output: Final = spend_log.get("response")
+ if isinstance(_response_output, dict):
+ return _response_output or None
+ if isinstance(_response_output, str):
+ try:
+ parsed: Final = json.loads(_response_output)
+ except json.JSONDecodeError:
+ return None
+ return parsed if isinstance(parsed, dict) and parsed else None
+ return None
+
@staticmethod
async def get_proxy_server_request_from_spend_log(
spend_log: SpendLogsPayload,
@@ -256,11 +274,12 @@ class ResponsesSessionHandler:
SELECT session_id FROM spend_logs WHERE response_id = previous_response_id, SELECT * FROM spend_logs WHERE session_id = session_id
"""
from litellm.proxy.proxy_server import prisma_client
+ from litellm.proxy.utils import peek_spend_logs
verbose_proxy_logger.debug("decoding response id=%s", previous_response_id)
decoded_response_id: Final = ResponsesAPIRequestUtils._decode_responses_api_response_id(previous_response_id)
- previous_response_id = decoded_response_id.get("response_id", previous_response_id)
+ response_id: Final = decoded_response_id.get("response_id", previous_response_id)
if prisma_client is None:
return []
@@ -276,12 +295,46 @@ class ResponsesSessionHandler:
ORDER BY "endTime" ASC;
"""
- spend_logs: Final = await prisma_client.db.query_raw(query, previous_response_id)
+ written_spend_logs: Final = await prisma_client.db.query_raw(query, response_id)
+ queued_spend_logs: Final = await peek_spend_logs(prisma_client)
+ spend_logs: Final = list(
+ ResponsesSessionHandler._merge_queued_spend_logs(
+ response_id=response_id,
+ written_spend_logs=written_spend_logs,
+ queued_spend_logs=queued_spend_logs,
+ )
+ )
verbose_proxy_logger.debug(
"Found the following spend logs for previous response id %s: %s",
- previous_response_id,
+ response_id,
json.dumps(spend_logs, indent=4, default=str),
)
return spend_logs
+
+ @staticmethod
+ def _merge_queued_spend_logs(
+ response_id: str,
+ written_spend_logs: Sequence[SpendLogsPayload],
+ queued_spend_logs: Sequence[SpendLogsPayload],
+ ) -> tuple[SpendLogsPayload, ...]:
+ """
+ Append the session's spend logs that the batch writer has not flushed to the DB yet.
+
+ Without this a follow-up sent inside the ``PROXY_BATCH_WRITE_AT`` window sees an
+ empty session and silently drops the conversation. The queue is FIFO, so anything
+ still on it is newer than every row already written.
+ """
+ session_ids: Final = frozenset(
+ session_id
+ for spend_log in (*written_spend_logs, *queued_spend_logs)
+ if spend_log.get("request_id") == response_id and (session_id := spend_log.get("session_id"))
+ ) | frozenset(session_id for spend_log in written_spend_logs if (session_id := spend_log.get("session_id")))
+ written_request_ids: Final = frozenset(spend_log.get("request_id") for spend_log in written_spend_logs)
+ unflushed: Final = tuple(
+ spend_log
+ for spend_log in queued_spend_logs
+ if spend_log.get("session_id") in session_ids and spend_log.get("request_id") not in written_request_ids
+ )
+ return (*written_spend_logs, *unflushed)
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
index aa5708088b7..a8092edc625 100644
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -86,6 +86,9 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self.final_text: str = ""
self._cached_item_id: str | None = None
self._cached_response_id: str | None = None
+ self._buffered_chunk: ModelResponseStream | None = None
+ self._upstream_exhausted: bool = False
+ self._response_id_primed: bool = False
self._pending_tool_events: list[BaseLiteLLMOpenAIResponseObject] = []
self._tool_output_index_by_call_id: dict[str, int] = {}
self._tool_args_by_call_id: dict[str, str] = {}
@@ -330,6 +333,59 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
)
self._pending_tool_events.append(item_done_event)
+ def _adopt_response_id_from_chunk(self, chunk: ModelResponseStream) -> None:
+ if self._cached_response_id is not None:
+ return
+ chunk_id: Final = getattr(chunk, "id", None)
+ if chunk_id and isinstance(chunk_id, str):
+ self._cached_response_id = chunk_id
+
+ async def _aprime_response_id(self) -> None:
+ """
+ Pull the first upstream chunk before `response.created` is emitted so every event
+ carries the chat completion id that spend tracking stores as `request_id`.
+ """
+ if self._response_id_primed:
+ return
+ self._response_id_primed = True
+ while True:
+ try:
+ chunk = await self.litellm_custom_stream_wrapper.__anext__()
+ except StopAsyncIteration:
+ self._upstream_exhausted = True
+ return
+ if chunk is not None:
+ self._buffered_chunk = chunk
+ self._adopt_response_id_from_chunk(chunk)
+ return
+
+ def _prime_response_id(self) -> None:
+ if self._response_id_primed:
+ return
+ self._response_id_primed = True
+ while True:
+ try:
+ chunk = self.litellm_custom_stream_wrapper.__next__()
+ except StopIteration:
+ self._upstream_exhausted = True
+ return
+ if chunk is not None:
+ self._buffered_chunk = chunk
+ self._adopt_response_id_from_chunk(chunk)
+ return
+
+ def _take_buffered_chunk(self) -> ModelResponseStream | None:
+ buffered: Final = self._buffered_chunk
+ self._buffered_chunk = None
+ return buffered
+
+ def _with_encoded_response_id(self, response: ResponsesAPIResponse) -> ResponsesAPIResponse:
+ return ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(
+ responses_api_response=response,
+ custom_llm_provider=self.custom_llm_provider,
+ litellm_metadata=self.litellm_metadata,
+ )
+
def _default_response_created_event_data(self) -> dict:
# Use cached response ID if available, otherwise generate a new one
if self._cached_response_id is None:
@@ -388,7 +444,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self._sequence_number += 1
event: Final = ResponseCreatedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_CREATED,
- response=ResponsesAPIResponse(**response_created_event_data),
+ response=self._with_encoded_response_id(ResponsesAPIResponse(**response_created_event_data)),
)
event.__dict__["sequence_number"] = self._sequence_number
return event
@@ -399,7 +455,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
self._sequence_number += 1
event: Final = ResponseInProgressEvent(
type=ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS,
- response=ResponsesAPIResponse(**response_in_progress_event_data),
+ response=self._with_encoded_response_id(ResponsesAPIResponse(**response_in_progress_event_data)),
)
event.__dict__["sequence_number"] = self._sequence_number
return event
@@ -811,6 +867,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
if self.finished is True:
raise StopAsyncIteration
+ await self._aprime_response_id()
result = self.return_default_initial_events()
if result:
return result
@@ -822,7 +879,11 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
return self._pending_tool_events.pop(0)
try:
- chunk = await self.litellm_custom_stream_wrapper.__anext__()
+ chunk = self._take_buffered_chunk()
+ if chunk is None:
+ if self._upstream_exhausted:
+ raise StopAsyncIteration
+ chunk = await self.litellm_custom_stream_wrapper.__anext__()
if chunk is not None:
chunk = cast(ModelResponseStream, chunk)
self._ensure_output_item_for_chunk(chunk)
@@ -912,6 +973,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
while True:
if self.finished is True:
raise StopIteration
+ self._prime_response_id()
result = self.return_default_initial_events()
if result:
return result
@@ -922,7 +984,13 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
if self._pending_tool_events:
return self._pending_tool_events.pop(0)
try:
- chunk = self.litellm_custom_stream_wrapper.__next__()
+ buffered_chunk = self._take_buffered_chunk()
+ if buffered_chunk is not None:
+ chunk = buffered_chunk
+ elif self._upstream_exhausted:
+ raise StopIteration
+ else:
+ chunk = self.litellm_custom_stream_wrapper.__next__()
self._ensure_output_item_for_chunk(chunk)
# Accumulate provider_specific_fields from chunk and delta
for src in (
@@ -1082,11 +1150,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):
responses_api_response.id = self._cached_response_id
# Encode the response ID to match non-streaming behavior
- encoded_response: Final = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id(
- responses_api_response=responses_api_response,
- custom_llm_provider=self.custom_llm_provider,
- litellm_metadata=self.litellm_metadata,
- )
+ encoded_response: Final = self._with_encoded_response_id(responses_api_response)
return ResponseCompletedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.py b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.py
index 19f240fa3d4..926e9e0af2a 100644
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_session_handler.py
@@ -1,3 +1,4 @@
+import asyncio
import json
from unittest.mock import AsyncMock, patch
@@ -10,6 +11,7 @@ from litellm.responses.litellm_completion_transformation import session_handler
from litellm.responses.litellm_completion_transformation.session_handler import (
ResponsesSessionHandler,
)
+from litellm.responses.utils import ResponsesAPIRequestUtils
@pytest.mark.asyncio
@@ -430,3 +432,236 @@ async def test_get_chat_completion_message_history_empty_response_dict():
# Verify the session was still created correctly
assert result["litellm_session_id"] == "test-session"
+
+
+def _chat_completion_response(request_id: str, content: str) -> dict:
+ return {
+ "id": request_id,
+ "object": "chat.completion",
+ "created": 1748575031,
+ "model": "claude-haiku-4-5",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": content},
+ "finish_reason": "stop",
+ }
+ ],
+ }
+
+
+class _FakePrismaDB:
+ def __init__(self, rows):
+ self._rows = rows
+ self.calls = []
+
+ async def query_raw(self, query, *args):
+ self.calls.append(args)
+ return list(self._rows)
+
+
+class _FakePrismaClient:
+ def __init__(self, written_rows, queued_rows):
+ self.db = _FakePrismaDB(written_rows)
+ self.spend_log_transactions = list(queued_rows)
+ self._spend_log_transactions_lock = asyncio.Lock()
+
+
+async def test_message_history_reconstructs_list_shaped_input():
+ """
+ The Responses API sends `input` as a list of items, which is what lands in the stored
+ proxy_server_request. The user turns have to survive session reconstruction.
+ """
+ request_id = "chatcmpl-935b8dad-fdc2-466e-a8ca-e26e5a8a21bb"
+ mock_spend_logs = [
+ {
+ "request_id": request_id,
+ "call_type": "aresponses",
+ "session_id": "a96757c4-c6dc-4c76-b37e-e7dfa526b701",
+ "proxy_server_request": {
+ "input": [
+ {
+ "role": "user",
+ "content": "Remember this: my favorite color is chartreuse.",
+ }
+ ],
+ "model": "claude-bridge",
+ },
+ "response": _chat_completion_response(request_id, "OK"),
+ }
+ ]
+
+ with patch.object(
+ ResponsesSessionHandler,
+ "get_all_spend_logs_for_previous_response_id",
+ new_callable=AsyncMock,
+ ) as mock_get_spend_logs:
+ mock_get_spend_logs.return_value = mock_spend_logs
+
+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(
+ request_id
+ )
+
+ messages = result["messages"]
+ assert [(message.get("role"), message.get("content")) for message in messages] == [
+ ("user", "Remember this: my favorite color is chartreuse."),
+ ("assistant", "OK"),
+ ]
+ assert result["litellm_session_id"] == "a96757c4-c6dc-4c76-b37e-e7dfa526b701"
+
+
+async def test_message_history_includes_spend_logs_still_waiting_on_the_batch_writer():
+ """
+ A follow-up sent right after the previous turn arrives before the batch writer has
+ flushed that turn's spend log, so the row is only in memory. The history has to
+ include it anyway.
+ """
+ request_id = "chatcmpl-6c1f5f6c-6a2b-4c62-8d1f-0d9d4ce0a1b2"
+ queued_spend_log = {
+ "request_id": request_id,
+ "call_type": "aresponses",
+ "session_id": "b7d0a5b0-6d20-4a68-9d24-6ba0f6d1f1a3",
+ "proxy_server_request": json.dumps(
+ {
+ "input": [
+ {
+ "role": "user",
+ "content": "Remember this: my favorite color is chartreuse.",
+ }
+ ],
+ "model": "claude-bridge",
+ }
+ ),
+ "response": json.dumps(_chat_completion_response(request_id, "OK")),
+ }
+ fake_prisma_client = _FakePrismaClient(written_rows=[], queued_rows=[queued_spend_log])
+
+ with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma_client):
+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(
+ request_id
+ )
+
+ messages = result["messages"]
+ assert [(message.get("role"), message.get("content")) for message in messages] == [
+ ("user", "Remember this: my favorite color is chartreuse."),
+ ("assistant", "OK"),
+ ]
+ assert result["litellm_session_id"] == "b7d0a5b0-6d20-4a68-9d24-6ba0f6d1f1a3"
+ assert fake_prisma_client.spend_log_transactions == [queued_spend_log]
+
+
+async def test_message_history_merges_written_and_queued_turns_in_order():
+ """
+ Turn 1 already flushed to the DB, turn 2 still queued: the follow-up sees the whole
+ conversation, in order, with no row counted twice.
+ """
+ session_id = "5c5f9a3e-1c86-4c0e-9d7c-0a54b8a0f2f1"
+ first_request_id = "chatcmpl-1111"
+ second_request_id = "chatcmpl-2222"
+ written_spend_log = {
+ "request_id": first_request_id,
+ "call_type": "aresponses",
+ "session_id": session_id,
+ "proxy_server_request": {
+ "input": [{"role": "user", "content": "My favorite color is chartreuse."}],
+ "model": "claude-bridge",
+ },
+ "response": _chat_completion_response(first_request_id, "Got it."),
+ }
+ queued_spend_log = {
+ "request_id": second_request_id,
+ "call_type": "aresponses",
+ "session_id": session_id,
+ "proxy_server_request": json.dumps(
+ {
+ "input": [{"role": "user", "content": "And my favorite city is Lisbon."}],
+ "model": "claude-bridge",
+ }
+ ),
+ "response": json.dumps(_chat_completion_response(second_request_id, "Noted.")),
+ }
+ fake_prisma_client = _FakePrismaClient(
+ written_rows=[written_spend_log],
+ queued_rows=[written_spend_log, queued_spend_log],
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma_client):
+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(
+ second_request_id
+ )
+
+ messages = result["messages"]
+ assert [(message.get("role"), message.get("content")) for message in messages] == [
+ ("user", "My favorite color is chartreuse."),
+ ("assistant", "Got it."),
+ ("user", "And my favorite city is Lisbon."),
+ ("assistant", "Noted."),
+ ]
+ assert result["litellm_session_id"] == session_id
+
+
+async def test_message_history_ignores_queued_spend_logs_from_other_sessions():
+ request_id = "chatcmpl-3333"
+ written_spend_log = {
+ "request_id": request_id,
+ "call_type": "aresponses",
+ "session_id": "session-a",
+ "proxy_server_request": {
+ "input": [{"role": "user", "content": "Hello from session a."}],
+ "model": "claude-bridge",
+ },
+ "response": _chat_completion_response(request_id, "Hi."),
+ }
+ other_session_spend_log = {
+ "request_id": "chatcmpl-4444",
+ "call_type": "aresponses",
+ "session_id": "session-b",
+ "proxy_server_request": json.dumps(
+ {
+ "input": [{"role": "user", "content": "Hello from session b."}],
+ "model": "claude-bridge",
+ }
+ ),
+ "response": json.dumps(_chat_completion_response("chatcmpl-4444", "Hi there.")),
+ }
+ fake_prisma_client = _FakePrismaClient(
+ written_rows=[written_spend_log],
+ queued_rows=[other_session_spend_log],
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma_client):
+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(
+ request_id
+ )
+
+ messages = result["messages"]
+ assert [(message.get("role"), message.get("content")) for message in messages] == [
+ ("user", "Hello from session a."),
+ ("assistant", "Hi."),
+ ]
+
+
+async def test_message_history_looks_up_the_decoded_chat_completion_id():
+ """
+ A `previous_response_id` handed back by the proxy is base64 encoded; spend logs store
+ the bare chat completion id, so that is what the lookup has to query on.
+ """
+ request_id = "chatcmpl-935b8dad-fdc2-466e-a8ca-e26e5a8a21bb"
+ encoded_response_id = ResponsesAPIRequestUtils._build_responses_api_response_id(
+ custom_llm_provider="anthropic",
+ model_id="e0f302a1412e78470ebb28cbed01fff5f88c0d331c667e9f2ba4b413c6fbd282",
+ response_id=request_id,
+ )
+ fake_prisma_client = _FakePrismaClient(written_rows=[], queued_rows=[])
+
+ with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma_client):
+ await ResponsesSessionHandler.get_all_spend_logs_for_previous_response_id(
+ encoded_response_id
+ )
+
+ assert fake_prisma_client.db.calls == [(request_id,)]
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_streaming_iterator_response_id.py b/tests/test_litellm/responses/litellm_completion_transformation/test_streaming_iterator_response_id.py
new file mode 100644
index 00000000000..97f35900e9d
--- /dev/null
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_streaming_iterator_response_id.py
@@ -0,0 +1,130 @@
+from unittest.mock import MagicMock
+
+import pytest
+
+from litellm.responses.litellm_completion_transformation.streaming_iterator import (
+ LiteLLMCompletionStreamingIterator,
+)
+from litellm.responses.utils import ResponsesAPIRequestUtils
+from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+CHAT_COMPLETION_ID = "chatcmpl-77d33d09-effa-4cd2-9c0d-c742d4358256"
+RESPONSE_ID_EVENT_TYPES = frozenset(
+ {"response.created", "response.in_progress", "response.completed"}
+)
+
+
+def _chunk(content: str, finish_reason: str | None = None) -> ModelResponseStream:
+ return ModelResponseStream(
+ id=CHAT_COMPLETION_ID,
+ created=1748575031,
+ model="claude-haiku-4-5",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(role="assistant", content=content),
+ finish_reason=finish_reason,
+ )
+ ],
+ )
+
+
+class _FakeStreamWrapper:
+ def __init__(self, chunks):
+ self._chunks = list(chunks)
+ self.logging_obj = MagicMock()
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if not self._chunks:
+ raise StopIteration
+ return self._chunks.pop(0)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ if not self._chunks:
+ raise StopAsyncIteration
+ return self._chunks.pop(0)
+
+
+def _build_iterator(chunks) -> LiteLLMCompletionStreamingIterator:
+ return LiteLLMCompletionStreamingIterator(
+ model="claude-haiku-4-5",
+ litellm_custom_stream_wrapper=_FakeStreamWrapper(chunks),
+ request_input="What is the weather in San Francisco?",
+ responses_api_request={},
+ custom_llm_provider="anthropic",
+ litellm_metadata={},
+ )
+
+
+def _response_ids(events) -> list[str]:
+ return [
+ event.response.id
+ for event in events
+ if getattr(event, "type", None) in RESPONSE_ID_EVENT_TYPES
+ ]
+
+
+async def test_streaming_events_share_the_chat_completion_response_id():
+ """
+ Every event of a bridged stream has to carry the same id, and that id has to decode
+ to the chat completion id spend tracking stores as `request_id`. Otherwise a
+ follow-up `previous_response_id` matches no session and the conversation is dropped.
+ """
+ iterator = _build_iterator([_chunk("Hello"), _chunk("!", finish_reason="stop")])
+
+ events = [event async for event in iterator]
+
+ response_ids = _response_ids(events)
+ assert len(response_ids) == 3
+ assert len(set(response_ids)) == 1
+ decoded = ResponsesAPIRequestUtils._decode_responses_api_response_id(response_ids[0])
+ assert decoded["response_id"] == CHAT_COMPLETION_ID
+ assert decoded["custom_llm_provider"] == "anthropic"
+
+
+def test_sync_streaming_events_share_the_chat_completion_response_id():
+ iterator = _build_iterator([_chunk("Hello"), _chunk("!", finish_reason="stop")])
+
+ events = list(iterator)
+
+ response_ids = _response_ids(events)
+ assert len(response_ids) == 3
+ assert len(set(response_ids)) == 1
+ assert (
+ ResponsesAPIRequestUtils._decode_responses_api_response_id(response_ids[0])["response_id"]
+ == CHAT_COMPLETION_ID
+ )
+
+
+async def test_streaming_emits_every_chunk_after_priming_the_response_id():
+ iterator = _build_iterator(
+ [_chunk("Hel"), _chunk("lo"), _chunk("!", finish_reason="stop")]
+ )
+
+ events = [event async for event in iterator]
+
+ deltas = "".join(
+ event.delta for event in events if getattr(event, "type", None) == "response.output_text.delta"
+ )
+ assert deltas == "Hello!"
+
+
+async def test_streaming_response_id_falls_back_when_upstream_yields_nothing():
+ iterator = _build_iterator([])
+
+ events = [event async for event in iterator]
+
+ response_ids = _response_ids(events)
+ assert response_ids
+ assert len(set(response_ids)) == 1
+ assert response_ids[0].startswith("resp_")