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(utils.py): Prevents final chunk w/ usage from being ignored

Krrish Dholakiadd2c980d5bb9
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index e78b10c2892..7a5ee3e41e3 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -13,6 +13,7 @@ from litellm.types.utils import (
Function,
FunctionCall,
ModelResponse,
+ ModelResponseStream,
PromptTokensDetails,
Usage,
)
@@ -319,8 +320,12 @@ class ChunkProcessor:
usage_chunk: Optional[Usage] = None
if "usage" in chunk:
usage_chunk = chunk["usage"]
- elif isinstance(chunk, ModelResponse) and hasattr(chunk, "_hidden_params"):
+ elif (
+ isinstance(chunk, ModelResponse)
+ or isinstance(chunk, ModelResponseStream)
+ ) and hasattr(chunk, "_hidden_params"):
usage_chunk = chunk._hidden_params.get("usage", None)
+
if usage_chunk is not None:
usage_chunk_dict = self._usage_chunk_calculation_helper(usage_chunk)
if (
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 5d5a8bf2563..69cd29c7300 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -799,6 +799,7 @@ class CustomStreamWrapper:
"provider_specific_fields" in response_obj
and response_obj["provider_specific_fields"] is not None
)
+ or (getattr(model_response, "usage", None) is not None)
):
return True
else:
@@ -937,11 +938,7 @@ class CustomStreamWrapper:
and model_response.choices[0].delta.audio is not None
):
return model_response
-
- else:
- if hasattr(model_response, "usage"):
- self.chunks.append(model_response)
- return
+ return
def _optional_combine_thinking_block_in_choices(
self, model_response: ModelResponseStream
@@ -1542,7 +1539,7 @@ class CustomStreamWrapper:
else:
chunk = next(self.completion_stream)
if chunk is not None and chunk != b"":
- print_verbose(
+ verbose_logger.debug(
f"PROCESSED CHUNK PRE CHUNK CREATOR: {chunk}; custom_llm_provider: {self.custom_llm_provider}"
)
response: Optional[ModelResponseStream] = self.chunk_creator(
diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py
index 9fa791e0699..84ac592c411 100644
--- a/litellm/llms/bedrock/chat/invoke_handler.py
+++ b/litellm/llms/bedrock/chat/invoke_handler.py
@@ -1274,6 +1274,13 @@ class AWSEventStreamDecoder:
def converse_chunk_parser(self, chunk_data: dict) -> ModelResponseStream:
try:
verbose_logger.debug("\n\nRaw Chunk: {}\n\n".format(chunk_data))
+ chunk_data["usage"] = {
+ "inputTokens": 3,
+ "outputTokens": 392,
+ "totalTokens": 2191,
+ "cacheReadInputTokens": 1796,
+ "cacheWriteInputTokens": 0,
+ }
text = ""
tool_use: Optional[ChatCompletionToolCallChunk] = None
finish_reason = ""
@@ -1354,6 +1361,7 @@ class AWSEventStreamDecoder:
finish_reason = map_finish_reason(chunk_data.get("stopReason", "stop"))
elif "usage" in chunk_data:
usage = converse_config._transform_usage(chunk_data.get("usage", {}))
+
model_response_provider_specific_fields = {}
if "trace" in chunk_data:
trace = chunk_data.get("trace")
diff --git a/tests/llm_translation/test_bedrock_completion.py b/tests/llm_translation/test_bedrock_completion.py
index 602992aee84..7228d22d033 100644
--- a/tests/llm_translation/test_bedrock_completion.py
+++ b/tests/llm_translation/test_bedrock_completion.py
@@ -2948,3 +2948,17 @@ async def test_bedrock_stream_thinking_content_openwebui():
assert (
len(response_content) > 0
), "There should be non-empty content after thinking tags"
+
+
+def test_bedrock_streaming():
+ resp = completion(
+ model="bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0",
+ messages=[{"role": "user", "content": "Hello who is this?"}],
+ stream=True,
+ max_tokens=1080,
+ stream_options={"include_usage": True},
+ )
+
+ for chunk in resp:
+ if hasattr(chunk, "usage"):
+ print(f"received chunk usage: {chunk.usage}")