Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a method for normalizing data passed to set_data #2800

Merged
merged 3 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
55 changes: 40 additions & 15 deletions sentry_sdk/integrations/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,28 @@
hub.capture_event(event, hint=hint)


def _normalize_data(data):

Check warning on line 76 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L76

Added line #L76 was not covered by tests
# type: (Any) -> Any

# convert pydantic data (e.g. OpenAI v1+) to json compatible format
if hasattr(data, "model_dump"):
try:
return data.model_dump()
except Exception as e:
logger.warning("Could not convert pydantic data to JSON: %s", e)
return data

Check warning on line 85 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L81-L85

Added lines #L81 - L85 were not covered by tests
if isinstance(data, list):
return list(_normalize_data(x) for x in data)
if isinstance(data, dict):
return {k: _normalize_data(v) for (k, v) in data.items()}
return data

Check warning on line 90 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L90

Added line #L90 was not covered by tests


def set_data_normalized(span, key, value):

Check warning on line 93 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L93

Added line #L93 was not covered by tests
# type: (Span, str, Any) -> None
span.set_data(key, _normalize_data(value))

Check warning on line 95 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L95

Added line #L95 was not covered by tests


def _calculate_chat_completion_usage(
messages, response, span, streaming_message_responses=None
):
Expand Down Expand Up @@ -112,11 +134,11 @@
total_tokens = prompt_tokens + completion_tokens

if completion_tokens != 0:
span.set_data(COMPLETION_TOKENS_USED, completion_tokens)
set_data_normalized(span, COMPLETION_TOKENS_USED, completion_tokens)

Check warning on line 137 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L137

Added line #L137 was not covered by tests
if prompt_tokens != 0:
span.set_data(PROMPT_TOKENS_USED, prompt_tokens)
set_data_normalized(span, PROMPT_TOKENS_USED, prompt_tokens)

Check warning on line 139 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L139

Added line #L139 was not covered by tests
if total_tokens != 0:
span.set_data(TOTAL_TOKENS_USED, total_tokens)
set_data_normalized(span, TOTAL_TOKENS_USED, total_tokens)

Check warning on line 141 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L141

Added line #L141 was not covered by tests


def _wrap_chat_completion_create(f):
Expand Down Expand Up @@ -160,14 +182,17 @@

with capture_internal_exceptions():
if _should_send_default_pii() and integration.include_prompts:
span.set_data("ai.input_messages", messages)
span.set_data("ai.model_id", model)
span.set_data("ai.streaming", streaming)
set_data_normalized(span, "ai.input_messages", messages)

Check warning on line 185 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L185

Added line #L185 was not covered by tests

set_data_normalized(span, "ai.model_id", model)
set_data_normalized(span, "ai.streaming", streaming)

Check warning on line 188 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L187-L188

Added lines #L187 - L188 were not covered by tests

if hasattr(res, "choices"):
if _should_send_default_pii() and integration.include_prompts:
span.set_data(
"ai.responses", list(map(lambda x: x.message, res.choices))
set_data_normalized(
span,
"ai.responses",
list(map(lambda x: x.message, res.choices)),
)
_calculate_chat_completion_usage(messages, res, span)
span.__exit__(None, None, None)
Expand Down Expand Up @@ -200,15 +225,15 @@
_should_send_default_pii()
and integration.include_prompts
):
span.set_data("ai.responses", all_responses)
set_data_normalized(span, "ai.responses", all_responses)

Check warning on line 228 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L228

Added line #L228 was not covered by tests
_calculate_chat_completion_usage(
messages, res, span, all_responses
)
span.__exit__(None, None, None)

res._iterator = new_iterator()
else:
span.set_data("unknown_response", True)
set_data_normalized(span, "unknown_response", True)

Check warning on line 236 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L236

Added line #L236 was not covered by tests
span.__exit__(None, None, None)
return res

Expand Down Expand Up @@ -238,15 +263,15 @@
_should_send_default_pii() and integration.include_prompts
):
if isinstance(kwargs["input"], str):
span.set_data("ai.input_messages", [kwargs["input"]])
set_data_normalized(span, "ai.input_messages", kwargs["input"])

Check warning on line 266 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L266

Added line #L266 was not covered by tests
elif (
isinstance(kwargs["input"], list)
and len(kwargs["input"]) > 0
and isinstance(kwargs["input"][0], str)
):
span.set_data("ai.input_messages", kwargs["input"])
set_data_normalized(span, "ai.input_messages", kwargs["input"])

Check warning on line 272 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L272

Added line #L272 was not covered by tests
if "model" in kwargs:
span.set_data("ai.model_id", kwargs["model"])
set_data_normalized(span, "ai.model_id", kwargs["model"])

Check warning on line 274 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L274

Added line #L274 was not covered by tests
try:
response = f(*args, **kwargs)
except Exception as e:
Expand All @@ -271,8 +296,8 @@
if total_tokens == 0:
total_tokens = prompt_tokens

span.set_data(PROMPT_TOKENS_USED, prompt_tokens)
span.set_data(TOTAL_TOKENS_USED, total_tokens)
set_data_normalized(span, PROMPT_TOKENS_USED, prompt_tokens)
set_data_normalized(span, TOTAL_TOKENS_USED, total_tokens)

Check warning on line 300 in sentry_sdk/integrations/openai.py

View check run for this annotation

Codecov / codecov/patch

sentry_sdk/integrations/openai.py#L299-L300

Added lines #L299 - L300 were not covered by tests

return response

Expand Down
2 changes: 1 addition & 1 deletion tests/integrations/openai/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def test_nonstreaming_chat_completion(

if send_default_pii and include_prompts:
assert "hello" in span["data"]["ai.input_messages"][0]["content"]
assert "the model response" in span["data"]["ai.responses"][0]
assert "the model response" in span["data"]["ai.responses"][0]["content"]
else:
assert "ai.input_messages" not in span["data"]
assert "ai.responses" not in span["data"]
Expand Down