-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializer.py
More file actions
54 lines (46 loc) · 1.83 KB
/
serializer.py
File metadata and controls
54 lines (46 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from datetime import date, datetime
from dataclasses import is_dataclass, asdict
from json import JSONEncoder
from typing import Any
from uuid import UUID
from datetime_util import serialize_datetime
from pydantic import BaseModel
# Attempt to import Serializable
try:
from langchain.load.serializable import Serializable
except ImportError:
# If Serializable is not available, set it to NoneType
Serializable = type(None)
class EventSerializer(JSONEncoder):
def default(self, obj: Any):
if isinstance(obj, (datetime)):
# Timezone-awareness check
return serialize_datetime(obj)
# LlamaIndex StreamingAgentChatResponse is not serializable by default as it is a generator
# Attention: StreamingAgentChatResponse is a also a dataclass, so check for it first
if type(obj).__name__ == "StreamingAgentChatResponse":
return str(obj)
if is_dataclass(obj):
return asdict(obj)
if isinstance(obj, UUID):
return str(obj)
if isinstance(obj, bytes):
return obj.decode("utf-8")
if isinstance(obj, (date)):
return obj.isoformat()
if isinstance(obj, BaseModel):
return obj.dict()
# if langchain is not available, the Serializable type is NoneType
if Serializable is not None and isinstance(obj, Serializable):
return obj.to_json()
# Standard JSON-encodable types
if isinstance(obj, (dict, list, str, int, float, type(None))):
return obj
if hasattr(obj, "__slots__"):
return self.default(
{slot: getattr(obj, slot, None) for slot in obj.__slots__}
)
elif hasattr(obj, "__dict__"):
return self.default(vars(obj))
else:
return JSONEncoder.default(self, obj)