Skip to content

Commit acfc5a0

Browse files
feat: add serialization of numpy ndarray (#1246)
Co-authored-by: Hassieb Pakzad <68423100+hassiebp@users.noreply.github.com>
1 parent 11b907b commit acfc5a0

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

langfuse/_utils/serializer.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ def default(self, obj: Any):
5757
if np is not None and isinstance(obj, np.generic):
5858
return obj.item()
5959

60+
# Check if numpy is available and if the object is a numpy array
61+
# If so, convert it to a Python list using the tolist() method
62+
if np is not None and isinstance(obj, np.ndarray):
63+
return obj.tolist()
64+
6065
if isinstance(obj, float) and math.isnan(obj):
6166
return None
6267

tests/test_serializer.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,29 @@ def test_numpy_float32():
183183
serializer = EventSerializer()
184184

185185
assert serializer.encode(data) == "1.0"
186+
187+
188+
def test_numpy_arrays():
189+
import numpy as np
190+
191+
serializer = EventSerializer()
192+
193+
# Test 1D array
194+
arr_1d = np.array([1, 2, 3])
195+
assert json.loads(serializer.encode(arr_1d)) == [1, 2, 3]
196+
197+
# Test 2D array
198+
arr_2d = np.array([[1, 2], [3, 4]])
199+
assert json.loads(serializer.encode(arr_2d)) == [[1, 2], [3, 4]]
200+
201+
# Test float array
202+
arr_float = np.array([1.1, 2.2, 3.3])
203+
assert json.loads(serializer.encode(arr_float)) == [1.1, 2.2, 3.3]
204+
205+
# Test empty array
206+
arr_empty = np.array([])
207+
assert json.loads(serializer.encode(arr_empty)) == []
208+
209+
# Test mixed types that numpy can handle
210+
arr_mixed = np.array([1, 2.5, 3])
211+
assert json.loads(serializer.encode(arr_mixed)) == [1.0, 2.5, 3.0]

0 commit comments

Comments
 (0)