[docs]classInMemoryMemory(MemoryBase):"""The in-memory memory class for storing messages."""
[docs]def__init__(self,)->None:"""Initialize the in-memory memory object."""super().__init__()self.content:list[Msg]=[]
[docs]defstate_dict(self)->dict:"""Convert the current memory into JSON data format."""return{"content":[_.to_dict()for_inself.content],}
[docs]defload_state_dict(self,state_dict:dict,strict:bool=True,)->None:"""Load the memory from JSON data. Args: state_dict (`dict`): The state dictionary to load, which should have a "content" field. strict (`bool`, defaults to `True`): If `True`, raises an error if any key in the module is not found in the state_dict. If `False`, skips missing keys. """self.content=[]fordatainstate_dict["content"]:data.pop("type",None)self.content.append(Msg.from_dict(data))
[docs]asyncdefsize(self)->int:"""The size of the memory."""returnlen(self.content)
[docs]asyncdefretrieve(self,*args:Any,**kwargs:Any)->None:"""Retrieve items from the memory."""raiseNotImplementedError("The retrieve method is not implemented in "f"{self.__class__.__name__} class.",)
[docs]asyncdefdelete(self,index:Union[Iterable,int])->None:"""Delete the specified item by index(es). Args: index (`Union[Iterable, int]`): The index to delete. """ifisinstance(index,int):index=[index]invalid_index=[_for_inindexif0>_or_>=len(self.content)]ifinvalid_index:raiseIndexError(f"The index {invalid_index} does not exist.",)self.content=[_foridx,_inenumerate(self.content)ifidxnotinindex]
[docs]asyncdefadd(self,memories:Union[list[Msg],Msg,None],allow_duplicates:bool=False,)->None:"""Add message into the memory. Args: memories (`Union[list[Msg], Msg, None]`): The message to add. allow_duplicates (`bool`, defaults to `False`): If allow adding duplicate messages (with the same id) into the memory. """ifmemoriesisNone:returnifisinstance(memories,Msg):memories=[memories]ifnotisinstance(memories,list):raiseTypeError(f"The memories should be a list of Msg or a single Msg, "f"but got {type(memories)}.",)formsginmemories:ifnotisinstance(msg,Msg):raiseTypeError(f"The memories should be a list of Msg or a single Msg, "f"but got {type(msg)}.",)ifnotallow_duplicates:existing_ids=[_.idfor_inself.content]memories=[_for_inmemoriesif_.idnotinexisting_ids]self.content.extend(memories)
[docs]asyncdefget_memory(self)->list[Msg]:"""Get the memory content."""returnself.content
[docs]asyncdefclear(self)->None:"""Clear the memory content."""self.content=[]