From f9f23f9f24e8e27a3ce43adba60b80a3a4a381b4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:38:07 +0000 Subject: [PATCH 1/5] feat(ai): Set gen_ai.tool.definitions.hash and gen_ai.system_instructions.hash Hash the tools and system instructions of Anthropic and OpenAI requests, so a reader can tell a changed prompt prefix apart from an expired provider cache. The hashes are set even when inputs are not recorded. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- sentry_sdk/ai/utils.py | 80 +++++++++++++++- sentry_sdk/consts.py | 12 +++ sentry_sdk/integrations/anthropic.py | 3 + sentry_sdk/integrations/openai.py | 17 ++++ .../integrations/anthropic/test_anthropic.py | 58 ++++++++++++ tests/integrations/openai/test_openai.py | 91 +++++++++++++++++++ 6 files changed, 260 insertions(+), 1 deletion(-) diff --git a/sentry_sdk/ai/utils.py b/sentry_sdk/ai/utils.py index 4ec9806da8..c831b922b5 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,75 @@ def set_conversation_id(conversation_id: str) -> None: """ scope = sentry_sdk.get_current_scope() scope.set_conversation_id(conversation_id) + + +def _without_cache_control(value: "object") -> "object": + if isinstance(value, dict): + return { + key: _without_cache_control(item) + for key, item in value.items() + if key != "cache_control" + } + if isinstance(value, (list, tuple)): + return [_without_cache_control(item) for item in value] + return value + + +def _hash_request_value(value: "object") -> "Optional[str]": + try: + canonical = json.dumps( + _without_cache_control(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + except (TypeError, ValueError): + return None + return hashlib.sha256(canonical).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..7498c74707 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -5739,3 +5739,61 @@ 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.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 expected values are the examples of the attribute definitions in sentry-conventions. + assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "9faa2f609693ce94" + assert first[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "776e84186ddaa3b9" + assert second[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "9faa2f609693ce94" + assert second[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "f6627a526a7f0ea5" + 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..0dd9c7bac2 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -4511,3 +4511,94 @@ async def test_streaming_responses_api_ttft_async( assert isinstance(ttft, float) assert ttft > 0 + + +@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] == "70fa612a9e191fe0" + # Only the leading system message is part of the hash. + assert first[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "5278c395f9a424a4" + 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] == "24df1612c955df8e" + 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] == "7f62469f38f0303b" From 9c090c5ec8779d1f7fec729c9efcb9967e582a58 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:47:34 +0000 Subject: [PATCH 2/5] test(anthropic): Skip request hash test on versions without tools --- tests/integrations/anthropic/test_anthropic.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index 7498c74707..8daeee162c 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -5741,6 +5741,10 @@ def test_stream_messages_reasoning_tokens( 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( From 97c62e1d38229f094c923fd85b8d33ccd8bb6c79 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:58:07 +0000 Subject: [PATCH 3/5] test(openai): Skip request hash test on versions without tools --- tests/integrations/openai/test_openai.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/integrations/openai/test_openai.py b/tests/integrations/openai/test_openai.py index 0dd9c7bac2..48da3f49f2 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -4513,6 +4513,10 @@ async def test_streaming_responses_api_ttft_async( 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, From 1fe7b0436084f46ac0b3bed02b21410d8845c0b4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:06:59 +0000 Subject: [PATCH 4/5] perf(ai): Skip the cache_control copy when hashing request values that have none Hash list items one by one with a shared JSON encoder, and copy an item without cache_control only when its JSON has that key. The hashes stay the same. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- sentry_sdk/ai/utils.py | 30 +++++++++++++++++++++++------- tests/test_ai_monitoring.py | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/sentry_sdk/ai/utils.py b/sentry_sdk/ai/utils.py index c831b922b5..4385a58b5b 100644 --- a/sentry_sdk/ai/utils.py +++ b/sentry_sdk/ai/utils.py @@ -512,17 +512,33 @@ def _without_cache_control(value: "object") -> "object": return value +# One encoder, because `json.dumps` with options builds a new encoder on every call. +_CANONICAL_JSON_ENCODER = json.JSONEncoder( + sort_keys=True, separators=(",", ":"), ensure_ascii=False +) +_canonical_json = _CANONICAL_JSON_ENCODER.encode + + +def _canonical_json_without_cache_control(value: "object") -> str: + # Most values have no `cache_control` key, so skip the copy that removes it. The JSON of a + # `cache_control` key always contains this string. List items are checked one by one, because + # usually only one tool or content block has the key. + if isinstance(value, (list, tuple)): + return "[%s]" % ",".join( + _canonical_json_without_cache_control(item) for item in value + ) + canonical = _canonical_json(value) + if '"cache_control"' in canonical: + canonical = _canonical_json(_without_cache_control(value)) + return canonical + + def _hash_request_value(value: "object") -> "Optional[str]": try: - canonical = json.dumps( - _without_cache_control(value), - sort_keys=True, - separators=(",", ":"), - ensure_ascii=False, - ).encode("utf-8") + canonical = _canonical_json_without_cache_control(value) except (TypeError, ValueError): return None - return hashlib.sha256(canonical).hexdigest()[:_REQUEST_HASH_LENGTH] + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:_REQUEST_HASH_LENGTH] def get_leading_system_messages(messages: "object") -> "list[object]": diff --git a/tests/test_ai_monitoring.py b/tests/test_ai_monitoring.py index e6ea0eef6e..6c3c28d0ad 100644 --- a/tests/test_ai_monitoring.py +++ b/tests/test_ai_monitoring.py @@ -1,6 +1,11 @@ +import hashlib +import json + import pytest from sentry_sdk.ai.utils import ( + _hash_request_value, + _without_cache_control, get_modality_from_mime_type, parse_data_uri, transform_anthropic_content_part, @@ -887,3 +892,25 @@ def test_google_file_data_not_dict_returns_none(self): """Test that Google file_data with non-dict value returns None""" content_part = {"file_data": "not_a_dict"} assert transform_content_part(content_part) is None + + +@pytest.mark.parametrize( + "value", + [ + [{"name": "get_weather", "input_schema": {"type": "object", "b": 1, "a": 2}}], + [{"type": "text", "text": "Hi", "cache_control": {"type": "ephemeral"}}], + [{"type": "text", "text": "Hi", "extra": [{"cache_control": None}]}], + ({"text": "mentions cache_control", "é": "ü"},), + [{"text": '"cache_control"'}], + "You are a helpful assistant", + ], +) +def test_hash_request_value_fast_path_matches_cache_control_copy(value): + # The hash skips the copy that removes `cache_control` when the JSON has no such key. + slow = json.dumps( + _without_cache_control(value), + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ).encode("utf-8") + assert _hash_request_value(value) == hashlib.sha256(slow).hexdigest()[:16] From 0548142ec98d55eec05f2c3e1b2df09a6b9fd93a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:20:29 +0000 Subject: [PATCH 5/5] ref(ai): Hash gen_ai request values as the provider client sends them Hash the JSON in insertion order and keep cache_control, instead of a canonical form. A key reorder or a moved cache_control breakpoint now changes the hash, because the provider sees different bytes. The expected values are now per-SDK vectors. Co-Authored-By: Burak Yigit Kaya <126780+BYK@users.noreply.github.com> --- sentry_sdk/ai/utils.py | 38 ++----------------- .../integrations/anthropic/test_anthropic.py | 8 ++-- tests/integrations/openai/test_openai.py | 8 ++-- tests/test_ai_monitoring.py | 27 ------------- 4 files changed, 11 insertions(+), 70 deletions(-) diff --git a/sentry_sdk/ai/utils.py b/sentry_sdk/ai/utils.py index 4385a58b5b..ad09f016fe 100644 --- a/sentry_sdk/ai/utils.py +++ b/sentry_sdk/ai/utils.py @@ -500,45 +500,13 @@ def set_conversation_id(conversation_id: str) -> None: scope.set_conversation_id(conversation_id) -def _without_cache_control(value: "object") -> "object": - if isinstance(value, dict): - return { - key: _without_cache_control(item) - for key, item in value.items() - if key != "cache_control" - } - if isinstance(value, (list, tuple)): - return [_without_cache_control(item) for item in value] - return value - - -# One encoder, because `json.dumps` with options builds a new encoder on every call. -_CANONICAL_JSON_ENCODER = json.JSONEncoder( - sort_keys=True, separators=(",", ":"), ensure_ascii=False -) -_canonical_json = _CANONICAL_JSON_ENCODER.encode - - -def _canonical_json_without_cache_control(value: "object") -> str: - # Most values have no `cache_control` key, so skip the copy that removes it. The JSON of a - # `cache_control` key always contains this string. List items are checked one by one, because - # usually only one tool or content block has the key. - if isinstance(value, (list, tuple)): - return "[%s]" % ",".join( - _canonical_json_without_cache_control(item) for item in value - ) - canonical = _canonical_json(value) - if '"cache_control"' in canonical: - canonical = _canonical_json(_without_cache_control(value)) - return canonical - - 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: - canonical = _canonical_json_without_cache_control(value) + serialized = json.dumps(value, separators=(",", ":"), ensure_ascii=False) except (TypeError, ValueError): return None - return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:_REQUEST_HASH_LENGTH] + return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:_REQUEST_HASH_LENGTH] def get_leading_system_messages(messages: "object") -> "list[object]": diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index 8daeee162c..4b4619f772 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -5794,10 +5794,10 @@ def test_request_hash_attributes(sentry_init, capture_items, record_inputs): sentry_sdk.flush() first, second, third = (item.payload["attributes"] for item in items) - # The expected values are the examples of the attribute definitions in sentry-conventions. - assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "9faa2f609693ce94" + # 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] == "9faa2f609693ce94" - assert second[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "f6627a526a7f0ea5" + 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 48da3f49f2..5a62f97b28 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -4564,9 +4564,9 @@ def test_chat_completion_request_hash_attributes( sentry_sdk.flush() first, second = (item.payload["attributes"] for item in items) - assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "70fa612a9e191fe0" + 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] == "5278c395f9a424a4" + 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 @@ -4602,7 +4602,7 @@ def test_responses_request_hash_attributes(sentry_init, capture_items, record_in sentry_sdk.flush() first, second = (item.payload["attributes"] for item in items) - assert first[SPANDATA.GEN_AI_TOOL_DEFINITIONS_HASH] == "24df1612c955df8e" + 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] == "7f62469f38f0303b" + assert second[SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS_HASH] == "c8deddee8fe0b279" diff --git a/tests/test_ai_monitoring.py b/tests/test_ai_monitoring.py index 6c3c28d0ad..e6ea0eef6e 100644 --- a/tests/test_ai_monitoring.py +++ b/tests/test_ai_monitoring.py @@ -1,11 +1,6 @@ -import hashlib -import json - import pytest from sentry_sdk.ai.utils import ( - _hash_request_value, - _without_cache_control, get_modality_from_mime_type, parse_data_uri, transform_anthropic_content_part, @@ -892,25 +887,3 @@ def test_google_file_data_not_dict_returns_none(self): """Test that Google file_data with non-dict value returns None""" content_part = {"file_data": "not_a_dict"} assert transform_content_part(content_part) is None - - -@pytest.mark.parametrize( - "value", - [ - [{"name": "get_weather", "input_schema": {"type": "object", "b": 1, "a": 2}}], - [{"type": "text", "text": "Hi", "cache_control": {"type": "ephemeral"}}], - [{"type": "text", "text": "Hi", "extra": [{"cache_control": None}]}], - ({"text": "mentions cache_control", "é": "ü"},), - [{"text": '"cache_control"'}], - "You are a helpful assistant", - ], -) -def test_hash_request_value_fast_path_matches_cache_control_copy(value): - # The hash skips the copy that removes `cache_control` when the JSON has no such key. - slow = json.dumps( - _without_cache_control(value), - sort_keys=True, - separators=(",", ":"), - ensure_ascii=False, - ).encode("utf-8") - assert _hash_request_value(value) == hashlib.sha256(slow).hexdigest()[:16]