diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index abeafdb22a..851a198bb4 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -32,6 +32,7 @@ Baggage, PropagationContext, _make_sampling_decision, + add_gen_ai_source, has_tracing_enabled, is_ignored_span, ) @@ -1034,7 +1035,7 @@ def start_span( sample_rate=sample_rate, ) - return Span( + span = Span( name=name, attributes=attributes, active=active, @@ -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(): @@ -1073,7 +1077,7 @@ def start_span( unsampled_reason=parent_span._unsampled_reason, ) - return Span( + span = Span( name=name, attributes=attributes, active=active, @@ -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 diff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py index f168403ab8..f59c734166 100644 --- a/sentry_sdk/tracing_utils.py +++ b/sentry_sdk/tracing_utils.py @@ -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 @@ -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]]]": diff --git a/tests/integrations/openai/llm_wrapper.py b/tests/integrations/openai/llm_wrapper.py new file mode 100644 index 0000000000..4d545698c2 --- /dev/null +++ b/tests/integrations/openai/llm_wrapper.py @@ -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}] + ) diff --git a/tests/integrations/openai/test_openai.py b/tests/integrations/openai/test_openai.py index 763b927b98..c95705a158 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -1,4 +1,5 @@ import json +import sys import pytest @@ -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: @@ -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, diff --git a/tests/tracing/test_span_streaming.py b/tests/tracing/test_span_streaming.py index 5e2ae35c8a..99d3a1a5d7 100644 --- a/tests/tracing/test_span_streaming.py +++ b/tests/tracing/test_span_streaming.py @@ -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,