codekingpro/portable-devtools
114k
1from typing import Any2 3from langchain_core._api import deprecated4from langchain_core.messages import BaseMessage, get_buffer_string5from typing_extensions import override6 7from langchain_classic.memory.chat_memory import BaseChatMemory8 9 10@deprecated(11 since="0.3.1",12 removal="2.0.0",13 alternative="langchain.agents.create_agent",14 addendum=(15 "For agents that need to remember prior interactions, use "16 "`create_agent` with checkpointing or the `Store` API. See "17 "https://docs.langchain.com/oss/python/langchain/short-term-memory and "18 "https://docs.langchain.com/oss/python/langchain/long-term-memory"19 ),20)21class ConversationBufferWindowMemory(BaseChatMemory):22 """Use to keep track of the last k turns of a conversation.23 24 If the number of messages in the conversation is more than the maximum number25 of messages to keep, the oldest messages are dropped.26 """27 28 human_prefix: str = "Human"29 ai_prefix: str = "AI"30 memory_key: str = "history"31 k: int = 532 """Number of messages to store in buffer."""33 34 @property35 def buffer(self) -> str | list[BaseMessage]:36 """String buffer of memory."""37 return self.buffer_as_messages if self.return_messages else self.buffer_as_str38 39 @property40 def buffer_as_str(self) -> str:41 """Exposes the buffer as a string in case return_messages is False."""42 messages = self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []43 return get_buffer_string(44 messages,45 human_prefix=self.human_prefix,46 ai_prefix=self.ai_prefix,47 )48 49 @property50 def buffer_as_messages(self) -> list[BaseMessage]:51 """Exposes the buffer as a list of messages in case return_messages is True."""52 return self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []53 54 @property55 def memory_variables(self) -> list[str]:56 """Will always return list of memory variables."""57 return [self.memory_key]58 59 @override60 def load_memory_variables(self, inputs: dict[str, Any]) -> dict[str, Any]:61 """Return history buffer."""62 return {self.memory_key: self.buffer}63 