The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: handle missing choice indices in streamed output recording (#46947)
yucheng-berrib3c0f3457df5
diff --git a/litellm/litellm_core_utils/served_output_texts.py b/litellm/litellm_core_utils/served_output_texts.pyindex ce9a568ea72..e23db5200a3 100644--- a/litellm/litellm_core_utils/served_output_texts.py+++ b/litellm/litellm_core_utils/served_output_texts.py@@ -126,13 +126,13 @@ def _chat_stream_choice_text(chunks: Sequence[ModelResponseStream], index: int)contentfor chunk in chunksfor choice in chunk.choices- if choice.index == index and isinstance(content := choice.delta.content, str)+ if (choice.index or 0) == index and isinstance(content := choice.delta.content, str))return "".join(contents) if contents else Nonedef _chat_stream_texts(chunks: Sequence[ModelResponseStream]) -> ServedTexts | None:- choice_count: Final = max((choice.index + 1 for chunk in chunks for choice in chunk.choices), default=0)+ choice_count: Final = max(((choice.index or 0) + 1 for chunk in chunks for choice in chunk.choices), default=0)texts: Final = tuple(_chat_stream_choice_text(chunks, index) for index in range(choice_count))return texts if any(text is not None for text in texts) else Nonediff --git a/tests/integration/observability/test_guardrail_effects.py b/tests/integration/observability/test_guardrail_effects.pyindex f267cff04f3..4e0c3d45cdf 100644--- a/tests/integration/observability/test_guardrail_effects.py+++ b/tests/integration/observability/test_guardrail_effects.py@@ -8,6 +8,7 @@ from concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezonefrom contextlib import contextmanagerfrom dataclasses import dataclass+from itertools import chainfrom pathlib import Pathfrom types import MappingProxyTypefrom typing import Final@@ -22,7 +23,8 @@ from integration._support.mcp import mcp_peer, register_mcp, tool_namesfrom integration._support.process import OwnedProxy, owned_proxy, owned_proxy_processfrom integration._support.wire import Reply, Request, Wire, wire_serverfrom integration._support.ports import allocate_port-from openai import AsyncOpenAI, OpenAI+from openai import APIError, AsyncOpenAI, OpenAI+from openai.types.chat import ChatCompletionChunkfrom pydantic import BaseModel, JsonValue@@ -2858,6 +2860,281 @@ def test_a_fully_read_stream_is_scanned_exactly_once(assert len(rig.scans.response_scans(rig.secret())) == 1, rig.scans.seen+def _pre_call_progress_config(tmp_path: Path, identity: str, policy_url: str, *, store_prompts: bool) -> Path:+ path: Final = _post_call_config(tmp_path, identity, policy_url, {**_END_OF_STREAM_ONLY, "mode": "pre_call"}, True)+ if store_prompts:+ config: Final = yaml.safe_load(path.read_text())+ settings: Final = {**config["general_settings"], "store_prompts_in_spend_logs": True}+ path.write_text(yaml.safe_dump({**config, "general_settings": settings}))+ return path+++def _openai_chat_chunks(candidate: Gateway, model: str, prompt: str) -> tuple[ChatCompletionChunk, ...]:+ with OpenAI(+ base_url=str(candidate.client.base_url) + "/v1", api_key=candidate.key, max_retries=0, timeout=30+ ) as client:+ return tuple(+ client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": prompt}],+ stream=True,+ extra_headers={"x-litellm-call-id": prompt},+ )+ )+++def _async_openai_chat_chunks(candidate: Gateway, model: str, prompt: str) -> tuple[ChatCompletionChunk, ...]:+ async def consume() -> tuple[ChatCompletionChunk, ...]:+ async with AsyncOpenAI(+ base_url=str(candidate.client.base_url) + "/v1", api_key=candidate.key, max_retries=0, timeout=30+ ) as client:+ stream: Final = await client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": prompt}],+ stream=True,+ extra_headers={"x-litellm-call-id": prompt},+ )+ return tuple([chunk async for chunk in stream])++ return asyncio.run(consume())+++_PROGRESS_STREAM_READERS: Final = (+ pytest.param(_openai_chat_chunks, id="sync-openai-sdk"),+ pytest.param(_async_openai_chat_chunks, id="async-openai-sdk"),+)++[email protected]("read_stream", _PROGRESS_STREAM_READERS)[email protected]("index_fields", ({}, {"index": None}), ids=("omitted-index", "null-index"))[email protected]("progress_content", (None, "progress "), ids=("null-content", "text-content"))+def test_progress_chunk_without_choice_index_streams_and_logs_served_answer(+ gateway: Gateway,+ tmp_path: Path,+ record_property: Callable[[str, object], None],+ index_fields: dict[str, JsonValue],+ progress_content: str | None,+ read_stream: Callable[[Gateway, str, str], tuple[ChatCompletionChunk, ...]],+) -> None:+ identity: Final = "guardrail" + uuid.uuid4().hex+ record_property("litellm_call_id", identity)+ answer: Final = "synthetic answer " + identity+ reasoning: Final = "backend progress " + identity+ expected: Final = (progress_content or "") + answer+ frames: Final = (+ _chat_frame(+ identity,+ (+ {+ **index_fields,+ "delta": {"reasoning_content": reasoning, "content": progress_content},+ "finish_reason": None,+ },+ ),+ ),+ _chat_frame(identity, (_chat_choice(0, {"content": answer}),)),+ _chat_frame(identity, (_chat_choice(0, {}, "stop"),)),+ b"data: [DONE]\n\n",+ )++ def provider(request: Request) -> Reply:+ assert request.target == "/v1/chat/completions", request.target+ body: Final = json.loads(request.body)+ assert body["stream"] is True, body+ assert body["messages"] == [{"role": "user", "content": identity}], body+ return Reply(content_type="text/event-stream", chunks=frames)++ with wire_server(_allowing_guardrail) as policy, wire_server(provider) as upstream:+ path: Final = _pre_call_progress_config(tmp_path, identity, policy.url, store_prompts=True)+ with (+ owned_proxy_process(gateway, tmp_path, {}, config=path, workers=2) as owned,+ owned.gateway.scenario() as scenario,+ ):+ candidate: Final = owned.gateway+ model: Final = scenario.model(model_info={"id": identity}, api_base=upstream.url + "/v1")+ eventually(lambda: owned.serves_only_on_every_worker(model, identity), bool, seconds=70)+ chunks: Final = read_stream(candidate, model, identity)+ choices: Final = tuple(chain.from_iterable(chunk.choices for chunk in chunks))+ actual: Final = "".join(choice.delta.content or "" for choice in choices)+ assert actual == expected, chunks+ assert tuple(choice.index for choice in choices if choice.finish_reason == "stop") == (0,), chunks+ assert reasoning in json.dumps([chunk.model_dump() for chunk in chunks]), chunks+ assert len(upstream.drain()) == 1+ rows: Final = eventually(+ lambda: read_rows(+ 'SELECT request_id, status, response, metadata FROM "LiteLLM_SpendLogs" '+ "WHERE model_group=%s AND (request_id=%s OR metadata->>'litellm_call_id'=%s)",+ (model, identity, identity),+ ),+ lambda values: len(values) == 1,+ seconds=70,+ )+ record_property("spend_request_id", rows[0]["request_id"])+ assert rows[0]["status"] == "success", rows+ logged_choices: Final = object_value(rows[0]["response"])["choices"]+ assert isinstance(logged_choices, list), rows+ assert tuple(object_value(object_value(choice)["message"])["content"] for choice in logged_choices) == (+ expected,+ ), rows+ entries: Final = object_value(rows[0]["metadata"])["guardrail_information"]+ assert isinstance(entries, list), rows+ assert tuple(+ (entry["guardrail_name"], entry["guardrail_mode"], entry["guardrail_status"])+ for entry in map(object_value, entries)+ ) == ((identity, "pre_call", "success"),), rows+ scans: Final = tuple(json.loads(request.body) for request in policy.drain())+ assert len(scans) == 1 and scans[0]["input_type"] == "request", scans+ assert scans[0]["texts"] == [identity], scans++[email protected]("read_stream", _PROGRESS_STREAM_READERS)+def test_progress_chunk_without_choice_index_preserves_upstream_stream_error(+ gateway: Gateway,+ tmp_path: Path,+ record_property: Callable[[str, object], None],+ read_stream: Callable[[Gateway, str, str], tuple[ChatCompletionChunk, ...]],+) -> None:+ identity: Final = "guardrail" + uuid.uuid4().hex+ record_property("litellm_call_id", identity)+ message: Final = "synthetic upstream failure marker " + identity+ frames: Final = (+ _chat_frame(+ identity,+ ({"delta": {"reasoning_content": "backend progress", "content": None}, "finish_reason": None},),+ ),+ b"data: "+ + json.dumps({"error": {"message": message, "type": "server_error", "code": "upstream_failed"}}).encode()+ + b"\n\n",+ b"data: [DONE]\n\n",+ )++ def provider(request: Request) -> Reply:+ assert request.target == "/v1/chat/completions", request.target+ body: Final = json.loads(request.body)+ assert body["stream"] is True, body+ assert body["messages"] == [{"role": "user", "content": identity}], body+ return Reply(content_type="text/event-stream", chunks=frames)++ with wire_server(_allowing_guardrail) as policy, wire_server(provider) as upstream:+ path: Final = _pre_call_progress_config(tmp_path, identity, policy.url, store_prompts=False)+ with (+ owned_proxy_process(gateway, tmp_path, {}, config=path, workers=2) as owned,+ owned.gateway.scenario() as scenario,+ ):+ candidate: Final = owned.gateway+ model: Final = scenario.model(model_info={"id": identity}, api_base=upstream.url + "/v1", num_retries=0)+ eventually(lambda: owned.serves_only_on_every_worker(model, identity), bool, seconds=70)+ with pytest.raises(APIError, match=message) as raised:+ read_stream(candidate, model, identity)+ assert "NoneType" not in str(raised.value), raised.value+ assert len(upstream.drain()) == 1+ rows: Final = eventually(+ lambda: read_rows(+ 'SELECT request_id, status, metadata FROM "LiteLLM_SpendLogs" '+ "WHERE model_group=%s AND (request_id=%s OR metadata->>'litellm_call_id'=%s)",+ (model, identity, identity),+ ),+ lambda values: len(values) == 1,+ seconds=70,+ )+ record_property("spend_request_id", rows[0]["request_id"])+ assert rows[0]["status"] == "failure", rows+ error: Final = object_value(rows[0]["metadata"])["error_information"]+ assert message in str(object_value(error)["error_message"]), rows+ scans: Final = tuple(json.loads(request.body) for request in policy.drain())+ assert len(scans) == 1 and scans[0]["texts"] == [identity], scans++[email protected]("index_fields", ({}, {"index": None}), ids=("omitted-index", "null-index"))+def test_disconnect_after_progress_without_choice_index_logs_only_the_received_prefix(+ gateway: Gateway,+ tmp_path: Path,+ index_fields: dict[str, JsonValue],+ record_property: Callable[[str, object], None],+) -> None:+ identity: Final = "guardrail" + uuid.uuid4().hex+ record_property("litellm_call_id", identity)+ prefix: Final = "synthetic received prefix " + identity+ tail: Final = "synthetic withheld tail " + identity+ gate: Final = threading.Event()+ frames: Final = (+ _chat_frame(+ identity,+ (+ {+ **index_fields,+ "delta": {"reasoning_content": "backend progress", "content": prefix},+ "finish_reason": None,+ },+ ),+ ),+ _chat_frame(identity, (_chat_choice(0, {"content": tail}, "stop"),)),+ b"data: [DONE]\n\n",+ )++ def provider(request: Request) -> Reply:+ assert request.target == "/v1/chat/completions", request.target+ body: Final = json.loads(request.body)+ assert body["stream"] is True, body+ assert body["messages"] == [{"role": "user", "content": identity}], body+ return Reply(content_type="text/event-stream", chunks=frames, gate_after_first=gate)++ with wire_server(_allowing_guardrail) as policy, wire_server(provider) as upstream:+ path: Final = _pre_call_progress_config(tmp_path, identity, policy.url, store_prompts=True)+ with (+ owned_proxy_process(gateway, tmp_path, {}, config=path, workers=2) as owned,+ owned.gateway.scenario() as scenario,+ ):+ candidate: Final = owned.gateway+ model: Final = scenario.model(model_info={"id": identity}, api_base=upstream.url + "/v1", num_retries=0)+ eventually(lambda: owned.serves_only_on_every_worker(model, identity), bool, seconds=70)++ try:++ async def disconnect() -> str:+ async with AsyncOpenAI(+ base_url=str(candidate.client.base_url) + "/v1",+ api_key=candidate.key,+ max_retries=0,+ timeout=30,+ ) as client:+ stream: Final = await client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": identity}],+ stream=True,+ extra_headers={"x-litellm-call-id": identity},+ )+ async for chunk in stream:+ for choice in chunk.choices:+ if choice.delta.content == prefix:+ await stream.close()+ return choice.delta.content+ raise AssertionError("The stream ended before the SDK received the provider prefix")++ assert asyncio.run(disconnect()) == prefix+ rows: Final = eventually(+ lambda: read_rows(+ 'SELECT request_id, status, response FROM "LiteLLM_SpendLogs" '+ "WHERE model_group=%s AND (request_id=%s OR metadata->>'litellm_call_id'=%s)",+ (model, identity, identity),+ ),+ lambda values: len(values) == 1,+ seconds=70,+ )+ record_property("spend_request_id", rows[0]["request_id"])+ assert rows[0]["status"] == "success", rows+ logged_choices: Final = object_value(rows[0]["response"])["choices"]+ assert isinstance(logged_choices, list), rows+ assert tuple(object_value(object_value(choice)["message"])["content"] for choice in logged_choices) == (+ prefix,+ ), rows+ assert len(upstream.drain()) == 1+ scans: Final = tuple(json.loads(request.body) for request in policy.drain())+ assert len(scans) == 1 and scans[0]["texts"] == [identity], scans+ finally:+ gate.set()++def _cached_twin_rows(rig: _DisconnectRig) -> tuple[tuple[str, ...], ...]:first: Final = rig.candidate.request("POST", "/v1/chat/completions", _chat_body(rig, 0, stream=False))second: Final = rig.candidate.request("POST", "/v1/chat/completions", _chat_body(rig, 0, stream=False))diff --git a/tests/unit/litellm_core_utils/test_served_output_texts.py b/tests/unit/litellm_core_utils/test_served_output_texts.pyindex ade39b8fca9..637a20571c8 100644--- a/tests/unit/litellm_core_utils/test_served_output_texts.py+++ b/tests/unit/litellm_core_utils/test_served_output_texts.py@@ -1,3 +1,7 @@+from typing import Final++import pytest+from litellm.litellm_core_utils.served_output_texts import (SERVED_OUTPUT_TEXTS_KEY,overlay_served_output_texts,@@ -79,6 +83,29 @@ def test_served_stream_output_texts_keeps_every_choice_index_when_chunks_carry_oassert served_stream_output_texts(chunks) == ("first choice", MASKED)[email protected]("content", (None, "", "first"))+def test_null_choice_index_joins_choice_zero_without_changing_other_choices(content: str | None) -> None:+ chunks: Final = (+ _stream_chunk("other", 1),+ ModelResponseStream(+ choices=[StreamingChoices(index=None, delta=Delta(content=content, reasoning_content="loading"))]+ ),+ _stream_chunk(" answer"),+ )+ assert served_stream_output_texts(chunks) == ((content or "") + " answer", "other")+ assert chunks[1].choices[0].index is None++[email protected]("content, expected", ((None, None), ("", ("",)), ("answer", ("answer",))))+def test_null_choice_index_preserves_empty_text_and_ignores_reasoning(+ content: str | None, expected: tuple[str, ...] | None+) -> None:+ chunk: Final = ModelResponseStream(+ choices=[StreamingChoices(index=None, delta=Delta(content=content, reasoning_content="loading"))]+ )+ assert served_stream_output_texts((chunk,)) == expected++def test_blanked_output_is_served_as_empty_text_and_overlaid():assert served_output_texts(_chat_response("")) == ("",)assert served_output_texts({"type": "message", "role": "assistant", "content": [{"type": "text", "text": ""}]}) == (