diff --git a/sentry_sdk/ai/utils.py b/sentry_sdk/ai/utils.py index 4ec9806da8..ad09f016fe 100644 --- a/sentry_sdk/ai/utils.py +++ b/sentry_sdk/ai/utils.py @@ -1,3 +1,4 @@ +import hashlib import inspect import json from typing import TYPE_CHECKING @@ -8,7 +9,9 @@ from sentry_sdk.traces import Span import sentry_sdk -from sentry_sdk.utils import logger +from sentry_sdk.consts import SPANDATA +from sentry_sdk.traces import NoOpSpan +from sentry_sdk.utils import capture_internal_exceptions, logger class GEN_AI_ALLOWED_MESSAGE_ROLES: @@ -30,6 +33,9 @@ class GEN_AI_ALLOWED_MESSAGE_ROLES: for source_role in source_roles: GEN_AI_MESSAGE_ROLE_MAPPING[source_role] = target_role +_REQUEST_HASH_LENGTH = 16 +_SYSTEM_INSTRUCTION_ROLES = ("system", "developer") + def parse_data_uri(url: str) -> "Tuple[str, str]": """ @@ -492,3 +498,59 @@ def set_conversation_id(conversation_id: str) -> None: """ scope = sentry_sdk.get_current_scope() scope.set_conversation_id(conversation_id) + + +def _hash_request_value(value: "object") -> "Optional[str]": + # The JSON of the value as the provider client sends it: keys in insertion order, `cache_control` kept. + try: + serialized = json.dumps(value, separators=(",", ":"), ensure_ascii=False) + except (TypeError, ValueError): + return None + return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:_REQUEST_HASH_LENGTH] + + +def get_leading_system_messages(messages: "object") -> "list[object]": + """ + Return the messages with a system or developer role at the start of a message list. + """ + if not isinstance(messages, (list, tuple)): + return [] + + leading: "list[object]" = [] + for message in messages: + if ( + not isinstance(message, dict) + or message.get("role") not in _SYSTEM_INSTRUCTION_ROLES + ): + break + leading.append(message) + return leading + + +def set_request_hash_attributes( + span: "Span", tools: "object", system_instructions: "object" +) -> None: + """ + Set the gen_ai.tool.definitions.hash and gen_ai.system_instructions.hash attributes. + + Pass the request values as the caller passed them. The hashes let a reader tell a changed + prompt prefix apart from an expired provider cache, so they are set even when inputs are + not recorded. + """ + if isinstance(span, NoOpSpan): + return + + with capture_internal_exceptions(): + if isinstance(tools, (list, tuple)) and len(tools) > 0: + tools_hash = _hash_request_value(tools) + if tools_hash is not None: + span.set_attribute(SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH, tools_hash) + + if isinstance(system_instructions, (str, list, tuple)) and ( + len(system_instructions) > 0 + ): + system_hash = _hash_request_value(system_instructions) + if system_hash is not None: + span.set_attribute( + SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH, system_hash + ) diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index c78de49e79..fc790e566a 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -849,6 +849,12 @@ class SPANDATA: Example: [{"name": "get_weather", "description": "Get the weather for a given location"}, {"name": "get_news", "description": "Get the news for a given topic"}] """ + GEN_AI_TOOL_DEFINITIONS_HASH = "gen_ai.tool.definitions.hash" + """ + A short hash of the tool definitions in the request, to tell whether they changed between calls. + Example: "9faa2f609693ce94" + """ + GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions" """ The list of source system tool definitions available to the GenAI agent or model. @@ -873,6 +879,12 @@ class SPANDATA: Example: [{"type": "text", "text": "You are a helpful assistant."},{"type": "text", "text": "Be concise and clear."}] """ + GEN_AI_SYSTEM_INSTRUCTIONS_HASH = "gen_ai.system_instructions.hash" + """ + A short hash of the system instructions in the request, to tell whether they changed between calls. + Example: "776e84186ddaa3b9" + """ + GEN_AI_REQUEST_MESSAGES = "gen_ai.request.messages" """ .. deprecated:: diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index c09c0fdb9e..c36b574299 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -9,6 +9,7 @@ GEN_AI_ALLOWED_MESSAGE_ROLES, normalize_message_roles, set_data_normalized, + set_request_hash_attributes, transform_anthropic_content_part, ) from sentry_sdk.consts import OP, SPANDATA @@ -545,6 +546,8 @@ def _set_common_input_data( if top_p is not None and _is_given(top_p): span.set_attribute(SPANDATA.GEN_AI_REQUEST_TOP_P, top_p) + set_request_hash_attributes(span, tools, system) + if sentry_sdk.get_client().options["data_collection"]["gen_ai"]["inputs"]: if tools is not None and _is_given(tools) and len(tools) > 0: # type: ignore span.set_attribute( diff --git a/sentry_sdk/integrations/openai.py b/sentry_sdk/integrations/openai.py index e2fde6af33..c212ba574d 100644 --- a/sentry_sdk/integrations/openai.py +++ b/sentry_sdk/integrations/openai.py @@ -35,8 +35,10 @@ _transform_tool_definitions as _transform_tool_definitions_responses, ) from sentry_sdk.ai.utils import ( + get_leading_system_messages, normalize_message_roles, set_data_normalized, + set_request_hash_attributes, ) from sentry_sdk.consts import SPANDATA from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version @@ -391,6 +393,15 @@ def _set_responses_api_input_data( reasoning["effort"], ) + instructions = kwargs.get("instructions") + set_request_hash_attributes( + span, + kwargs.get("tools"), + instructions + if isinstance(instructions, str) and instructions + else get_leading_system_messages(kwargs.get("input")), + ) + if not sentry_sdk.get_client().options["data_collection"]["gen_ai"]["inputs"]: return @@ -502,6 +513,12 @@ def _set_completions_api_input_data( if reasoning_level is not None and _is_given(reasoning_level): span.set_attribute(SPANDATA.GEN_AI_REQUEST_REASONING_LEVEL, reasoning_level) + set_request_hash_attributes( + span, + kwargs.get("tools"), + get_leading_system_messages(kwargs.get("messages")), + ) + if not sentry_sdk.get_client().options["data_collection"]["gen_ai"]["inputs"]: return diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index 40bcfd55de..4b4619f772 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -5739,3 +5739,65 @@ def test_stream_messages_reasoning_tokens( assert span["attributes"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 assert span["attributes"][SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 assert span["attributes"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 15 + + +@pytest.mark.skipif( + ANTHROPIC_VERSION < (0, 27), + reason="Versions <0.27.0 do not accept tools in messages.create.", +) +@pytest.mark.parametrize("record_inputs", [True, False]) +def test_request_hash_attributes(sentry_init, capture_items, record_inputs): + sentry_init( + integrations=[AnthropicIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + data_collection={"gen_ai": {"inputs": record_inputs}}, + ) + + client = Anthropic(api_key="z") + client.messages._post = mock.Mock(return_value=EXAMPLE_MESSAGE) + items = capture_items("span") + + tool = { + "name": "get_weather", + "description": "Get the weather for a location", + "input_schema": { + "type": "object", + "properties": {"location": {"type": "string"}}, + "required": ["location"], + }, + } + messages = [{"role": "user", "content": "Hello, Claude"}] + + client.messages.create( + max_tokens=1024, + messages=messages, + model="model", + system="You are a helpful assistant.", + tools=[tool], + ) + client.messages.create( + max_tokens=1024, + messages=messages, + model="model", + system=[ + { + "type": "text", + "text": "You are a helpful assistant.", + "cache_control": {"type": "ephemeral"}, + } + ], + tools=[{**tool, "cache_control": {"type": "ephemeral"}}], + ) + client.messages.create(max_tokens=1024, messages=messages, model="model") + + sentry_sdk.flush() + first, second, third = (item.payload["attributes"] for item in items) + + # The hashes cover the JSON as sent, so a `cache_control` breakpoint changes them. + assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "d02cb9adda84be28" + assert first[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "776e84186ddaa3b9" + assert second[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "20a37e77f12e237c" + assert second[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "6007219e748f1109" + assert SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH not in third + assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH not in third diff --git a/tests/integrations/openai/test_openai.py b/tests/integrations/openai/test_openai.py index 763b927b98..5a62f97b28 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -4511,3 +4511,98 @@ async def test_streaming_responses_api_ttft_async( assert isinstance(ttft, float) assert ttft > 0 + + +@pytest.mark.skipif( + OPENAI_VERSION <= (1, 1, 0), + reason="Versions <=1.1.0 do not accept tools in chat.completions.create.", +) +@pytest.mark.parametrize("record_inputs", [True, False]) +def test_chat_completion_request_hash_attributes( + sentry_init, + capture_items, + nonstreaming_chat_completions_model_response, + record_inputs, +): + sentry_init( + integrations=[OpenAIIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + data_collection={"gen_ai": {"inputs": record_inputs}}, + ) + + client = OpenAI(api_key="z") + client.chat.completions._post = mock.Mock( + return_value=nonstreaming_chat_completions_model_response( + response_id="chat-id", + response_model="gpt-3.5-turbo", + message_content="the model response", + created=10000000, + usage=CompletionUsage( + prompt_tokens=20, + completion_tokens=10, + total_tokens=30, + ), + ) + ) + items = capture_items("span") + + client.chat.completions.create( + model="some-model", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "hello"}, + {"role": "system", "content": "Answer in French."}, + ], + tools=EXAMPLE_COMPLETIONS_TOOLS, + ) + client.chat.completions.create( + model="some-model", + messages=[{"role": "user", "content": "hello"}], + ) + + sentry_sdk.flush() + first, second = (item.payload["attributes"] for item in items) + + assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "f48d4663c473d689" + # Only the leading system message is part of the hash. + assert first[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "6a5ece0dad192db8" + assert SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH not in second + assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH not in second + + +@pytest.mark.skipif(SKIP_RESPONSES_TESTS, reason="Responses API not available") +@pytest.mark.parametrize("record_inputs", [True, False]) +def test_responses_request_hash_attributes(sentry_init, capture_items, record_inputs): + sentry_init( + integrations=[OpenAIIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + data_collection={"gen_ai": {"inputs": record_inputs}}, + ) + + client = OpenAI(api_key="z") + client.responses._post = mock.Mock(return_value=EXAMPLE_RESPONSE) + items = capture_items("span") + + client.responses.create( + model="gpt-4o", + instructions="You are a helpful assistant.", + input="hello", + tools=EXAMPLE_TOOLS, + ) + client.responses.create( + model="gpt-4o", + input=[ + {"role": "developer", "content": "You are a helpful assistant."}, + {"role": "user", "content": "hello"}, + ], + ) + + sentry_sdk.flush() + first, second = (item.payload["attributes"] for item in items) + + assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "4805d7a22e6f7471" + assert first[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "776e84186ddaa3b9" + assert SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH not in second + assert second[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "c8deddee8fe0b279"