Metadata-Version: 2.4
Name: mem1
Version: 0.0.4
Summary: 基于云服务的用户记忆系统
Project-URL: Homepage, https://github.com/sougannkyou/mem1
Project-URL: Repository, https://github.com/sougannkyou/mem1
Author: Song
License: MIT
Keywords: langchain,llm,memory,user-profile
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.12
Requires-Dist: elasticsearch>=8.0.0
Requires-Dist: openai>=1.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: ipython>=8.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# mem1 - 用户记忆系统

让 AI 真正"记住"用户：三层记忆架构 + 图片记忆 + 话题隔离 + 业务场景解耦。

## 为什么需要 mem1？

LLM 本身无状态，每次对话都是"失忆"的。mem1 让 AI 助手能够：
- 记住用户是谁（身份、背景）
- 记住用户喜欢什么（偏好、习惯）  
- 记住用户说过什么（历史对话、图片）
- 记住用户的反馈（表扬、批评）

## 核心特性

- **三层记忆架构**：短期会话 → 用户画像 → 长期记录，参考 ChatGPT Memory 设计
- **话题隔离**：同一用户可有多个话题，对话按话题隔离，画像跨话题共享
- **图片记忆**：支持存储和语义搜索用户发送的图片
- **业务解耦**：通过 ProfileTemplate 适配不同场景（舆情、电商、医疗等）
- **智能检索**：LLM 判断是否需要回溯历史，节省 token
- **画像自动更新**：基于对话轮数/时间自动触发 LLM 更新用户画像
- **助手回复摘要**：超长回复自动摘要，节省存储

## 三层记忆架构

```
┌─────────────────────────────────────────────────────────────┐
│  Tier 1: 短期记忆 (LangChain 管理)                           │
│  - 当前会话 messages，会话结束即清空                          │
└─────────────────────────────────────────────────────────────┘
                              ↓ 会话结束时保存
┌─────────────────────────────────────────────────────────────┐
│  Tier 2: 用户画像 (ES: mem1_user_profile)                    │
│  - LLM 从历史对话中提炼的结构化信息                           │
│  - 基本信息、偏好习惯、任务时间线、待办事项、待澄清事项         │
│  - 跨话题共享                                                │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│  Tier 3: 长期记忆 (ES: conversation_history)                 │
│  - 原始对话记录（带时间戳、元数据、图片）                      │
│  - 按 user_id + topic_id 隔离                                │
│  - 按需加载，避免 token 浪费                                  │
└─────────────────────────────────────────────────────────────┘
```

## 安装

```bash
pip install mem1
```

## 快速开始

```python
from mem1 import Mem1Memory, Mem1Config

# 方式1：从环境变量加载配置
config = Mem1Config.from_env()

# 方式2：手动配置
from mem1 import LLMConfig
from mem1.config import MemoryConfig, ESConfig, ImagesConfig

config = Mem1Config(
    llm=LLMConfig(
        provider="openai",
        model="deepseek-chat",
        api_key="your-api-key",
        base_url="https://api.deepseek.com"
    ),
    memory=MemoryConfig(
        memory_dir="./memories",
        auto_update_profile=True,
        max_profile_chars=3000,
        update_interval_rounds=5,
        update_interval_minutes=3,
        save_assistant_messages=True,
        max_assistant_chars=500
    ),
    es=ESConfig(
        hosts=["http://localhost:9200"],
        index_name="conversation_history"
    ),
    images=ImagesConfig(
        images_dir="./memories/images"
    )
)

# 创建记忆实例（绑定用户和话题）
memory = Mem1Memory(
    config=config,
    user_id="user001",
    topic_id="project_a"  # 可选，默认 "default"
)

# 添加对话
memory.add_conversation(
    messages=[
        {"role": "user", "content": "你好，我是张明"},
        {"role": "assistant", "content": "你好张明！"}
    ],
    metadata={"topic": "自我介绍"}
)

# 获取上下文（含用户画像）
ctx = memory.get_context(query="帮我写报告")
print(ctx['import_content'])  # 用户画像
print(ctx['current_time'])    # 当前时间

# 手动更新画像
memory.update_profile()
```

## 环境变量配置

```bash
# LLM 配置
MEM1_LLM_API_KEY=your-api-key
MEM1_LLM_BASE_URL=https://api.deepseek.com
MEM1_LLM_MODEL=deepseek-chat

# ES 配置
MEM1_ES_HOSTS=http://localhost:9200
MEM1_ES_INDEX=conversation_history

# 记忆配置
MEM1_MEMORY_DIR=./memories
MEM1_AUTO_UPDATE_PROFILE=true
MEM1_MAX_PROFILE_CHARS=3000
MEM1_UPDATE_INTERVAL_ROUNDS=5
MEM1_UPDATE_INTERVAL_MINUTES=3
MEM1_SAVE_ASSISTANT_MESSAGES=true
MEM1_MAX_ASSISTANT_CHARS=500
```

## ES 索引

| 索引 | 用途 |
|------|------|
| `conversation_history` | 对话记录（按 user_id + topic_id 隔离） |
| `mem1_user_state` | 用户状态（更新轮数、时间） |
| `mem1_user_profile` | 用户画像（跨话题共享） |

## 核心接口

```python
# 创建实例（绑定用户和话题）
memory = Mem1Memory(config, user_id="user001", topic_id="project_a")

# 添加对话（支持图片、元数据）
memory.add_conversation(
    messages=[...],
    images=[{"filename": "截图.png", "path": "./test.png"}],
    metadata={"topic": "舆情分析"}
)

# 获取上下文
ctx = memory.get_context(query="问题")

# 查询当前话题的对话
convs = memory.get_conversations(days_limit=7)

# 查询用户所有话题的对话
all_convs = memory.get_all_conversations(days_limit=7)

# 搜索图片
results = memory.search_images(query="麻花")

# 列出用户所有话题
topics = memory.list_topics()

# 删除当前话题
memory.delete_topic()

# 删除用户所有数据
memory.delete_user()
```

## 示例

见 `examples/` 目录：
- `basic_usage.py` - 基础用法
- `langchain_integration.py` - LangChain 集成
- `batch_import.py` - 批量导入
- `image_usage.py` - 图片功能

## 参考资料

- [Reverse Engineering Latest ChatGPT Memory Feature](https://agentman.ai/blog/reverse-ngineering-latest-ChatGPT-memory-feature-and-building-your-own)
- [How ChatGPT's Memory Actually Works](https://manthanguptaa.in/posts/chatgpt_memory/)

## License

MIT
