-
Notifications
You must be signed in to change notification settings - Fork 610
Expand file tree
/
Copy pathtest_ai_monitoring.py
More file actions
759 lines (608 loc) · 25.3 KB
/
test_ai_monitoring.py
File metadata and controls
759 lines (608 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import json
import uuid
import pytest
import sentry_sdk
from sentry_sdk._types import (
AnnotatedValue,
SENSITIVE_DATA_SUBSTITUTE,
BLOB_DATA_SUBSTITUTE,
)
from sentry_sdk.ai.monitoring import ai_track
from sentry_sdk.ai.utils import (
MAX_GEN_AI_MESSAGE_BYTES,
MAX_SINGLE_MESSAGE_CONTENT_CHARS,
set_data_normalized,
truncate_and_annotate_messages,
truncate_messages_by_size,
_find_truncation_index,
redact_blob_message_parts,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.utils import safe_serialize
def test_ai_track(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my tool")
def tool(**kwargs):
pass
@ai_track("some test pipeline")
def pipeline():
tool()
with sentry_sdk.start_transaction():
pipeline()
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 2
spans = transaction["spans"]
ai_pipeline_span = spans[0] if spans[0]["op"] == "ai.pipeline" else spans[1]
ai_run_span = spans[0] if spans[0]["op"] == "ai.run" else spans[1]
assert ai_pipeline_span["description"] == "some test pipeline"
assert ai_run_span["description"] == "my tool"
def test_ai_track_with_tags(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my tool")
def tool(**kwargs):
pass
@ai_track("some test pipeline")
def pipeline():
tool()
with sentry_sdk.start_transaction():
pipeline(sentry_tags={"user": "colin"}, sentry_data={"some_data": "value"})
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 2
spans = transaction["spans"]
ai_pipeline_span = spans[0] if spans[0]["op"] == "ai.pipeline" else spans[1]
ai_run_span = spans[0] if spans[0]["op"] == "ai.run" else spans[1]
assert ai_pipeline_span["description"] == "some test pipeline"
print(ai_pipeline_span)
assert ai_pipeline_span["tags"]["user"] == "colin"
assert ai_pipeline_span["data"]["some_data"] == "value"
assert ai_run_span["description"] == "my tool"
@pytest.mark.asyncio
async def test_ai_track_async(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my async tool")
async def async_tool(**kwargs):
pass
@ai_track("some async test pipeline")
async def async_pipeline():
await async_tool()
with sentry_sdk.start_transaction():
await async_pipeline()
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 2
spans = transaction["spans"]
ai_pipeline_span = spans[0] if spans[0]["op"] == "ai.pipeline" else spans[1]
ai_run_span = spans[0] if spans[0]["op"] == "ai.run" else spans[1]
assert ai_pipeline_span["description"] == "some async test pipeline"
assert ai_run_span["description"] == "my async tool"
@pytest.mark.asyncio
async def test_ai_track_async_with_tags(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my async tool")
async def async_tool(**kwargs):
pass
@ai_track("some async test pipeline")
async def async_pipeline():
await async_tool()
with sentry_sdk.start_transaction():
await async_pipeline(
sentry_tags={"user": "czyber"}, sentry_data={"some_data": "value"}
)
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 2
spans = transaction["spans"]
ai_pipeline_span = spans[0] if spans[0]["op"] == "ai.pipeline" else spans[1]
ai_run_span = spans[0] if spans[0]["op"] == "ai.run" else spans[1]
assert ai_pipeline_span["description"] == "some async test pipeline"
assert ai_pipeline_span["tags"]["user"] == "czyber"
assert ai_pipeline_span["data"]["some_data"] == "value"
assert ai_run_span["description"] == "my async tool"
def test_ai_track_with_explicit_op(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my tool", op="custom.operation")
def tool(**kwargs):
pass
with sentry_sdk.start_transaction():
tool()
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 1
span = transaction["spans"][0]
assert span["description"] == "my tool"
assert span["op"] == "custom.operation"
@pytest.mark.asyncio
async def test_ai_track_async_with_explicit_op(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()
@ai_track("my async tool", op="custom.async.operation")
async def async_tool(**kwargs):
pass
with sentry_sdk.start_transaction():
await async_tool()
transaction = events[0]
assert transaction["type"] == "transaction"
assert len(transaction["spans"]) == 1
span = transaction["spans"][0]
assert span["description"] == "my async tool"
assert span["op"] == "custom.async.operation"
@pytest.fixture
def sample_messages():
"""Sample messages similar to what gen_ai integrations would use"""
return [
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": "What is the difference between a list and a tuple in Python?",
},
{
"role": "assistant",
"content": "Lists are mutable and use [], tuples are immutable and use ().",
},
{"role": "user", "content": "Can you give me some examples?"},
{
"role": "assistant",
"content": "Sure! Here are examples:\n\n```python\n# List\nmy_list = [1, 2, 3]\nmy_list.append(4)\n\n# Tuple\nmy_tuple = (1, 2, 3)\n# my_tuple.append(4) would error\n```",
},
]
@pytest.fixture
def large_messages():
"""Messages that will definitely exceed size limits"""
large_content = "This is a very long message. " * 100
return [
{"role": "system", "content": large_content},
{"role": "user", "content": large_content},
{"role": "assistant", "content": large_content},
{"role": "user", "content": large_content},
]
class TestTruncateMessagesBySize:
def test_no_truncation_needed(self, sample_messages):
"""Test that messages under the limit are not truncated"""
result, truncation_index = truncate_messages_by_size(
sample_messages, max_bytes=MAX_GEN_AI_MESSAGE_BYTES
)
assert len(result) == len(sample_messages)
assert result == sample_messages
assert truncation_index == 0
def test_truncation_removes_oldest_first(self, large_messages):
"""Test that oldest messages are removed first during truncation"""
small_limit = 3000
result, truncation_index = truncate_messages_by_size(
large_messages, max_bytes=small_limit
)
assert len(result) < len(large_messages)
assert result[-1] == large_messages[-1]
assert truncation_index == len(large_messages) - len(result)
def test_empty_messages_list(self):
"""Test handling of empty messages list"""
result, truncation_index = truncate_messages_by_size(
[], max_bytes=MAX_GEN_AI_MESSAGE_BYTES // 500
)
assert result == []
assert truncation_index == 0
def test_find_truncation_index(
self,
):
"""Test that the truncation index is found correctly"""
# when represented in JSON, these are each 7 bytes long
messages = ["A" * 5, "B" * 5, "C" * 5, "D" * 5, "E" * 5]
truncation_index = _find_truncation_index(messages, 20)
assert truncation_index == 3
assert messages[truncation_index:] == ["D" * 5, "E" * 5]
messages = ["A" * 5, "B" * 5, "C" * 5, "D" * 5, "E" * 5]
truncation_index = _find_truncation_index(messages, 40)
assert truncation_index == 0
assert messages[truncation_index:] == [
"A" * 5,
"B" * 5,
"C" * 5,
"D" * 5,
"E" * 5,
]
def test_progressive_truncation(self, large_messages):
"""Test that truncation works progressively with different limits"""
limits = [
MAX_GEN_AI_MESSAGE_BYTES // 5,
MAX_GEN_AI_MESSAGE_BYTES // 10,
MAX_GEN_AI_MESSAGE_BYTES // 25,
MAX_GEN_AI_MESSAGE_BYTES // 100,
MAX_GEN_AI_MESSAGE_BYTES // 500,
]
prev_count = len(large_messages)
for limit in limits:
result = truncate_messages_by_size(large_messages, max_bytes=limit)
current_count = len(result)
assert current_count <= prev_count
assert current_count >= 1
prev_count = current_count
def test_single_message_truncation(self):
large_content = "This is a very long message. " * 10_000
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": large_content},
]
result, truncation_index = truncate_messages_by_size(
messages, max_single_message_chars=MAX_SINGLE_MESSAGE_CONTENT_CHARS
)
assert len(result) == 1
assert (
len(result[0]["content"].rstrip("...")) <= MAX_SINGLE_MESSAGE_CONTENT_CHARS
)
# If the last message is too large, the system message is not present
system_msgs = [m for m in result if m.get("role") == "system"]
assert len(system_msgs) == 0
# Confirm the user message is truncated with '...'
user_msgs = [m for m in result if m.get("role") == "user"]
assert len(user_msgs) == 1
assert user_msgs[0]["content"].endswith("...")
assert len(user_msgs[0]["content"]) < len(large_content)
class TestTruncateAndAnnotateMessages:
def test_no_truncation_returns_list(self, sample_messages):
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
span = MockSpan()
scope = MockScope()
result = truncate_and_annotate_messages(sample_messages, span, scope)
assert isinstance(result, list)
assert not isinstance(result, AnnotatedValue)
assert len(result) == len(sample_messages)
assert result == sample_messages
assert span.span_id not in scope._gen_ai_original_message_count
def test_truncation_sets_metadata_on_scope(self, large_messages):
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
small_limit = 3000
span = MockSpan()
scope = MockScope()
original_count = len(large_messages)
result = truncate_and_annotate_messages(
large_messages, span, scope, max_bytes=small_limit
)
assert isinstance(result, list)
assert not isinstance(result, AnnotatedValue)
assert len(result) < len(large_messages)
assert scope._gen_ai_original_message_count[span.span_id] == original_count
def test_scope_tracks_original_message_count(self, large_messages):
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
small_limit = 3000
original_count = len(large_messages)
span = MockSpan()
scope = MockScope()
result = truncate_and_annotate_messages(
large_messages, span, scope, max_bytes=small_limit
)
assert scope._gen_ai_original_message_count[span.span_id] == original_count
assert len(result) == 1
def test_empty_messages_returns_none(self):
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
span = MockSpan()
scope = MockScope()
result = truncate_and_annotate_messages([], span, scope)
assert result is None
result = truncate_and_annotate_messages(None, span, scope)
assert result is None
def test_truncated_messages_newest_first(self, large_messages):
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
small_limit = 3000
span = MockSpan()
scope = MockScope()
result = truncate_and_annotate_messages(
large_messages, span, scope, max_bytes=small_limit
)
assert isinstance(result, list)
assert result[0] == large_messages[-len(result)]
def test_preserves_original_messages_with_blobs(self):
"""Test that truncate_and_annotate_messages doesn't mutate the original messages"""
class MockSpan:
def __init__(self):
self.span_id = "test_span_id"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
messages = [
{
"role": "user",
"content": [
{"text": "What's in this image?", "type": "text"},
{
"type": "blob",
"modality": "image",
"content": "data:image/jpeg;base64,original_content",
},
],
}
]
original_blob_content = messages[0]["content"][1]["content"]
span = MockSpan()
scope = MockScope()
# This should NOT mutate the original messages
result = truncate_and_annotate_messages(messages, span, scope)
# Verify original is unchanged
assert messages[0]["content"][1]["content"] == original_blob_content
# Verify result has redacted content
assert result[0]["content"][1]["content"] == BLOB_DATA_SUBSTITUTE
class TestClientAnnotation:
def test_client_wraps_truncated_messages_in_annotated_value(self, large_messages):
"""Test that client.py properly wraps truncated messages in AnnotatedValue using scope data"""
from sentry_sdk._types import AnnotatedValue
from sentry_sdk.consts import SPANDATA
class MockSpan:
def __init__(self):
self.span_id = "test_span_123"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
small_limit = 3000
span = MockSpan()
scope = MockScope()
original_count = len(large_messages)
# Simulate what integrations do
truncated_messages = truncate_and_annotate_messages(
large_messages, span, scope, max_bytes=small_limit
)
span.set_data(SPANDATA.GEN_AI_REQUEST_MESSAGES, truncated_messages)
# Verify metadata was set on scope
assert span.span_id in scope._gen_ai_original_message_count
assert scope._gen_ai_original_message_count[span.span_id] > 0
# Simulate what client.py does
event = {"spans": [{"span_id": span.span_id, "data": span.data.copy()}]}
# Mimic client.py logic - using scope to get the original length
for event_span in event["spans"]:
span_id = event_span.get("span_id")
span_data = event_span.get("data", {})
if (
span_id
and span_id in scope._gen_ai_original_message_count
and SPANDATA.GEN_AI_REQUEST_MESSAGES in span_data
):
messages = span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES]
n_original_count = scope._gen_ai_original_message_count[span_id]
span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES] = AnnotatedValue(
safe_serialize(messages),
{"len": n_original_count},
)
# Verify the annotation happened
messages_value = event["spans"][0]["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
assert isinstance(messages_value, AnnotatedValue)
assert messages_value.metadata["len"] == original_count
assert isinstance(messages_value.value, str)
def test_annotated_value_shows_correct_original_length(self, large_messages):
"""Test that the annotated value correctly shows the original message count before truncation"""
from sentry_sdk.consts import SPANDATA
class MockSpan:
def __init__(self):
self.span_id = "test_span_456"
self.data = {}
def set_data(self, key, value):
self.data[key] = value
class MockScope:
def __init__(self):
self._gen_ai_original_message_count = {}
small_limit = 3000
span = MockSpan()
scope = MockScope()
original_message_count = len(large_messages)
truncated_messages = truncate_and_annotate_messages(
large_messages, span, scope, max_bytes=small_limit
)
assert len(truncated_messages) < original_message_count
assert span.span_id in scope._gen_ai_original_message_count
stored_original_length = scope._gen_ai_original_message_count[span.span_id]
assert stored_original_length == original_message_count
event = {
"spans": [
{
"span_id": span.span_id,
"data": {SPANDATA.GEN_AI_REQUEST_MESSAGES: truncated_messages},
}
]
}
for event_span in event["spans"]:
span_id = event_span.get("span_id")
span_data = event_span.get("data", {})
if (
span_id
and span_id in scope._gen_ai_original_message_count
and SPANDATA.GEN_AI_REQUEST_MESSAGES in span_data
):
span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES] = AnnotatedValue(
span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES],
{"len": scope._gen_ai_original_message_count[span_id]},
)
messages_value = event["spans"][0]["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
assert isinstance(messages_value, AnnotatedValue)
assert messages_value.metadata["len"] == stored_original_length
assert len(messages_value.value) == len(truncated_messages)
class TestRedactBlobMessageParts:
def test_redacts_single_blob_content(self):
"""Test that blob content is redacted without mutating original messages"""
messages = [
{
"role": "user",
"content": [
{
"text": "How many ponies do you see in the image?",
"type": "text",
},
{
"type": "blob",
"modality": "image",
"mime_type": "image/jpeg",
"content": "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
],
}
]
# Save original blob content for comparison
original_blob_content = messages[0]["content"][1]["content"]
result = redact_blob_message_parts(messages)
# Original messages should be UNCHANGED
assert messages[0]["content"][1]["content"] == original_blob_content
# Result should have redacted content
assert (
result[0]["content"][0]["text"]
== "How many ponies do you see in the image?"
)
assert result[0]["content"][0]["type"] == "text"
assert result[0]["content"][1]["type"] == "blob"
assert result[0]["content"][1]["modality"] == "image"
assert result[0]["content"][1]["mime_type"] == "image/jpeg"
assert result[0]["content"][1]["content"] == BLOB_DATA_SUBSTITUTE
def test_redacts_multiple_blob_parts(self):
"""Test that multiple blob parts are redacted without mutation"""
messages = [
{
"role": "user",
"content": [
{"text": "Compare these images", "type": "text"},
{
"type": "blob",
"modality": "image",
"mime_type": "image/jpeg",
"content": "data:image/jpeg;base64,first_image",
},
{
"type": "blob",
"modality": "image",
"mime_type": "image/png",
"content": "data:image/png;base64,second_image",
},
],
}
]
original_first = messages[0]["content"][1]["content"]
original_second = messages[0]["content"][2]["content"]
result = redact_blob_message_parts(messages)
# Original should be unchanged
assert messages[0]["content"][1]["content"] == original_first
assert messages[0]["content"][2]["content"] == original_second
# Result should be redacted
assert result[0]["content"][0]["text"] == "Compare these images"
assert result[0]["content"][1]["content"] == BLOB_DATA_SUBSTITUTE
assert result[0]["content"][2]["content"] == BLOB_DATA_SUBSTITUTE
def test_redacts_blobs_in_multiple_messages(self):
"""Test that blob parts are redacted across multiple messages without mutation"""
messages = [
{
"role": "user",
"content": [
{"text": "First message", "type": "text"},
{
"type": "blob",
"modality": "image",
"content": "data:image/jpeg;base64,first",
},
],
},
{
"role": "assistant",
"content": "I see the image.",
},
{
"role": "user",
"content": [
{"text": "Second message", "type": "text"},
{
"type": "blob",
"modality": "image",
"content": "data:image/jpeg;base64,second",
},
],
},
]
original_first = messages[0]["content"][1]["content"]
original_second = messages[2]["content"][1]["content"]
result = redact_blob_message_parts(messages)
# Original should be unchanged
assert messages[0]["content"][1]["content"] == original_first
assert messages[2]["content"][1]["content"] == original_second
# Result should be redacted
assert result[0]["content"][1]["content"] == BLOB_DATA_SUBSTITUTE
assert result[1]["content"] == "I see the image." # Unchanged
assert result[2]["content"][1]["content"] == BLOB_DATA_SUBSTITUTE
def test_no_blobs_returns_original_list(self):
"""Test that messages without blobs are returned as-is (performance optimization)"""
messages = [
{"role": "user", "content": "Simple text message"},
{"role": "assistant", "content": "Simple response"},
]
result = redact_blob_message_parts(messages)
# Should return the same list object when no blobs present
assert result is messages
def test_handles_non_dict_messages(self):
"""Test that non-dict messages are handled gracefully"""
messages = [
"string message",
{"role": "user", "content": "text"},
None,
123,
]
result = redact_blob_message_parts(messages)
# Should return same list since no blobs
assert result is messages
def test_handles_non_dict_content_items(self):
"""Test that non-dict content items in arrays are handled"""
messages = [
{
"role": "user",
"content": [
"string item",
{"text": "text item", "type": "text"},
None,
],
}
]
result = redact_blob_message_parts(messages)
# Should return same list since no blobs
assert result is messages