@@ -54,6 +54,27 @@ def stream_generator():
5454
5555 return stream_generator ()
5656
57+ @pytest .fixture
58+ def mock_anthropic_response_with_cached_tokens ():
59+ # Create a mock Usage object with cached_tokens in input_tokens_details
60+ usage = Usage (
61+ input_tokens = 20 ,
62+ output_tokens = 10 ,
63+ cache_read_input_tokens = 15 ,
64+ cache_creation_input_tokens = 2 ,
65+ )
66+
67+ return Message (
68+ id = "msg_123" ,
69+ type = "message" ,
70+ role = "assistant" ,
71+ content = [{"type" : "text" , "text" : "Test response" }],
72+ model = "claude-3-opus-20240229" ,
73+ usage = usage ,
74+ stop_reason = "end_turn" ,
75+ stop_sequence = None ,
76+ )
77+
5778
5879def test_basic_completion (mock_client , mock_anthropic_response ):
5980 with patch ("anthropic.resources.Messages.create" , return_value = mock_anthropic_response ):
@@ -339,3 +360,34 @@ def test_error(mock_client, mock_anthropic_response):
339360 props = call_args ["properties" ]
340361 assert props ["$ai_is_error" ] is True
341362 assert props ["$ai_error" ] == "Test error"
363+
364+
365+ def test_cached_tokens (mock_client , mock_anthropic_response_with_cached_tokens ):
366+ with patch ("anthropic.resources.Messages.create" , return_value = mock_anthropic_response_with_cached_tokens ):
367+ client = Anthropic (api_key = "test-key" , posthog_client = mock_client )
368+ response = client .messages .create (
369+ model = "claude-3-opus-20240229" ,
370+ messages = [{"role" : "user" , "content" : "Hello" }],
371+ posthog_distinct_id = "test-id" ,
372+ posthog_properties = {"foo" : "bar" },
373+ )
374+
375+ assert response == mock_anthropic_response_with_cached_tokens
376+ assert mock_client .capture .call_count == 1
377+
378+ call_args = mock_client .capture .call_args [1 ]
379+ props = call_args ["properties" ]
380+
381+ assert call_args ["distinct_id" ] == "test-id"
382+ assert call_args ["event" ] == "$ai_generation"
383+ assert props ["$ai_provider" ] == "anthropic"
384+ assert props ["$ai_model" ] == "claude-3-opus-20240229"
385+ assert props ["$ai_input" ] == [{"role" : "user" , "content" : "Hello" }]
386+ assert props ["$ai_output_choices" ] == [{"role" : "assistant" , "content" : "Test response" }]
387+ assert props ["$ai_input_tokens" ] == 20
388+ assert props ["$ai_output_tokens" ] == 10
389+ assert props ["$ai_cache_read_input_tokens" ] == 15
390+ assert props ["$ai_cache_creation_input_tokens" ] == 2
391+ assert props ["$ai_http_status" ] == 200
392+ assert props ["foo" ] == "bar"
393+ assert isinstance (props ["$ai_latency" ], float )
0 commit comments