forked from Archives/langchain
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
from typing import Any, Dict, List
|
|
|
|
from pydantic import BaseModel
|
|
|
|
from langchain.memory.chat_memory import BaseChatMemory
|
|
from langchain.schema import BaseMessage, get_buffer_string
|
|
|
|
|
|
class ConversationBufferWindowMemory(BaseChatMemory, BaseModel):
|
|
"""Buffer for storing conversation memory."""
|
|
|
|
human_prefix: str = "Human"
|
|
ai_prefix: str = "AI"
|
|
memory_key: str = "history" #: :meta private:
|
|
k: int = 5
|
|
|
|
@property
|
|
def buffer(self) -> List[BaseMessage]:
|
|
"""String buffer of memory."""
|
|
return self.chat_memory.messages
|
|
|
|
@property
|
|
def memory_variables(self) -> List[str]:
|
|
"""Will always return list of memory variables.
|
|
|
|
:meta private:
|
|
"""
|
|
return [self.memory_key]
|
|
|
|
def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
|
|
"""Return history buffer."""
|
|
|
|
if self.return_messages:
|
|
buffer: Any = self.buffer[-self.k * 2 :]
|
|
else:
|
|
buffer = get_buffer_string(
|
|
self.buffer[-self.k * 2 :],
|
|
human_prefix=self.human_prefix,
|
|
ai_prefix=self.ai_prefix,
|
|
)
|
|
return {self.memory_key: buffer}
|