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]

[Bug Fix] Cost tracking and logging via the /v1/messages API are not working when using Claude Code (#11928)

Ishaan Jaff75298af605b6
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 273b9c477a1..070069988c2 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@ -5,6 +5,7 @@ import traceback
from typing import Any, AsyncIterator, Iterator, Optional
from litellm import verbose_logger
+from litellm.types.llms.anthropic import UsageDelta
from litellm.types.utils import AdapterCompletionStreamWrapper
@@ -37,7 +38,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
"model": "claude-3-5-sonnet-20240620",
"stop_reason": None,
"stop_sequence": None,
- "usage": {"input_tokens": 25, "output_tokens": 1},
+ "usage": UsageDelta(input_tokens=0, output_tokens=0),
},
}
if self.sent_content_block_start is False:
@@ -106,7 +107,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):
"model": "claude-3-5-sonnet-20240620",
"stop_reason": None,
"stop_sequence": None,
- "usage": {"input_tokens": 25, "output_tokens": 1},
+ "usage": UsageDelta(input_tokens=0, output_tokens=0),
},
}
if self.sent_content_block_start is False:
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py
new file mode 100644
index 00000000000..df106c0e696
--- /dev/null
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py
@@ -0,0 +1,108 @@
+import asyncio
+import json
+from datetime import datetime
+from typing import Any, AsyncIterator, List, Union
+
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.proxy.pass_through_endpoints.success_handler import (
+ PassThroughEndpointLogging,
+)
+from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType
+from litellm.types.utils import GenericStreamingChunk, ModelResponseStream
+
+GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging()
+
+class BaseAnthropicMessagesStreamingIterator:
+ """
+ Base class for Anthropic Messages streaming iterators that provides common logic
+ for streaming response handling and logging.
+ """
+
+ def __init__(
+ self,
+ litellm_logging_obj: LiteLLMLoggingObj,
+ request_body: dict,
+ ):
+ self.litellm_logging_obj = litellm_logging_obj
+ self.request_body = request_body
+ self.start_time = datetime.now()
+
+
+ async def _handle_streaming_logging(self, collected_chunks: List[bytes]):
+ """Handle the logging after all chunks have been collected."""
+ from litellm.proxy.pass_through_endpoints.streaming_handler import (
+ PassThroughStreamingHandler,
+ )
+
+ end_time = datetime.now()
+ asyncio.create_task(
+ PassThroughStreamingHandler._route_streaming_logging_to_handler(
+ litellm_logging_obj=self.litellm_logging_obj,
+ passthrough_success_handler_obj=GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ,
+ url_route="/v1/messages",
+ request_body=self.request_body or {},
+ endpoint_type=EndpointType.ANTHROPIC,
+ start_time=self.start_time,
+ raw_bytes=collected_chunks,
+ end_time=end_time,
+ )
+ )
+
+ def get_async_streaming_response_iterator(
+ self,
+ httpx_response,
+ request_body: dict,
+ litellm_logging_obj: LiteLLMLoggingObj,
+ ) -> AsyncIterator:
+ """Helper function to handle Anthropic streaming responses using the existing logging handlers"""
+ from litellm.proxy.pass_through_endpoints.streaming_handler import (
+ PassThroughStreamingHandler,
+ )
+
+ # Use the existing streaming handler for Anthropic
+ return PassThroughStreamingHandler.chunk_processor(
+ response=httpx_response,
+ request_body=request_body,
+ litellm_logging_obj=litellm_logging_obj,
+ endpoint_type=EndpointType.ANTHROPIC,
+ start_time=self.start_time,
+ passthrough_success_handler_obj=GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ,
+ url_route="/v1/messages",
+ )
+
+ def _convert_chunk_to_sse_format(self, chunk: Union[dict, Any]) -> bytes:
+ """
+ Convert a chunk to Server-Sent Events format.
+
+ This method should be overridden by subclasses if they need custom
+ chunk formatting logic.
+ """
+ if isinstance(chunk, dict):
+ event_type: str = str(chunk.get("type", "message"))
+ payload = f"event: {event_type}\n" f"data: {json.dumps(chunk)}\n\n"
+ return payload.encode()
+ else:
+ # For non-dict chunks, return as is
+ return chunk
+
+ async def async_sse_wrapper(
+ self,
+ completion_stream: AsyncIterator[
+ Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]
+ ],
+ ) -> AsyncIterator[bytes]:
+ """
+ Generic async SSE wrapper that converts streaming chunks to SSE format
+ and handles logging.
+
+ This method provides the common logic for both Anthropic and Bedrock implementations.
+ """
+ collected_chunks = []
+
+ async for chunk in completion_stream:
+ encoded_chunk = self._convert_chunk_to_sse_format(chunk)
+ collected_chunks.append(encoded_chunk)
+ yield encoded_chunk
+
+ # Handle logging after all chunks are processed
+ await self._handle_streaming_logging(collected_chunks)
\ No newline at end of file
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
index aee56dc6f94..160d4eafb57 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
@@ -122,29 +122,17 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
litellm_logging_obj: LiteLLMLoggingObj,
) -> AsyncIterator:
"""Helper function to handle Anthropic streaming responses using the existing logging handlers"""
- from datetime import datetime
-
- from litellm.proxy.pass_through_endpoints.streaming_handler import (
- PassThroughStreamingHandler,
- )
- from litellm.proxy.pass_through_endpoints.success_handler import (
- PassThroughEndpointLogging,
+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (
+ BaseAnthropicMessagesStreamingIterator,
)
- from litellm.types.passthrough_endpoints.pass_through_endpoints import (
- EndpointType,
- )
-
- # Create success handler object
- passthrough_success_handler_obj = PassThroughEndpointLogging()
- # Use the existing streaming handler for Anthropic
- start_time = datetime.now()
- return PassThroughStreamingHandler.chunk_processor(
- response=httpx_response,
+ # Use the shared streaming handler for Anthropic
+ handler = BaseAnthropicMessagesStreamingIterator(
+ litellm_logging_obj=litellm_logging_obj,
+ request_body=request_body,
+ )
+ return handler.get_async_streaming_response_iterator(
+ httpx_response=httpx_response,
request_body=request_body,
litellm_logging_obj=litellm_logging_obj,
- endpoint_type=EndpointType.ANTHROPIC,
- start_time=start_time,
- passthrough_success_handler_obj=passthrough_success_handler_obj,
- url_route="/v1/messages",
)
diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
index 52e751d24af..ba9b478b29f 100644
--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
@@ -1,4 +1,3 @@
-import json
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional, Tuple, Union
import httpx
@@ -142,25 +141,34 @@ class AmazonAnthropicClaude3MessagesConfig(
httpx_response.aiter_bytes(chunk_size=aws_decoder.DEFAULT_CHUNK_SIZE)
)
# Convert decoded Bedrock events to Server-Sent Events expected by Anthropic clients.
- return self.bedrock_sse_wrapper(completion_stream)
+ return self.bedrock_sse_wrapper(
+ completion_stream=completion_stream,
+ litellm_logging_obj=litellm_logging_obj,
+ request_body=request_body,
+ )
async def bedrock_sse_wrapper(
self,
completion_stream: AsyncIterator[
Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]
],
+ litellm_logging_obj: LiteLLMLoggingObj,
+ request_body: dict,
):
"""
Bedrock invoke does not return SSE formatted data. This function is a wrapper to ensure litellm chunks are SSE formatted.
"""
- async for chunk in completion_stream:
- if isinstance(chunk, dict):
- event_type: str = str(chunk.get("type", "message"))
- payload = f"event: {event_type}\n" f"data: {json.dumps(chunk)}\n\n"
- yield payload.encode()
- else:
- # For non-dict chunks, forward the original value unchanged so callers can leverage the richer Python objects if they wish.
- yield chunk
+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (
+ BaseAnthropicMessagesStreamingIterator,
+ )
+ handler = BaseAnthropicMessagesStreamingIterator(
+ litellm_logging_obj=litellm_logging_obj,
+ request_body=request_body,
+ )
+
+ async for chunk in handler.async_sse_wrapper(completion_stream):
+ yield chunk
+
class AmazonAnthropicClaudeMessagesStreamDecoder(AWSEventStreamDecoder):
diff --git a/litellm/utils.py b/litellm/utils.py
index e8eade6871e..e3b14a16763 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -694,6 +694,7 @@ def function_setup( # noqa: PLR0915
if (
call_type == CallTypes.completion.value
or call_type == CallTypes.acompletion.value
+ or call_type == CallTypes.anthropic_messages.value
):
messages = None
if len(args) > 1:
diff --git a/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py
index e67fb011894..b334966b441 100644
--- a/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py
+++ b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py
@@ -26,6 +26,16 @@ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.router import Router
import importlib
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+class TestCustomLogger(CustomLogger):
+ def __init__(self):
+ super().__init__()
+ self.logged_standard_logging_payload: Optional[StandardLoggingPayload] = None
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ print("inside async_log_success_event")
+ self.logged_standard_logging_payload = kwargs.get("standard_logging_object")
+
+ pass
class BaseAnthropicMessagesTest:
@@ -36,6 +46,13 @@ class BaseAnthropicMessagesTest:
"""Override in subclasses to provide model-specific configuration"""
raise NotImplementedError("Subclasses must implement model_config")
+ @property
+ def expected_model_name_in_logging(self) -> str:
+ """
+ This is the model name that is expected to be in the logging payload
+ """
+ raise NotImplementedError("Subclasses must implement expected_model_name_in_logging")
+
def _validate_response(self, response: Any):
"""Validate non-streaming response structure"""
# Handle type checking - response should be a dict for non-streaming
@@ -48,7 +65,8 @@ class BaseAnthropicMessagesTest:
assert "model" in response
assert response.get("role") == "assistant"
- async def _test_non_streaming_base(self):
+ @pytest.mark.asyncio
+ async def test_non_streaming_base(self):
"""Base test for non-streaming requests"""
litellm._turn_on_debug()
@@ -80,7 +98,8 @@ class BaseAnthropicMessagesTest:
print(f"Non-streaming response: {json.dumps(response, indent=2, default=str)}")
return response
- async def _test_streaming_base(self):
+ @pytest.mark.asyncio
+ async def test_streaming_base(self):
"""Base test for streaming requests"""
request_params = self.model_config
# Set up test parameters
@@ -108,4 +127,134 @@ class BaseAnthropicMessagesTest:
collected_chunks.append(chunk)
print("collected_chunks=", collected_chunks)
- return collected_chunks
\ No newline at end of file
+ return collected_chunks
+
+
+ @pytest.mark.asyncio
+ async def test_anthropic_messages_litellm_router_streaming_with_logging(self):
+ """
+ Test that logging and cost tracking works for anthropic_messages with streaming request
+ """
+ test_custom_logger = TestCustomLogger()
+ litellm.callbacks = [test_custom_logger]
+ litellm._turn_on_debug()
+ router = Router(
+ model_list=[
+ {
+ "model_name": "claude-special-alias",
+ "litellm_params": {
+ **self.model_config
+ },
+ }
+ ]
+ )
+
+ # Set up test parameters
+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]
+
+ # Call the handler
+ response = await router.aanthropic_messages(
+ messages=messages,
+ model="claude-special-alias",
+ max_tokens=100,
+ stream=True,
+ )
+
+ response_prompt_tokens = 0
+ response_completion_tokens = 0
+ all_anthropic_usage_chunks = []
+ buffer = ""
+
+ async for chunk in response:
+ # Decode chunk if it's bytes
+ print("chunk=", chunk)
+
+ # Handle SSE format chunks
+ if isinstance(chunk, bytes):
+ chunk_str = chunk.decode("utf-8")
+ buffer += chunk_str
+ # Extract the JSON data part from SSE format
+ for line in buffer.split("\n"):
+ if line.startswith("data: "):
+ try:
+ json_data = json.loads(line[6:]) # Skip the 'data: ' prefix
+ print(
+ "\n\nJSON data:",
+ json.dumps(json_data, indent=4, default=str),
+ )
+
+ # Extract usage information
+ if (
+ json_data.get("type") == "message_start"
+ and "message" in json_data
+ ):
+ if "usage" in json_data["message"]:
+ usage = json_data["message"]["usage"]
+ all_anthropic_usage_chunks.append(usage)
+ print(
+ "USAGE BLOCK",
+ json.dumps(usage, indent=4, default=str),
+ )
+ elif "usage" in json_data:
+ usage = json_data["usage"]
+ all_anthropic_usage_chunks.append(usage)
+ print(
+ "USAGE BLOCK", json.dumps(usage, indent=4, default=str)
+ )
+ except json.JSONDecodeError:
+ print(f"Failed to parse JSON from: {line[6:]}")
+ elif hasattr(chunk, "message"):
+ if chunk.message.usage:
+ print(
+ "USAGE BLOCK",
+ json.dumps(chunk.message.usage, indent=4, default=str),
+ )
+ all_anthropic_usage_chunks.append(chunk.message.usage)
+ elif hasattr(chunk, "usage"):
+ print("USAGE BLOCK", json.dumps(chunk.usage, indent=4, default=str))
+ all_anthropic_usage_chunks.append(chunk.usage)
+
+ print(
+ "all_anthropic_usage_chunks",
+ json.dumps(all_anthropic_usage_chunks, indent=4, default=str),
+ )
+
+ # Extract token counts from usage data
+ if all_anthropic_usage_chunks:
+ response_prompt_tokens = max(
+ [usage.get("input_tokens", 0) for usage in all_anthropic_usage_chunks]
+ )
+ response_completion_tokens = max(
+ [usage.get("output_tokens", 0) for usage in all_anthropic_usage_chunks]
+ )
+
+ print("input_tokens_anthropic_api", response_prompt_tokens)
+ print("output_tokens_anthropic_api", response_completion_tokens)
+
+ await asyncio.sleep(4)
+
+ print(
+ "logged_standard_logging_payload",
+ json.dumps(
+ test_custom_logger.logged_standard_logging_payload, indent=4, default=str
+ ),
+ )
+
+ assert test_custom_logger.logged_standard_logging_payload is not None, "Logging payload should not be None"
+ assert test_custom_logger.logged_standard_logging_payload["messages"] == messages
+ assert test_custom_logger.logged_standard_logging_payload["response"] is not None
+ assert (
+ test_custom_logger.logged_standard_logging_payload["model"]
+ == self.expected_model_name_in_logging
+ )
+
+ # check logged usage + spend
+ assert test_custom_logger.logged_standard_logging_payload["response_cost"] > 0
+ assert (
+ test_custom_logger.logged_standard_logging_payload["prompt_tokens"]
+ == response_prompt_tokens
+ )
+ assert (
+ test_custom_logger.logged_standard_logging_payload["completion_tokens"]
+ == response_completion_tokens
+ )
\ No newline at end of file
diff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
index 0fbc95e4480..2a7ac967e39 100644
--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
@@ -79,6 +79,15 @@ class TestAnthropicDirectAPI(BaseAnthropicMessagesTest):
"model": "claude-3-haiku-20240307",
"api_key": os.getenv("ANTHROPIC_API_KEY"),
}
+
+ @property
+ def expected_model_name_in_logging(self) -> str:
+ """
+ This is the model name that is expected to be in the logging payload
+ """
+ return "claude-3-haiku-20240307"
+
+
class TestAnthropicBedrockAPI(BaseAnthropicMessagesTest):
"""Tests for Anthropic via Bedrock"""
@@ -87,6 +96,14 @@ class TestAnthropicBedrockAPI(BaseAnthropicMessagesTest):
return {
"model": "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",
}
+
+
+ @property
+ def expected_model_name_in_logging(self) -> str:
+ """
+ This is the model name that is expected to be in the logging payload
+ """
+ return "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
@@ -96,7 +113,22 @@ class TestAnthropicOpenAIAPI(BaseAnthropicMessagesTest):
def model_config(self) -> Dict[str, Any]:
return {
"model": "openai/gpt-4o-mini",
+ "client": None,
}
+
+ @property
+ def expected_model_name_in_logging(self) -> str:
+ """
+ This is the model name that is expected to be in the logging payload
+ """
+ return "gpt-4o-mini"
+
+ @pytest.mark.asyncio
+ async def test_anthropic_messages_litellm_router_streaming_with_logging(self):
+ """
+ Test the anthropic_messages with streaming request
+ """
+ pass
@pytest.mark.asyncio
@@ -276,138 +308,6 @@ async def test_anthropic_messages_litellm_router_non_streaming_with_logging():
assert test_custom_logger.logged_standard_logging_payload["model_group"] == MODEL_GROUP
-async def test_anthropic_messages_litellm_router_streaming_with_logging():
- """
- Test the anthropic_messages with streaming request
-
- - Ensure Cost + Usage is tracked
- """
- test_custom_logger = TestCustomLogger()
- litellm.callbacks = [test_custom_logger]
- # litellm._turn_on_debug()
- router = Router(
- model_list=[
- {
- "model_name": "claude-special-alias",
- "litellm_params": {
- "model": "claude-3-haiku-20240307",
- "api_key": os.getenv("ANTHROPIC_API_KEY"),
- },
- }
- ]
- )
-
- # Set up test parameters
- messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]
-
- # Call the handler
- response = await router.aanthropic_messages(
- messages=messages,
- model="claude-special-alias",
- max_tokens=100,
- stream=True,
- )
-
- response_prompt_tokens = 0
- response_completion_tokens = 0
- all_anthropic_usage_chunks = []
- buffer = ""
-
- async for chunk in response:
- # Decode chunk if it's bytes
- print("chunk=", chunk)
-
- # Handle SSE format chunks
- if isinstance(chunk, bytes):
- chunk_str = chunk.decode("utf-8")
- buffer += chunk_str
- # Extract the JSON data part from SSE format
- for line in buffer.split("\n"):
- if line.startswith("data: "):
- try:
- json_data = json.loads(line[6:]) # Skip the 'data: ' prefix
- print(
- "\n\nJSON data:",
- json.dumps(json_data, indent=4, default=str),
- )
-
- # Extract usage information
- if (
- json_data.get("type") == "message_start"
- and "message" in json_data
- ):
- if "usage" in json_data["message"]:
- usage = json_data["message"]["usage"]
- all_anthropic_usage_chunks.append(usage)
- print(
- "USAGE BLOCK",
- json.dumps(usage, indent=4, default=str),
- )
- elif "usage" in json_data:
- usage = json_data["usage"]
- all_anthropic_usage_chunks.append(usage)
- print(
- "USAGE BLOCK", json.dumps(usage, indent=4, default=str)
- )
- except json.JSONDecodeError:
- print(f"Failed to parse JSON from: {line[6:]}")
- elif hasattr(chunk, "message"):
- if chunk.message.usage:
- print(
- "USAGE BLOCK",
- json.dumps(chunk.message.usage, indent=4, default=str),
- )
- all_anthropic_usage_chunks.append(chunk.message.usage)
- elif hasattr(chunk, "usage"):
- print("USAGE BLOCK", json.dumps(chunk.usage, indent=4, default=str))
- all_anthropic_usage_chunks.append(chunk.usage)
-
- print(
- "all_anthropic_usage_chunks",
- json.dumps(all_anthropic_usage_chunks, indent=4, default=str),
- )
-
- # Extract token counts from usage data
- if all_anthropic_usage_chunks:
- response_prompt_tokens = max(
- [usage.get("input_tokens", 0) for usage in all_anthropic_usage_chunks]
- )
- response_completion_tokens = max(
- [usage.get("output_tokens", 0) for usage in all_anthropic_usage_chunks]
- )
-
- print("input_tokens_anthropic_api", response_prompt_tokens)
- print("output_tokens_anthropic_api", response_completion_tokens)
-
- await asyncio.sleep(4)
-
- print(
- "logged_standard_logging_payload",
- json.dumps(
- test_custom_logger.logged_standard_logging_payload, indent=4, default=str
- ),
- )
-
- assert test_custom_logger.logged_standard_logging_payload is not None, "Logging payload should not be None"
- assert test_custom_logger.logged_standard_logging_payload["messages"] == messages
- assert test_custom_logger.logged_standard_logging_payload["response"] is not None
- assert (
- test_custom_logger.logged_standard_logging_payload["model"]
- == "claude-3-haiku-20240307"
- )
-
- # check logged usage + spend
- assert test_custom_logger.logged_standard_logging_payload["response_cost"] > 0
- assert (
- test_custom_logger.logged_standard_logging_payload["prompt_tokens"]
- == response_prompt_tokens
- )
- assert (
- test_custom_logger.logged_standard_logging_payload["completion_tokens"]
- == response_completion_tokens
- )
-
@pytest.mark.asyncio
async def test_anthropic_messages_with_extra_headers():
diff --git a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
index c972c07ce16..661962bc526 100644
--- a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
+++ b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
@@ -2,6 +2,7 @@ import asyncio
import json
import os
import sys
+from datetime import datetime
import pytest
@@ -9,6 +10,7 @@ import pytest
# tests are executed from any working directory.
sys.path.insert(0, os.path.abspath("../../../../../.."))
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.bedrock.messages.invoke_transformations.anthropic_claude3_transformation import (
AmazonAnthropicClaude3MessagesConfig,
AmazonAnthropicClaudeMessagesStreamDecoder,
@@ -27,7 +29,19 @@ async def test_bedrock_sse_wrapper_encodes_dict_chunks():
# Collect all chunks returned by the wrapper
collected: list[bytes] = []
- async for chunk in cfg.bedrock_sse_wrapper(_dummy_stream()):
+ async for chunk in cfg.bedrock_sse_wrapper(
+ _dummy_stream(),
+ litellm_logging_obj=LiteLLMLoggingObj(
+ model="bedrock/invoke/anthropic.claude-3-sonnet-20240229-v1:0",
+ messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],
+ stream=True,
+ call_type="chat",
+ start_time=datetime.now(),
+ litellm_call_id="test_bedrock_sse_wrapper_encodes_dict_chunks",
+ function_id="test_bedrock_sse_wrapper_encodes_dict_chunks",
+ ),
+ request_body={},
+ ):
collected.append(chunk)
assert collected, "No chunks returned from wrapper"