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(bedrock): stop emitting an empty assistant delta after the finish_reason chunk
mateo3db1759d04ba
diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex 8d2b3dae71b..595884ae630 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -561,6 +561,10 @@ class AWSEventStreamDecoder:elif "usage" in chunk_data:usage = converse_config._transform_usage(chunk_data.get("usage", {}))+ carries_message_content: Final = any(+ key in chunk_data for key in ("start", "delta", "contentBlockIndex", "stopReason")+ )+model_response_provider_specific_fields: Final = {}if "trace" in chunk_data:trace: Final = chunk_data.get("trace")@@ -571,8 +575,8 @@ class AWSEventStreamDecoder:finish_reason=finish_reason,index=0, # Always 0 - Bedrock never returns multiple choicesdelta=Delta(- content=text,- role="assistant",+ content=text if carries_message_content else None,+ role="assistant" if carries_message_content else None,tool_calls=[tool_use] if tool_use else None,provider_specific_fields=(provider_specific_fields if provider_specific_fields else None),thinking_blocks=thinking_blocks,diff --git a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.pyindex ee50b9db015..9783976db4a 100644--- a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py+++ b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py@@ -1,3 +1,4 @@+import datetimeimport osimport sysfrom unittest.mock import AsyncMock, MagicMock@@ -8,6 +9,8 @@ sys.path.insert(0, os.path.abspath("../../../../..")) # Adds the parent directory to the system path+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapperfrom litellm.llms.bedrock.chat.invoke_handler import (AWSEventStreamDecoder,make_call,@@ -293,3 +296,46 @@ def test_make_sync_call_honors_explicit_stream_chunk_size():response.iter_bytes.assert_called_once_with(chunk_size=2048)++async def test_converse_stream_ends_on_finish_reason_chunk():+ """The usage-only metadata event Bedrock sends after messageStop must not reach the caller as an extra+ assistant delta following the finish_reason chunk."""+ model = "anthropic.claude-sonnet-4-6"+ events = (+ {"role": "assistant"},+ {"contentBlockIndex": 0, "delta": {"text": "Hello"}},+ {"contentBlockIndex": 0, "delta": {"text": " world"}},+ {"contentBlockIndex": 0},+ {"stopReason": "end_turn"},+ {"usage": {"inputTokens": 10, "outputTokens": 5, "totalTokens": 15}, "metrics": {"latencyMs": 100}},+ )++ async def bedrock_stream():+ decoder = AWSEventStreamDecoder(model=model)+ for event in events:+ yield decoder._chunk_parser(chunk_data=event)++ wrapper = CustomStreamWrapper(+ completion_stream=bedrock_stream(),+ model=model,+ custom_llm_provider="bedrock",+ logging_obj=LiteLLMLoggingObj(+ model=model,+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ call_type="completion",+ start_time=datetime.datetime.now(),+ litellm_call_id="1234",+ function_id="1234",+ ),+ )++ chunks = [chunk async for chunk in wrapper]++ assert [choice.finish_reason for chunk in chunks for choice in chunk.choices].count("stop") == 1+ assert chunks[-1].choices[0].finish_reason == "stop", (+ f"stream must end on the finish_reason chunk, got trailing {chunks[-1].model_dump(exclude_none=True)}"+ )+ assert any(getattr(chunk, "usage", None) is not None for chunk in wrapper.chunks)+