# -*- coding: utf-8 -*-"""The serialization module for the package."""importimportlibimportjsonfromtypingimportAnydef_default_serialize(obj:Any)->Any:"""Serialize the object when `json.dumps` cannot handle it."""ifhasattr(obj,"__module__")andhasattr(obj,"__class__"):# To avoid circular import, we hard code the module name hereif(obj.__module__=="agentscope.message.msg"andobj.__class__.__name__=="Msg"):returnobj.to_dict()returnobjdef_deserialize_hook(data:dict)->Any:"""Deserialize the JSON string to an object, including Msg object in AgentScope."""module_name=data.get("__module__",None)class_name=data.get("__name__",None)ifmodule_nameisnotNoneandclass_nameisnotNone:module=importlib.import_module(module_name)cls=getattr(module,class_name)ifhasattr(cls,"from_dict"):returncls.from_dict(data)returndata
[docs]defserialize(obj:Any)->str:"""Serialize the object to a JSON string. For AgentScope, this function supports to serialize `Msg` object for now. """# TODO: We leave the serialization of agents in next PRreturnjson.dumps(obj,ensure_ascii=False,default=_default_serialize)
[docs]defdeserialize(s:str)->Any:"""Deserialize the JSON string to an object For AgentScope, this function supports to serialize `Msg` object for now. """# TODO: We leave the serialization of agents in next PRreturnjson.loads(s,object_hook=_deserialize_hook)
[docs]defis_serializable(obj:Any)->bool:"""Check if the object is serializable in the scope of AgentScope."""try:serialize(obj)returnTrueexceptException:returnFalse