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
11 changes: 9 additions & 2 deletions sentry_sdk/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
Baggage,
PropagationContext,
_make_sampling_decision,
add_gen_ai_source,
has_tracing_enabled,
is_ignored_span,
)
Expand Down Expand Up @@ -1034,7 +1035,7 @@ def start_span(
sample_rate=sample_rate,
)

return Span(
span = Span(
name=name,
attributes=attributes,
active=active,
Expand All @@ -1048,6 +1049,9 @@ def start_span(
sample_rate=sample_rate,
links=links,
)
with capture_internal_exceptions():
add_gen_ai_source(span, attributes)
return span

# This is a child span; take propagation context from the parent span
with new_scope():
Expand All @@ -1073,7 +1077,7 @@ def start_span(
unsampled_reason=parent_span._unsampled_reason,
)

return Span(
span = Span(
name=name,
attributes=attributes,
active=active,
Expand All @@ -1084,6 +1088,9 @@ def start_span(
parent_sampled=parent_span.sampled,
links=links,
)
with capture_internal_exceptions():
add_gen_ai_source(span, attributes)
return span

def _update_sample_rate(self, sample_rate: float) -> None:
# If we had to adjust the sample rate when setting the sampling decision
Expand Down
36 changes: 36 additions & 0 deletions sentry_sdk/tracing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@
from sentry_sdk.utils import ParsedUrl


# Ops of spans for a single request to an LLM. They get the call site in the
# user's code, so the requests can be grouped by where they were made.
_GEN_AI_REQUEST_OPS = frozenset(
(
OP.GEN_AI_CHAT,
OP.GEN_AI_EMBEDDINGS,
OP.GEN_AI_RESPONSES,
OP.GEN_AI_TEXT_COMPLETION,
)
)

SENTRY_TRACE_REGEX = re.compile(
"^[ \t]*" # whitespace
"([0-9a-f]{32})?" # trace_id
Expand Down Expand Up @@ -367,6 +378,31 @@ def add_http_request_source(span: "sentry_sdk.traces.Span") -> None:
)


def add_gen_ai_source(
span: "sentry_sdk.traces.Span", attributes: "Optional[Attributes]"
) -> None:
"""
Adds OTel compatible source code information to a span for an LLM request.

Unlike database and HTTP spans, this runs when the span starts: a streamed
response ends the span wherever the stream is consumed, not where the
request was made.
"""
if attributes is None or attributes.get("sentry.op") not in _GEN_AI_REQUEST_OPS:
return

client = sentry_sdk.get_client()
if not client.is_active():
return

add_source(
span=span,
project_root=client.options["project_root"],
in_app_include=client.options.get("in_app_include"),
in_app_exclude=client.options.get("in_app_exclude"),
)


def extract_sentrytrace_data(
header: "Optional[str]",
) -> "Optional[Dict[str, Union[str, bool, None]]]":
Expand Down
8 changes: 8 additions & 0 deletions tests/integrations/openai/llm_wrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from openai import OpenAI
from openai.types.chat import ChatCompletion


def create_chat_completion(client: OpenAI, content: str) -> ChatCompletion:
return client.chat.completions.create(
model="some-model", messages=[{"role": "user", "content": content}]
)
137 changes: 137 additions & 0 deletions tests/integrations/openai/test_openai.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import sys

import pytest

Expand Down Expand Up @@ -87,6 +88,8 @@
from sentry_sdk.integrations.stdlib import StdlibIntegration
from sentry_sdk.utils import safe_serialize

from .llm_wrapper import create_chat_completion

try:
from unittest.mock import AsyncMock
except ImportError:
Expand Down Expand Up @@ -2449,6 +2452,140 @@ async def test_span_origin_streaming_chat_async(
assert spans[0]["attributes"]["sentry.origin"] == "auto.ai.openai"


def _streamed_chat_completion_chunks() -> "list[ChatCompletionChunk]":
return [
ChatCompletionChunk(
id="1",
choices=[
DeltaChoice(
index=0, delta=ChoiceDelta(content="hello"), finish_reason="stop"
)
],
created=100000,
model="model-id",
object="chat.completion.chunk",
),
]


def _consume_stream(stream: "Stream[ChatCompletionChunk]") -> None:
for _ in stream:
pass


def test_call_site_streaming_chat(sentry_init, capture_items):
sentry_init(
integrations=[OpenAIIntegration()],
disabled_integrations=[StdlibIntegration],
traces_sample_rate=1.0,
)

client = OpenAI(api_key="z")
returned_stream = Stream(cast_to=None, response=None, client=client)
returned_stream._iterator = _streamed_chat_completion_chunks()
client.chat.completions._post = mock.Mock(return_value=returned_stream)
items = capture_items("span")

call_line = sys._getframe().f_lineno + 1
response_stream = client.chat.completions.create(
model="some-model", messages=[{"role": "user", "content": "hello"}]
)
# The span ends here, in another function, but the call site is above.
_consume_stream(response_stream)

sentry_sdk.flush()
(span,) = [item.payload for item in items]
assert span["attributes"]["sentry.op"] == "gen_ai.chat"
assert span["attributes"][SPANDATA.CODE_FUNCTION] == "test_call_site_streaming_chat"
assert (
span["attributes"][SPANDATA.CODE_NAMESPACE]
== "tests.integrations.openai.test_openai"
)
assert (
span["attributes"][SPANDATA.CODE_FILE_PATH]
== "tests/integrations/openai/test_openai.py"
)
assert span["attributes"][SPANDATA.CODE_LINE_NUMBER] == call_line


@pytest.mark.asyncio
async def test_call_site_streaming_chat_async(
sentry_init, capture_items, async_iterator
):
sentry_init(
integrations=[OpenAIIntegration()],
disabled_integrations=[StdlibIntegration],
traces_sample_rate=1.0,
)

client = AsyncOpenAI(api_key="z")
returned_stream = AsyncStream(cast_to=None, response=None, client=client)
returned_stream._iterator = async_iterator(_streamed_chat_completion_chunks())
client.chat.completions._post = AsyncMock(return_value=returned_stream)
items = capture_items("span")

call_line = sys._getframe().f_lineno + 1
response_stream = await client.chat.completions.create(
model="some-model", messages=[{"role": "user", "content": "hello"}]
)
async for _ in response_stream:
pass

sentry_sdk.flush()
(span,) = [item.payload for item in items]
assert (
span["attributes"][SPANDATA.CODE_FUNCTION]
== "test_call_site_streaming_chat_async"
)
assert span["attributes"][SPANDATA.CODE_LINE_NUMBER] == call_line


@pytest.mark.parametrize(
"in_app_exclude, expected_function",
[
([], "create_chat_completion"),
(
["tests.integrations.openai.llm_wrapper"],
"test_call_site_skips_excluded_wrapper",
),
],
)
def test_call_site_skips_excluded_wrapper(
sentry_init,
capture_items,
nonstreaming_chat_completions_model_response,
in_app_exclude,
expected_function,
):
sentry_init(
integrations=[OpenAIIntegration()],
traces_sample_rate=1.0,
in_app_exclude=in_app_exclude,
)

client = OpenAI(api_key="z")
client.chat.completions._post = mock.Mock(
return_value=nonstreaming_chat_completions_model_response(
response_id="chat-id",
response_model="gpt-3.5-turbo",
message_content="the model response",
created=10000000,
usage=CompletionUsage(
prompt_tokens=20,
completion_tokens=10,
total_tokens=30,
),
)
)
items = capture_items("span")

create_chat_completion(client, "hello")

sentry_sdk.flush()
(span,) = [item.payload for item in items]
assert span["attributes"][SPANDATA.CODE_FUNCTION] == expected_function


def test_span_origin_embeddings(
sentry_init,
capture_items,
Expand Down
27 changes: 27 additions & 0 deletions tests/tracing/test_span_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,33 @@ def test_start_span(sentry_init, capture_items):
assert segment["status"] == "ok"


def test_start_span_gen_ai_call_site(sentry_init, capture_items):
sentry_init(
traces_sample_rate=1.0,
)

items = capture_items("span")

attributes = {"sentry.op": "gen_ai.chat"}
with sentry_sdk.start_span(name="segment"):
# Keep the call on one line: Python 3.7 reports the last line of a multi-line call.
call_line = sys._getframe().f_lineno + 1
with sentry_sdk.start_span(name="chat some-model", attributes=attributes):
pass

sentry_sdk.flush()
gen_ai_span, segment = [item.payload for item in items]

assert gen_ai_span["attributes"]["code.function"] == (
"test_start_span_gen_ai_call_site"
)
assert gen_ai_span["attributes"]["code.line.number"] == call_line
assert gen_ai_span["attributes"]["code.file.path"].endswith(
"test_span_streaming.py"
)
assert "code.function" not in segment["attributes"]


def test_start_span_no_context_manager(sentry_init, capture_items):
sentry_init(
traces_sample_rate=1.0,
Expand Down
Loading