Skip to content

Commit c6716c6

Browse files
committed
truncate simply
1 parent 80d905d commit c6716c6

File tree

1 file changed

+1
-29
lines changed

1 file changed

+1
-29
lines changed

sentry_sdk/ai/message_utils.py

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -59,35 +59,7 @@ def truncate_messages_by_size(messages, max_bytes=MAX_GEN_AI_MESSAGE_BYTES):
5959
content = last_message.get("content", "")
6060

6161
if content and isinstance(content, str):
62-
# Binary search to find the optimal content length
63-
left, right = 0, len(content)
64-
best_length = 0
65-
66-
while left <= right:
67-
mid = (left + right) // 2
68-
test_message = last_message.copy()
69-
test_message["content"] = content[:mid] + (
70-
"..." if mid < len(content) else ""
71-
)
72-
73-
test_serialized = serialize(
74-
[test_message],
75-
is_vars=False,
76-
max_value_length=round(max_bytes * 0.8),
77-
)
78-
test_json = json.dumps(test_serialized, separators=(",", ":"))
79-
test_size = len(test_json.encode("utf-8"))
80-
81-
if test_size <= max_bytes:
82-
best_length = mid
83-
left = mid + 1
84-
else:
85-
right = mid - 1
86-
87-
# Apply the truncation
88-
if best_length < len(content):
89-
last_message["content"] = content[:best_length] + "..."
90-
62+
last_message["content"] = content[: max_bytes * 0.8] + "..."
9163
truncated_messages[0] = last_message
9264

9365
return truncated_messages

0 commit comments

Comments
 (0)