Spaces:
No application file
No application file
File size: 1,225 Bytes
a7dcd7f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | # chat_memory.py
from collections import deque
from typing import Deque, Tuple, List
class ChatMemory:
"""
Sliding window chat memory. Stores (user_turn, bot_turn) pairs.
get_context() returns a concatenated string of the last N turns, formatted.
"""
def __init__(self, window_size: int = 4):
self.window_size = window_size
self.buffer: Deque[Tuple[str, str]] = deque(maxlen=window_size)
def add_turn(self, user_text: str, bot_text: str):
self.buffer.append((user_text.strip(), bot_text.strip()))
def get_context(self, with_prefix: bool = True) -> str:
"""
Return the assembled context. Example format:
User: ...
Bot: ...
User: ...
Bot: ...
"""
pieces: List[str] = []
for u, b in self.buffer:
if with_prefix:
pieces.append(f"User: {u}")
pieces.append(f"Bot: {b}")
else:
pieces.append(u)
pieces.append(b)
return "\n".join(pieces)
def get_recent_user(self) -> str:
if not self.buffer:
return ""
return self.buffer[-1][0]
def clear(self):
self.buffer.clear()
|