[docs]def__init__(self,session_id:str,save_dir:str)->None:"""Initialize the JSON session class. Args: session_id (`str`): The session id. save_dir (`str`): The directory to save the session state. """super().__init__(session_id=session_id)self.save_dir=save_dir
@propertydefsave_path(self)->str:"""The path to save the session state."""os.makedirs(self.save_dir,exist_ok=True)returnos.path.join(self.save_dir,f"{self.session_id}.json")
[docs]asyncdefsave_session_state(self,**state_modules_mapping:StateModule,)->None:"""Load the state dictionary from a JSON file. Args: **state_modules_mapping (`dict[str, StateModule]`): A dictionary mapping of state module names to their instances. """state_dicts={name:state_module.state_dict()forname,state_moduleinstate_modules_mapping.items()}withopen(self.save_path,"w",encoding="utf-8")asfile:json.dump(state_dicts,file,ensure_ascii=False)
[docs]asyncdefload_session_state(self,**state_modules_mapping:StateModule,)->None:"""Get the state dictionary to be saved to a JSON file. Args: state_modules_mapping (`list[StateModule]`): The list of state modules to be loaded. """ifos.path.exists(self.save_path):withopen(self.save_path,"r",encoding="utf-8")asfile:states=json.load(file)forname,state_moduleinstate_modules_mapping.items():ifnameinstates:state_module.load_state_dict(states[name])else:raiseValueError(f"Failed to load session state for file {self.save_path} ""does not exist.",)