Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 63 additions & 1 deletion sentry_sdk/ai/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hashlib
import inspect
import json
from typing import TYPE_CHECKING
Expand All @@ -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:
Expand All @@ -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]":
"""
Expand Down Expand Up @@ -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
)
12 changes: 12 additions & 0 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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::
Expand Down
3 changes: 3 additions & 0 deletions sentry_sdk/integrations/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
17 changes: 17 additions & 0 deletions sentry_sdk/integrations/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
62 changes: 62 additions & 0 deletions tests/integrations/anthropic/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
95 changes: 95 additions & 0 deletions tests/integrations/openai/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading