Mem0 的 CRUD 到底是如何实现的?我们来看下源码。
使用
先来看下,如何使用 Mem0
MemoryBase
MemoryBase 是一个抽象类,定义了一些接口方法
- get
- get_all
- update
- delete
- history
Memory
Memory 实现 MemoryBase 接口
init
初始化 embedding_model, vector_store(这里只能是 Qdrant), llm, db, collection_name
add
- 将用户 data 发给 llm ,得到 extracted_memories
- 将用户 data 转成 embeddings
- vector_store 根据 embeddings search 得到 existing_memories
- 将新,老 memory 发给 llm 来 merge
- 调用函数 _create_memory_tool 进行实际操作
- vector_store insert
- db add_history
get
- vector_store 根据 memory_id 去 get
get_all
- vector_store 根据 collection_name, filters, limit 调用 list 接口
search
- embedding_model 将 query 转 embeddings
- vector_store 根据 embeddings search
update
- 调用 _update_memory_tool
- existing_memory = self.vector_store.get
- embeddings = self.embedding_model.embed(data)
- self.vector_store.update
- self.db.add_history
delete
- 调用 _delete_memory_tool
- existing_memory = self.vector_store.get
- self.vector_store.delete
- self.db.add_history
delete_all
- memories = self.vector_store.list
- foreach memories
- _delete_memory_tool
history
- self.db.get_history
reset
- self.vector_store.delete_col
- self.db.reset()
AnonymousTelemetry
- capture_event 收集信息
- telemetry 用的是 Posthog(https://us.i.posthog.com)
SQLiteManager
- db 用的是 sqlite3
- 一个记录历史的表
MemoryClient
- 主要用于跟平台(https://api.mem0.ai/v1)交互
- 接口
- add
- get
- get_all
- search
- delete
- delete_all
- history
- reset
Embedding
- HuggingFaceEmbedding(model_name=“multi-qa-MiniLM-L6-cos-v1”)
- Ollama(model=“nomic-embed-text”)
- OpenAI(model=“text-embedding-3-small”)
LLM
- AWSBedrockLLM(anthropic.claude-3-5-sonnet-20240620-v1:0)
- GroqLLM(llama3-70b-8192)
- LiteLLM(gpt-4o)
- OllamaLLM(llama3)
- OpenAILLM(gpt-4o)
- TogetherLLM(mistralai/Mixtral-8x7B-Instruct-v0.1)
VectorStore
- 只有 Qdrant 一个实现
总结
- 核心就是 Memory 类,实现了 MemoryBase 接口
- 通过 embedding_model 来处理文本
- 通过 vector_store 存储 embedding
- 通过 llm 处理数据
- 通过 db 记录 Memory 的历史