diff --git a/sentry_sdk/integrations/langchain.py b/sentry_sdk/integrations/langchain.py index bbf3002d44..521cdaeca8 100644 --- a/sentry_sdk/integrations/langchain.py +++ b/sentry_sdk/integrations/langchain.py @@ -5,6 +5,8 @@ from functools import wraps from typing import TYPE_CHECKING, NamedTuple +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai.utils import ( GEN_AI_ALLOWED_MESSAGE_ROLES, @@ -12,7 +14,7 @@ set_data_normalized, transform_content_part, ) -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version from sentry_sdk.traces import Span, _AgentFrameworkChatGenerationContext from sentry_sdk.tracing_utils import ( @@ -240,8 +242,8 @@ def _create_span( else parent, name=name, attributes={ - "sentry.op": op, - "sentry.origin": origin, + ATTRIBUTE_NAMES.SENTRY_OP: op, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: origin, }, ) @@ -249,8 +251,8 @@ def _create_span( span = sentry_sdk.start_span( name=name, attributes={ - "sentry.op": op, - "sentry.origin": origin, + ATTRIBUTE_NAMES.SENTRY_OP: op, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: origin, }, ) @@ -277,8 +279,8 @@ def _create_generation_span( else parent, name=name, attributes={ - "sentry.op": op, - "sentry.origin": origin, + ATTRIBUTE_NAMES.SENTRY_OP: op, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: origin, }, ) @@ -286,8 +288,8 @@ def _create_generation_span( context = _AgentFrameworkChatGenerationContext( name=name, attributes={ - "sentry.op": op, - "sentry.origin": origin, + ATTRIBUTE_NAMES.SENTRY_OP: op, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: origin, }, ) @@ -335,21 +337,21 @@ def on_llm_start( origin=LangchainIntegration.origin, ) - span.set_attribute(SPANDATA.GEN_AI_OPERATION_NAME, "text_completion") + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME, "text_completion") run_name = kwargs.get("name") if run_name: - span.set_attribute(SPANDATA.GEN_AI_FUNCTION_ID, run_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID, run_name) if model: span.set_attribute( - SPANDATA.GEN_AI_REQUEST_MODEL, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL, model, ) ai_system = _get_ai_system(all_params) if ai_system: - span.set_attribute(SPANDATA.GEN_AI_PROVIDER_NAME, ai_system) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME, ai_system) client = sentry_sdk.get_client() @@ -357,7 +359,7 @@ def on_llm_start( if frequency_penalty is not None: set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_FREQUENCY_PENALTY, frequency_penalty, unpack=False, ) @@ -365,14 +367,17 @@ def on_llm_start( max_tokens = all_params.get("max_tokens") if max_tokens is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, max_tokens, unpack=False + span, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS, + max_tokens, + unpack=False, ) presence_penalty = all_params.get("presence_penalty") if presence_penalty is not None: set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_PRESENCE_PENALTY, presence_penalty, unpack=False, ) @@ -380,19 +385,22 @@ def on_llm_start( temperature = all_params.get("temperature") if temperature is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TEMPERATURE, temperature, unpack=False + span, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE, + temperature, + unpack=False, ) top_k = all_params.get("top_k") if top_k is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TOP_K, top_k, unpack=False + span, ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_K, top_k, unpack=False ) top_p = all_params.get("top_p") if top_p is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TOP_P, top_p, unpack=False + span, ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P, top_p, unpack=False ) _set_tools_on_span(span, all_params.get("tools")) @@ -404,7 +412,7 @@ def on_llm_start( if function_call is not None: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, function_call, unpack=False, ) @@ -413,7 +421,7 @@ def on_llm_start( if tool_calls is not None: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, tool_calls, unpack=False, ) @@ -427,7 +435,7 @@ def on_llm_start( ] set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -464,24 +472,24 @@ def on_chat_model_start( ) span = context.span - span.set_attribute(SPANDATA.GEN_AI_OPERATION_NAME, "chat") + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME, "chat") if model: - span.set_attribute(SPANDATA.GEN_AI_REQUEST_MODEL, model) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL, model) ai_system = _get_ai_system(all_params) if ai_system: - span.set_attribute(SPANDATA.GEN_AI_PROVIDER_NAME, ai_system) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME, ai_system) agent_metadata = kwargs.get("metadata") if isinstance(agent_metadata, dict) and "lc_agent_name" in agent_metadata: span.set_attribute( - SPANDATA.GEN_AI_AGENT_NAME, agent_metadata["lc_agent_name"] + ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent_metadata["lc_agent_name"] ) run_name = kwargs.get("name") if run_name: span.set_attribute( - SPANDATA.GEN_AI_FUNCTION_ID, + ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID, run_name, ) @@ -491,7 +499,7 @@ def on_chat_model_start( if frequency_penalty is not None: set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_FREQUENCY_PENALTY, frequency_penalty, unpack=False, ) @@ -499,14 +507,17 @@ def on_chat_model_start( max_tokens = all_params.get("max_tokens") if max_tokens is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, max_tokens, unpack=False + span, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS, + max_tokens, + unpack=False, ) presence_penalty = all_params.get("presence_penalty") if presence_penalty is not None: set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_PRESENCE_PENALTY, presence_penalty, unpack=False, ) @@ -514,19 +525,22 @@ def on_chat_model_start( temperature = all_params.get("temperature") if temperature is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TEMPERATURE, temperature, unpack=False + span, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE, + temperature, + unpack=False, ) top_k = all_params.get("top_k") if top_k is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TOP_K, top_k, unpack=False + span, ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_K, top_k, unpack=False ) top_p = all_params.get("top_p") if top_p is not None: set_data_normalized( - span, SPANDATA.GEN_AI_REQUEST_TOP_P, top_p, unpack=False + span, ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P, top_p, unpack=False ) _set_tools_on_span(span, all_params.get("tools")) @@ -538,7 +552,7 @@ def on_chat_model_start( if function_call is not None: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, function_call, unpack=False, ) @@ -547,7 +561,7 @@ def on_chat_model_start( if tool_calls is not None: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, tool_calls, unpack=False, ) @@ -555,7 +569,7 @@ def on_chat_model_start( system_instructions = _get_system_instructions(messages) if len(system_instructions) > 0: span.set_attribute( - SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS, json.dumps(_transform_system_instructions(system_instructions)), ) @@ -571,7 +585,7 @@ def on_chat_model_start( normalized_messages = normalize_message_roles(normalized_messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -598,7 +612,7 @@ def on_chat_model_end( if sentry_sdk.get_client().options["data_collection"]["gen_ai"]["outputs"]: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TEXT, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, [[x.text for x in list_] for list_ in response.generations], ) @@ -635,21 +649,23 @@ def on_llm_end( finish_reason = generation.generation_info.get("finish_reason") if finish_reason is not None: span.set_attribute( - SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS, [finish_reason], ) if isinstance(generation, ChatGeneration): response_model = generation.message.response_metadata.get("model_name") if response_model is not None: - span.set_attribute(SPANDATA.GEN_AI_RESPONSE_MODEL, response_model) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL, response_model + ) if client.options["data_collection"]["gen_ai"]["outputs"]: tool_calls = getattr(generation.message, "tool_calls", None) if tool_calls is not None and tool_calls != []: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, tool_calls, unpack=False, ) @@ -657,7 +673,7 @@ def on_llm_end( if client.options["data_collection"]["gen_ai"]["outputs"]: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TEXT, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, [[x.text for x in list_] for list_ in response.generations], ) @@ -707,23 +723,25 @@ def on_tool_start( origin=LangchainIntegration.origin, ) - span.set_attribute(SPANDATA.GEN_AI_OPERATION_NAME, "execute_tool") - span.set_attribute(SPANDATA.GEN_AI_TOOL_NAME, tool_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME, "execute_tool") + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME, tool_name) tool_description = serialized.get("description") if tool_description is not None: - span.set_attribute(SPANDATA.GEN_AI_TOOL_DESCRIPTION, tool_description) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION, tool_description + ) agent_metadata = kwargs.get("metadata") if isinstance(agent_metadata, dict) and "lc_agent_name" in agent_metadata: span.set_attribute( - SPANDATA.GEN_AI_AGENT_NAME, agent_metadata["lc_agent_name"] + ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent_metadata["lc_agent_name"] ) run_name = kwargs.get("name") if run_name: span.set_attribute( - SPANDATA.GEN_AI_FUNCTION_ID, + ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID, run_name, ) @@ -734,7 +752,7 @@ def on_tool_start( set_data_normalized( span, - SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS, + ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS, kwargs.get("inputs", [input_str]), ) @@ -754,7 +772,9 @@ def on_tool_end( ) if sentry_sdk.get_client().options["data_collection"]["gen_ai"]["outputs"]: - set_data_normalized(span, SPANDATA.GEN_AI_TOOL_CALL_RESULT, output) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT, output + ) self._exit_span(span, run_id) @@ -908,26 +928,29 @@ def _record_token_usage(span: "Span", response: "LLMResult") -> None: reasoning = token_usage.reasoning if input_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS, input_tokens) if output_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens) if total_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens) if cache_read_tokens is not None: span.set_attribute( - SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cache_read_tokens + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cache_read_tokens ) if cache_creation_tokens is not None: span.set_attribute( - SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cache_creation_tokens + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, + cache_creation_tokens, ) if reasoning is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, reasoning) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, reasoning + ) def _get_request_data( @@ -1037,7 +1060,7 @@ def _set_tools_on_span(span: "Span", tools: "Any") -> None: if simplified_tools: set_data_normalized( span, - SPANDATA.GEN_AI_TOOL_DEFINITIONS, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS, simplified_tools, unpack=False, ) @@ -1133,13 +1156,13 @@ def new_invoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": with sentry_sdk.start_span( name=f"invoke_agent {run_name}" if run_name else "invoke_agent", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": LangchainIntegration.origin, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: LangchainIntegration.origin, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) as span: if run_name: - span.set_attribute(SPANDATA.GEN_AI_FUNCTION_ID, run_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID, run_name) # Run the agent result = f(self, *args, **kwargs) @@ -1152,7 +1175,7 @@ def new_invoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": normalized_messages = normalize_message_roles([input]) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -1162,7 +1185,7 @@ def new_invoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": output is not None and client.options["data_collection"]["gen_ai"]["outputs"] ): - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, output) + set_data_normalized(span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, output) return result @@ -1182,21 +1205,21 @@ def new_stream(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": span = sentry_sdk.start_span( name=f"invoke_agent {run_name}" if run_name else "invoke_agent", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": LangchainIntegration.origin, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: LangchainIntegration.origin, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) if run_name: - span.set_attribute(SPANDATA.GEN_AI_FUNCTION_ID, run_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID, run_name) input = args[0].get("input") if len(args) >= 1 else None if input is not None and client.options["data_collection"]["gen_ai"]["inputs"]: normalized_messages = normalize_message_roles([input]) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -1221,7 +1244,9 @@ def new_iterator() -> "Iterator[Any]": output is not None and client.options["data_collection"]["gen_ai"]["outputs"] ): - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, output) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, output + ) span.__exit__(None, None, None) except Exception: @@ -1245,7 +1270,9 @@ async def new_iterator_async() -> "AsyncIterator[Any]": output is not None and client.options["data_collection"]["gen_ai"]["outputs"] ): - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, output) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, output + ) span.__exit__(None, None, None) except Exception: diff --git a/sentry_sdk/integrations/langgraph.py b/sentry_sdk/integrations/langgraph.py index 114d835cd6..1110e9877f 100644 --- a/sentry_sdk/integrations/langgraph.py +++ b/sentry_sdk/integrations/langgraph.py @@ -1,12 +1,14 @@ from functools import wraps from typing import TYPE_CHECKING, Any, Callable, List, Optional +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai.utils import ( normalize_message_roles, set_data_normalized, ) -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version # This is fine because langgraph depends on langchain-base, and LangchainIntegration only imports from langchain-base. @@ -123,14 +125,14 @@ def new_invoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": with sentry_sdk.start_span( name=f"invoke_agent {graph_name}".strip() if graph_name else "invoke_agent", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": LanggraphIntegration.origin, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: LanggraphIntegration.origin, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) as span: if graph_name: - span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, graph_name) - span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, graph_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME, graph_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, graph_name) # Store input messages to later compare with output input_messages = None @@ -143,7 +145,7 @@ def new_invoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": normalized_input_messages = normalize_message_roles(input_messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_input_messages, unpack=False, ) @@ -170,14 +172,14 @@ async def new_ainvoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": with sentry_sdk.start_span( name=f"invoke_agent {graph_name}".strip() if graph_name else "invoke_agent", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": LanggraphIntegration.origin, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: LanggraphIntegration.origin, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) as span: if graph_name: - span.set_attribute(SPANDATA.GEN_AI_PIPELINE_NAME, graph_name) - span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, graph_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME, graph_name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, graph_name) input_messages = None if len(args) > 0: @@ -189,7 +191,7 @@ async def new_ainvoke(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": normalized_input_messages = normalize_message_roles(input_messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_input_messages, unpack=False, ) @@ -268,17 +270,19 @@ def _set_response_attributes( llm_response_text = _extract_llm_response_text(new_messages) if llm_response_text: - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, llm_response_text) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, llm_response_text + ) elif new_messages: - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, new_messages) + set_data_normalized(span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, new_messages) else: - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, result) + set_data_normalized(span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, result) tool_calls = _extract_tool_calls(new_messages) if tool_calls: set_data_normalized( span, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, safe_serialize(tool_calls), unpack=False, ) diff --git a/sentry_sdk/integrations/openai_agents/patches/agent_run.py b/sentry_sdk/integrations/openai_agents/patches/agent_run.py index 5080dfb9a7..794c3b778d 100644 --- a/sentry_sdk/integrations/openai_agents/patches/agent_run.py +++ b/sentry_sdk/integrations/openai_agents/patches/agent_run.py @@ -1,7 +1,8 @@ import sys from typing import TYPE_CHECKING -from sentry_sdk.consts import SPANDATA +from sentry_conventions.attributes import ATTRIBUTE_NAMES + from sentry_sdk.integrations import DidNotEnable from sentry_sdk.traces import Span from sentry_sdk.utils import capture_internal_exceptions, reraise @@ -70,7 +71,7 @@ def _maybe_start_agent_span( if not is_streaming: return span - span.set_attribute(SPANDATA.GEN_AI_RESPONSE_STREAMING, True) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_RESPONSE_STREAMING, True) return span diff --git a/sentry_sdk/integrations/openai_agents/patches/models.py b/sentry_sdk/integrations/openai_agents/patches/models.py index 1f24f26cea..c2d16e6966 100644 --- a/sentry_sdk/integrations/openai_agents/patches/models.py +++ b/sentry_sdk/integrations/openai_agents/patches/models.py @@ -3,8 +3,9 @@ from functools import wraps from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import SPANDATA from sentry_sdk.integrations import DidNotEnable from sentry_sdk.traces import BAGGAGE_HEADER_NAME, Span from sentry_sdk.tracing_utils import ( @@ -139,7 +140,9 @@ async def wrapped_stream_response(*args: "Any", **kwargs: "Any") -> "Any": for hosted_tool in hosted_tools: _inject_trace_propagation_headers(hosted_tool, span=context.span) - context.span.set_attribute(SPANDATA.GEN_AI_RESPONSE_STREAMING, True) + context.span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_STREAMING, True + ) streaming_response = None ttft_recorded = False @@ -151,7 +154,7 @@ async def wrapped_stream_response(*args: "Any", **kwargs: "Any") -> "Any": if not ttft_recorded and hasattr(event, "delta"): ttft = time.perf_counter() - start_time context.span.set_attribute( - SPANDATA.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, ttft + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, ttft ) ttft_recorded = True diff --git a/sentry_sdk/integrations/openai_agents/patches/runner.py b/sentry_sdk/integrations/openai_agents/patches/runner.py index 1c7d3abe13..bf90361cb4 100644 --- a/sentry_sdk/integrations/openai_agents/patches/runner.py +++ b/sentry_sdk/integrations/openai_agents/patches/runner.py @@ -1,8 +1,9 @@ import sys from functools import wraps +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import SPANDATA from sentry_sdk.integrations import DidNotEnable from sentry_sdk.utils import ( capture_internal_exceptions, @@ -57,7 +58,9 @@ async def on_tool_start( if not client.options["data_collection"]["gen_ai"]["inputs"]: return - span.set_attribute(SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS, context.tool_arguments) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS, context.tool_arguments + ) async def on_tool_end( self, diff --git a/sentry_sdk/integrations/openai_agents/spans/ai_client.py b/sentry_sdk/integrations/openai_agents/spans/ai_client.py index 0ece07965b..ac3e4e1af6 100644 --- a/sentry_sdk/integrations/openai_agents/spans/ai_client.py +++ b/sentry_sdk/integrations/openai_agents/spans/ai_client.py @@ -1,8 +1,10 @@ import json from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.integrations import DidNotEnable from sentry_sdk.traces import Span, _AgentFrameworkChatGenerationContext @@ -210,14 +212,14 @@ def ai_client_context( context = _AgentFrameworkChatGenerationContext( name=f"chat {model_name}", attributes={ - "sentry.op": OP.GEN_AI_CHAT, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "chat", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_CHAT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "chat", }, ) - context.span.set_attribute(SPANDATA.GEN_AI_PROVIDER_NAME, "openai") - context.span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, agent.name) + context.span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME, "openai") + context.span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent.name) request_model_name: "Optional[str]" = None if isinstance(agent.model, Model) and hasattr(agent.model, "model"): @@ -228,38 +230,40 @@ def ai_client_context( request_model_name = agent._sentry_request_model if request_model_name: - context.span.set_attribute(SPANDATA.GEN_AI_REQUEST_MODEL, request_model_name) + context.span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL, request_model_name + ) if agent.model_settings.max_tokens: context.span.set_attribute( - SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, agent.model_settings.max_tokens + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS, agent.model_settings.max_tokens ) if agent.model_settings.presence_penalty: context.span.set_attribute( - SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_PRESENCE_PENALTY, agent.model_settings.presence_penalty, ) if agent.model_settings.temperature: context.span.set_attribute( - SPANDATA.GEN_AI_REQUEST_TEMPERATURE, agent.model_settings.temperature + ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE, agent.model_settings.temperature ) if agent.model_settings.top_p: context.span.set_attribute( - SPANDATA.GEN_AI_REQUEST_TOP_P, agent.model_settings.top_p + ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P, agent.model_settings.top_p ) if agent.model_settings.frequency_penalty: context.span.set_attribute( - SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_FREQUENCY_PENALTY, agent.model_settings.frequency_penalty, ) if client_options["data_collection"]["gen_ai"]["inputs"]: context.span.set_attribute( - SPANDATA.GEN_AI_TOOL_DEFINITIONS, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS, json.dumps(_transform_tool_definitions(agent.tools)), ) @@ -282,12 +286,12 @@ def update_ai_client_span( _set_output_data(span, response) if response_model is not None: - span.set_attribute(SPANDATA.GEN_AI_RESPONSE_MODEL, response_model) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL, response_model) elif hasattr(response, "model") and response.model: - span.set_attribute(SPANDATA.GEN_AI_RESPONSE_MODEL, str(response.model)) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL, str(response.model)) # Set conversation ID from agent if available if agent: conv_id = getattr(agent, "_sentry_conversation_id", None) if conv_id: - span.set_attribute(SPANDATA.GEN_AI_CONVERSATION_ID, conv_id) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID, conv_id) diff --git a/sentry_sdk/integrations/openai_agents/spans/execute_tool.py b/sentry_sdk/integrations/openai_agents/spans/execute_tool.py index 4104f602fe..3add2c36df 100644 --- a/sentry_sdk/integrations/openai_agents/spans/execute_tool.py +++ b/sentry_sdk/integrations/openai_agents/spans/execute_tool.py @@ -1,7 +1,9 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.traces import Span, SpanStatus from ..consts import SPAN_ORIGIN @@ -18,11 +20,11 @@ def execute_tool_span( return sentry_sdk.start_span( name=f"execute_tool {tool.name}", attributes={ - "sentry.op": OP.GEN_AI_EXECUTE_TOOL, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "execute_tool", - SPANDATA.GEN_AI_TOOL_NAME: tool.name, - SPANDATA.GEN_AI_TOOL_DESCRIPTION: tool.description, + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_EXECUTE_TOOL, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "execute_tool", + ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME: tool.name, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION: tool.description, }, ) @@ -35,7 +37,7 @@ def update_execute_tool_span( ) -> None: client = sentry_sdk.get_client() - span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, agent.name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent.name) if isinstance(result, str) and result.startswith( "An error occurred while running the tool" @@ -43,9 +45,9 @@ def update_execute_tool_span( span.status = SpanStatus.ERROR if client.options["data_collection"]["gen_ai"]["outputs"]: - span.set_attribute(SPANDATA.GEN_AI_TOOL_CALL_RESULT, result) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT, result) # Add conversation ID from agent conv_id = getattr(agent, "_sentry_conversation_id", None) if conv_id: - span.set_attribute(SPANDATA.GEN_AI_CONVERSATION_ID, conv_id) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID, conv_id) diff --git a/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py b/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py index 9da8223ba1..30a5a6c64b 100644 --- a/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +++ b/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py @@ -1,11 +1,13 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai.utils import ( normalize_message_roles, set_data_normalized, ) -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.traces import Span from sentry_sdk.utils import safe_serialize @@ -25,9 +27,9 @@ def invoke_agent_span( span = sentry_sdk.start_span( name=f"invoke_agent {agent.name}", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) @@ -64,12 +66,12 @@ def invoke_agent_span( normalized_messages = normalize_message_roles(messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) - span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, agent.name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent.name) return span @@ -81,9 +83,11 @@ def update_invoke_agent_span( ) -> None: client = sentry_sdk.get_client() if client.options["data_collection"]["gen_ai"]["outputs"]: - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, output, unpack=False) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, output, unpack=False + ) # Add conversation ID from agent conv_id = getattr(agent, "_sentry_conversation_id", None) if conv_id: - span.set_attribute(SPANDATA.GEN_AI_CONVERSATION_ID, conv_id) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID, conv_id) diff --git a/sentry_sdk/integrations/openai_agents/utils.py b/sentry_sdk/integrations/openai_agents/utils.py index e19e399f4e..807cc29486 100644 --- a/sentry_sdk/integrations/openai_agents/utils.py +++ b/sentry_sdk/integrations/openai_agents/utils.py @@ -1,6 +1,8 @@ import json from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai._openai_responses_api import ( _get_system_instructions, @@ -13,7 +15,6 @@ normalize_message_roles, set_data_normalized, ) -from sentry_sdk.consts import SPANDATA from sentry_sdk.traces import Span from sentry_sdk.utils import ( event_from_exception, @@ -37,17 +38,17 @@ def _capture_exception(exc: "Any") -> None: def _set_usage_data(span: "Span", usage: "Usage") -> None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens) span.set_attribute( - SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, usage.input_tokens_details.cached_tokens, ) - span.set_attribute(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens) span.set_attribute( - SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.output_tokens_details.reasoning_tokens, ) - span.set_attribute(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens) def _set_input_data( @@ -78,7 +79,7 @@ def _set_input_data( if len(instructions_text_parts) > 0: span.set_attribute( - SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS, json.dumps(instructions_text_parts), ) @@ -120,7 +121,7 @@ def _set_input_data( normalized_messages = normalize_message_roles(request_messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -150,11 +151,11 @@ def _set_output_data(span: "Span", result: "Any") -> None: if len(output_messages["tool"]) > 0: span.set_attribute( - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, safe_serialize(output_messages["tool"]), ) if len(output_messages["response"]) > 0: set_data_normalized( - span, SPANDATA.GEN_AI_RESPONSE_TEXT, output_messages["response"] + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, output_messages["response"] ) diff --git a/sentry_sdk/integrations/pydantic_ai/spans/ai_client.py b/sentry_sdk/integrations/pydantic_ai/spans/ai_client.py index 8e1e4a2366..b4016166b6 100644 --- a/sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +++ b/sentry_sdk/integrations/pydantic_ai/spans/ai_client.py @@ -1,12 +1,14 @@ import json from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai.utils import ( normalize_message_roles, set_data_normalized, ) -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.traces import Span, _AgentFrameworkChatGenerationContext from sentry_sdk.utils import safe_serialize @@ -108,7 +110,7 @@ def _set_input_messages(span: "Span", messages: "list[ModelMessage]") -> None: permanent_instructions, current_instructions = _get_system_instructions(messages) if len(permanent_instructions) > 0 or len(current_instructions) > 0: span.set_attribute( - SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS, json.dumps( _transform_system_instructions( permanent_instructions, current_instructions @@ -200,7 +202,7 @@ def _set_input_messages(span: "Span", messages: "list[ModelMessage]") -> None: normalized_messages = normalize_message_roles(formatted_messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -217,7 +219,7 @@ def _set_output_data( if not response: return - span.set_attribute(SPANDATA.GEN_AI_RESPONSE_MODEL, response.model_name) # type: ignore[arg-type] + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL, response.model_name) # type: ignore[arg-type] if not sentry_sdk.get_client().options["data_collection"]["gen_ai"]["outputs"]: return @@ -254,7 +256,7 @@ def _set_output_data( if parts: span.set_attribute( - SPANDATA.GEN_AI_OUTPUT_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_OUTPUT_MESSAGES, json.dumps([{"role": "assistant", "parts": parts}]), ) @@ -282,9 +284,9 @@ def ai_client_context( context = _AgentFrameworkChatGenerationContext( name=f"chat {model_name}", attributes={ - "sentry.op": OP.GEN_AI_CHAT, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "chat", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_CHAT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "chat", }, ) @@ -298,12 +300,14 @@ def ai_client_context( if model_obj: # Set system from model if hasattr(model_obj, "system"): - context.span.set_attribute(SPANDATA.GEN_AI_PROVIDER_NAME, model_obj.system) + context.span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME, model_obj.system + ) # Set model name model_name = _get_model_name(model_obj) if model_name: - context.span.set_attribute(SPANDATA.GEN_AI_REQUEST_MODEL, model_name) + context.span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL, model_name) # Extract model settings settings = model_settings @@ -312,11 +316,11 @@ def ai_client_context( if settings: settings_map = { - "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, - "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE, - "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P, - "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, - "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, + "max_tokens": ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS, + "temperature": ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE, + "top_p": ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P, + "frequency_penalty": ATTRIBUTE_NAMES.GEN_AI_REQUEST_FREQUENCY_PENALTY, + "presence_penalty": ATTRIBUTE_NAMES.GEN_AI_REQUEST_PRESENCE_PENALTY, } # ModelSettings is a TypedDict (dict at runtime), so use dict access diff --git a/sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py b/sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py index 13583cdb23..435b0e96ab 100644 --- a/sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +++ b/sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py @@ -1,7 +1,9 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.traces import Span from sentry_sdk.utils import safe_serialize @@ -32,16 +34,16 @@ def execute_tool_span( span = sentry_sdk.start_span( name=f"execute_tool {tool_name}", attributes={ - "sentry.op": OP.GEN_AI_EXECUTE_TOOL, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "execute_tool", - SPANDATA.GEN_AI_TOOL_NAME: tool_name, + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_EXECUTE_TOOL, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "execute_tool", + ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME: tool_name, }, ) if tool_definition is not None and hasattr(tool_definition, "description"): span.set_attribute( - SPANDATA.GEN_AI_TOOL_DESCRIPTION, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION, tool_definition.description, ) @@ -53,7 +55,9 @@ def execute_tool_span( ): return span - span.set_attribute(SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS, safe_serialize(tool_args)) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS, safe_serialize(tool_args) + ) return span @@ -69,4 +73,4 @@ def update_execute_tool_span(span: "Span", result: "Any") -> None: ): return - span.set_attribute(SPANDATA.GEN_AI_TOOL_CALL_RESULT, safe_serialize(result)) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT, safe_serialize(result)) diff --git a/sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py b/sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py index c197966000..2ed060b2d0 100644 --- a/sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +++ b/sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py @@ -1,11 +1,13 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk from sentry_sdk.ai.utils import ( normalize_message_roles, set_data_normalized, ) -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.traces import Span from ..consts import SPAN_ORIGIN @@ -45,9 +47,9 @@ def invoke_agent_span( span = sentry_sdk.start_span( name=f"invoke_agent {name}", attributes={ - "sentry.op": OP.GEN_AI_INVOKE_AGENT, - "sentry.origin": SPAN_ORIGIN, - SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + ATTRIBUTE_NAMES.SENTRY_OP: OP.GEN_AI_INVOKE_AGENT, + ATTRIBUTE_NAMES.SENTRY_ORIGIN: SPAN_ORIGIN, + ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME: "invoke_agent", }, ) @@ -120,7 +122,7 @@ def invoke_agent_span( normalized_messages = normalize_message_roles(messages) set_data_normalized( span, - SPANDATA.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, normalized_messages, unpack=False, ) @@ -145,4 +147,6 @@ def update_invoke_agent_span( ): return - set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, str(output), unpack=False) + set_data_normalized( + span, ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT, str(output), unpack=False + ) diff --git a/sentry_sdk/integrations/pydantic_ai/spans/utils.py b/sentry_sdk/integrations/pydantic_ai/spans/utils.py index b48fc788fa..71a339b5bc 100644 --- a/sentry_sdk/integrations/pydantic_ai/spans/utils.py +++ b/sentry_sdk/integrations/pydantic_ai/spans/utils.py @@ -2,10 +2,11 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + from sentry_sdk._types import BLOB_DATA_SUBSTITUTE from sentry_sdk.ai.consts import DATA_URL_BASE64_REGEX from sentry_sdk.ai.utils import get_modality_from_mime_type -from sentry_sdk.consts import SPANDATA if TYPE_CHECKING: from typing import Any, Dict, Union @@ -63,23 +64,30 @@ def _set_usage_data( return if hasattr(usage, "input_tokens") and usage.input_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens + ) # Pydantic AI uses cache_read_tokens (not input_tokens_cached) if hasattr(usage, "cache_read_tokens") and usage.cache_read_tokens is not None: span.set_attribute( - SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, usage.cache_read_tokens + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, + usage.cache_read_tokens, ) # Pydantic AI uses cache_write_tokens (not input_tokens_cache_write) if hasattr(usage, "cache_write_tokens") and usage.cache_write_tokens is not None: span.set_attribute( - SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, usage.cache_write_tokens, ) if hasattr(usage, "output_tokens") and usage.output_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens + ) if hasattr(usage, "total_tokens") and usage.total_tokens is not None: - span.set_attribute(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens) + span.set_attribute( + ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens + ) diff --git a/sentry_sdk/integrations/pydantic_ai/utils.py b/sentry_sdk/integrations/pydantic_ai/utils.py index 837c16a171..e09e2fd7f5 100644 --- a/sentry_sdk/integrations/pydantic_ai/utils.py +++ b/sentry_sdk/integrations/pydantic_ai/utils.py @@ -1,7 +1,8 @@ from typing import TYPE_CHECKING +from sentry_conventions.attributes import ATTRIBUTE_NAMES + import sentry_sdk -from sentry_sdk.consts import SPANDATA from sentry_sdk.traces import Span from sentry_sdk.utils import ( event_from_exception, @@ -23,7 +24,7 @@ def _set_agent_data(span: "Span", agent: "Optional[Agent]") -> None: agent: Agent object """ if agent and hasattr(agent, "name") and agent.name: - span.set_attribute(SPANDATA.GEN_AI_AGENT_NAME, agent.name) + span.set_attribute(ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME, agent.name) def _get_model_name( @@ -88,7 +89,7 @@ def _set_available_tools(span: "Span", agent: "Optional[Agent[Any, Any]]") -> No if tools: span.set_attribute( - SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools) + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools) ) except Exception: diff --git a/tests/integrations/langchain/test_langchain.py b/tests/integrations/langchain/test_langchain.py index a1ee29d24e..8521430393 100644 --- a/tests/integrations/langchain/test_langchain.py +++ b/tests/integrations/langchain/test_langchain.py @@ -4,8 +4,7 @@ from unittest.mock import Mock, patch import pytest - -from sentry_sdk.consts import SPANDATA +from sentry_conventions.attributes import ATTRIBUTE_NAMES try: # Langchain >= 0.2 @@ -343,22 +342,27 @@ def test_langchain_text_completion( llm_spans = [ span for span in spans - if span["attributes"].get("sentry.op") == "gen_ai.text_completion" + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.text_completion" ] assert len(llm_spans) > 0 llm_span = llm_spans[0] assert llm_span["name"] == "text_completion gpt-3.5-turbo" - assert llm_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert llm_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" - assert llm_span["attributes"]["gen_ai.request.model"] == "gpt-3.5-turbo" + assert llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + assert ( + llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" + ) + assert ( + llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" + ) assert ( - llm_span["attributes"]["gen_ai.response.text"] + llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == "The capital of France is Paris." ) - assert llm_span["attributes"]["gen_ai.usage.total_tokens"] == 25 - assert llm_span["attributes"]["gen_ai.usage.input_tokens"] == 10 - assert llm_span["attributes"]["gen_ai.usage.output_tokens"] == 15 + assert llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 25 + assert llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + assert llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 15 def test_langchain_chat_with_run_name( @@ -419,10 +423,13 @@ def test_langchain_chat_with_run_name( sentry_sdk.flush() spans = [item.payload for item in items] - chat_spans = list(x for x in spans if x["attributes"]["sentry.op"] == "gen_ai.chat") + chat_spans = list( + x for x in spans if x["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.chat" + ) assert len(chat_spans) == 1 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_FUNCTION_ID] == "my-snazzy-pipeline" + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" ) @@ -471,15 +478,20 @@ def test_langchain_multi_choice_response( sentry_sdk.flush() spans = [item.payload for item in items] - chat_spans = list(x for x in spans if x["attributes"]["sentry.op"] == "gen_ai.chat") + chat_spans = list( + x for x in spans if x["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.chat" + ) assert len(chat_spans) == 1 - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 10 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 25 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 30 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 25 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 30 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 4 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 4 ) @@ -508,11 +520,14 @@ def test_langchain_tool_call_with_run_name( sentry_sdk.flush() spans = [item.payload for item in items] tool_spans = list( - x for x in spans if x["attributes"]["sentry.op"] == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.execute_tool" ) assert len(tool_spans) == 1 assert ( - tool_spans[0]["attributes"][SPANDATA.GEN_AI_FUNCTION_ID] == "my-snazzy-pipeline" + tool_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" ) @@ -625,40 +640,62 @@ def test_langchain_create_agent( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) assert len(chat_spans) == 1 - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" - assert chat_spans[0]["attributes"]["gen_ai.agent.name"] == "word_length_agent" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 10 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 20 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 30 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 20 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 30 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 4 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 4 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 6 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 5 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 5 ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4" + ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == "Hello, how can I help you?" ) assert json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] ) == [ { "role": "user", @@ -671,7 +708,7 @@ def test_langchain_create_agent( ] assert expected_system_instructions == json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS] ) @@ -751,38 +788,64 @@ def test_langchain_create_agent_no_sensitive_data( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) assert len(chat_spans) == 1 - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" - assert chat_spans[0]["attributes"]["gen_ai.agent.name"] == "word_length_agent" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 10 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 20 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 30 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 20 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 30 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 4 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 4 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 6 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 5 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 5 ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4" + ) - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get( "attributes", {} ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get("attributes", {}) @pytest.mark.skipif( @@ -886,73 +949,126 @@ def test_tool_execution_span( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) assert len(chat_spans) == 2 tool_exec_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(tool_exec_spans) == 1 tool_exec_span = tool_exec_spans[0] - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert chat_spans[0]["attributes"]["gen_ai.agent.name"] == "word_length_agent" - assert chat_spans[1]["attributes"]["gen_ai.agent.name"] == "word_length_agent" - assert tool_exec_span["attributes"]["gen_ai.agent.name"] == "word_length_agent" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 142 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 192 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 69 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 69 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 31 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 10 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 10 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" ) - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 28 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 117 assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 69 + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 69 ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 10 ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 11 + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 11 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" ) - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4-0613" + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4-0613" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4-0613" + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4-0613" ) - assert "word" in tool_exec_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] + assert ( + "word" + in tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] + ) - assert "5" in chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + assert "5" in chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get("attributes", {}) - tool_calls_data = chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get( + "attributes", {} + ) + tool_calls_data = chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] assert isinstance(tool_calls_data, str) assert "get_word_length" in tool_calls_data for chat_span in chat_spans: - tools_data = chat_span["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS] + tools_data = chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] assert "get_word_length" in tools_data @@ -1057,75 +1173,131 @@ def test_tool_execution_span_no_sensitive_data( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) assert len(chat_spans) == 2 tool_exec_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(tool_exec_spans) == 1 tool_exec_span = tool_exec_spans[0] - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert chat_spans[0]["attributes"]["gen_ai.agent.name"] == "word_length_agent" - assert chat_spans[1]["attributes"]["gen_ai.agent.name"] == "word_length_agent" - assert tool_exec_span["attributes"]["gen_ai.agent.name"] == "word_length_agent" + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "word_length_agent" + ) - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 142 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 192 assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 69 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 69 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 31 ) assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 10 + chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 10 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" ) - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 28 + assert chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 117 assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 69 + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] + == 69 ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS + ] == 10 ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] == 11 + chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] + == 11 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == "openai-chat" ) - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4-0613" + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4-0613" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gpt-4-0613" + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4-0613" ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get( "attributes", {} ) - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( "attributes", {} ) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( "attributes", {} ) @@ -1250,56 +1422,102 @@ def test_langchain_openai_tools_agent( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) tool_exec_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(chat_spans) == 2 - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) # We can't guarantee anything about the "shape" of the langchain execution graph assert ( - len(list(x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat")) + len( + list( + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ) + ) > 0 ) # Token usage is only available in newer versions of langchain (v0.2+) # where usage_metadata is supported on AIMessageChunk - if "gen_ai.usage.input_tokens" in chat_spans[0]["attributes"]: - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[0]["attributes"]: + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] + == 142 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 50 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 192 + ) - if "gen_ai.usage.input_tokens" in chat_spans[1]["attributes"]: - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[1]["attributes"]: + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 28 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 117 + ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) - assert "5" in chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] - assert "word" in tool_exec_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] - assert 5 == int(tool_exec_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_RESULT]) + assert "5" in chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] + assert ( + "word" + in tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] + ) + assert 5 == int( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT] + ) assert json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] ) == [ { "role": "user", @@ -1308,13 +1526,17 @@ def test_langchain_openai_tools_agent( ] assert expected_system_instructions == json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS] ) - assert "5" in chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + assert "5" in chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get("attributes", {}) - tool_calls_data = chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get( + "attributes", {} + ) + tool_calls_data = chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] assert isinstance(tool_calls_data, (list, str)) # Could be serialized if isinstance(tool_calls_data, str): @@ -1325,15 +1547,15 @@ def test_langchain_openai_tools_agent( assert "get_word_length" in tool_call_str # Verify finish_reasons is always an array of strings - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "function_call" - ] - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "stop" - ] + assert chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["function_call"] + assert chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["stop"] for chat_span in chat_spans: - tools_data = chat_span["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS] + tools_data = chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] assert tools_data is not None assert "get_word_length" in tools_data @@ -1409,81 +1631,135 @@ def test_langchain_openai_tools_agent_no_sensitive_data( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) tool_exec_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(chat_spans) == 2 - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert invoke_agent_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" + ) # We can't guarantee anything about the "shape" of the langchain execution graph assert ( - len(list(x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat")) + len( + list( + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ) + ) > 0 ) # Token usage is only available in newer versions of langchain (v0.2+) # where usage_metadata is supported on AIMessageChunk - if "gen_ai.usage.input_tokens" in chat_spans[0]["attributes"]: - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[0]["attributes"]: + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] + == 142 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 50 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 192 + ) - if "gen_ai.usage.input_tokens" in chat_spans[1]["attributes"]: - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[1]["attributes"]: + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 28 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 117 + ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get( "attributes", {} ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[1].get( + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[1].get( "attributes", {} ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get( "attributes", {} ) - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( "attributes", {} ) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( "attributes", {} ) # Verify finish_reasons is always an array of strings - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "function_call" - ] - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "stop" - ] + assert chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["function_call"] + assert chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["stop"] def test_langchain_openai_tools_agent_with_config( @@ -1558,9 +1834,14 @@ def test_langchain_openai_tools_agent_with_config( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" ) - assert invoke_agent_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" def test_langchain_openai_tools_agent_stream_no_sensitive_data( @@ -1634,83 +1915,137 @@ def test_langchain_openai_tools_agent_stream_no_sensitive_data( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) tool_exec_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(chat_spans) == 2 - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert invoke_agent_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" + ) sentry_sdk.flush() spans = [item.payload for item in items] # We can't guarantee anything about the "shape" of the langchain execution graph assert ( - len(list(x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat")) + len( + list( + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ) + ) > 0 ) # Token usage is only available in newer versions of langchain (v0.2+) # where usage_metadata is supported on AIMessageChunk - if "gen_ai.usage.input_tokens" in chat_spans[0]["attributes"]: - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[0]["attributes"]: + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] + == 142 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 50 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 192 + ) - if "gen_ai.usage.input_tokens" in chat_spans[1]["attributes"]: - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[1]["attributes"]: + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 28 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 117 + ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get( "attributes", {} ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get("attributes", {}) - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_spans[1].get( + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( "attributes", {} ) - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get("attributes", {}) - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_exec_span.get( + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get( "attributes", {} ) - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_exec_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get( "attributes", {} ) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get( "attributes", {} ) # Verify finish_reasons is always an array of strings - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "function_call" - ] - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "stop" - ] + assert chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["function_call"] + assert chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["stop"] @pytest.mark.parametrize( @@ -1835,58 +2170,107 @@ def test_langchain_openai_tools_agent_stream( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) chat_spans = list( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ) tool_exec_span = next( - x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.execute_tool" + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) assert len(chat_spans) == 2 - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[0]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert chat_spans[1]["attributes"]["sentry.origin"] == "auto.ai.langchain" - assert tool_exec_span["attributes"]["sentry.origin"] == "auto.ai.langchain" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) + assert ( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.langchain" + ) - assert invoke_agent_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" + ) # We can't guarantee anything about the "shape" of the langchain execution graph assert ( - len(list(x for x in spans if x["attributes"].get("sentry.op") == "gen_ai.chat")) + len( + list( + x + for x in spans + if x["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ) + ) > 0 ) # Token usage is only available in newer versions of langchain (v0.2+) # where usage_metadata is supported on AIMessageChunk - if "gen_ai.usage.input_tokens" in chat_spans[0]["attributes"]: - assert chat_spans[0]["attributes"]["gen_ai.usage.input_tokens"] == 142 - assert chat_spans[0]["attributes"]["gen_ai.usage.output_tokens"] == 50 - assert chat_spans[0]["attributes"]["gen_ai.usage.total_tokens"] == 192 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[0]["attributes"]: + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] + == 142 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 50 + ) + assert ( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 192 + ) - if "gen_ai.usage.input_tokens" in chat_spans[1]["attributes"]: - assert chat_spans[1]["attributes"]["gen_ai.usage.input_tokens"] == 89 - assert chat_spans[1]["attributes"]["gen_ai.usage.output_tokens"] == 28 - assert chat_spans[1]["attributes"]["gen_ai.usage.total_tokens"] == 117 + if ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[1]["attributes"]: + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 89 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] + == 28 + ) + assert ( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] + == 117 + ) if LANGCHAIN_OPENAI_VERSION >= (0, 3, 13): assert ( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) assert ( - chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_MODEL] + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-3.5-turbo" ) - assert "5" in chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] - assert "word" in tool_exec_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] - assert 5 == int(tool_exec_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_RESULT]) + assert "5" in chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] + assert ( + "word" + in tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] + ) + assert 5 == int( + tool_exec_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT] + ) assert json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] ) == [ { "role": "user", @@ -1895,13 +2279,17 @@ def test_langchain_openai_tools_agent_stream( ] assert expected_system_instructions == json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS] ) - assert "5" in chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + assert "5" in chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get("attributes", {}) - tool_calls_data = chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get( + "attributes", {} + ) + tool_calls_data = chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] assert isinstance(tool_calls_data, (list, str)) # Could be serialized if isinstance(tool_calls_data, str): @@ -1912,15 +2300,15 @@ def test_langchain_openai_tools_agent_stream( assert "get_word_length" in tool_call_str # Verify finish_reasons is always an array of strings - assert chat_spans[0]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "function_call" - ] - assert chat_spans[1]["attributes"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == [ - "stop" - ] + assert chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["function_call"] + assert chat_spans[1]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_FINISH_REASONS + ] == ["stop"] for chat_span in chat_spans: - tools_data = chat_span["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS] + tools_data = chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] assert tools_data is not None assert "get_word_length" in tools_data @@ -1997,9 +2385,14 @@ def test_langchain_openai_tools_agent_stream_with_config( sentry_sdk.flush() spans = [item.payload for item in items] invoke_agent_span = next( - x for x in spans if x["attributes"]["sentry.op"] == "gen_ai.invoke_agent" + x + for x in spans + if x["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_FUNCTION_ID] + == "my-snazzy-pipeline" ) - assert invoke_agent_span["attributes"]["gen_ai.function_id"] == "my-snazzy-pipeline" def test_langchain_error( @@ -2486,15 +2879,15 @@ def _llm_type(self) -> str: gen_ai_spans = [ span for span in spans - if span["attributes"].get("sentry.op", "").startswith("gen_ai") + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "").startswith("gen_ai") ] # Check if any span has message data with normalized roles for span in gen_ai_spans: span_data = span.get("attributes", {}) - if SPANDATA.GEN_AI_REQUEST_MESSAGES in span_data: + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in span_data: message_data_found = True - messages_data = span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES] + messages_data = span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] # Parse the message data (might be JSON string) if isinstance(messages_data, str): @@ -2862,16 +3255,21 @@ def test_langchain_ai_system_detection( llm_spans = [ span for span in spans - if span["attributes"].get("sentry.op") == "gen_ai.text_completion" + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.text_completion" ] assert len(llm_spans) > 0 llm_span = llm_spans[0] if expected_system is not None: - assert llm_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == expected_system + assert ( + llm_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] + == expected_system + ) else: - assert SPANDATA.GEN_AI_PROVIDER_NAME not in llm_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME not in llm_span.get( + "attributes", {} + ) class TestTransformLangchainMessageContent: @@ -2996,22 +3394,22 @@ def test_transform_list_with_legacy_image_url(self): pytest.param( {"gen_ai": {"inputs": True, "outputs": False}}, { - SPANDATA.GEN_AI_REQUEST_MESSAGES: [ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES: [ {"role": "user", "content": "How many letters in the word eudca"} ], - SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS: [ + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS: [ {"type": "text", "content": "You are a helpful assistant."} ], }, - [SPANDATA.GEN_AI_RESPONSE_TEXT], + [ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT], id="gen-ai-inputs-enabled-outputs-disabled", ), pytest.param( {"gen_ai": {"inputs": False, "outputs": True}}, - {SPANDATA.GEN_AI_RESPONSE_TEXT: "the model response"}, + {ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT: "the model response"}, [ - SPANDATA.GEN_AI_REQUEST_MESSAGES, - SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS, ], id="gen-ai-outputs-enabled-inputs-disabled", ), @@ -3079,7 +3477,11 @@ def test_langchain_chat_data_collection( sentry_sdk.flush() spans = [item.payload for item in captured] - (span,) = [s for s in spans if s["attributes"].get("sentry.op") == "gen_ai.chat"] + (span,) = [ + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ] span_data = span["attributes"] for key, expected in expected_present.items(): @@ -3092,9 +3494,9 @@ def test_langchain_chat_data_collection( for key in expected_absent: assert key not in span_data, f"{key} should not have been collected" - assert span_data[SPANDATA.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" - assert span_data[SPANDATA.GEN_AI_PROVIDER_NAME] == "openai-chat" - assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 30 + assert span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai-chat" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 30 @pytest.mark.parametrize( @@ -3103,7 +3505,7 @@ def test_langchain_chat_data_collection( pytest.param( {"gen_ai": {"inputs": True, "outputs": False}}, { - SPANDATA.GEN_AI_REQUEST_MESSAGES: [ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES: [ { "role": "user", "content": { @@ -3113,13 +3515,13 @@ def test_langchain_chat_data_collection( } ], }, - [SPANDATA.GEN_AI_RESPONSE_TEXT], + [ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT], id="gen-ai-inputs-enabled-outputs-disabled", ), pytest.param( {"gen_ai": {"inputs": False, "outputs": True}}, - {SPANDATA.GEN_AI_RESPONSE_TEXT: "The capital of France is Paris."}, - [SPANDATA.GEN_AI_REQUEST_MESSAGES], + {ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT: "The capital of France is Paris."}, + [ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES], id="gen-ai-outputs-enabled-inputs-disabled", ), ], @@ -3183,7 +3585,9 @@ def test_langchain_text_completion_data_collection( sentry_sdk.flush() spans = [item.payload for item in captured] (span,) = [ - s for s in spans if s["attributes"].get("sentry.op") == "gen_ai.text_completion" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.text_completion" ] span_data = span["attributes"] @@ -3197,10 +3601,10 @@ def test_langchain_text_completion_data_collection( for key in expected_absent: assert key not in span_data, f"{key} should not have been collected" - assert span_data[SPANDATA.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" - assert span_data[SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert span_data[SPANDATA.GEN_AI_REQUEST_TEMPERATURE] == 0.7 - assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 25 + assert span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + assert span_data[ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 25 @pytest.mark.parametrize( @@ -3208,20 +3612,20 @@ def test_langchain_text_completion_data_collection( [ pytest.param( {"gen_ai": {"inputs": True, "outputs": False}}, - [SPANDATA.GEN_AI_TOOL_DEFINITIONS], + [ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS], [ # REQUEST_AVAILABLE_TOOLS is the legacy value set when data collection is not enabled - SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, - SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS, + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS, ], id="gen-ai-inputs-enabled-outputs-disabled-only-tool-definitions-collected", ), pytest.param( {"gen_ai": {"inputs": False, "outputs": True}}, - [SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS], + [ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS], [ - SPANDATA.GEN_AI_TOOL_DEFINITIONS, - SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS, ], id="gen-ai-outputs-enabled-inputs-disabled-only-response-tool-calls-collected", ), @@ -3289,7 +3693,7 @@ def test_langchain_data_collection_tools( chat_spans = [ s["attributes"] for s in spans - if s["attributes"].get("sentry.op") == "gen_ai.chat" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ] assert len(chat_spans) == 2 @@ -3304,8 +3708,8 @@ def test_langchain_data_collection_tools( # Tool definitions are gated the same way on every span they are set on for key in ( - SPANDATA.GEN_AI_TOOL_DEFINITIONS, - SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, + ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS, + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS, ): collected = key in expected_present assert (key in chat_spans[1]) is collected @@ -3365,15 +3769,17 @@ def test_langchain_data_collection_request_tool_call_params( (span_data,) = [ s["attributes"] for s in spans - if s["attributes"].get("sentry.op") == "gen_ai.chat" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ] if tool_calls_collected: - assert "get_word_length" in span_data[SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ( + "get_word_length" in span_data[ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS] + ) else: - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in span_data + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in span_data - assert span_data[SPANDATA.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-3.5-turbo" @pytest.mark.parametrize( @@ -3381,14 +3787,14 @@ def test_langchain_data_collection_request_tool_call_params( [ pytest.param( {"gen_ai": {"inputs": True, "outputs": False}}, - {SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS: {"word": "eudca"}}, - [SPANDATA.GEN_AI_TOOL_CALL_RESULT], + {ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS: {"word": "eudca"}}, + [ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT], id="gen-ai-inputs-enabled-outputs-disabled", ), pytest.param( {"gen_ai": {"inputs": False, "outputs": True}}, - {SPANDATA.GEN_AI_TOOL_CALL_RESULT: 5}, - [SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS], + {ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT: 5}, + [ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS], id="gen-ai-outputs-enabled-inputs-disabled", ), ], @@ -3455,7 +3861,7 @@ def test_langchain_tool_execution_data_collection( span_data = next( s["attributes"] for s in spans - if s["attributes"].get("sentry.op") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.execute_tool" ) for key, expected in expected_present.items(): @@ -3468,8 +3874,8 @@ def test_langchain_tool_execution_data_collection( for key in expected_absent: assert key not in span_data, f"{key} should not have been collected" - assert span_data[SPANDATA.GEN_AI_TOOL_NAME] == "get_word_length" - assert span_data[SPANDATA.GEN_AI_OPERATION_NAME] == "execute_tool" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "get_word_length" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "execute_tool" @pytest.mark.parametrize("agent_method", ["invoke", "stream"]) @@ -3478,14 +3884,18 @@ def test_langchain_tool_execution_data_collection( [ pytest.param( {"gen_ai": {"inputs": True, "outputs": False}}, - {SPANDATA.GEN_AI_REQUEST_MESSAGES: ["How many letters in the word eudca"]}, - [SPANDATA.GEN_AI_RESPONSE_TEXT], + { + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES: [ + "How many letters in the word eudca" + ] + }, + [ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT], id="gen-ai-inputs-enabled-outputs-disabled", ), pytest.param( {"gen_ai": {"inputs": False, "outputs": True}}, - {SPANDATA.GEN_AI_RESPONSE_TEXT: "The word eudca has 5 letters."}, - [SPANDATA.GEN_AI_REQUEST_MESSAGES], + {ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT: "The word eudca has 5 letters."}, + [ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES], id="gen-ai-outputs-enabled-inputs-disabled", ), ], @@ -3556,7 +3966,7 @@ def test_langchain_agent_executor_data_collection( span_data = next( s["attributes"] for s in spans - if s["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) for key, expected in expected_present.items(): @@ -3569,4 +3979,4 @@ def test_langchain_agent_executor_data_collection( for key in expected_absent: assert key not in span_data, f"{key} should not have been collected" - assert span_data[SPANDATA.GEN_AI_OPERATION_NAME] == "invoke_agent" + assert span_data[ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "invoke_agent" diff --git a/tests/integrations/langgraph/test_langgraph.py b/tests/integrations/langgraph/test_langgraph.py index 79f8f806cc..02cf164be9 100644 --- a/tests/integrations/langgraph/test_langgraph.py +++ b/tests/integrations/langgraph/test_langgraph.py @@ -8,9 +8,10 @@ from langchain_core.messages import HumanMessage from langchain_core.outputs import ChatResult from langgraph.errors import GraphBubbleUp +from sentry_conventions.attributes import ATTRIBUTE_NAMES import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP def mock_langgraph_imports(): @@ -194,21 +195,30 @@ def original_invoke(self, *args, **kwargs): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 invoke_span = invoke_spans[0] assert invoke_span["name"] == "invoke_agent test_graph" - assert invoke_span["attributes"]["sentry.origin"] == "auto.ai.langgraph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_OPERATION_NAME] == "invoke_agent" - assert invoke_span["attributes"][SPANDATA.GEN_AI_PIPELINE_NAME] == "test_graph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_AGENT_NAME] == "test_graph" + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.langgraph" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME] == "test_graph" + ) + assert invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_graph" - assert SPANDATA.GEN_AI_REQUEST_MESSAGES in invoke_span["attributes"] - assert SPANDATA.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in invoke_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] - request_messages = invoke_span["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + request_messages = invoke_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES + ] if isinstance(request_messages, str): request_messages = json.loads(request_messages) @@ -216,11 +226,13 @@ def original_invoke(self, *args, **kwargs): assert request_messages[0]["content"] == "Hello, can you help me?" assert request_messages[1]["content"] == "Of course! How can I assist you?" - response_text = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + response_text = invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] assert response_text == expected_assistant_response - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] - tool_calls_data = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] + tool_calls_data = invoke_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] if isinstance(tool_calls_data, str): tool_calls_data = json.loads(tool_calls_data) @@ -287,20 +299,31 @@ def original_invoke(self, *args, **kwargs): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 invoke_span = invoke_spans[0] assert invoke_span["name"] == "invoke_agent test_graph" - assert invoke_span["attributes"]["sentry.origin"] == "auto.ai.langgraph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_OPERATION_NAME] == "invoke_agent" - assert invoke_span["attributes"][SPANDATA.GEN_AI_PIPELINE_NAME] == "test_graph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_AGENT_NAME] == "test_graph" + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.langgraph" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME] == "test_graph" + ) + assert invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_graph" - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in invoke_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in invoke_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in invoke_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in invoke_span.get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in invoke_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in invoke_span.get( + "attributes", {} + ) def test_pregel_ainvoke( @@ -357,25 +380,34 @@ async def run_test(): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 invoke_span = invoke_spans[0] assert invoke_span["name"] == "invoke_agent async_graph" - assert invoke_span["attributes"]["sentry.origin"] == "auto.ai.langgraph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_OPERATION_NAME] == "invoke_agent" - assert invoke_span["attributes"][SPANDATA.GEN_AI_PIPELINE_NAME] == "async_graph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_AGENT_NAME] == "async_graph" + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.langgraph" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME] == "async_graph" + ) + assert invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "async_graph" - assert SPANDATA.GEN_AI_REQUEST_MESSAGES in invoke_span["attributes"] - assert SPANDATA.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in invoke_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] - response_text = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + response_text = invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] assert response_text == expected_assistant_response - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] - tool_calls_data = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] + tool_calls_data = invoke_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] if isinstance(tool_calls_data, str): tool_calls_data = json.loads(tool_calls_data) @@ -439,20 +471,31 @@ async def run_test(): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 invoke_span = invoke_spans[0] assert invoke_span["name"] == "invoke_agent async_graph" - assert invoke_span["attributes"]["sentry.origin"] == "auto.ai.langgraph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_OPERATION_NAME] == "invoke_agent" - assert invoke_span["attributes"][SPANDATA.GEN_AI_PIPELINE_NAME] == "async_graph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_AGENT_NAME] == "async_graph" + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.langgraph" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME] == "async_graph" + ) + assert invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "async_graph" - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in invoke_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in invoke_span.get("attributes", {}) - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in invoke_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in invoke_span.get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in invoke_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in invoke_span.get( + "attributes", {} + ) def test_pregel_invoke_error( @@ -488,7 +531,7 @@ def original_invoke(self, *args, **kwargs): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 @@ -532,7 +575,7 @@ async def run_error_test(): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 @@ -576,7 +619,7 @@ def original_invoke(self, *args, **kwargs): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 @@ -584,12 +627,21 @@ def original_invoke(self, *args, **kwargs): if graph_name and graph_name.strip(): assert invoke_span["name"] == "invoke_agent my_graph" - assert invoke_span["attributes"][SPANDATA.GEN_AI_PIPELINE_NAME] == graph_name - assert invoke_span["attributes"][SPANDATA.GEN_AI_AGENT_NAME] == graph_name + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME] + == graph_name + ) + assert ( + invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == graph_name + ) else: assert invoke_span["name"] == "invoke_agent" - assert SPANDATA.GEN_AI_PIPELINE_NAME not in invoke_span.get("attributes", {}) - assert SPANDATA.GEN_AI_AGENT_NAME not in invoke_span.get("attributes", {}) + assert ATTRIBUTE_NAMES.GEN_AI_PIPELINE_NAME not in invoke_span.get( + "attributes", {} + ) + assert ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME not in invoke_span.get( + "attributes", {} + ) def test_complex_message_parsing(): @@ -700,18 +752,20 @@ def original_invoke(self, *args, **kwargs): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 invoke_span = invoke_spans[0] - assert SPANDATA.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] - response_text = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT in invoke_span["attributes"] + response_text = invoke_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] assert response_text == "Final response" - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS in invoke_span["attributes"] - tool_calls_data = invoke_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS] + tool_calls_data = invoke_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS + ] if isinstance(tool_calls_data, str): tool_calls_data = json.loads(tool_calls_data) @@ -769,12 +823,12 @@ def __init__(self, content, message_type="human"): span = next(item.payload for item in items) # Verify that the span was created correctly - assert span["attributes"]["sentry.op"] == "gen_ai.invoke_agent" + assert span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.invoke_agent" # If messages were captured, verify role mapping - if SPANDATA.GEN_AI_REQUEST_MESSAGES in span["attributes"]: + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in span["attributes"]: stored_messages = json.loads( - span["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] ) # Find messages with specific content to verify role mapping @@ -819,7 +873,7 @@ def _invoke_span_data(items_or_events): invoke_spans = [ span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ] assert len(invoke_spans) == 1 return invoke_spans[0]["attributes"] @@ -892,15 +946,16 @@ async def run_test(): data = _invoke_span_data(captured) if expect_inputs: - assert SPANDATA.GEN_AI_REQUEST_MESSAGES in data + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in data else: - assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in data + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in data if expect_outputs: - assert data[SPANDATA.GEN_AI_RESPONSE_TEXT] == expected_assistant_response + assert data[ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == expected_assistant_response assert ( - json.loads(data[SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS]) == expected_tool_calls + json.loads(data[ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS]) + == expected_tool_calls ) else: - assert SPANDATA.GEN_AI_RESPONSE_TEXT not in data - assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in data + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in data + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS not in data diff --git a/tests/integrations/openai_agents/test_openai_agents.py b/tests/integrations/openai_agents/test_openai_agents.py index e4849dc6d5..8266f87fa3 100644 --- a/tests/integrations/openai_agents/test_openai_agents.py +++ b/tests/integrations/openai_agents/test_openai_agents.py @@ -26,6 +26,7 @@ from agents.tool import HostedMCPTool from openai import AsyncOpenAI, InternalServerError from openai.types.responses.tool_param import CodeInterpreter, ImageGeneration +from sentry_conventions.attributes import ATTRIBUTE_NAMES from sentry_sdk.integrations import DidNotEnable @@ -67,7 +68,7 @@ from typing import Any, cast import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA +from sentry_sdk.consts import OP from sentry_sdk.integrations.logging import LoggingIntegration from sentry_sdk.integrations.openai_agents import OpenAIAgentsIntegration from sentry_sdk.integrations.openai_agents.utils import _set_input_data, safe_serialize @@ -428,11 +429,15 @@ def some_function(a: str, b: list[int]) -> str: sentry_sdk.flush() spans = [item.payload for item in items] ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) assert ( - json.loads(ai_client_span["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS]) + json.loads( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] + ) == expected_available_tools ) @@ -499,29 +504,50 @@ async def test_agent_invocation_span_no_sensitive_data( invoke_agent_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ) ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) assert invoke_agent_span["name"] == "invoke_agent test_agent" - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in invoke_agent_span["attributes"] - assert "gen_ai.request.messages" not in invoke_agent_span["attributes"] - assert "gen_ai.response.text" not in invoke_agent_span["attributes"] + assert ( + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + not in invoke_agent_span["attributes"] + ) + assert ( + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in invoke_agent_span["attributes"] + ) + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in invoke_agent_span["attributes"] - assert invoke_agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" - assert invoke_agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "test_agent" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["gen_ai.operation.name"] == "chat" - assert ai_client_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert ai_client_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert ai_client_span["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span["attributes"]["gen_ai.request.top_p"] == 1.0 + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 @pytest.mark.asyncio @@ -786,33 +812,52 @@ async def test_agent_invocation_span( assert invoke_agent_span["name"] == "invoke_agent test_agent" if expected_system_instructions is None: - assert "gen_ai.system_instructions" not in ai_client_span["attributes"] + assert ( + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + not in ai_client_span["attributes"] + ) else: assert ai_client_span["attributes"][ - "gen_ai.system_instructions" + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS ] == safe_serialize(expected_system_instructions) assert ( - json.loads(ai_client_span["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES]) + json.loads( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + ) == expected_request_messages ) assert ( - invoke_agent_span["attributes"]["gen_ai.response.text"] + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == "Hello, how can I help you?" ) - assert invoke_agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" - assert invoke_agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "test_agent" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["gen_ai.operation.name"] == "chat" - assert ai_client_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert ai_client_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert ai_client_span["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span["attributes"]["gen_ai.request.top_p"] == 1.0 + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 @pytest.mark.asyncio @@ -872,11 +917,16 @@ async def test_client_span_custom_model( sentry_sdk.flush() spans = [item.payload for item in items] ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) assert ai_client_span["name"] == "chat my-custom-model" - assert ai_client_span["attributes"]["gen_ai.request.model"] == "my-custom-model" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] + == "my-custom-model" + ) def test_agent_invocation_span_sync_no_sensitive_data( @@ -942,26 +992,45 @@ def test_agent_invocation_span_sync_no_sensitive_data( invoke_agent_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ) ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) assert invoke_agent_span["name"] == "invoke_agent test_agent" - assert invoke_agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" - assert invoke_agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "test_agent" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["gen_ai.operation.name"] == "chat" - assert ai_client_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert ai_client_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert ai_client_span["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span["attributes"]["gen_ai.request.top_p"] == 1.0 + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in invoke_agent_span["attributes"] + assert ( + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + not in invoke_agent_span["attributes"] + ) @pytest.mark.parametrize( @@ -1224,27 +1293,46 @@ def test_agent_invocation_span_sync( ai_client_span, invoke_agent_span = spans assert invoke_agent_span["name"] == "invoke_agent test_agent" - assert invoke_agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" - assert invoke_agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] + == "test_agent" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["gen_ai.operation.name"] == "chat" - assert ai_client_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert ai_client_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert ai_client_span["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span["attributes"]["gen_ai.request.top_p"] == 1.0 + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 if expected_system_instructions is None: - assert "gen_ai.system_instructions" not in ai_client_span["attributes"] + assert ( + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + not in ai_client_span["attributes"] + ) else: assert ai_client_span["attributes"][ - "gen_ai.system_instructions" + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS ] == safe_serialize(expected_system_instructions) assert ( - json.loads(ai_client_span["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES]) + json.loads( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + ) == expected_request_messages ) @@ -1344,15 +1432,17 @@ async def test_tool_execution_span( agent_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ) ai_client_span1, ai_client_span2 = ( - span for span in spans if span["attributes"].get("sentry.op") == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == OP.GEN_AI_CHAT ) tool_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_EXECUTE_TOOL + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_EXECUTE_TOOL ) available_tool = { @@ -1368,25 +1458,41 @@ async def test_tool_execution_span( } assert agent_span["name"] == "invoke_agent test_agent" - assert agent_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" - assert agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" + assert ( + agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) + assert agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + assert ( + agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) assert ai_client_span1["name"] == "chat gpt-4" - assert ai_client_span1["attributes"]["gen_ai.operation.name"] == "chat" - assert ai_client_span1["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" - assert ai_client_span1["attributes"]["gen_ai.agent.name"] == "test_agent" + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + ) + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) ai_client_span1_available_tool = json.loads( - ai_client_span1["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS] + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] )[0] assert all( ai_client_span1_available_tool[k] == v for k, v in available_tool.items() ) - assert ai_client_span1["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span1["attributes"]["gen_ai.request.messages"] == safe_serialize( + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span1["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES + ] == safe_serialize( [ { "role": "user", @@ -1396,20 +1502,34 @@ async def test_tool_execution_span( }, ] ) - assert ai_client_span1["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span1["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span1["attributes"]["gen_ai.request.top_p"] == 1.0 - assert ai_client_span1["attributes"]["gen_ai.usage.input_tokens"] == 10 assert ( - ai_client_span1["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + ) + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + ) + assert ( + ai_client_span1["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] == 0 ) - assert ai_client_span1["attributes"]["gen_ai.usage.output_tokens"] == 5 assert ( - ai_client_span1["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 5 + ) + assert ( + ai_client_span1["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] == 0 ) - assert ai_client_span1["attributes"]["gen_ai.usage.total_tokens"] == 15 + assert ( + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 15 + ) tool_call = { "arguments": '{"message": "hello"}', @@ -1424,39 +1544,54 @@ async def test_tool_execution_span( tool_call["namespace"] = None parsed_tool_calls = json.loads( - ai_client_span1["attributes"]["gen_ai.response.tool_calls"] + ai_client_span1["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TOOL_CALLS] ) assert len(parsed_tool_calls) == 1 assert tool_call.items() <= parsed_tool_calls[0].items() assert tool_span["name"] == "execute_tool simple_test_tool" - assert tool_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert tool_span["attributes"]["gen_ai.operation.name"] == "execute_tool" + assert tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "execute_tool" + ) - assert tool_span["attributes"]["gen_ai.tool.description"] == "A simple tool" assert ( - tool_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION] + == "A simple tool" + ) + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] == '{"message": "hello"}' ) - assert tool_span["attributes"]["gen_ai.tool.name"] == "simple_test_tool" assert ( - tool_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_RESULT] + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "simple_test_tool" + ) + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT] == "Tool executed with: hello" ) assert ai_client_span2["name"] == "chat gpt-4" - assert ai_client_span2["attributes"]["gen_ai.agent.name"] == "test_agent" - assert ai_client_span2["attributes"]["gen_ai.operation.name"] == "chat" + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + ) + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + ) ai_client_span2_available_tool = json.loads( - ai_client_span2["attributes"][SPANDATA.GEN_AI_TOOL_DEFINITIONS] + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DEFINITIONS] )[0] assert all( ai_client_span2_available_tool[k] == v for k, v in available_tool.items() ) - assert ai_client_span2["attributes"]["gen_ai.request.max_tokens"] == 100 - assert ai_client_span2["attributes"]["gen_ai.request.messages"] == safe_serialize( + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS] == 100 + ) + assert ai_client_span2["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES + ] == safe_serialize( [ { "role": "user", @@ -1488,25 +1623,41 @@ async def test_tool_execution_span( }, ] ) - assert ai_client_span2["attributes"]["gen_ai.request.model"] == "gpt-4" - assert ai_client_span2["attributes"]["gen_ai.request.temperature"] == 0.7 - assert ai_client_span2["attributes"]["gen_ai.request.top_p"] == 1.0 assert ( - ai_client_span2["attributes"]["gen_ai.response.text"] + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MODEL] == "gpt-4" + ) + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE] == 0.7 + ) + assert ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P] == 1.0 + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == "Task completed using the tool" ) - assert ai_client_span2["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "openai" assert ( - ai_client_span2["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "openai" + ) + assert ( + ai_client_span2["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS + ] == 0 ) - assert ai_client_span2["attributes"]["gen_ai.usage.input_tokens"] == 15 assert ( - ai_client_span2["attributes"][SPANDATA.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 15 + ) + assert ( + ai_client_span2["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_USAGE_REASONING_OUTPUT_TOKENS + ] == 0 ) - assert ai_client_span2["attributes"]["gen_ai.usage.output_tokens"] == 10 - assert ai_client_span2["attributes"]["gen_ai.usage.total_tokens"] == 25 + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 10 + ) + assert ( + ai_client_span2["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_TOTAL_TOKENS] == 25 + ) @pytest.mark.parametrize("user_hooks", [True, False]) @@ -1614,31 +1765,44 @@ async def test_run_streamed_tool_execution_span( agent_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ) tool_span = next( span for span in spans - if span["attributes"].get("sentry.op") == OP.GEN_AI_EXECUTE_TOOL + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == OP.GEN_AI_EXECUTE_TOOL ) assert agent_span["name"] == "invoke_agent test_agent" - assert agent_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" - assert agent_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert agent_span["attributes"]["gen_ai.operation.name"] == "invoke_agent" + assert ( + agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) + assert agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + assert ( + agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "invoke_agent" + ) assert tool_span["name"] == "execute_tool simple_test_tool" - assert tool_span["attributes"]["gen_ai.agent.name"] == "test_agent" - assert tool_span["attributes"]["gen_ai.operation.name"] == "execute_tool" + assert tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_AGENT_NAME] == "test_agent" + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "execute_tool" + ) - assert tool_span["attributes"]["gen_ai.tool.description"] == "A simple tool" assert ( - tool_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION] + == "A simple tool" + ) + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] == '{"message": "hello"}' ) - assert tool_span["attributes"]["gen_ai.tool.name"] == "simple_test_tool" assert ( - tool_span["attributes"][SPANDATA.GEN_AI_TOOL_CALL_RESULT] + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "simple_test_tool" + ) + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT] == "Tool executed with: hello" ) @@ -1725,7 +1889,8 @@ async def inner(tool, run_kwargs=None, **init_kwargs): tool_span = next( item.payload for item in items - if item.payload["attributes"].get("sentry.op") == OP.GEN_AI_EXECUTE_TOOL + if item.payload["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) + == OP.GEN_AI_EXECUTE_TOOL ) return tool_span, tool_span["attributes"] @@ -1786,19 +1951,19 @@ async def test_tool_execution_span_data_collection( if expect_input: assert ( - tool_span_data[SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS] + tool_span_data[ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS] == '{"message": "hello"}' ) else: - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_span_data + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_span_data if expect_output: assert ( - tool_span_data[SPANDATA.GEN_AI_TOOL_CALL_RESULT] + tool_span_data[ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT] == "Tool executed with: hello" ) else: - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_span_data + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_span_data @pytest.mark.asyncio @@ -1811,9 +1976,11 @@ async def test_tool_execution_span_non_sensitive_data_always_set( run_kwargs={"conversation_id": "conv_tool_test_456"}, ) - assert tool_span_data[SPANDATA.GEN_AI_TOOL_NAME] == "simple_test_tool" - assert tool_span_data[SPANDATA.GEN_AI_TOOL_DESCRIPTION] == "A simple tool" - assert tool_span_data[SPANDATA.GEN_AI_CONVERSATION_ID] == "conv_tool_test_456" + assert tool_span_data[ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "simple_test_tool" + assert tool_span_data[ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION] == "A simple tool" + assert ( + tool_span_data[ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID] == "conv_tool_test_456" + ) @pytest.mark.asyncio @@ -1937,7 +2104,7 @@ async def test_hosted_mcp_tool_propagation_header_streamed( with sentry_sdk.start_span( name="/interactions/other-dogs/new-dog", attributes={ - "sentry.op": "greeting.sniff", + ATTRIBUTE_NAMES.SENTRY_OP: "greeting.sniff", }, ) as span: result = agents.Runner.run_streamed( @@ -1955,7 +2122,7 @@ async def test_hosted_mcp_tool_propagation_header_streamed( ai_client_span = next( span for span in spans - if span["attributes"].get("sentry.op") == OP.GEN_AI_CHAT + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == OP.GEN_AI_CHAT ) args, kwargs = create.call_args @@ -2039,7 +2206,7 @@ async def test_hosted_mcp_tool_propagation_headers( with sentry_sdk.start_span( name="/interactions/other-dogs/new-dog", attributes={ - "sentry.op": "greeting.sniff", + ATTRIBUTE_NAMES.SENTRY_OP: "greeting.sniff", }, ) as span: await agents.Runner.run( @@ -2054,7 +2221,7 @@ async def test_hosted_mcp_tool_propagation_headers( ai_client_span = next( span for span in spans - if span["attributes"].get("sentry.op") == OP.GEN_AI_CHAT + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == OP.GEN_AI_CHAT ) args, kwargs = send.call_args @@ -2149,7 +2316,10 @@ async def test_model_behavior_error( ) = spans assert agent_span["name"] == "invoke_agent test_agent" - assert agent_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" + assert ( + agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) # Error due to unrecognized tool in model response. assert agent_span["status"] == "error" @@ -2199,10 +2369,16 @@ async def test_run_error_handling( ) = spans assert invoke_agent_span["name"] == "invoke_agent test_agent" - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) assert ai_client_span["status"] == "error" @@ -2247,10 +2423,16 @@ async def test_run_streamed_error_handling( ) = spans assert invoke_agent_span["name"] == "invoke_agent test_agent" - assert invoke_agent_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) assert ai_client_span["name"] == "chat gpt-4" - assert ai_client_span["attributes"]["sentry.origin"] == "auto.ai.openai_agents" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] + == "auto.ai.openai_agents" + ) assert ai_client_span["status"] == "error" @@ -2310,19 +2492,24 @@ async def test_error_captures_input_data( sentry_sdk.flush() spans = [item.payload for item in items if item.type == "span"] ai_client_span = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ][0] assert ai_client_span["name"] == "chat gpt-4" assert ai_client_span["status"] == "error" - assert "gen_ai.request.messages" in ai_client_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in ai_client_span["attributes"] request_messages = safe_serialize( [ {"role": "user", "content": [{"type": "text", "text": "Test input"}]}, ] ) - assert ai_client_span["attributes"]["gen_ai.request.messages"] == request_messages + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + == request_messages + ) @pytest.mark.asyncio @@ -2394,9 +2581,10 @@ def test_openai_agents_message_role_mapping(sentry_init, test_message, expected_ _set_input_data(span, get_response_kwargs) # Verify that messages were processed and roles were mapped - from sentry_sdk.consts import SPANDATA - stored_messages = json.loads(span._attributes[SPANDATA.GEN_AI_REQUEST_MESSAGES]) + stored_messages = json.loads( + span._attributes[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + ) # Verify roles were properly mapped assert stored_messages[0]["role"] == expected_role @@ -2516,7 +2704,10 @@ def failing_tool(message: str) -> str: # Verify the execute_tool span was created assert execute_tool_span is not None, "execute_tool span was not created" assert execute_tool_span["name"] == "execute_tool failing_tool" - assert execute_tool_span["attributes"]["gen_ai.tool.name"] == "failing_tool" + assert ( + execute_tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] + == "failing_tool" + ) # Verify error status was set (this is the key test for our patch) # The span should be marked as error because the tool execution failed @@ -2604,13 +2795,18 @@ async def test_ai_client_span_includes_response_model( sentry_sdk.flush() spans = [item.payload for item in items] ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) # Verify ai_client span has response model from API response assert ai_client_span["name"] == "chat gpt-4" - assert "gen_ai.response.model" in ai_client_span["attributes"] - assert ai_client_span["attributes"]["gen_ai.response.model"] == "gpt-4.1-2025-04-14" + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL in ai_client_span["attributes"] + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4.1-2025-04-14" + ) @pytest.mark.asyncio @@ -2694,13 +2890,15 @@ async def test_ai_client_span_response_model_with_chat_completions( sentry_sdk.flush() spans = [item.payload for item in items] ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) # Verify response model from API response is captured - assert "gen_ai.response.model" in ai_client_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL in ai_client_span["attributes"] assert ( - ai_client_span["attributes"]["gen_ai.response.model"] + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-4o-mini-2024-07-18" ) @@ -2786,12 +2984,17 @@ async def test_invoke_agent_span_includes_response_model( sentry_sdk.flush() spans = [item.payload for item in items] ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) # Also verify ai_client span has it - assert "gen_ai.response.model" in ai_client_span["attributes"] - assert ai_client_span["attributes"]["gen_ai.response.model"] == "gpt-4.1-2025-04-14" + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL in ai_client_span["attributes"] + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4.1-2025-04-14" + ) @pytest.mark.asyncio @@ -2922,9 +3125,12 @@ def calculator(a: int, b: int) -> int: second_ai_client_span = spans[2] # After tool span # Each ai_client span has its own response model from the API - assert first_ai_client_span["attributes"]["gen_ai.response.model"] == "gpt-4-0613" assert ( - second_ai_client_span["attributes"]["gen_ai.response.model"] + first_ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] + == "gpt-4-0613" + ) + assert ( + second_ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-4.1-2025-04-14" ) @@ -2974,15 +3180,20 @@ async def test_streaming_span_update_captures_response_data( # Test the unified update function (works for both streaming and non-streaming) with sentry_sdk.start_span( - attributes={"sentry.op": "gen_ai.chat"}, name="test chat" + attributes={ATTRIBUTE_NAMES.SENTRY_OP: "gen_ai.chat"}, name="test chat" ) as span: update_ai_client_span(span, mock_streaming_response) # Verify the span data was set correctly - assert span._attributes["gen_ai.response.text"] == "Hello from streaming!" - assert span._attributes["gen_ai.usage.input_tokens"] == 10 - assert span._attributes["gen_ai.usage.output_tokens"] == 20 - assert span._attributes["gen_ai.response.model"] == "gpt-4-streaming" + assert ( + span._attributes[ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] + == "Hello from streaming!" + ) + assert span._attributes[ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS] == 10 + assert span._attributes[ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS] == 20 + assert ( + span._attributes[ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL] == "gpt-4-streaming" + ) @pytest.mark.asyncio @@ -3124,12 +3335,20 @@ async def test_streaming_ttft_on_chat_span( spans = [item.payload for item in items] # Verify TTFT is recorded on the chat span - chat_spans = [s for s in spans if s["attributes"].get("sentry.op") == "gen_ai.chat"] + chat_spans = [ + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" + ] assert len(chat_spans) >= 1 chat_span = chat_spans[0] - assert SPANDATA.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK in chat_span["attributes"] - assert chat_span["attributes"].get(SPANDATA.GEN_AI_RESPONSE_STREAMING) is True + assert ( + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK in chat_span["attributes"] + ) + assert ( + chat_span["attributes"].get(ATTRIBUTE_NAMES.GEN_AI_RESPONSE_STREAMING) is True + ) @pytest.mark.asyncio @@ -3193,17 +3412,25 @@ async def test_conversation_id_on_all_spans( invoke_agent_span = next( span for span in spans - if span["attributes"]["sentry.op"] == OP.GEN_AI_INVOKE_AGENT + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_INVOKE_AGENT ) ai_client_span = next( - span for span in spans if span["attributes"]["sentry.op"] == OP.GEN_AI_CHAT + span + for span in spans + if span["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == OP.GEN_AI_CHAT ) # Verify invoke_agent span has conversation_id - assert invoke_agent_span["attributes"]["gen_ai.conversation.id"] == "conv_test_123" + assert ( + invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID] + == "conv_test_123" + ) # Verify ai_client span has conversation_id - assert ai_client_span["attributes"]["gen_ai.conversation.id"] == "conv_test_123" + assert ( + ai_client_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID] + == "conv_test_123" + ) @pytest.mark.asyncio @@ -3331,4 +3558,7 @@ def simple_tool(message: str) -> str: assert tool_span is not None # Tool span should have the conversation_id passed to Runner.run() - assert tool_span["attributes"]["gen_ai.conversation.id"] == "conv_tool_test_456" + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_CONVERSATION_ID] + == "conv_tool_test_456" + ) diff --git a/tests/integrations/pydantic_ai/test_pydantic_ai.py b/tests/integrations/pydantic_ai/test_pydantic_ai.py index fe60e307ca..d084a3d287 100644 --- a/tests/integrations/pydantic_ai/test_pydantic_ai.py +++ b/tests/integrations/pydantic_ai/test_pydantic_ai.py @@ -19,10 +19,10 @@ ) from pydantic_ai.models.function import FunctionModel from pydantic_ai.usage import RequestUsage +from sentry_conventions.attributes import ATTRIBUTE_NAMES import sentry_sdk from sentry_sdk._types import BLOB_DATA_SUBSTITUTE -from sentry_sdk.consts import SPANDATA from sentry_sdk.integrations.pydantic_ai import PydanticAIIntegration from sentry_sdk.integrations.pydantic_ai.spans.ai_client import _set_input_messages from sentry_sdk.integrations.pydantic_ai.spans.utils import _set_usage_data @@ -112,20 +112,26 @@ async def test_agent_run_async( spans = [item.payload for item in items] assert spans[1]["name"] == "invoke_agent test_agent" - assert spans[1]["attributes"]["sentry.origin"] == "auto.ai.pydantic_ai" + assert ( + spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.pydantic_ai" + ) - assert spans[1]["attributes"]["sentry.op"] == "gen_ai.invoke_agent" + assert spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_OP] == "gen_ai.invoke_agent" chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 # Check chat span chat_span = chat_spans[0] assert "chat" in chat_span["name"] - assert chat_span["attributes"]["gen_ai.operation.name"] == "chat" - assert json.loads(chat_span["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES]) == [ + assert chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "chat" + assert json.loads( + chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + ) == [ { "role": "user", "content": [ @@ -140,8 +146,8 @@ async def test_agent_run_async( ], } ] - assert "gen_ai.usage.input_tokens" in chat_span["attributes"] - assert "gen_ai.usage.output_tokens" in chat_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_USAGE_OUTPUT_TOKENS in chat_span["attributes"] @pytest.mark.asyncio @@ -210,10 +216,14 @@ def test_agent_run_sync( spans = [item.payload for item in items] assert spans[1]["name"] == "invoke_agent test_agent" - assert spans[1]["attributes"]["sentry.origin"] == "auto.ai.pydantic_ai" + assert ( + spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.pydantic_ai" + ) chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 @@ -284,15 +294,19 @@ async def test_agent_run_stream( spans = [item.payload for item in items] assert spans[1]["name"] == "invoke_agent test_agent" - assert spans[1]["attributes"]["sentry.origin"] == "auto.ai.pydantic_ai" + assert ( + spans[1]["attributes"][ATTRIBUTE_NAMES.SENTRY_ORIGIN] == "auto.ai.pydantic_ai" + ) chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 assert json.loads( - chat_spans[0]["attributes"][SPANDATA.GEN_AI_REQUEST_MESSAGES] + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] ) == [ { "role": "user", @@ -308,11 +322,11 @@ async def test_agent_run_stream( ], } ] - assert "gen_ai.usage.input_tokens" in chat_spans[0]["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_USAGE_INPUT_TOKENS in chat_spans[0]["attributes"] # Streaming responses should still have output data assert ( - "gen_ai.response.text" in chat_spans[0]["attributes"] - or "gen_ai.response.model" in chat_spans[0]["attributes"] + ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT in chat_spans[0]["attributes"] + or ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL in chat_spans[0]["attributes"] ) @@ -358,7 +372,9 @@ async def test_agent_run_stream_events( assert spans[-1]["name"] == "invoke_agent test_agent" chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 @@ -401,12 +417,14 @@ def add_numbers(a: int, b: int) -> int: # Find child span types (invoke_agent is the transaction, not a child span) chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] tool_spans = [ s for s in spans - if s["attributes"].get("sentry.op", "") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.execute_tool" ] # Should have tool spans @@ -415,15 +433,19 @@ def add_numbers(a: int, b: int) -> int: # Check tool span tool_span = tool_spans[0] assert "execute_tool" in tool_span["name"] - assert tool_span["attributes"]["gen_ai.operation.name"] == "execute_tool" - assert tool_span["attributes"]["gen_ai.tool.name"] == "add_numbers" - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "execute_tool" + ) + assert tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "add_numbers" + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] # Check chat spans have available_tools for chat_span in chat_spans: - assert "gen_ai.request.available_tools" in chat_span["attributes"] - available_tools_str = chat_span["attributes"]["gen_ai.request.available_tools"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS in chat_span["attributes"] + available_tools_str = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS + ] # Available tools is serialized as a string assert "add_numbers" in available_tools_str @@ -485,12 +507,14 @@ def add_numbers(a: int, b: int) -> float: spans = [item.payload for item in items if item.type == "span"] # Find child span types (invoke_agent is the transaction, not a child span) chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] tool_spans = [ s for s in spans - if s["attributes"].get("sentry.op", "") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.execute_tool" ] # Should have tool spans @@ -500,22 +524,33 @@ def add_numbers(a: int, b: int) -> float: model_retry_tool_span = tool_spans[0] assert "execute_tool" in model_retry_tool_span["name"] assert ( - model_retry_tool_span["attributes"]["gen_ai.operation.name"] == "execute_tool" + model_retry_tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] + == "execute_tool" + ) + assert ( + model_retry_tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] + == "add_numbers" + ) + assert ( + ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS + in model_retry_tool_span["attributes"] ) - assert model_retry_tool_span["attributes"]["gen_ai.tool.name"] == "add_numbers" - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS in model_retry_tool_span["attributes"] tool_span = tool_spans[1] assert "execute_tool" in tool_span["name"] - assert tool_span["attributes"]["gen_ai.operation.name"] == "execute_tool" - assert tool_span["attributes"]["gen_ai.tool.name"] == "add_numbers" - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME] == "execute_tool" + ) + assert tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "add_numbers" + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] # Check chat spans have available_tools for chat_span in chat_spans: - assert "gen_ai.request.available_tools" in chat_span["attributes"] - available_tools_str = chat_span["attributes"]["gen_ai.request.available_tools"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS in chat_span["attributes"] + available_tools_str = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS + ] # Available tools is serialized as a string assert "add_numbers" in available_tools_str @@ -575,12 +610,16 @@ def add_numbers(a: Annotated[int, Field(gt=0, lt=0)], b: int) -> int: sentry_sdk.flush() spans = [item.payload for item in items if item.type == "span"] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] # Check chat spans have available_tools - assert "gen_ai.request.available_tools" in chat_spans[0]["attributes"] - available_tools_str = chat_spans[0]["attributes"]["gen_ai.request.available_tools"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS in chat_spans[0]["attributes"] + available_tools_str = chat_spans[0]["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS + ] # Available tools is serialized as a string assert "add_numbers" in available_tools_str @@ -625,7 +664,7 @@ def multiply(a: int, b: int) -> int: tool_spans = [ s for s in spans - if s["attributes"].get("sentry.op", "") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.execute_tool" ] # Should have tool spans @@ -633,9 +672,9 @@ def multiply(a: int, b: int) -> int: # Check tool span tool_span = tool_spans[0] - assert tool_span["attributes"]["gen_ai.tool.name"] == "multiply" - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] + assert tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "multiply" + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS in tool_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT in tool_span["attributes"] @pytest.mark.asyncio @@ -662,15 +701,19 @@ async def test_model_settings( # Find chat span chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] # Check that model settings are captured - assert chat_span["attributes"].get("gen_ai.request.temperature") == 0.7 - assert chat_span["attributes"].get("gen_ai.request.max_tokens") == 100 - assert chat_span["attributes"].get("gen_ai.request.top_p") == 0.9 + assert ( + chat_span["attributes"].get(ATTRIBUTE_NAMES.GEN_AI_REQUEST_TEMPERATURE) == 0.7 + ) + assert chat_span["attributes"].get(ATTRIBUTE_NAMES.GEN_AI_REQUEST_MAX_TOKENS) == 100 + assert chat_span["attributes"].get(ATTRIBUTE_NAMES.GEN_AI_REQUEST_TOP_P) == 0.9 @pytest.mark.asyncio @@ -706,13 +749,17 @@ async def test_system_prompt_attribute( # The transaction IS the invoke_agent span, check for messages in chat spans instead chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] - system_instructions = chat_span["attributes"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS] + system_instructions = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + ] assert json.loads(system_instructions) == [ { "type": "text", @@ -754,13 +801,15 @@ async def test_system_prompt_attribute_no_sensitive_data( # The transaction IS the invoke_agent span, check for messages in chat spans instead chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_span["attributes"] @pytest.mark.asyncio @@ -820,13 +869,15 @@ async def test_no_sensitive_data( # Find child spans (invoke_agent is the transaction, not a child span) chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] # Verify that messages and response text are not captured for span in chat_spans: - assert "gen_ai.request.messages" not in span["attributes"] - assert "gen_ai.response.text" not in span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES not in span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT not in span["attributes"] @pytest.mark.asyncio @@ -864,13 +915,13 @@ def sensitive_tool(data: str) -> str: tool_spans = [ s for s in spans - if s["attributes"].get("sentry.op", "") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.execute_tool" ] # If tool was executed, verify input/output are not captured for tool_span in tool_spans: - assert SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_span["attributes"] - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS not in tool_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_span["attributes"] @pytest.mark.asyncio @@ -953,13 +1004,17 @@ async def test_message_history( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] if chat_spans: chat_span = chat_spans[0] - if "gen_ai.request.messages" in chat_span["attributes"]: - messages_data = chat_span["attributes"]["gen_ai.request.messages"] + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in chat_span["attributes"]: + messages_data = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES + ] # Should have multiple messages including history assert len(messages_data) > 1 @@ -988,14 +1043,16 @@ async def test_gen_ai_system( # Find chat span chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] # gen_ai.system should be set from the model (TestModel -> 'test') - assert SPANDATA.GEN_AI_PROVIDER_NAME in chat_span["attributes"] - assert chat_span["attributes"][SPANDATA.GEN_AI_PROVIDER_NAME] == "test" + assert ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME in chat_span["attributes"] + assert chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_PROVIDER_NAME] == "test" @pytest.mark.asyncio @@ -1187,8 +1244,8 @@ async def test_invoke_agent_with_list_user_prompt( sentry_sdk.flush() spans = [item.payload for item in items] - if "gen_ai.request.messages" in spans[0]["attributes"]: - messages_str = spans[0]["attributes"]["gen_ai.request.messages"] + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in spans[0]["attributes"]: + messages_str = spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] assert "First part" in messages_str assert "Second part" in messages_str @@ -1232,13 +1289,17 @@ async def test_invoke_agent_with_instructions( # The transaction IS the invoke_agent span, check for messages in chat spans instead chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] - system_instructions = chat_span["attributes"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS] + system_instructions = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS + ] assert json.loads(system_instructions) == [ {"type": "text", "content": "System prompt"}, { @@ -1284,13 +1345,15 @@ async def test_invoke_agent_with_instructions_no_sensitive_data( # The transaction IS the invoke_agent span, check for messages in chat spans instead chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] - assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_span["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_SYSTEM_INSTRUCTIONS not in chat_span["attributes"] @pytest.mark.asyncio @@ -1377,7 +1440,9 @@ async def test_usage_data_partial( spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 @@ -1446,12 +1511,16 @@ def tool_without_desc(x: int) -> int: spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] if chat_spans: chat_span = chat_spans[0] - if "gen_ai.request.available_tools" in chat_span["attributes"]: - tools_str = chat_span["attributes"]["gen_ai.request.available_tools"] + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS in chat_span["attributes"]: + tools_str = chat_span["attributes"][ + ATTRIBUTE_NAMES.GEN_AI_REQUEST_AVAILABLE_TOOLS + ] assert "tool_without_desc" in tools_str @@ -1490,7 +1559,9 @@ def calc_tool(value: int) -> int: spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] # At least one chat span should exist @@ -1499,7 +1570,7 @@ def calc_tool(value: int) -> int: # Check if tool calls are captured in response # Tool calls may or may not be in response depending on TestModel behavior # Just verify the span was created and has basic data - assert "gen_ai.operation.name" in chat_spans[0]["attributes"] + assert ATTRIBUTE_NAMES.GEN_AI_OPERATION_NAME in chat_spans[0]["attributes"] @pytest.mark.asyncio @@ -1546,7 +1617,9 @@ async def test_message_formatting_with_different_parts( spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] # Should have chat spans @@ -1554,8 +1627,8 @@ async def test_message_formatting_with_different_parts( # Check that messages are captured chat_span = chat_spans[0] - if "gen_ai.request.messages" in chat_span["attributes"]: - messages_data = chat_span["attributes"]["gen_ai.request.messages"] + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in chat_span["attributes"]: + messages_data = chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] assert messages_data is not None @@ -1793,7 +1866,9 @@ def test_tool(x: int) -> int: spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] # Should have chat spans @@ -1888,16 +1963,20 @@ def multiply(a: int, b: int) -> int: invoke_agent_span = next( span for span in spans - if span["attributes"].get("sentry.op") == "gen_ai.invoke_agent" + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.invoke_agent" ) - assert invoke_agent_span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] == ( + assert invoke_agent_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_RESPONSE_TEXT] == ( "The answer is 15." ) chat_spans = [ - span for span in spans if span["attributes"].get("sentry.op") == "gen_ai.chat" + span + for span in spans + if span["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP) == "gen_ai.chat" ] - assert json.loads(chat_spans[0]["attributes"][SPANDATA.GEN_AI_OUTPUT_MESSAGES]) == [ + assert json.loads( + chat_spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_OUTPUT_MESSAGES] + ) == [ { "role": "assistant", "parts": [ @@ -1909,7 +1988,9 @@ def multiply(a: int, b: int) -> int: ], } ] - assert json.loads(chat_spans[1]["attributes"][SPANDATA.GEN_AI_OUTPUT_MESSAGES]) == [ + assert json.loads( + chat_spans[1]["attributes"][ATTRIBUTE_NAMES.GEN_AI_OUTPUT_MESSAGES] + ) == [ { "role": "assistant", "parts": [ @@ -2510,7 +2591,7 @@ async def test_ai_client_span_gets_agent_from_scope( def _get_messages_from_span(span_data): """Helper to extract and parse messages from span data.""" - messages_data = span_data["gen_ai.request.messages"] + messages_data = span_data[ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] return ( json.loads(messages_data) if isinstance(messages_data, str) else messages_data ) @@ -2549,7 +2630,7 @@ async def test_binary_content_encoding_image( items = capture_items("span") span = sentry_sdk.start_span( - name="custom span", attributes={"sentry.op": "test_span"} + name="custom span", attributes={ATTRIBUTE_NAMES.SENTRY_OP: "test_span"} ) binary_content = BinaryContent( data=b"fake_image_data_12345", media_type="image/png" @@ -2589,7 +2670,7 @@ async def test_binary_content_encoding_mixed_content( items = capture_items("span") span = sentry_sdk.start_span( - name="custom span", attributes={"sentry.op": "test_span"} + name="custom span", attributes={ATTRIBUTE_NAMES.SENTRY_OP: "test_span"} ) binary_content = BinaryContent(data=b"fake_image_bytes", media_type="image/jpeg") user_part = UserPromptPart( @@ -2648,13 +2729,17 @@ async def test_binary_content_in_agent_run( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 chat_span = chat_spans[0] - if "gen_ai.request.messages" in chat_span["attributes"]: - messages_str = str(chat_span["attributes"]["gen_ai.request.messages"]) + if ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES in chat_span["attributes"]: + messages_str = str( + chat_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES] + ) assert any(keyword in messages_str for keyword in ["blob", "image", "base64"]) @@ -2672,7 +2757,7 @@ async def test_set_usage_data_with_cache_tokens( items = capture_items("span") span = sentry_sdk.start_span( - name="custom span", attributes={"sentry.op": "test_span"} + name="custom span", attributes={ATTRIBUTE_NAMES.SENTRY_OP: "test_span"} ) usage = RequestUsage( input_tokens=100, @@ -2686,9 +2771,13 @@ async def test_set_usage_data_with_cache_tokens( sentry_sdk.flush() spans = [item.payload for item in items] - assert spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] == 80 assert ( - spans[0]["attributes"][SPANDATA.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] == 20 + spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] + == 80 + ) + assert ( + spans[0]["attributes"][ATTRIBUTE_NAMES.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] + == 20 ) @@ -2768,7 +2857,9 @@ def test_image_url_base64_content_in_span( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] assert len(chat_spans) == 1 messages_data = _get_messages_from_span(chat_spans[0]["attributes"]) @@ -2844,7 +2935,9 @@ async def test_invoke_agent_image_url( sentry_sdk.flush() spans = [item.payload for item in items] chat_spans = [ - s for s in spans if s["attributes"].get("sentry.op", "") == "gen_ai.chat" + s + for s in spans + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.chat" ] messages_data = _get_messages_from_span(chat_spans[0]["attributes"]) for msg in messages_data: @@ -2898,18 +2991,20 @@ def multiply_numbers(a: int, b: int) -> int: tool_spans = [ s for s in spans - if s["attributes"].get("sentry.op", "") == "gen_ai.execute_tool" + if s["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, "") == "gen_ai.execute_tool" ] assert len(tool_spans) >= 1 tool_span = tool_spans[0] - assert tool_span["attributes"]["gen_ai.tool.name"] == "multiply_numbers" - assert SPANDATA.GEN_AI_TOOL_DESCRIPTION in tool_span["attributes"] + assert ( + tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_NAME] == "multiply_numbers" + ) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION in tool_span["attributes"] assert ( "Multiply two numbers" - in tool_span["attributes"][SPANDATA.GEN_AI_TOOL_DESCRIPTION] + in tool_span["attributes"][ATTRIBUTE_NAMES.GEN_AI_TOOL_DESCRIPTION] ) @@ -2922,7 +3017,7 @@ def _spans_by_op(items): sentry_sdk.flush() return [ ( - item.payload["attributes"].get("sentry.op", ""), + item.payload["attributes"].get(ATTRIBUTE_NAMES.SENTRY_OP, ""), item.payload["attributes"], ) for item in items @@ -2979,7 +3074,9 @@ def add_numbers(a: int, b: int) -> int: parts = [] for chat_span in chat_spans: - for message in json.loads(chat_span.get(SPANDATA.GEN_AI_OUTPUT_MESSAGES, "[]")): + for message in json.loads( + chat_span.get(ATTRIBUTE_NAMES.GEN_AI_OUTPUT_MESSAGES, "[]") + ): parts.extend(message["parts"]) part_types = {part["type"] for part in parts} @@ -2995,10 +3092,10 @@ def add_numbers(a: int, b: int) -> int: assert part_types == set() for chat_span in chat_spans: - assert SPANDATA.GEN_AI_RESPONSE_MODEL in chat_span + assert ATTRIBUTE_NAMES.GEN_AI_RESPONSE_MODEL in chat_span if not expect_outputs: - assert SPANDATA.GEN_AI_OUTPUT_MESSAGES not in chat_span + assert ATTRIBUTE_NAMES.GEN_AI_OUTPUT_MESSAGES not in chat_span @pytest.mark.asyncio @@ -3041,14 +3138,16 @@ def add_numbers(a: int, b: int) -> int: # Derive the expected return value from the arguments the model actually # sent, so the assertion does not depend on the test model's defaults. tool_span = tool_spans[0] - assert SPANDATA.GEN_AI_TOOL_CALL_RESULT not in tool_span - tool_input = json.loads(tool_span[SPANDATA.GEN_AI_TOOL_CALL_ARGUMENTS]) + assert ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_RESULT not in tool_span + tool_input = json.loads(tool_span[ATTRIBUTE_NAMES.GEN_AI_TOOL_CALL_ARGUMENTS]) expected_tool_return = str(tool_input["a"] + tool_input["b"]) tool_messages = [ message for chat_span in chat_spans - for message in json.loads(chat_span.get(SPANDATA.GEN_AI_REQUEST_MESSAGES, "[]")) + for message in json.loads( + chat_span.get(ATTRIBUTE_NAMES.GEN_AI_REQUEST_MESSAGES, "[]") + ) if message["role"] == "tool" ]