From e2dc235cd0988d2e8be6b36a292183eda6aa6681 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 7 Jul 2025 18:46:49 +0000 Subject: [PATCH] Add numpy array serialization support to EventSerializer Co-authored-by: marc --- langfuse/_utils/serializer.py | 5 +++++ tests/test_serializer.py | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/langfuse/_utils/serializer.py b/langfuse/_utils/serializer.py index f8ae4ed92..0d6237f1c 100644 --- a/langfuse/_utils/serializer.py +++ b/langfuse/_utils/serializer.py @@ -57,6 +57,11 @@ def default(self, obj: Any): if np is not None and isinstance(obj, np.generic): return obj.item() + # Check if numpy is available and if the object is a numpy array + # If so, convert it to a Python list using the tolist() method + if np is not None and isinstance(obj, np.ndarray): + return obj.tolist() + if isinstance(obj, float) and math.isnan(obj): return None diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 259e9d185..e9f1277bd 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -183,3 +183,29 @@ def test_numpy_float32(): serializer = EventSerializer() assert serializer.encode(data) == "1.0" + + +def test_numpy_arrays(): + import numpy as np + + serializer = EventSerializer() + + # Test 1D array + arr_1d = np.array([1, 2, 3]) + assert json.loads(serializer.encode(arr_1d)) == [1, 2, 3] + + # Test 2D array + arr_2d = np.array([[1, 2], [3, 4]]) + assert json.loads(serializer.encode(arr_2d)) == [[1, 2], [3, 4]] + + # Test float array + arr_float = np.array([1.1, 2.2, 3.3]) + assert json.loads(serializer.encode(arr_float)) == [1.1, 2.2, 3.3] + + # Test empty array + arr_empty = np.array([]) + assert json.loads(serializer.encode(arr_empty)) == [] + + # Test mixed types that numpy can handle + arr_mixed = np.array([1, 2.5, 3]) + assert json.loads(serializer.encode(arr_mixed)) == [1.0, 2.5, 3.0]