Spaces:
Runtime error
Runtime error
Upload conversation_memory.py
Browse files- conversation_memory.py +21 -0
conversation_memory.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
class ConversationMemory:
|
| 3 |
+
def __init__(self):
|
| 4 |
+
self.sessions = {}
|
| 5 |
+
|
| 6 |
+
def add_to_history(self, session_id: str, user_input: str, response: str):
|
| 7 |
+
if session_id not in self.sessions:
|
| 8 |
+
self.sessions[session_id] = []
|
| 9 |
+
self.sessions[session_id].append({"user": user_input, "bot": response})
|
| 10 |
+
|
| 11 |
+
def get_history(self, session_id: str, last_n=5):
|
| 12 |
+
history = self.sessions.get(session_id, [])
|
| 13 |
+
return history[-last_n:]
|
| 14 |
+
|
| 15 |
+
def clear_history(self, session_id: str):
|
| 16 |
+
if session_id in self.sessions:
|
| 17 |
+
self.sessions[session_id] = []
|
| 18 |
+
|
| 19 |
+
def summarize_history(self, session_id: str):
|
| 20 |
+
history = self.get_history(session_id)
|
| 21 |
+
return "\n".join([f"User: {h['user']}\nBot: {h['bot']}" for h in history])
|