Skip to content

Commit d9e701f

Browse files
authored
fix: improve json serialization (#358)
1 parent 85388ef commit d9e701f

4 files changed

Lines changed: 145 additions & 5 deletions

File tree

langfuse/serializer.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,11 @@ def default(self, obj: Any):
3939
if isinstance(obj, (dict, list, str, int, float, type(None))):
4040
return obj
4141

42-
return JSONEncoder.default(self, obj)
42+
if hasattr(obj, "__slots__"):
43+
return self.default(
44+
{slot: getattr(obj, slot, None) for slot in obj.__slots__}
45+
)
46+
elif hasattr(obj, "__dict__"):
47+
return self.default(vars(obj))
48+
else:
49+
return JSONEncoder.default(self, obj)

poetry.lock

Lines changed: 127 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ cohere = "^4.46"
3939
langchain-google-vertexai = "^0.0.5"
4040
langchain-openai = "^0.0.5"
4141
dashscope = "^1.14.1"
42+
pymongo = "^4.6.1"
4243

4344
[tool.poetry.extras]
4445
langchain = ["langchain"]

tests/test_json.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from datetime import datetime, timezone, date
66
from unittest.mock import patch
77
import uuid
8+
from bson import ObjectId
89

910
import pytest
1011
from langchain.schema.messages import HumanMessage
@@ -123,3 +124,11 @@ def test_data_uuid():
123124
result = json.dumps(test_id, cls=EventSerializer)
124125

125126
assert result == f'"{str(test_id)}"'
127+
128+
129+
def test_mongo_cursor():
130+
test_id = ObjectId("5f3e3e3e3e3e3e3e3e3e3e3e")
131+
132+
result = json.dumps(test_id, cls=EventSerializer)
133+
134+
assert result == '{"__id": null}'

0 commit comments

Comments
 (0)