Version: 0.5.9.dev.260315

 为原有流式聊天链路补充“聊天结束后异步调用 LLM 生成对话标题并落库”的机制,相关测试已通过
📄 新增“获取对话元信息”接口,便于前端统一获取对话的各类信息,包括上述异步生成的标题
This commit is contained in:
Losita
2026-03-15 19:54:49 +08:00
parent 7603a7561a
commit d91784d65f
7 changed files with 381 additions and 1 deletions

View File

@@ -3,6 +3,7 @@ package dao
import (
"context"
"errors"
"strings"
"github.com/LoveLosita/smartflow/backend/model"
"gorm.io/gorm"
@@ -70,3 +71,57 @@ func (a *AgentDAO) IfChatExists(ctx context.Context, userID int, chatID string)
}
return true, nil
}
// GetConversationMeta 查询单个会话的元信息。
// 用途:
// 1) 给前端提供“当前会话标题/消息数/最近消息时间”等展示字段;
// 2) 与流式聊天接口解耦,避免在 SSE 头部里塞动态标题。
func (a *AgentDAO) GetConversationMeta(ctx context.Context, userID int, chatID string) (*model.AgentChat, error) {
var chat model.AgentChat
err := a.db.WithContext(ctx).
Select("chat_id", "title", "message_count", "last_message_at", "status").
Where("user_id = ? AND chat_id = ?", userID, chatID).
First(&chat).Error
if err != nil {
return nil, err
}
return &chat, nil
}
// GetConversationTitle 读取当前会话标题。
// 返回值说明:
// 1) title标题内容若为空表示尚未生成
// 2) exists会话是否存在
// 3) err数据库错误。
func (a *AgentDAO) GetConversationTitle(ctx context.Context, userID int, chatID string) (title string, exists bool, err error) {
var chat model.AgentChat
queryErr := a.db.WithContext(ctx).
Select("title").
Where("user_id = ? AND chat_id = ?", userID, chatID).
First(&chat).Error
if queryErr != nil {
if errors.Is(queryErr, gorm.ErrRecordNotFound) {
return "", false, nil
}
return "", false, queryErr
}
if chat.Title == nil {
return "", true, nil
}
return strings.TrimSpace(*chat.Title), true, nil
}
// UpdateConversationTitleIfEmpty 仅在标题为空时写入会话标题。
// 设计目的:
// 1) 避免每轮对话都覆盖已有标题;
// 2) 并发下保持幂等:多个 goroutine 同时尝试写标题,最终只会成功一次。
func (a *AgentDAO) UpdateConversationTitleIfEmpty(ctx context.Context, userID int, chatID, title string) error {
normalized := strings.TrimSpace(title)
if normalized == "" {
return nil
}
return a.db.WithContext(ctx).
Model(&model.AgentChat{}).
Where("user_id = ? AND chat_id = ? AND (title IS NULL OR title = '')", userID, chatID).
Update("title", normalized).Error
}