Spaces:
Paused
Paused
Create memory.py
Browse files
memory.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
|
| 3 |
+
conn = sqlite3.connect("memory.db", check_same_thread=False)
|
| 4 |
+
cursor = conn.cursor()
|
| 5 |
+
|
| 6 |
+
cursor.execute("""
|
| 7 |
+
CREATE TABLE IF NOT EXISTS conversations (
|
| 8 |
+
user_id TEXT,
|
| 9 |
+
role TEXT,
|
| 10 |
+
content TEXT
|
| 11 |
+
)
|
| 12 |
+
""")
|
| 13 |
+
conn.commit()
|
| 14 |
+
|
| 15 |
+
def save_message(user_id, role, content):
|
| 16 |
+
cursor.execute(
|
| 17 |
+
"INSERT INTO conversations VALUES (?, ?, ?)",
|
| 18 |
+
(user_id, role, content)
|
| 19 |
+
)
|
| 20 |
+
conn.commit()
|
| 21 |
+
|
| 22 |
+
def load_memory(user_id, limit=6):
|
| 23 |
+
cursor.execute("""
|
| 24 |
+
SELECT role, content FROM conversations
|
| 25 |
+
WHERE user_id=?
|
| 26 |
+
ORDER BY rowid DESC
|
| 27 |
+
LIMIT ?
|
| 28 |
+
""", (user_id, limit))
|
| 29 |
+
|
| 30 |
+
rows = cursor.fetchall()
|
| 31 |
+
return list(reversed(rows))
|
| 32 |
+
|