Skip to content
Draft
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
191 changes: 62 additions & 129 deletions sentry_sdk/ai/monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@
from typing import TYPE_CHECKING

import sentry_sdk.utils
from sentry_sdk import start_span
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
from sentry_sdk.tracing_utils import has_span_streaming_enabled
from sentry_sdk.utils import ContextVar, capture_internal_exceptions, reraise

if TYPE_CHECKING:
Expand All @@ -31,141 +29,76 @@ def get_ai_pipeline_name() -> "Optional[str]":
def ai_track(description: str, **span_kwargs: "Any") -> "Callable[[F], F]":
def decorator(f: "F") -> "F":
def sync_wrapped(*args: "Any", **kwargs: "Any") -> "Any":
client = sentry_sdk.get_client()

curr_pipeline = _ai_pipeline_name.get()
op = span_kwargs.pop("op", "ai.run" if curr_pipeline else "ai.pipeline")

if has_span_streaming_enabled(client.options):
with sentry_sdk.traces.start_span(
name=description, attributes={"sentry.op": op}
) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_attribute(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_attribute(k, v)

if curr_pipeline:
span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res

else:
with start_span(name=description, op=op, **span_kwargs) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_tag(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_data(k, v)
if curr_pipeline:
span.set_data(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res
with sentry_sdk.traces.start_span(
name=description, attributes={"sentry.op": op}
) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_attribute(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_attribute(k, v)

if curr_pipeline:
span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res

async def async_wrapped(*args: "Any", **kwargs: "Any") -> "Any":
client = sentry_sdk.get_client()

curr_pipeline = _ai_pipeline_name.get()
op = span_kwargs.pop("op", "ai.run" if curr_pipeline else "ai.pipeline")

if has_span_streaming_enabled(client.options):
with sentry_sdk.traces.start_span(
name=description, attributes={"sentry.op": op}
) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_attribute(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_attribute(k, v)

if curr_pipeline:
span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return await f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = await f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res
else:
with start_span(name=description, op=op, **span_kwargs) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_tag(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_data(k, v)
if curr_pipeline:
span.set_data(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return await f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = await f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res
with sentry_sdk.traces.start_span(
name=description, attributes={"sentry.op": op}
) as span:
for k, v in kwargs.pop("sentry_tags", {}).items():
span.set_attribute(k, v)
for k, v in kwargs.pop("sentry_data", {}).items():
span.set_attribute(k, v)

if curr_pipeline:
span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
return await f(*args, **kwargs)
else:
_ai_pipeline_name.set(description)
try:
res = await f(*args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
with capture_internal_exceptions():
event, hint = sentry_sdk.utils.event_from_exception(
e,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": "ai_monitoring",
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
reraise(*exc_info)
finally:
_ai_pipeline_name.set(None)
return res

if inspect.iscoroutinefunction(f):
return wraps(f)(async_wrapped) # type: ignore
Expand Down
29 changes: 4 additions & 25 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
from sentry_sdk.sessions import SessionFlusher
from sentry_sdk.traces import SpanStatus, StreamedSpan
from sentry_sdk.tracing import trace
from sentry_sdk.tracing_utils import has_span_streaming_enabled
from sentry_sdk.transport import (
AsyncHttpTransport,
HttpTransportCore,
Expand Down Expand Up @@ -366,24 +365,6 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]":
env_to_bool(os.environ.get("SENTRY_KEEP_ALIVE"), strict=True) or False
)

if rv["trace_ignore_status_codes"] and has_span_streaming_enabled(rv):
warnings.warn(
"The `trace_ignore_status_codes` parameter is ignored in span streaming mode.",
stacklevel=2,
)

if rv["ignore_spans"] and not has_span_streaming_enabled(rv):
warnings.warn(
"The `ignore_spans` parameter only works when `trace_lifecycle` is set to `stream`.",
stacklevel=2,
)

if rv["before_send_span"] and not has_span_streaming_enabled(rv):
warnings.warn(
"The `before_send_span` parameter only works when `trace_lifecycle` is set to `stream`.",
stacklevel=2,
)

return rv


Expand Down Expand Up @@ -646,12 +627,10 @@ def _record_lost_event(
record_lost_func=_record_lost_event,
)

self.span_batcher = None
if has_span_streaming_enabled(self.options):
self.span_batcher = SpanBatcher(
capture_func=_capture_envelope,
record_lost_func=_record_lost_event,
)
self.span_batcher = SpanBatcher(
capture_func=_capture_envelope,
record_lost_func=_record_lost_event,
)

max_request_body_size = ("always", "never", "small", "medium")
if self.options["max_request_body_size"] not in max_request_body_size:
Expand Down
16 changes: 3 additions & 13 deletions sentry_sdk/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import sentry_sdk
from sentry_sdk._lru_cache import LRUCache
from sentry_sdk.tracing import Span
from sentry_sdk.tracing_utils import has_span_streaming_enabled

if TYPE_CHECKING:
from typing import TypedDict
Expand Down Expand Up @@ -59,17 +57,9 @@ def add_feature_flag(flag: str, result: bool) -> None:
Records a flag and its value to be sent on subsequent error events.
We recommend you do this on flag evaluations. Flags are buffered per Sentry scope.
"""
client = sentry_sdk.get_client()

flags = sentry_sdk.get_isolation_scope().flags
flags.set(flag, result)

if has_span_streaming_enabled(client.options):
span = sentry_sdk.traces.get_current_span()
if span and isinstance(span, sentry_sdk.traces.StreamedSpan):
span.set_attribute(f"flag.evaluation.{flag}", result)

else:
span = sentry_sdk.get_current_span()
if span and isinstance(span, Span):
span.set_flag(f"flag.evaluation.{flag}", result)
span = sentry_sdk.traces.get_current_span()
if span and isinstance(span, sentry_sdk.traces.StreamedSpan):
span.set_attribute(f"flag.evaluation.{flag}", result)
Loading
Loading