Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions sentry_sdk/ai/monitoring.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
from typing import TYPE_CHECKING

from sentry_sdk.ai.utils import _set_span_data_attribute
from sentry_sdk.consts import SPANDATA
from sentry_sdk.traces import StreamedSpan
from sentry_sdk.tracing import Span

if TYPE_CHECKING:
from typing import Any, Awaitable, Callable, Optional, TypeVar, Union

from sentry_sdk.traces import StreamedSpan

F = TypeVar("F", bound=Union[Callable[..., Any], Callable[..., Awaitable[Any]]])


def record_token_usage(
span: "Union[Span, StreamedSpan]",
span: "StreamedSpan",
input_tokens: "Optional[int]" = None,
input_tokens_cached: "Optional[int]" = None,
input_tokens_cache_write: "Optional[int]" = None,
Expand All @@ -21,30 +20,25 @@ def record_token_usage(
total_tokens: "Optional[int]" = None,
) -> None:
if input_tokens is not None:
_set_span_data_attribute(span, SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)
span.set_attribute(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)

if input_tokens_cached is not None:
_set_span_data_attribute(
span,
span.set_attribute(
SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED,
input_tokens_cached,
)

if input_tokens_cache_write is not None:
_set_span_data_attribute(
span,
span.set_attribute(
SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE,
input_tokens_cache_write,
)

if output_tokens is not None:
_set_span_data_attribute(
span, SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens
)
span.set_attribute(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)

if output_tokens_reasoning is not None:
_set_span_data_attribute(
span,
span.set_attribute(
SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING,
output_tokens_reasoning,
)
Expand All @@ -53,4 +47,4 @@ def record_token_usage(
total_tokens = input_tokens + output_tokens

if total_tokens is not None:
_set_span_data_attribute(span, SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens)
span.set_attribute(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens)
20 changes: 5 additions & 15 deletions sentry_sdk/ai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Any, Dict, Optional, Tuple, Union
from typing import Any, Dict, Optional, Tuple

from sentry_sdk.tracing import Span
from sentry_sdk.traces import StreamedSpan

import sentry_sdk
from sentry_sdk.traces import StreamedSpan
from sentry_sdk.utils import logger


Expand Down Expand Up @@ -449,25 +448,16 @@ def _normalize_data(data: "Any", unpack: bool = True) -> "Any":


def set_data_normalized(
span: "Union[Span, StreamedSpan]",
span: "StreamedSpan",
key: str,
value: "Any",
unpack: bool = True,
) -> None:
normalized = _normalize_data(value, unpack=unpack)
if isinstance(normalized, (int, float, bool, str)):
_set_span_data_attribute(span, key, normalized)
span.set_attribute(key, normalized)
else:
_set_span_data_attribute(span, key, json.dumps(normalized))


def _set_span_data_attribute(
span: "Union[Span, StreamedSpan]", key: str, value: "Any"
) -> None:
if isinstance(span, StreamedSpan):
span.set_attribute(key, value)
else:
span.set_data(key, value)
span.set_attribute(key, json.dumps(normalized))


def normalize_message_role(role: str) -> str:
Expand Down
3 changes: 1 addition & 2 deletions sentry_sdk/integrations/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@
from aiohttp.web_urldispatcher import UrlMappingMatchInfo

from sentry_sdk._types import Attributes, Event, EventProcessor
from sentry_sdk.tracing import Span
from sentry_sdk.utils import ExcInfo


Expand Down Expand Up @@ -343,7 +342,7 @@ async def on_request_start(
parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE,
)

span: "Union[Span, StreamedSpan, None]" = None
span: "Optional[StreamedSpan]" = None
attributes: "Attributes" = {
"sentry.op": OP.HTTP_CLIENT,
"sentry.origin": AioHttpIntegration.origin,
Expand Down
23 changes: 6 additions & 17 deletions sentry_sdk/integrations/aiomysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,32 +241,21 @@ def _get_connect_data(conn: Any, *, use_streaming_keys: bool = False) -> dict[st

def _set_db_data(span: Any, conn: Any) -> None:
"""Set database-related span data from connection object."""
if isinstance(span, StreamedSpan):
set_value = span.set_attribute
db_system = SPANDATA.DB_SYSTEM_NAME
db_name = SPANDATA.DB_NAMESPACE
else:
# Remove this else block once we've completely migrated to streamed spans
# The use of deprecated attributes here is to ensure backwards compatibility
set_value = span.set_data
db_system = SPANDATA.DB_SYSTEM
db_name = SPANDATA.DB_NAME

set_value(db_system, "mysql")
set_value(SPANDATA.DB_DRIVER_NAME, "aiomysql")
span.set_attribute(SPANDATA.DB_SYSTEM_NAME, "mysql")
span.set_attribute(SPANDATA.DB_DRIVER_NAME, "aiomysql")

host = getattr(conn, "host", None)
if host is not None:
set_value(SPANDATA.SERVER_ADDRESS, host)
span.set_attribute(SPANDATA.SERVER_ADDRESS, host)

port = getattr(conn, "port", None)
if port is not None:
set_value(SPANDATA.SERVER_PORT, port)
span.set_attribute(SPANDATA.SERVER_PORT, port)

database = getattr(conn, "db", None)
if database is not None:
set_value(db_name, database)
span.set_attribute(SPANDATA.DB_NAMESPACE, database)

user = getattr(conn, "user", None)
if user is not None:
set_value(SPANDATA.DB_USER, user)
span.set_attribute(SPANDATA.DB_USER, user)
28 changes: 13 additions & 15 deletions sentry_sdk/integrations/google_genai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
)
from sentry_sdk.consts import OP, SPANDATA
from sentry_sdk.scope import should_send_default_pii
from sentry_sdk.traces import StreamedSpan
from sentry_sdk.utils import (
capture_internal_exceptions,
event_from_exception,
Expand All @@ -52,6 +51,7 @@
)

from sentry_sdk._types import TextPart
from sentry_sdk.traces import StreamedSpan

_is_PIL_available = False
try:
Expand Down Expand Up @@ -708,22 +708,21 @@ def wrapped_tool(tool: "Tool | Callable[..., Any]") -> "Tool | Callable[..., Any
@wraps(tool)
async def async_wrapped(*args: "Any", **kwargs: "Any") -> "Any":
with _create_tool_span(tool_name, tool_doc) as span:
set_on_span = (
span.set_attribute
if isinstance(span, StreamedSpan)
else span.set_data
)
# Capture tool input
tool_input = _capture_tool_input(args, kwargs, tool)
with capture_internal_exceptions():
set_on_span(SPANDATA.GEN_AI_TOOL_INPUT, safe_serialize(tool_input))
span.set_attribute(
SPANDATA.GEN_AI_TOOL_INPUT, safe_serialize(tool_input)
)

try:
result = await tool(*args, **kwargs)

# Capture tool output
with capture_internal_exceptions():
set_on_span(SPANDATA.GEN_AI_TOOL_OUTPUT, safe_serialize(result))
span.set_attribute(
SPANDATA.GEN_AI_TOOL_OUTPUT, safe_serialize(result)
)

return result
except Exception as exc:
Expand All @@ -736,22 +735,21 @@ async def async_wrapped(*args: "Any", **kwargs: "Any") -> "Any":
@wraps(tool)
def sync_wrapped(*args: "Any", **kwargs: "Any") -> "Any":
with _create_tool_span(tool_name, tool_doc) as span:
set_on_span = (
span.set_attribute
if isinstance(span, StreamedSpan)
else span.set_data
)
# Capture tool input
tool_input = _capture_tool_input(args, kwargs, tool)
with capture_internal_exceptions():
set_on_span(SPANDATA.GEN_AI_TOOL_INPUT, safe_serialize(tool_input))
span.set_attribute(
SPANDATA.GEN_AI_TOOL_INPUT, safe_serialize(tool_input)
)

try:
result = tool(*args, **kwargs)

# Capture tool output
with capture_internal_exceptions():
set_on_span(SPANDATA.GEN_AI_TOOL_OUTPUT, safe_serialize(result))
span.set_attribute(
SPANDATA.GEN_AI_TOOL_OUTPUT, safe_serialize(result)
)

return result
except Exception as exc:
Expand Down
19 changes: 7 additions & 12 deletions sentry_sdk/integrations/huggingface_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@

import sentry_sdk
from sentry_sdk.ai.monitoring import record_token_usage
from sentry_sdk.ai.utils import (
_set_span_data_attribute,
set_data_normalized,
)
from sentry_sdk.ai.utils import set_data_normalized
from sentry_sdk.consts import OP, SPANDATA
from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version
from sentry_sdk.scope import should_send_default_pii
Expand Down Expand Up @@ -106,10 +103,10 @@ def new_huggingface_task(*args: "Any", **kwargs: "Any") -> "Any":
},
)

_set_span_data_attribute(span, SPANDATA.GEN_AI_OPERATION_NAME, operation_name)
span.set_attribute(SPANDATA.GEN_AI_OPERATION_NAME, operation_name)

if model:
_set_span_data_attribute(span, SPANDATA.GEN_AI_REQUEST_MODEL, model)
span.set_attribute(SPANDATA.GEN_AI_REQUEST_MODEL, model)

attribute_mapping = {
"frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY,
Expand Down Expand Up @@ -143,7 +140,7 @@ def new_huggingface_task(*args: "Any", **kwargs: "Any") -> "Any":
value = kwargs.get(attribute, None)
if value is not None:
if isinstance(value, (int, float, bool, str)):
_set_span_data_attribute(span, span_attribute, value)
span.set_attribute(span_attribute, value)
else:
set_data_normalized(span, span_attribute, value, unpack=False)

Expand Down Expand Up @@ -204,9 +201,7 @@ def new_huggingface_task(*args: "Any", **kwargs: "Any") -> "Any":
response_text_buffer.append(choice.message.content)

if response_model is not None:
_set_span_data_attribute(
span, SPANDATA.GEN_AI_RESPONSE_MODEL, response_model
)
span.set_attribute(SPANDATA.GEN_AI_RESPONSE_MODEL, response_model)

if finish_reason is not None:
set_data_normalized(
Expand Down Expand Up @@ -380,8 +375,8 @@ def new_iterator() -> "Iterable[ChatCompletionStreamOutput]":
yield chunk

if response_model is not None:
_set_span_data_attribute(
span, SPANDATA.GEN_AI_RESPONSE_MODEL, response_model
span.set_attribute(
SPANDATA.GEN_AI_RESPONSE_MODEL, response_model
)

if finish_reason is not None:
Expand Down
20 changes: 9 additions & 11 deletions sentry_sdk/integrations/langgraph.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from functools import wraps
from typing import Any, Callable, List, Optional
from typing import TYPE_CHECKING, Any, Callable, List, Optional

import sentry_sdk
from sentry_sdk.ai.utils import (
Expand All @@ -12,13 +12,15 @@
# This is fine because langgraph depends on langchain-base, and LangchainIntegration only imports from langchain-base.
from sentry_sdk.integrations.langchain import LangchainIntegration
from sentry_sdk.scope import should_send_default_pii
from sentry_sdk.traces import StreamedSpan
from sentry_sdk.utils import (
has_data_collection_enabled,
package_version,
safe_serialize,
)

if TYPE_CHECKING:
from sentry_sdk.traces import StreamedSpan

try:
from langgraph.errors import GraphBubbleUp
from langgraph.pregel import Pregel
Expand Down Expand Up @@ -266,7 +268,7 @@ def _extract_tool_calls(messages: "Optional[List[Any]]") -> "Optional[List[Any]]
return tool_calls if tool_calls else None


def _set_usage_data(span: "sentry_sdk.tracing.Span", messages: "Any") -> None:
def _set_usage_data(span: "StreamedSpan", messages: "Any") -> None:
input_tokens = 0
output_tokens = 0
total_tokens = 0
Expand All @@ -284,24 +286,20 @@ def _set_usage_data(span: "sentry_sdk.tracing.Span", messages: "Any") -> None:
output_tokens += int(token_usage.get("completion_tokens", 0))
total_tokens += int(token_usage.get("total_tokens", 0))

set_on_span = (
span.set_attribute if isinstance(span, StreamedSpan) else span.set_data
)

if input_tokens > 0:
set_on_span(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)
span.set_attribute(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)

if output_tokens > 0:
set_on_span(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)
span.set_attribute(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)

if total_tokens > 0:
set_on_span(
span.set_attribute(
SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS,
total_tokens,
)


def _set_response_model_name(span: "sentry_sdk.tracing.Span", messages: "Any") -> None:
def _set_response_model_name(span: "StreamedSpan", messages: "Any") -> None:
if len(messages) == 0:
return

Expand Down
Loading
Loading