05|什麼是 記憶 / Session?AI 為什麼會「忘了你」

🧠 一句話:LLM 本身沒有記憶——所謂「AI 記得我們上次說過」,都是介面在每次呼叫時把對話歷史塞回 Context 製造的錯覺。
一、Session 是什麼
Session(會話)= 一連串「算同一次對話」的訊息範圍。
Session 開始
├── 你說 A
├── AI 回 A'
├── 你說 B(此時 AI 還記得 A → 因為 A 還在 Context)
├── AI 回 B'
└── ...
Session 結束 → 全部進垃圾桶
開新對話 = 開新 Session = AI 完全不記得上次。
二、為什麼 LLM「沒有記憶」?
LLM 是個無狀態函式:
output = LLM(input)
每次呼叫獨立——它不知道上次叫過它什麼。所有「記憶」都得開發者自己管。
你以為的 AI: 實際的 AI:
┌────────────────┐ ┌────────────────┐
│ AI(會記得) │ │ LLM(無狀態函式) │
│ 過去的我們 │ vs │ │
└────────────────┘ └────────────────┘
↑
每次傳完整 history
製造「有記憶」假象
三、記憶的三個層次
Layer 1:Session 記憶(最常見)
範圍:當下這個對話框內 實作:每次呼叫把對話歷史塞進 Context 失效:開新對話、超過 Context Window → 早期內容被截掉
Layer 2:User 記憶(跨 session)
範圍:同一使用者跨對話、跨日子 實作:vector DB 存對話摘要、上次 preferences、姓名等 例:ChatGPT 的「Memory」功能
Layer 3:Long-term Knowledge(跨使用者、跨產品)
範圍:產品級別的知識庫 實作:RAG over 公司文件、CRM、規範 例:Skill 系統、企業 RAG
四、實作模式
模式 A:純對話歷史(最簡單)
history = []
def chat(user_msg):
history.append({"role": "user", "content": user_msg})
response = claude.messages.create(
model="claude-opus-4-7",
messages=history,
)
history.append({"role": "assistant", "content": response.content})
return response.content
問題:對話一長 → 爆 Context Window。
模式 B:滑動視窗(保留最近 N 輪)
history.append(...)
trimmed = history[-20:] # 只保留最近 10 輪
問題:忘掉早期重要 context。
模式 C:摘要 + 滑動視窗
if len(history) > 50:
summary = claude.summarize(history[:30])
history = [summary] + history[-20:]
→ 多數 production app 用這招。
模式 D:Vector store + retrieval
# 對話完,存進 vector DB
vector_db.upsert(user_id, msg_embedding, msg_content)
# 下次對話,依當下問題撈相關歷史
relevant = vector_db.search(new_query_embedding, top_k=5)
context = format(relevant) + new_query
→ Memory 變 RAG。最 scalable。
五、跟 Session 相關的常見場景
| 場景 | 怎麼設計 |
|---|---|
| 客服 Bot | Session = 一通客訴;客戶離開 24h 後 archive |
| 個人助理 | User memory(preferences、上次提過的事) |
| Agent 工作流 | Skill memory + task state(不是真的 LLM 記憶) |
| 多 agent 協作 | Shared memory store(agents 互相讀寫) |
六、Memory 的「安全與隱私」考量
| 風險 | 解法 |
|---|---|
| 客戶資料外洩 | Memory 加密 + 分租戶隔離 |
| 模型訓練竊取 | 用「不訓客戶資料」的 vendor(如 Anthropic) |
| Prompt injection 污染記憶 | 寫入前過濾 + 信心評分 |
| 過時資訊 | 加 TTL 自動過期 |
→ 對金融業 / 上市櫃客戶來說,Memory 設計就是 安全龍蝦 規範的延伸。
七、案例:把資深專家的知識變成「分身」
想把一位資深專家數十萬字的經驗變成隨時可問的 AI,本質就是 Layer 3 long-term knowledge:
- ❌ 不是「把整批內容灌進 Context Window 每次都用」(太貴 + 中段精度差)
- ✅ 是「把內容 chunk + 進 vector DB,每次依當下問題撈 5-10 段」(詳見 RAG)
訪談這些專家 = 累積 Memory; 有人提問時 = 從 Memory 撈出最相關的幾位專家觀點。
八、常見誤解
| ❌ 誤解 | ✅ 正解 |
|---|---|
| 「ChatGPT 真的記得我」 | 它記得是介面把歷史塞回去,模型本身沒記憶 |
| 「LLM 可以 fine-tune 出記憶」 | 不行。Fine-tune 改的是「行為傾向」,不是「具體事實」 |
| 「越長 session 越聰明」 | 反而會慢、貴、精度下降 |
| 「Memory = vector DB」 | Vector DB 只是工具,Memory 是設計 |