refactor: 统一 Packet 通信协议 + 后端配置管理 + UI 清理

- 合并 server.py 到 core/__init__.py,使用统一 Packet 协议
- 后端管理配置持久化 (~/.trulymem/config.json)
- 前端移除 ConfigService,通过 BackendClient 与后端通信
- 删除 UI 中冗余的 AI 推理逻辑 (chat_service, tool_service, message_handler)
- 删除 core/tools 重复文件 (tool_executor, tool_limiter)
- 提示词管理器支持用户自定义 (~/.trulyemem/system_prompt.md)
- 启动入口优化配置路径逻辑
- 更新测试覆盖 (42 tests)
- 更新文档
This commit is contained in:
root
2026-04-14 11:49:39 +08:00
parent 2a76fc6477
commit c742a30e1b
19 changed files with 1020 additions and 2349 deletions

View File

@ -4,7 +4,7 @@
## 概述
TrulyMEM 后端采用**请求-响应队列模式**,通过 `queue.Queue` 实现线程安全通信。后端在独立线程中运行,处理来自客户端的请求。
TrulyMEM 后端采用 **Packet 通信协议**,通过 `queue.Queue` 实现线程安全通信。后端在独立线程中运行,处理来自客户端的请求。
### 核心组件
@ -12,50 +12,51 @@ TrulyMEM 后端采用**请求-响应队列模式**,通过 `queue.Queue` 实现
|------|------|
| `BackendServer` | 后端服务器,独立线程运行 |
| `BackendClient` | 客户端封装,提供便捷方法 |
| `MessageType` | 请求类型枚举 |
| `BackendRequest` | 请求数据包 |
| `BackendResponse` | 响应数据包 |
| `PacketType` | 请求类型枚举 |
| `Packet` | 数据包(请求) |
| `PacketResponse` | 数据包响应 |
---
## 请求类型 (MessageType)
## 请求类型 (PacketType)
```python
class MessageType(Enum):
class PacketType(Enum):
PROCESS_MESSAGE = "process_message" # 处理消息
EXECUTE_TOOL = "execute_tool" # 执行工具
GET_STATUS = "get_status" # 获取状态
GET_CONFIG = "get_config" # 获取配置
SET_CONFIG = "set_config" # 设置配置
GET_HISTORY = "get_history" # 获取历史
SAVE_HISTORY = "save_history" # 保存历史
SHUTDOWN = "shutdown" # 关闭服务
GET_HISTORY = "get_history" # 获取历史
SAVE_HISTORY = "save_history" # 保存历史
SHUTDOWN = "shutdown" # 关闭服务
```
---
## 数据包格式
### BackendRequest
### Packet
```python
@dataclass
class BackendRequest:
request_id: str # 请求唯一标识
message_type: MessageType # 请求类型
payload: Dict[str, Any] # 请求参数
response_queue: queue.Queue # 响应队列(用于返回结果
class Packet:
id: str # 唯一标识
type: PacketType # 请求类型
body: Dict[str, Any] # 请求参数
response_queue: queue.Queue # 响应队列(可选
created_at: float # 创建时间
```
### BackendResponse
### PacketResponse
```python
@dataclass
class BackendResponse:
request_id: str # 对应的请求ID
success: bool # 是否成功
data: Any = None # 返回数据
error: Optional[str] = None # 错误信息
class PacketResponse:
id: str # 对应的请求ID
success: bool # 是否成功
data: Any = None # 返回数据
error: Optional[str] = None # 错误信息
```
---
@ -68,14 +69,15 @@ class BackendResponse:
**请求参数:**
```python
payload = {
body = {
"user_input": str # 用户输入的消息
}
```
**响应数据:**
```python
data = {
{
"success": True,
"content": str, # AI 回复内容
"tool_calls": [ # 工具调用记录
{
@ -92,11 +94,16 @@ data = {
**示例:**
```python
from core import BackendClient
from core import BackendServer, BackendClient
server = BackendServer(db_path="graph_memory.db", use_embedded_db=True)
server.start(api_key="your-api-key")
client = BackendClient(server)
result = client.process_message("你好,请记住我的名字是小明")
# result = {"success": True, "data": {"content": "...", "tool_calls": [...]}}
if result.get("success"):
print(result["content"])
```
---
@ -109,15 +116,16 @@ result = client.process_message("你好,请记住我的名字是小明")
**请求参数:**
```python
payload = {
body = {
"tool_name": str, # 工具名称
"arguments": dict # 工具参数
"arguments": dict # 工具参数
}
```
**响应数据:**
```python
data = {
{
"success": True,
"result": str # 工具执行结果
}
```
@ -135,22 +143,23 @@ result = client.execute_tool("memory_recall", {"query_intent": "用户信息"})
**请求参数:**
```python
payload = {} # 无参数
body = {} # 无参数
```
**响应数据:**
```python
data = {
"graph_initialized": bool, # 图数据库是否初始化
"client_initialized": bool, # API 客户端是否初始化
"running": bool # 后端是否运行中
{
"running": bool, # 后端是否运行中
"config": dict, # 当前配置
"graph_initialized": bool, # 图数据库是否初始化
"client_initialized": bool # API 客户端是否初始化
}
```
**示例:**
```python
status = client.get_status()
# status = {"success": True, "data": {"running": True, ...}}
print(status["data"]["running"]) # True
```
---
@ -161,12 +170,12 @@ status = client.get_status()
**请求参数:**
```python
payload = {} # 无参数
body = {} # 无参数
```
**响应数据:**
```python
data = {
{
"api_key": str, # API Key
"base_url": str # API Base URL
}
@ -180,7 +189,7 @@ data = {
**请求参数:**
```python
payload = {
body = {
"api_key": str, # API Key
"base_url": str # API Base URL (默认: https://api.deepseek.com)
}
@ -188,7 +197,7 @@ payload = {
**响应数据:**
```python
data = {
{
"status": "config_updated"
}
```
@ -209,12 +218,12 @@ result = client.update_config(
**请求参数:**
```python
payload = {} # 无参数
body = {} # 无参数
```
**响应数据:**
```python
data = {
{
"history": list # 消息历史列表
}
```
@ -227,14 +236,14 @@ data = {
**请求参数:**
```python
payload = {
body = {
"messages": list # 消息列表
}
```
**响应数据:**
```python
data = {
{
"status": "history_saved"
}
```
@ -247,12 +256,12 @@ data = {
**请求参数:**
```python
payload = {} # 无参数
body = {} # 无参数
```
**响应数据:**
```python
data = {
{
"status": "shutdown"
}
```
@ -275,36 +284,36 @@ client = BackendClient(server)
# 3. 发送消息
result = client.process_message("你好")
print(result["data"]["content"])
print(result["content"])
# 4. 关闭
client.shutdown()
```
### 直接使用请求队列
### 使用 Packet 协议
```python
import queue
from core import BackendServer, MessageType, BackendRequest, BackendResponse
from core import BackendServer, Packet, PacketType
server = BackendServer()
server.start(api_key="your-key")
# 创建请求
# 创建请求
response_queue = queue.Queue()
request = BackendRequest(
request_id="req-001",
message_type=MessageType.PROCESS_MESSAGE,
payload={"user_input": "你好"},
packet = Packet(
id="req-001",
type=PacketType.PROCESS_MESSAGE,
body={"user_input": "你好"},
response_queue=response_queue
)
# 发送请求
server._request_queue.put(request)
result = server.send(packet)
print(result.body)
# 等待响应
response = response_queue.get(timeout=30.0)
print(response.data)
# 关闭
server.shutdown()
```
---
@ -357,7 +366,7 @@ client = BackendClient(server)
async def handler(websocket):
async for message in websocket:
data = json.loads(message)
msg_type = data["type"]
msg_type = data.get("type")
if msg_type == "message":
result = client.process_message(data["content"])
@ -373,41 +382,18 @@ async def handler(websocket):
async def main():
server.start()
async with websockets.serve(handler, "localhost", 8765):
await asyncio.Future() # run forever
await asyncio.Future()
asyncio.run(main())
```
### 扩展为 gRPC
```protobuf
// truly_mem.proto
syntax = "proto3";
service TrulyMEM {
rpc ProcessMessage(MessageRequest) returns (MessageResponse);
rpc UpdateConfig(ConfigRequest) returns (ConfigResponse);
rpc GetStatus(Empty) returns (StatusResponse);
}
message MessageRequest {
string message = 1;
}
message MessageResponse {
bool success = 1;
string content = 2;
string error = 3;
}
```
---
## 线程安全说明
- `BackendServer` 使用 `threading.Lock` 保护共享资源
- 所有请求通过 `queue.Queue` 传递,线程安全
- 响应通过每个请求独立的 `response_queue` 返回
- 响应通过每个请求独立的响应队列返回
- 默认超时时间30 秒
---
@ -463,4 +449,4 @@ message MessageResponse {
|---------|------|
| `API Key 未配置` | 未设置 API Key |
| `timeout` | 请求超时 |
| `工具调用被拒绝: ...` | 工具调用频率超限 |
| `工具调用被拒绝: ...` | 工具调用频率超限 |

View File

@ -5,20 +5,17 @@
### 从源码运行
```bash
# 克隆仓库
git clone <repo-url>
cd TrulyMEM-TrueHumanMEM
# 安装依赖
pip install -r requirements.txt
# 运行
python trulymem_entry.py
```
### 打包后运行
打包后会生成可执行文件Windows: TrulyMEM.exe, Linux/macOS: TrulyMEM
打包后会生成可执行文件:
```bash
# Linux/macOS
@ -38,9 +35,11 @@ TrulyMEM.exe
1. 运行应用
2.**F2** 展开侧边栏
3. 输入 **API Key**
3. 输入 **API Key**、**模型**、**Base URL**
4.**Enter** 保存
配置会自动保存到 `~/.trulymem/config.json`,下次启动自动加载。
## 快捷键
| 按键 | 功能 |
@ -53,9 +52,32 @@ TrulyMEM.exe
## 数据存储
- **数据库**: `graph_memory.db`(应用目录)
- **配置**: `config.json`(应用目录)
- **格式**: SQLite
| 数据 | 位置 |
|------|------|
| 图数据库 | `graph_memory.db`(应用目录) |
| 配置文件 | `~/.trulymem/config.json` |
| 数据库格式 | SQLite |
## 架构说明
### 通信协议
UI 与后端通过 **Packet 协议** 通信:
```
UI (Textual TUI)
↓ BackendClient
Packet → queue.Queue → BackendServer (独立线程)
处理请求 → 返回响应
```
### 配置管理
- **存储位置**: `~/.trulymem/config.json`
- **自动加载**: 启动时从文件读取配置
- **动态更新**: 运行时修改配置立即生效
- **持久化**: 修改后自动保存到文件
## 常见问题
@ -85,7 +107,7 @@ pip install -r requirements.txt
# 运行测试
pytest tests/
# 打包(需 PyInstaller
# 打包
bash build/build_windows.bat # Windows
bash build/build_linux.sh # Linux
```
```

View File

@ -6,6 +6,7 @@
- 极简视觉,信息密度优先
- 工具痕迹默认隐藏,需要时可展开
- TUI 与后端分离,多线程通信
- **一切皆图**AI 推理全部在后端
## 项目结构
@ -14,53 +15,25 @@ TrulyMEM-TrueHumanMEM/
├── trulymem_entry.py # 入口:先启动 core → 再启动 ui
├── core/ # 后端/业务逻辑
│ ├── __init__.py # 导出 BackendServer, BackendClient, EmbeddedGraphDB
│ ├── server.py # BackendServer (多线程队列通信)
│ ├── client.py # BackendClient
│ ├── server.py # BackendServer (Packet 通信协议)
│ ├── client.py # BackendClient (Packet 协议客户端)
│ ├── embedded_db.py # SQLite 图数据库实现
│ ├── graph_client.py
│ ├── tool_executor.py # 工具执行器
│ ├── graph_client.py # OpenAI/DeepSeek API 客户端
│ ├── tool_executor.py # 工具执行器
│ ├── tool_limiter.py # 工具调用限制器
│ ├── memory_tools.py # 工具定义
│ ├── prompts/ # 提示词管理
│ ├── tools/ # 工具定义
│ │ ├── __init__.py
│ │ ── prompt_manager.py
│ └── templates/
└── system_prompt.md
── tools/ # 工具模块
├── __init__.py
├── memory_tools.py
├── tool_executor.py
└── tool_limiter.py
├── ui/ # TUI 显示层
── __init__.py # 导出 GraphMemoryApp, AppConfig
│ ├── app.py # GraphMemoryApp (纯显示)
│ ├── widgets/ # TUI 组件
│ │ ├── left_panel.py
│ │ ├── right_panel.py
│ │ ├── message_history.py
│ │ ├── message_widget.py
│ │ ├── input_box.py
│ │ ├── config_section.py
│ │ ├── operation_log.py
│ │ ├── cypher_query_box.py
│ │ └── status_bar.py
│ ├── handlers/ # 事件处理
│ │ ├── focus_handler.py
│ │ ├── key_handler.py
│ │ └── message_handler.py
│ ├── models/ # 数据模型
│ │ ├── message.py
│ │ ├── config.py
│ │ └── log_entry.py
│ ├── services/ # 服务层
│ │ ├── config_manager.py
│ │ ├── config_service.py
│ │ └── chat_service.py
│ └── styles/ # 样式文件
│ ├── app.css
│ ├── components.css
│ └── messages.css
└── tests/ # 测试 (38 tests)
│ │ ── memory_tools.py
│ └── prompts/ # 提示词管理
├── ui/ # TUI 显示层(仅显示,无 AI 逻辑)
── __init__.py # 导出 GraphMemoryApp, AppConfig
├── app.py # GraphMemoryApp (通过 BackendClient 通信)
├── widgets/ # TUI 组件
├── handlers/ # 事件处理
├── models/ # 数据模型
│ ├── services/ # 服务层(仅配置管理)
── styles/ # 样式文件
└── tests/ # 测试 (42 tests)
```
## 架构图
@ -69,13 +42,14 @@ TrulyMEM-TrueHumanMEM/
trulymem_entry.py
├─ BackendServer.start() → 独立线程运行
│ ├─ 处理 PROCESS_MESSAGE 请求
│ ├─ 处理 EXECUTE_TOOL 请求
│ ├─ 处理 PROCESS_MESSAGE 请求 → AI 推理 + 工具调用
│ ├─ 处理 EXECUTE_TOOL 请求 → 外部工具调用(不限次数)
│ ├─ 处理 GET/SET_CONFIG 请求
│ └─ 管理 GraphMemoryClient, EmbeddedGraphDB
└─ GraphMemoryApp(backend_server=server)
└─ BackendClient ← queue.Queue → BackendServer
└─ BackendClient ← Packet 通信 → BackendServer
```
## 组件职责
@ -84,22 +58,38 @@ trulymem_entry.py
| 组件 | 职责 |
|------|------|
| `server.py` | 多线程队列通信,处理消息和工具调用 |
| `client.py` | TUI 端的通信客户端 |
| `server.py` | Packet 协议处理多线程队列通信AI 推理,工具限制 |
| `client.py` | 客户端封装UI 与后端通信桥梁 |
| `embedded_db.py` | SQLite 图数据库 CRUD |
| `graph_client.py` | OpenAI/DeepSeek API 客户端 |
| `tool_executor.py` | 工具执行逻辑 |
| `tool_limiter.py` | 工具调用频率限制 |
| `tool_limiter.py` | 工具调用频率限制(仅限 AI 推理) |
### ui/ (显示层)
| 组件 | 职责 |
|------|------|
| `app.py` | Textual 应用主类 |
| `widgets/` | TUI 组件(面板、输入框等) |
| `handlers/` | 事件处理(键盘、焦点) |
| `models/` | 数据模型(消息、配置) |
| `services/` | 配置管理、服务层 |
| `app.py` | Textual 应用主类,仅通过 BackendClient 通信 |
| `services/` | 仅配置管理,无 AI 逻辑 |
### 通信协议
UI 与后端通过 **Packet 通信协议** 交互:
```python
from core import BackendServer, BackendClient, Packet, PacketType
# 后端启动
server = BackendServer(db_path="graph_memory.db", use_embedded_db=True)
server.start(api_key="your-key")
# 客户端通信
client = BackendClient(server)
result = client.process_message("你好") # AI 推理
result = client.execute_tool("memory_introspect", {}) # 外部工具调用
```
---
## 数据流
@ -108,21 +98,27 @@ trulymem_entry.py
BackendClient.process_message(user_input)
queue.Queue → BackendServer (独立线程)
Packet (type=PROCESS_MESSAGE) → queue.Queue
BackendServer (独立线程)
GraphMemoryClient.send_message_with_history()
OpenAI API / DeepSeek API
execute_tool() → EmbeddedGraphDB
execute_tool() + ToolLimiter (AI 推理时受限)
EmbeddedGraphDB (图数据库)
循环调用 API 直到无 tool_calls
queue.Queue → 返回结果
Packet 响应返回
MessageHistory 显示
```
---
## 启动流程
```python
@ -146,82 +142,7 @@ def main():
backend_server.shutdown()
```
## 布局结构
### 默认视图(右侧展开)
```
┌─────────────────────────────────────┬─────────────────────┐
│ │ F2:隐藏侧边栏 │
│ 🟠 14:30:25 │ ────────────────────│
│ 用户: 量子力学是什么? │ API Key: *** │
│ │ 模型: deepseek-chat │
│ 🔵 14:30:26 │ Base URL: ... │
│ 是的!根据记忆... │ ────────────────────│
│ [工具:2次] (F3展开) │ [操作日志] │
│ │ 14:30:26 recall │
│ ┌─────────────────────────────┐ │ 实体: 量子力学 │
│ │ 🟠 [输入框...] │ │ ───────────────────│
│ └─────────────────────────────┘ │ >[查询...] │
└─────────────────────────────────────┴─────────────────────┘
```
### F2后右侧折叠
```
┌─────────────────────────────────────┐
│ 🟠 14:30:25 │
│ 用户: 量子力学是什么? │
│ │
│ 🔵 14:30:26 │
│ 是的!根据记忆... │
│ [工具:2次] (F3展开) │
│ │
│ ┌─────────────────────────────┐ │
│ │ 🟠 [输入框...] │ │
│ └─────────────────────────────┘ │
│ F1:帮助 F2:展开 F5:清屏 F6:退出 │
└─────────────────────────────────────┘
```
## 快捷键
| 按键 | 功能 |
|------|------|
| F1 | 显示帮助 |
| F2 | 切换侧边栏 |
| F3 | 工具详情 |
| F5 | 清屏 |
| F6 | 退出 |
## 技术栈
| 技术 | 用途 |
|------|------|
| Python 3.8+ | 编程语言 |
| Textual 0.47+ | TUI 框架 |
| SQLite | 图数据库(默认内嵌) |
| OpenAI SDK | API 调用(兼容 DeepSeek |
| threading.Queue | 多线程通信 |
| PyInstaller | 打包 |
## 数据库模式
### SQLite 内嵌(默认)
```python
# core/embedded_db.py
class EmbeddedGraphDB:
def __init__(self, db_path="graph_memory.db"):
self.conn = sqlite3.connect(db_path, check_same_thread=False)
```
### 可选Neo4j
```bash
export USE_EMBEDDED_DB=false
docker run -d --name neo4j -p 7474:7474 -p 7687:7687 neo4j:latest
```
---
## 工具系统
@ -241,4 +162,19 @@ docker run -d --name neo4j -p 7474:7474 -p 7687:7687 neo4j:latest
- `task_create` - 创建任务
- `task_set_state` - 设置状态
- `task_delete` - 删除任务
- `task_link_info` - 关联信息
- `task_link_info` - 关联信息
---
## 错误处理原则
所有 API **不抛出异常**,错误通过返回字典传递:
```python
result = client.process_message("hello")
if result.get("success"):
print(result["content"])
else:
print(result["error"]) # 错误描述
```