iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
自我挑戰組

從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講系列 第 17

Day 17|Agent Design - Memory - 長期記憶的處理-mem0(3/5)

  • 分享至 

  • xImage
  •  

目標先講清楚:
有沒有能夠讓langGraph的workflow agnets可以自動偵測訊息內容,自動儲存或更新到memory中?答案是mem0

mem0可以做到什麼

當agent出現多輪對話的情境,或這需要切份不同使用者時,除了使用langchain的user_id和thread_id去把整個內容都存下來,如果能夠有套件可以自動擷取重要訊息、為訊息中提到的資訊建立關聯、並且自動更新每個user_id的資訊,可以為整個系統開發省下token, 和開發時間。

mem0可以做到;在它的blog文章中有提到:

Instead of compressing everything, intelligent systems identify specific facts, preferences, and patterns worth remembering long-term.
*智慧系統不是壓縮一切,而是識別值得長期記住的具體事實、偏好和模式。*

mem0怎麼做到

mem0 提供三種長期記憶操作:

  1. 事實記憶(Facts)
    • 從訊息抽取結構化的「事實條目」(偏好、日期、公司、地點…),存入向量庫以供語義檢索。
    • 適合「跨會話個人化」與「常用關鍵資訊」。
  2. 情節記憶(Episodic / History)
    • 對每個記憶維護時間序列歷史(ADD/UPDATE/DELETE)與內容快照。
    • 適合稽核、回放「這條記憶怎麼從 A 變成 B」。
  3. 語義記憶(Graph / Relations)
    • 建立實體與關係(誰負責什麼、誰和哪個地點/時間相關),支援關係型查詢。
    • 適合需要問「誰—做了—什麼」的場景。

1)事實記憶(Facts)

事實記憶是預設的記憶類型,當你調用add方法且infer=True時會自動觸發
使用向量檢索

from mem0 import Memory  
  
mem = Memory()  

messages = [
  {"role": "user", "content": "我叫 王大明,是 A 公司採購,喜歡紅眼班機。"},
  {"role": "assistant", "content": "好的,我記下你的偏好。"}
]

# 1) 寫入:抽取條目後存入
mem.add(messages=messages, user_id="u1", infer=True)

# 2) 檢索:語義搜尋回條目,回填到 Prompt
facts = mem.search(query="這位使用者的航班偏好?", user_id="u1", top_k=3)
context = "\n".join([f"- {f['text']}" for f in facts])
print(context)
# - 喜歡紅眼班機
# - 名字是 王大明
# - 公司是 A 公司

透過使用system prompt-FACT_RETRIEVAL_PROMPT,擷取重要資訊:

#以下僅為FACT_RETRIEVAL_PROMPT的片段,詳細參考參考資訊

Types of Information to Remember: 
1. Store Personal Preferences: Keep track of likes, dislikes, and specific preferences in various categories such as food, products, activities, and entertainment. 
2. Maintain Important Personal Details: Remember significant personal information like names, relationships, and important dates. 
3. Track Plans and Intentions: Note upcoming events, trips, goals, and any plans the user has shared. 
4. Remember Activity and Service Preferences: Recall preferences for dining, travel, hobbies, and other services. 
5. Monitor Health and Wellness Preferences: Keep a record of dietary restrictions, fitness routines, and other wellness-related information. 
6. Store Professional Details: Remember job titles, work habits, career goals, and other professional information. 
7. Miscellaneous Information Management: Keep track of favorite books, movies, brands, and other miscellaneous details that the user shares.
......

2)情節記憶(Episodic / History)

情節記憶會在任何記憶操作時自動觸發,也就是三種長期操作都會存,通過SQLite歷史追蹤系統記錄.

from mem0 import Memory  
mem = Memory()  

messages = [
  {"role": "user", "content": "我叫王大明,我喜歡紅眼班機。"},
  {"role": "assistant", "content": "收到。"}
]
# 建議只存 user,避免把助理回覆也寫入長期記憶
user_only = [m for m in messages if m["role"] == "user"]
mem.add(messages=user_only, user_id="u4", infer=False)

使用system prompt-DEFAULT_UPDATE_MEMORY_PROMPT,指示進行記憶更新的做法

#以下僅為DEFAULT_UPDATE_MEMORY_PROMPT的片段,詳細參考參考資訊
You are a smart memory manager which controls the memory of a system.
You can perform four operations: (1) add into the memory, (2) update the memory, (3) delete from the memory, and (4) no change.

Based on the above four operations, the memory will change.

Compare newly retrieved facts with the existing memory. For each new fact, decide whether to:
- ADD: Add it to the memory as a new element
- UPDATE: Update an existing memory element
- DELETE: Delete an existing memory element
- NONE: Make no change (if the fact is already present or irrelevant)
......

3)語義記憶(Graph / Relations)

語義記憶通過圖數據庫系統觸發,需要啟用圖存儲配置

# 配置圖數據庫以啟用語義記憶  
config = {  
    "graph_store": {  
        "provider": "neo4j",  
        "config": {  
            "url": "neo4j://localhost:7687",  
            "username": "neo4j",  
            "password": "password"  
        }  
    }  
}  
  
memory = Memory.from_config(config)  
  
# 觸發語義記憶(實體關係提取)  
messages = [  
    {"role": "user", "content": "我的朋友John喜歡打籃球,他的狗叫Max"},  
    {"role": "assistant", "content": "我記住了John和Max的關係"}  
]  
  
# 這會同時觸發向量存儲和圖存儲  
result = memory.add(messages, user_id="charlie")

使用system prompt-EXTRACT_RELATIONS_PROMPT,進行實體和關係的識別

#以下僅為EXTRACT_RELATIONS_PROMPT的片段,詳細參考參考資訊

You are an advanced algorithm designed to extract structured information from text to construct knowledge graphs. Your goal is to capture comprehensive and accurate information. Follow these key principles:
38
391. Extract only explicitly stated information from the text.
402. Establish relationships among the entities provided.
413. Use "USER_ID" as the source entity for any self-references (e.g., "I," "me," "my," etc.) in user messages.

mem0和LangChain/LangGraph的搭配

補充:mem0不只支援langchain框架,還支援google ADK, ElevenLabs 等15種以上的框架

需求 建議
既有 Bot 需要在 1–2 天內具備「跨會話個人化」 mem0(直接掛上:抽條目→持久化→語義檢索→回填)
多入口/多產品要共用同一份使用者記憶 mem0 作為共用「記憶層」
多代理、多分支合併要「宣告式規則」與可審計重跑 LangGraph(State + Reducers + Checkpointer)
記憶不只人名偏好,還含中間產物(表格、URL、版本) LangGraph 的 Store/VFS +(選配)mem0 作長期偏好層
對隱私/部署有強控管(本地/自建) mem0 支援本地或 MCP/OpenMemory;LangGraph 完全自建亦可

接下來要做什麼

分享使用mcp 或 file(ex. md)管理memory


參考資源

  1. LLM Chat History Summarization: Best Practices And Techniques
  2. mem0 github
  3. Prompt for mem0 from official github
  4. Relationships extract prompt for mem0 form official github
  5. mem0 integration

上一篇
Day 16|Agent Design - Memory - 客製化的LangChain/LangGraph(2/5)
系列文
從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言