feat: 🚀 增强会话管理与缓存机制 * 会话 ID 空值兜底,若 `conversation_id` 为空时自动生成 UUID * 在响应头写入 `X-Conversation-ID`,供前端使用,保持同一会话状态 perf: ⚡ 会话状态缓存优化 * 当缓存未命中但 DB 已确认/创建会话后,调用 `SetConversationStatus` 回写 Redis * 缓存写回失败时记录日志,不中断聊天主流程,确保业务流畅性 fix: 🐛 修复历史消息顺序问题与编译错误 * 修复历史消息顺序问题,保证返回的 N 条历史消息按时间正序喂给模型 * 通过反转 `created_at desc` 查询结果的切片,确保模型输入顺序正确 * 修复 `fmt.Errorf` 参数不匹配问题,修正编译错误 * 整理 `agent-cache.go` 为标准 UTF-8 编码,避免 Go 编译报错 `invalid UTF-8 encoding` feat: 🛠️ 独立构建 MCP 服务器 * 使用 `Codex` 构建独立于后端的 MCP 服务器,简化与 Codex 的协作 * 通过该服务器方便 Codex 直接测试和查看 Redis 与 MySQL 中的数据
73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package dao
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/LoveLosita/smartflow/backend/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type AgentDAO struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewAgentDAO(db *gorm.DB) *AgentDAO {
|
|
return &AgentDAO{db: db}
|
|
}
|
|
|
|
func (a *AgentDAO) SaveChatHistory(ctx context.Context, userID int, conversationID string, role, message string) error {
|
|
userChat := model.ChatHistory{
|
|
UserID: userID,
|
|
MessageContent: &message,
|
|
Role: &role,
|
|
ChatID: conversationID,
|
|
}
|
|
if err := a.db.WithContext(ctx).Create(&userChat).Error; err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *AgentDAO) CreateNewChat(userID int, chatID string) (int64, error) {
|
|
chat := model.AgentChat{
|
|
ChatID: chatID,
|
|
UserID: userID,
|
|
MessageCount: 0,
|
|
LastMessageAt: nil,
|
|
}
|
|
if err := a.db.Create(&chat).Error; err != nil {
|
|
return 0, err
|
|
}
|
|
return chat.ID, nil
|
|
}
|
|
|
|
func (a *AgentDAO) GetUserChatHistories(ctx context.Context, userID, limit int, chatID string) ([]model.ChatHistory, error) {
|
|
var histories []model.ChatHistory
|
|
err := a.db.WithContext(ctx).
|
|
Where("user_id = ? AND chat_id = ?", userID, chatID).
|
|
Order("created_at desc").
|
|
Limit(limit).
|
|
Find(&histories).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 保留“最近 N 条”的前提下,反转为时间正序,便于模型消费
|
|
for i, j := 0, len(histories)-1; i < j; i, j = i+1, j-1 {
|
|
histories[i], histories[j] = histories[j], histories[i]
|
|
}
|
|
return histories, nil
|
|
}
|
|
|
|
func (a *AgentDAO) IfChatExists(ctx context.Context, userID int, chatID string) (bool, error) {
|
|
var chat model.AgentChat
|
|
err := a.db.WithContext(ctx).Where("user_id = ? AND chat_id = ?", userID, chatID).First(&chat).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return false, nil // 没有找到记录,表示会话不存在
|
|
}
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|