[docs]classUpstashRedisChatMessageHistory(BaseChatMessageHistory):"""Chat message history stored in an Upstash Redis database."""
[docs]def__init__(self,session_id:str,url:str="",token:str="",key_prefix:str="message_store:",ttl:Optional[int]=None,):try:fromupstash_redisimportRedisexceptImportError:raiseImportError("Could not import upstash redis python package. ""Please install it with `pip install upstash_redis`.")ifurl==""ortoken=="":raiseValueError("UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN are needed.")try:self.redis_client=Redis(url=url,token=token)exceptException:logger.error("Upstash Redis instance could not be initiated.")self.session_id=session_idself.key_prefix=key_prefixself.ttl=ttl
@propertydefkey(self)->str:"""Construct the record key to use"""returnself.key_prefix+self.session_id@propertydefmessages(self)->List[BaseMessage]:# type: ignore"""Retrieve the messages from Upstash Redis"""_items=self.redis_client.lrange(self.key,0,-1)items=[json.loads(m)formin_items[::-1]]messages=messages_from_dict(items)returnmessages
[docs]defadd_message(self,message:BaseMessage)->None:"""Append the message to the record in Upstash Redis"""self.redis_client.lpush(self.key,json.dumps(message_to_dict(message)))ifself.ttl:self.redis_client.expire(self.key,self.ttl)
[docs]defclear(self)->None:"""Clear session memory from Upstash Redis"""self.redis_client.delete(self.key)