"""Class for a VectorStore-backed memory object."""fromtypingimportAny,Dict,List,Optional,Sequence,Unionfromlangchain_core._apiimportdeprecatedfromlangchain_core.documentsimportDocumentfromlangchain_core.vectorstoresimportVectorStoreRetrieverfrompydanticimportFieldfromlangchain.memory.chat_memoryimportBaseMemoryfromlangchain.memory.utilsimportget_prompt_input_key
[docs]@deprecated(since="0.3.1",removal="1.0.0",message=("Please see the migration guide at: ""https://python.langchain.com/docs/versions/migrating_memory/"),)classVectorStoreRetrieverMemory(BaseMemory):"""Store the conversation history in a vector store and retrieves the relevant parts of past conversation based on the input. """retriever:VectorStoreRetriever=Field(exclude=True)"""VectorStoreRetriever object to connect to."""memory_key:str="history"#: :meta private:"""Key name to locate the memories in the result of load_memory_variables."""input_key:Optional[str]=None"""Key name to index the inputs to load_memory_variables."""return_docs:bool=False"""Whether or not to return the result of querying the database directly."""exclude_input_keys:Sequence[str]=Field(default_factory=tuple)"""Input keys to exclude in addition to memory key when constructing the document"""@propertydefmemory_variables(self)->List[str]:"""The list of keys emitted from the load_memory_variables method."""return[self.memory_key]def_get_prompt_input_key(self,inputs:Dict[str,Any])->str:"""Get the input key for the prompt."""ifself.input_keyisNone:returnget_prompt_input_key(inputs,self.memory_variables)returnself.input_keydef_documents_to_memory_variables(self,docs:List[Document])->Dict[str,Union[List[Document],str]]:result:Union[List[Document],str]ifnotself.return_docs:result="\n".join([doc.page_contentfordocindocs])else:result=docsreturn{self.memory_key:result}
[docs]defload_memory_variables(self,inputs:Dict[str,Any])->Dict[str,Union[List[Document],str]]:"""Return history buffer."""input_key=self._get_prompt_input_key(inputs)query=inputs[input_key]docs=self.retriever.invoke(query)returnself._documents_to_memory_variables(docs)
[docs]asyncdefaload_memory_variables(self,inputs:Dict[str,Any])->Dict[str,Union[List[Document],str]]:"""Return history buffer."""input_key=self._get_prompt_input_key(inputs)query=inputs[input_key]docs=awaitself.retriever.ainvoke(query)returnself._documents_to_memory_variables(docs)
def_form_documents(self,inputs:Dict[str,Any],outputs:Dict[str,str])->List[Document]:"""Format context from this conversation to buffer."""# Each document should only include the current turn, not the chat historyexclude=set(self.exclude_input_keys)exclude.add(self.memory_key)filtered_inputs={k:vfork,vininputs.items()ifknotinexclude}texts=[f"{k}: {v}"fork,vinlist(filtered_inputs.items())+list(outputs.items())]page_content="\n".join(texts)return[Document(page_content=page_content)]
[docs]defsave_context(self,inputs:Dict[str,Any],outputs:Dict[str,str])->None:"""Save context from this conversation to buffer."""documents=self._form_documents(inputs,outputs)self.retriever.add_documents(documents)
[docs]asyncdefasave_context(self,inputs:Dict[str,Any],outputs:Dict[str,str])->None:"""Save context from this conversation to buffer."""documents=self._form_documents(inputs,outputs)awaitself.retriever.aadd_documents(documents)
[docs]defclear(self)->None:"""Nothing to clear."""
[docs]asyncdefaclear(self)->None:"""Nothing to clear."""