Spaces:
No application file
No application file
Download chat_memory.py from Hemavathineelirothu/Assignment: direct link, hf CLI and curl.
- Browser
- Download file 1.23 kB
-
https://huggingface.co/spaces/Hemavathineelirothu/Assignment/resolve/main/chat_memory.py
- Command line
-
hf download hf://spaces/Hemavathineelirothu/Assignment/chat_memory.py
-
curl -L -o chat_memory.py https://huggingface.co/spaces/Hemavathineelirothu/Assignment/resolve/main/chat_memory.py
1.23 kB
| # 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() | |