類型 :
實作 :
i> 建立資料庫與基本函式
# --- memory_sqlite.py ---
import sqlite3
import time
from typing import List, Tuple
DB_PATH = "chat_memory.db"
def init_db():
"""初始化資料庫,若資料表不存在則建立"""
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
role TEXT, -- 'user' 或 'assistant'
text TEXT,
timestamp REAL
)
''')
conn.commit()
conn.close()
def log_message(user_id: str, role: str, text: str):
"""把對話紀錄存進資料庫"""
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
'INSERT INTO chat_history (user_id, role, text, timestamp) VALUES (?, ?, ?, ?)',
(user_id, role, text, time.time())
)
conn.commit()
conn.close()
def get_recent_messages(user_id: str, n: int = 5) -> List[Tuple[str, str]]:
"""取出最近 n 筆對話,依時間排序"""
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(
'SELECT role, text FROM chat_history WHERE user_id=? ORDER BY id DESC LIMIT ?',
(user_id, n)
)
rows = c.fetchall()
conn.close()
# 倒轉,讓舊的在上面、新的在下面
return list(reversed(rows))
# 初始化資料表
init_db()
print("✅ SQLite 記憶系統初始化完成")
ii> run_chat.py
from memory_sqlite import log_message, get_recent_messages
USER_ID = "demo_user"
def chatbot_loop():
print("💬 簡易對話系統(輸入 q 離開)")
while True:
user_input = input("你:")
if user_input.lower() in ["q", "quit", "exit"]:
print("👋 再見!")
break
# 1️⃣ 記錄使用者訊息
log_message(USER_ID, "user", user_input)
# 2️⃣ (這裡用簡單 echo 模擬回答)
reply = f"(回覆)你剛說:{user_input}"
log_message(USER_ID, "assistant", reply)
# 3️⃣ 顯示回覆
print("助理:", reply)
# 4️⃣ 顯示最近對話(方便檢查)
recent = get_recent_messages(USER_ID, n=5)
print("\n--- 📝 最近對話 ---")
for role, text in recent:
print(f"{role}: {text}")
print("--------------------\n")
# 啟動 CLI
chatbot_loop()