Skip to content

Commit 93ec283

Browse files
committed
JSON encoder handle datetimes
1 parent 96a9d0f commit 93ec283

File tree

1 file changed

+12
-1
lines changed
  • util/opentelemetry-util-genai/src/opentelemetry/util/genai

1 file changed

+12
-1
lines changed

util/opentelemetry-util-genai/src/opentelemetry/util/genai/utils.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import datetime
1516
import json
1617
import logging
1718
import os
@@ -68,7 +69,17 @@ class _GenAiJsonEncoder(json.JSONEncoder):
6869
def default(self, o: Any) -> Any:
6970
if isinstance(o, bytes):
7071
return b64encode(o).decode()
71-
return super().default(o)
72+
elif isinstance(o, (datetime.datetime, datetime.date)):
73+
return o.isoformat()
74+
75+
try:
76+
return super().default(o)
77+
except TypeError:
78+
logger.warning(
79+
'failed to encode object "%s" to JSON. Falling back to str()',
80+
o,
81+
)
82+
return str(o)
7283

7384

7485
gen_ai_json_dump = partial(

0 commit comments

Comments
 (0)