s2-api-crud.md
1.75 KB
S2: 后端 API:会话 & 消息 CRUD
目标
在 wechat-viewer 中实现 AI 聊天的 RESTful API,包括会话 CRUD 和消息 CRUD。
前提修复
S1 标记「待测」但 conversations/messages 表未创建。需先在 local_db.py 补表。
涉及文件
local_db.py— 新增 conversations + messages 表、辅助 CRUD 函数app.py— 新增 5 个 API 路由
数据流
前端 → GET/POST/DELETE /api/conversations → local_db → SQLite
前端 → GET/POST /api/conversations/<id>/messages → local_db → SQLite
POST messages → local_db 保存 user 消息 → subprocess hermes chat → 保存 assistant 回复
步骤
Step 1: 补表 (local_db.py)
- conversations: id, title, created_at, updated_at
- messages: id, conversation_id (FK), role (user/assistant), content, created_at
- 添加 CRUD 辅助函数:conv_list, conv_create, conv_delete, msg_list, msg_add
Step 2: API 路由 (app.py)
- GET /api/conversations — 列出会话
- POST /api/conversations — 新建
- DELETE /api/conversations/ — 删除+级联消息
- GET /api/conversations//messages — 列出消息
- POST /api/conversations//messages — 发消息+获取 AI 回复
Step 3: Hermes 调用
- subprocess 调用
hermes chat -m <message> - 捕获 stdout 作为 AI 回复
- 超时 120s
- 首条消息自动截断为 title
验证命令
# 测试用例
python3 test_s2_api.py
# curl 手动验证
curl -s http://127.0.0.1:5000/api/conversations
curl -s -X POST http://127.0.0.1:5000/api/conversations -H 'Content-Type: application/json' -d '{"title":"测试"}'
风险
- hermes chat 可能需要指定 skill,需要 -s 参数
- cron 模式下 hermes chat 子进程可能被阻断
- Flask 需要重启才能加载新路由