mem1 0.0.4__py3-none-any.whl → 0.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mem1/__init__.py CHANGED
@@ -2,7 +2,7 @@
2
2
  Mem1 - 基于 Elasticsearch 的用户记忆系统
3
3
  """
4
4
 
5
- __version__ = "0.1.0"
5
+ __version__ = "0.0.5"
6
6
 
7
7
  from mem1.memory_es import Mem1Memory
8
8
  from mem1.config import Mem1Config, LLMConfig
mem1/config.py CHANGED
@@ -20,6 +20,7 @@ class MemoryConfig(BaseModel):
20
20
  update_interval_minutes: int # 距上次更新超过 M 分钟触发
21
21
  save_assistant_messages: bool # 是否保存 assistant 回复
22
22
  max_assistant_chars: int # assistant 回复超过此长度触发摘要
23
+ context_days_limit: int # get_context 检索最近几天的对话
23
24
 
24
25
 
25
26
  class ESConfig(BaseModel):
@@ -97,7 +98,8 @@ class Mem1Config(BaseModel):
97
98
  update_interval_rounds=int(required_vars["MEM1_UPDATE_INTERVAL_ROUNDS"]),
98
99
  update_interval_minutes=int(required_vars["MEM1_UPDATE_INTERVAL_MINUTES"]),
99
100
  save_assistant_messages=required_vars["MEM1_SAVE_ASSISTANT_MESSAGES"].lower() == "true",
100
- max_assistant_chars=int(required_vars["MEM1_MAX_ASSISTANT_CHARS"])
101
+ max_assistant_chars=int(required_vars["MEM1_MAX_ASSISTANT_CHARS"]),
102
+ context_days_limit=int(os.getenv("MEM1_CONTEXT_DAYS_LIMIT", "31"))
101
103
  ),
102
104
  es=ESConfig(
103
105
  hosts=es_hosts,
mem1/memory_es.py CHANGED
@@ -475,11 +475,15 @@ class Mem1Memory:
475
475
 
476
476
  def get_context(
477
477
  self,
478
- query: str,
479
- include_normal: Optional[bool] = None,
478
+ query: str = "",
480
479
  days_limit: Optional[int] = None
481
480
  ) -> Dict[str, Any]:
482
- """获取记忆上下文(当前话题)"""
481
+ """获取记忆上下文(当前话题)
482
+
483
+ Args:
484
+ query: 用户问题(保留参数,暂未使用)
485
+ days_limit: 检索最近几天的对话,默认使用配置值
486
+ """
483
487
  user_id = self.user_id
484
488
  profile_content = self._init_profile(user_id)
485
489
 
@@ -495,39 +499,21 @@ class Mem1Memory:
495
499
  except Exception:
496
500
  pass
497
501
 
498
- result = {
502
+ # 强制检索最近 days_limit 天的对话
503
+ if days_limit is None:
504
+ days_limit = self.config.memory.context_days_limit
505
+ conversations = self.get_conversations(days_limit=days_limit)
506
+ normal_content = self._format_conversations_for_llm(conversations) if conversations else ""
507
+
508
+ return {
499
509
  "current_time": current_time,
500
510
  "user_id": user_id,
501
511
  "topic_id": self.topic_id,
502
512
  "import_content": profile_content,
503
- "normal_content": "",
504
- "need_history": False,
505
- "recall_reason": "",
506
- "recall_triggered_by": "none",
507
- "profile_last_updated": profile_last_updated,
508
- "conversations_count": 0
513
+ "normal_content": normal_content,
514
+ "conversations_count": len(conversations),
515
+ "profile_last_updated": profile_last_updated
509
516
  }
510
-
511
- # 判断是否需要历史记录
512
- if include_normal is None:
513
- need_history, reason = self._should_include_history(query)
514
- result["recall_reason"] = reason
515
- result["recall_triggered_by"] = "llm_decision"
516
- elif include_normal:
517
- need_history = True
518
- result["recall_triggered_by"] = "manual"
519
- else:
520
- need_history = False
521
- result["recall_triggered_by"] = "manual"
522
-
523
- if need_history:
524
- conversations = self.get_conversations(days_limit=days_limit)
525
- if conversations:
526
- result["normal_content"] = self._format_conversations_for_llm(conversations)
527
- result["need_history"] = True
528
- result["conversations_count"] = len(conversations)
529
-
530
- return result
531
517
 
532
518
  def _compress_profile(self, user_id: str, profile_content: str) -> str:
533
519
  """压缩用户画像"""
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: mem1
3
+ Version: 0.0.5
4
+ Summary: 基于云服务的用户记忆系统
5
+ Project-URL: Homepage, https://github.com/sougannkyou/mem1
6
+ Project-URL: Repository, https://github.com/sougannkyou/mem1
7
+ Author: Song
8
+ License: MIT
9
+ Keywords: langchain,llm,memory,user-profile
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: elasticsearch>=8.0.0
18
+ Requires-Dist: openai>=1.0.0
19
+ Requires-Dist: pydantic>=2.0.0
20
+ Requires-Dist: python-dotenv>=1.0.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: ipython>=8.0.0; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # mem1 - 用户记忆系统
26
+
27
+ 让 AI 真正"记住"用户:三层记忆架构 + 图片记忆 + 话题隔离 + 业务场景解耦。
28
+
29
+ ## 核心特性
30
+
31
+ - **三层记忆架构**:短期会话 → 用户画像 → 长期记录
32
+ - **话题隔离**:同一用户可有多个话题,对话按话题隔离,画像跨话题共享
33
+ - **图片记忆**:支持存储和语义搜索用户发送的图片
34
+ - **业务解耦**:通过 ProfileTemplate 适配不同场景
35
+ - **画像自动更新**:基于对话轮数/时间自动触发 LLM 更新用户画像
36
+
37
+ ## 安装
38
+
39
+ ```bash
40
+ pip install mem1
41
+ ```
42
+
43
+ ## 快速开始
44
+
45
+ ```python
46
+ from mem1 import Mem1Memory, Mem1Config
47
+
48
+ # 从环境变量加载配置
49
+ config = Mem1Config.from_env()
50
+
51
+ # 创建记忆实例(绑定用户和话题)
52
+ memory = Mem1Memory(config, user_id="user001", topic_id="project_a")
53
+
54
+ # 添加对话
55
+ memory.add_conversation(
56
+ messages=[
57
+ {"role": "user", "content": "你好,我是张明"},
58
+ {"role": "assistant", "content": "你好张明!"}
59
+ ]
60
+ )
61
+
62
+ # 获取上下文(含用户画像 + 最近对话)
63
+ ctx = memory.get_context()
64
+ print(ctx['import_content']) # 用户画像
65
+ print(ctx['normal_content']) # 最近对话记录
66
+ print(ctx['current_time']) # 当前时间
67
+ ```
68
+
69
+ ## 环境变量配置
70
+
71
+ ```bash
72
+ # LLM 配置
73
+ MEM1_LLM_API_KEY=your-api-key
74
+ MEM1_LLM_BASE_URL=https://api.deepseek.com
75
+ MEM1_LLM_MODEL=deepseek-chat
76
+
77
+ # ES 配置
78
+ MEM1_ES_HOSTS=http://localhost:9200
79
+ MEM1_ES_INDEX=conversation_history
80
+
81
+ # 记忆配置
82
+ MEM1_MEMORY_DIR=./memories
83
+ MEM1_AUTO_UPDATE_PROFILE=true
84
+ MEM1_MAX_PROFILE_CHARS=3000
85
+ MEM1_UPDATE_INTERVAL_ROUNDS=5
86
+ MEM1_UPDATE_INTERVAL_MINUTES=3
87
+ MEM1_SAVE_ASSISTANT_MESSAGES=true
88
+ MEM1_MAX_ASSISTANT_CHARS=500
89
+ MEM1_CONTEXT_DAYS_LIMIT=31
90
+ ```
91
+
92
+ ## 核心接口
93
+
94
+ ```python
95
+ memory = Mem1Memory(config, user_id="user001", topic_id="project_a")
96
+
97
+ # 添加对话
98
+ memory.add_conversation(messages=[...], images=[...], metadata={...})
99
+
100
+ # 获取上下文(画像 + 最近 N 天对话)
101
+ ctx = memory.get_context(days_limit=31)
102
+
103
+ # 查询对话
104
+ convs = memory.get_conversations(days_limit=7)
105
+ all_convs = memory.get_all_conversations(days_limit=7)
106
+
107
+ # 图片搜索
108
+ results = memory.search_images(query="麻花")
109
+
110
+ # 话题管理
111
+ topics = memory.list_topics()
112
+ memory.delete_topic()
113
+ memory.delete_user()
114
+ ```
115
+
116
+ ## ES 索引
117
+
118
+ | 索引 | 用途 |
119
+ |------|------|
120
+ | `conversation_history` | 对话记录 |
121
+ | `mem1_user_state` | 用户状态 |
122
+ | `mem1_user_profile` | 用户画像 |
123
+
124
+ ## LLM 提示词建议
125
+
126
+ 使用 `get_context()` 获取上下文后,建议在 system prompt 中加入以下规则,避免 LLM 编造信息:
127
+
128
+ ```
129
+ ## 重要规则
130
+ 1. 回答必须基于上述对话记录中的实际内容,严禁编造任何信息
131
+ 2. 涉及数字(金额、数量、百分比、日期等)时,必须从对话记录中原样提取,不得估算或编造
132
+ 3. 需要汇总累加时,必须列出计算过程(如:23+31+18+25=97)
133
+ 4. 涉及人名、公司名、账号名等实体时,必须使用对话中的原始名称
134
+ 5. 如果对话记录中没有相关信息,请明确说"对话记录中未提及",不要猜测
135
+ ```
136
+
137
+ ## License
138
+
139
+ MIT
@@ -0,0 +1,11 @@
1
+ mem1/__init__.py,sha256=D-o5MjyTl565vqyVOyigm9LiZmsk9S5DfyV4QobLNo8,219
2
+ mem1/config.py,sha256=Tr91k9P9T-znshYAFGSyL3KGNy38xQLjbSJWlHxxeIo,4309
3
+ mem1/langchain_middleware.py,sha256=h2mG7K2Tq1N7IovXMvCyvOhsAwTWOR1NAqivF4db2AE,6648
4
+ mem1/llm.py,sha256=EKsZHxLrRn-OTxCsPHOYcUTjnEF5RVMnEM8fqWzdkbg,1114
5
+ mem1/memory_es.py,sha256=nVkZ2W-MWL0ZLzNqDoZ7e5Ccgde8SKzy2ogMm1CKZu8,27787
6
+ mem1/memory_md.py,sha256=uu_TvdBoUpAncT1eissOSe1Y3vCy3iWMcuvCy3vCjEA,26258
7
+ mem1/memory_tools.py,sha256=b1YBiRNet0gXnW-KGIZ2KQclluB9Q6dli_DbWLS571k,3646
8
+ mem1/prompts.py,sha256=L0JGVa--V_h9KqqZnb1n1N9oaPqxBhxHFL71Us9J5qM,8685
9
+ mem1-0.0.5.dist-info/METADATA,sha256=ZbNrxTHxutoP5zK65emlcymBSFagU2AE2dLhpX74bjE,3957
10
+ mem1-0.0.5.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
11
+ mem1-0.0.5.dist-info/RECORD,,
@@ -1,217 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: mem1
3
- Version: 0.0.4
4
- Summary: 基于云服务的用户记忆系统
5
- Project-URL: Homepage, https://github.com/sougannkyou/mem1
6
- Project-URL: Repository, https://github.com/sougannkyou/mem1
7
- Author: Song
8
- License: MIT
9
- Keywords: langchain,llm,memory,user-profile
10
- Classifier: Development Status :: 3 - Alpha
11
- Classifier: Intended Audience :: Developers
12
- Classifier: License :: OSI Approved :: MIT License
13
- Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Requires-Python: >=3.12
17
- Requires-Dist: elasticsearch>=8.0.0
18
- Requires-Dist: openai>=1.0.0
19
- Requires-Dist: pydantic>=2.0.0
20
- Requires-Dist: python-dotenv>=1.0.0
21
- Provides-Extra: dev
22
- Requires-Dist: ipython>=8.0.0; extra == 'dev'
23
- Description-Content-Type: text/markdown
24
-
25
- # mem1 - 用户记忆系统
26
-
27
- 让 AI 真正"记住"用户:三层记忆架构 + 图片记忆 + 话题隔离 + 业务场景解耦。
28
-
29
- ## 为什么需要 mem1?
30
-
31
- LLM 本身无状态,每次对话都是"失忆"的。mem1 让 AI 助手能够:
32
- - 记住用户是谁(身份、背景)
33
- - 记住用户喜欢什么(偏好、习惯)
34
- - 记住用户说过什么(历史对话、图片)
35
- - 记住用户的反馈(表扬、批评)
36
-
37
- ## 核心特性
38
-
39
- - **三层记忆架构**:短期会话 → 用户画像 → 长期记录,参考 ChatGPT Memory 设计
40
- - **话题隔离**:同一用户可有多个话题,对话按话题隔离,画像跨话题共享
41
- - **图片记忆**:支持存储和语义搜索用户发送的图片
42
- - **业务解耦**:通过 ProfileTemplate 适配不同场景(舆情、电商、医疗等)
43
- - **智能检索**:LLM 判断是否需要回溯历史,节省 token
44
- - **画像自动更新**:基于对话轮数/时间自动触发 LLM 更新用户画像
45
- - **助手回复摘要**:超长回复自动摘要,节省存储
46
-
47
- ## 三层记忆架构
48
-
49
- ```
50
- ┌─────────────────────────────────────────────────────────────┐
51
- │ Tier 1: 短期记忆 (LangChain 管理) │
52
- │ - 当前会话 messages,会话结束即清空 │
53
- └─────────────────────────────────────────────────────────────┘
54
- ↓ 会话结束时保存
55
- ┌─────────────────────────────────────────────────────────────┐
56
- │ Tier 2: 用户画像 (ES: mem1_user_profile) │
57
- │ - LLM 从历史对话中提炼的结构化信息 │
58
- │ - 基本信息、偏好习惯、任务时间线、待办事项、待澄清事项 │
59
- │ - 跨话题共享 │
60
- └─────────────────────────────────────────────────────────────┘
61
- ┌─────────────────────────────────────────────────────────────┐
62
- │ Tier 3: 长期记忆 (ES: conversation_history) │
63
- │ - 原始对话记录(带时间戳、元数据、图片) │
64
- │ - 按 user_id + topic_id 隔离 │
65
- │ - 按需加载,避免 token 浪费 │
66
- └─────────────────────────────────────────────────────────────┘
67
- ```
68
-
69
- ## 安装
70
-
71
- ```bash
72
- pip install mem1
73
- ```
74
-
75
- ## 快速开始
76
-
77
- ```python
78
- from mem1 import Mem1Memory, Mem1Config
79
-
80
- # 方式1:从环境变量加载配置
81
- config = Mem1Config.from_env()
82
-
83
- # 方式2:手动配置
84
- from mem1 import LLMConfig
85
- from mem1.config import MemoryConfig, ESConfig, ImagesConfig
86
-
87
- config = Mem1Config(
88
- llm=LLMConfig(
89
- provider="openai",
90
- model="deepseek-chat",
91
- api_key="your-api-key",
92
- base_url="https://api.deepseek.com"
93
- ),
94
- memory=MemoryConfig(
95
- memory_dir="./memories",
96
- auto_update_profile=True,
97
- max_profile_chars=3000,
98
- update_interval_rounds=5,
99
- update_interval_minutes=3,
100
- save_assistant_messages=True,
101
- max_assistant_chars=500
102
- ),
103
- es=ESConfig(
104
- hosts=["http://localhost:9200"],
105
- index_name="conversation_history"
106
- ),
107
- images=ImagesConfig(
108
- images_dir="./memories/images"
109
- )
110
- )
111
-
112
- # 创建记忆实例(绑定用户和话题)
113
- memory = Mem1Memory(
114
- config=config,
115
- user_id="user001",
116
- topic_id="project_a" # 可选,默认 "default"
117
- )
118
-
119
- # 添加对话
120
- memory.add_conversation(
121
- messages=[
122
- {"role": "user", "content": "你好,我是张明"},
123
- {"role": "assistant", "content": "你好张明!"}
124
- ],
125
- metadata={"topic": "自我介绍"}
126
- )
127
-
128
- # 获取上下文(含用户画像)
129
- ctx = memory.get_context(query="帮我写报告")
130
- print(ctx['import_content']) # 用户画像
131
- print(ctx['current_time']) # 当前时间
132
-
133
- # 手动更新画像
134
- memory.update_profile()
135
- ```
136
-
137
- ## 环境变量配置
138
-
139
- ```bash
140
- # LLM 配置
141
- MEM1_LLM_API_KEY=your-api-key
142
- MEM1_LLM_BASE_URL=https://api.deepseek.com
143
- MEM1_LLM_MODEL=deepseek-chat
144
-
145
- # ES 配置
146
- MEM1_ES_HOSTS=http://localhost:9200
147
- MEM1_ES_INDEX=conversation_history
148
-
149
- # 记忆配置
150
- MEM1_MEMORY_DIR=./memories
151
- MEM1_AUTO_UPDATE_PROFILE=true
152
- MEM1_MAX_PROFILE_CHARS=3000
153
- MEM1_UPDATE_INTERVAL_ROUNDS=5
154
- MEM1_UPDATE_INTERVAL_MINUTES=3
155
- MEM1_SAVE_ASSISTANT_MESSAGES=true
156
- MEM1_MAX_ASSISTANT_CHARS=500
157
- ```
158
-
159
- ## ES 索引
160
-
161
- | 索引 | 用途 |
162
- |------|------|
163
- | `conversation_history` | 对话记录(按 user_id + topic_id 隔离) |
164
- | `mem1_user_state` | 用户状态(更新轮数、时间) |
165
- | `mem1_user_profile` | 用户画像(跨话题共享) |
166
-
167
- ## 核心接口
168
-
169
- ```python
170
- # 创建实例(绑定用户和话题)
171
- memory = Mem1Memory(config, user_id="user001", topic_id="project_a")
172
-
173
- # 添加对话(支持图片、元数据)
174
- memory.add_conversation(
175
- messages=[...],
176
- images=[{"filename": "截图.png", "path": "./test.png"}],
177
- metadata={"topic": "舆情分析"}
178
- )
179
-
180
- # 获取上下文
181
- ctx = memory.get_context(query="问题")
182
-
183
- # 查询当前话题的对话
184
- convs = memory.get_conversations(days_limit=7)
185
-
186
- # 查询用户所有话题的对话
187
- all_convs = memory.get_all_conversations(days_limit=7)
188
-
189
- # 搜索图片
190
- results = memory.search_images(query="麻花")
191
-
192
- # 列出用户所有话题
193
- topics = memory.list_topics()
194
-
195
- # 删除当前话题
196
- memory.delete_topic()
197
-
198
- # 删除用户所有数据
199
- memory.delete_user()
200
- ```
201
-
202
- ## 示例
203
-
204
- 见 `examples/` 目录:
205
- - `basic_usage.py` - 基础用法
206
- - `langchain_integration.py` - LangChain 集成
207
- - `batch_import.py` - 批量导入
208
- - `image_usage.py` - 图片功能
209
-
210
- ## 参考资料
211
-
212
- - [Reverse Engineering Latest ChatGPT Memory Feature](https://agentman.ai/blog/reverse-ngineering-latest-ChatGPT-memory-feature-and-building-your-own)
213
- - [How ChatGPT's Memory Actually Works](https://manthanguptaa.in/posts/chatgpt_memory/)
214
-
215
- ## License
216
-
217
- MIT
@@ -1,11 +0,0 @@
1
- mem1/__init__.py,sha256=f722Z_XaYwc3dQVhLc4X8oy_ffB8qrR1SuvEH01MGf8,219
2
- mem1/config.py,sha256=WxZVcj_Hy3Rdf0emUz1l17oomAKj5S_2n7Je0tj-HDs,4146
3
- mem1/langchain_middleware.py,sha256=h2mG7K2Tq1N7IovXMvCyvOhsAwTWOR1NAqivF4db2AE,6648
4
- mem1/llm.py,sha256=EKsZHxLrRn-OTxCsPHOYcUTjnEF5RVMnEM8fqWzdkbg,1114
5
- mem1/memory_es.py,sha256=XPGoWYA2G9QkbrGOO3RVRQdLU4XiNw2CqsXnbV9w2TM,28263
6
- mem1/memory_md.py,sha256=uu_TvdBoUpAncT1eissOSe1Y3vCy3iWMcuvCy3vCjEA,26258
7
- mem1/memory_tools.py,sha256=b1YBiRNet0gXnW-KGIZ2KQclluB9Q6dli_DbWLS571k,3646
8
- mem1/prompts.py,sha256=L0JGVa--V_h9KqqZnb1n1N9oaPqxBhxHFL71Us9J5qM,8685
9
- mem1-0.0.4.dist-info/METADATA,sha256=rKxWIYdnDbYYQkNbTYdp5Ms9OEqarHU3JrBB8kBhxh4,7420
10
- mem1-0.0.4.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
11
- mem1-0.0.4.dist-info/RECORD,,
File without changes