Skip to content

Commit 3e62e97

Browse files
authored
Merge branch 'master' into feat/span-first
2 parents 908f2cf + 828e513 commit 3e62e97

File tree

2 files changed

+462
-4
lines changed

2 files changed

+462
-4
lines changed

sentry_sdk/integrations/anthropic.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
from collections.abc import Iterable
12
from functools import wraps
23
from typing import TYPE_CHECKING
34

45
import sentry_sdk
56
from sentry_sdk.ai.monitoring import record_token_usage
67
from sentry_sdk.ai.utils import (
8+
GEN_AI_ALLOWED_MESSAGE_ROLES,
79
set_data_normalized,
810
normalize_message_roles,
911
truncate_and_annotate_messages,
@@ -39,7 +41,7 @@
3941
raise DidNotEnable("Anthropic not installed")
4042

4143
if TYPE_CHECKING:
42-
from typing import Any, AsyncIterator, Iterator
44+
from typing import Any, AsyncIterator, Iterator, List, Optional, Union
4345
from sentry_sdk.tracing import Span
4446

4547

@@ -122,6 +124,7 @@ def _set_input_data(span, kwargs, integration):
122124
"""
123125
Set input data for the span based on the provided keyword arguments for the anthropic message creation.
124126
"""
127+
system_prompt = kwargs.get("system")
125128
messages = kwargs.get("messages")
126129
if (
127130
messages is not None
@@ -130,18 +133,40 @@ def _set_input_data(span, kwargs, integration):
130133
and integration.include_prompts
131134
):
132135
normalized_messages = []
136+
if system_prompt:
137+
system_prompt_content = None # type: Optional[Union[str, List[dict[str, Any]]]]
138+
if isinstance(system_prompt, str):
139+
system_prompt_content = system_prompt
140+
elif isinstance(system_prompt, Iterable):
141+
system_prompt_content = []
142+
for item in system_prompt:
143+
if (
144+
isinstance(item, dict)
145+
and item.get("type") == "text"
146+
and item.get("text")
147+
):
148+
system_prompt_content.append(item.copy())
149+
150+
if system_prompt_content:
151+
normalized_messages.append(
152+
{
153+
"role": GEN_AI_ALLOWED_MESSAGE_ROLES.SYSTEM,
154+
"content": system_prompt_content,
155+
}
156+
)
157+
133158
for message in messages:
134159
if (
135-
message.get("role") == "user"
160+
message.get("role") == GEN_AI_ALLOWED_MESSAGE_ROLES.USER
136161
and "content" in message
137162
and isinstance(message["content"], (list, tuple))
138163
):
139164
for item in message["content"]:
140165
if item.get("type") == "tool_result":
141166
normalized_messages.append(
142167
{
143-
"role": "tool",
144-
"content": {
168+
"role": GEN_AI_ALLOWED_MESSAGE_ROLES.TOOL,
169+
"content": { # type: ignore[dict-item]
145170
"tool_use_id": item.get("tool_use_id"),
146171
"output": item.get("content"),
147172
},

0 commit comments

Comments
 (0)