Skip to content

Commit a5e8596

Browse files
committed
Add a method for normalizing data passed to set_data
1 parent ff0a94b commit a5e8596

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

sentry_sdk/tracing.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,9 +410,26 @@ def set_tag(self, key, value):
410410
# type: (str, Any) -> None
411411
self._tags[key] = value
412412

413+
@staticmethod
414+
def _normalize_data(data):
415+
# type: (Any) -> Any
416+
417+
# convert pydantic data (e.g. OpenAI v1+) to json compatible format
418+
if hasattr(data, "model_dump"):
419+
try:
420+
return data.model_dump()
421+
except Exception as e:
422+
logger.warning("Could not convert pydantic data to JSON: %s", e)
423+
return data
424+
if isinstance(data, list):
425+
return list(Span._normalize_data(x) for x in data)
426+
if isinstance(data, dict):
427+
return {k: Span._normalize_data(v) for (k, v) in data.items()}
428+
return data
429+
413430
def set_data(self, key, value):
414431
# type: (str, Any) -> None
415-
self._data[key] = value
432+
self._data[key] = self._normalize_data(value)
416433

417434
def set_status(self, value):
418435
# type: (str) -> None

tests/integrations/openai/test_openai.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def test_nonstreaming_chat_completion(
7373

7474
if send_default_pii and include_prompts:
7575
assert "hello" in span["data"]["ai.input_messages"][0]["content"]
76-
assert "the model response" in span["data"]["ai.responses"][0]
76+
assert "the model response" in span["data"]["ai.responses"][0]["content"]
7777
else:
7878
assert "ai.input_messages" not in span["data"]
7979
assert "ai.responses" not in span["data"]

0 commit comments

Comments
 (0)