|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import abc |
| 4 | +import json |
4 | 5 | from collections.abc import Mapping, Sequence |
5 | 6 | from typing import TYPE_CHECKING, Any |
6 | 7 |
|
7 | 8 | if TYPE_CHECKING: |
8 | 9 | from openai.types.responses import Response, ResponseInputItemParam |
9 | 10 |
|
| 11 | +# JavaScript's Number.MAX_SAFE_INTEGER (2^53 - 1). Integers beyond this threshold |
| 12 | +# lose precision when parsed by JS, causing the Traces dashboard to display wrong values. |
| 13 | +_JS_MAX_SAFE_INTEGER = 9007199254740991 |
| 14 | + |
| 15 | + |
| 16 | +def _sanitize_bigint(value: Any) -> Any: |
| 17 | + """Recursively convert integers that exceed JS Number.MAX_SAFE_INTEGER to strings. |
| 18 | +
|
| 19 | + This prevents precision loss when the OpenAI Traces dashboard (JavaScript) parses |
| 20 | + large integer values that cannot be represented exactly as IEEE-754 doubles. |
| 21 | + """ |
| 22 | + if isinstance(value, bool): |
| 23 | + # bool is a subclass of int; must be checked first to avoid converting True/False |
| 24 | + return value |
| 25 | + if isinstance(value, int) and abs(value) > _JS_MAX_SAFE_INTEGER: |
| 26 | + return str(value) |
| 27 | + if isinstance(value, dict): |
| 28 | + return {k: _sanitize_bigint(v) for k, v in value.items()} |
| 29 | + if isinstance(value, list): |
| 30 | + return [_sanitize_bigint(item) for item in value] |
| 31 | + return value |
| 32 | + |
10 | 33 |
|
11 | 34 | class SpanData(abc.ABC): |
12 | 35 | """ |
@@ -157,10 +180,16 @@ def type(self) -> str: |
157 | 180 | return "function" |
158 | 181 |
|
159 | 182 | def export(self) -> dict[str, Any]: |
| 183 | + sanitized_input: str | None = None |
| 184 | + if self.input is not None: |
| 185 | + try: |
| 186 | + sanitized_input = json.dumps(_sanitize_bigint(json.loads(self.input))) |
| 187 | + except (json.JSONDecodeError, TypeError): |
| 188 | + sanitized_input = self.input |
160 | 189 | return { |
161 | 190 | "type": self.type, |
162 | 191 | "name": self.name, |
163 | | - "input": self.input, |
| 192 | + "input": sanitized_input, |
164 | 193 | "output": str(self.output) if self.output else None, |
165 | 194 | "mcp_data": self.mcp_data, |
166 | 195 | } |
|
0 commit comments