feat: AIOps智能助手对话历史持久化(按用户隔离,刷新后仍可见)

This commit is contained in:
attacker committed 2026-06-18 03:05:30 +08:00
1 parent 6321886b69
commit 32de3709ed
6 files changed
+109 -5

No files matched your search

+47 -1
View File
@@ -9,6 +9,7 @@ import (
"strings"
"time"
"ezops/internal/api/middleware"
"ezops/internal/models"
"github.com/gin-gonic/gin"
@@ -235,9 +236,23 @@ func (h *LLMHandler) Chat(c *gin.Context) {
c.JSON(http.StatusOK, models.Response{Code: 500, Message: "解析 LLM 响应失败"})
return
}
replyContent := chatResp.Choices[0].Message.Content
// 持久化对话历史(按用户隔离,成对写入 user + assistant) // Logan.Li
// 仅在成功时入库;错误气泡为瞬时 UI 不持久化
uid := middleware.GetUserID(c)
if uid != 0 && len(req.Messages) > 0 {
// 取最后一条用户消息(前端已附加当前提问)
lastUser := req.Messages[len(req.Messages)-1]
now := time.Now()
h.db.Create(&[]models.ChatHistory{
{UserID: uid, Role: "user", Content: lastUser.Content, CreatedAt: now},
{UserID: uid, Role: "assistant", Content: replyContent, Model: cfg.Model, CreatedAt: now.Add(time.Millisecond)},
})
}
c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ChatResponse{
Content: chatResp.Choices[0].Message.Content,
Content: replyContent,
Model: cfg.Model,
TokensUsed: chatResp.Usage.TotalTokens,
}})
@@ -292,3 +307,34 @@ func (h *LLMHandler) TestLLMConnection(c *gin.Context) {
}
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "连接成功"})
}
// GetChatHistory 获取当前用户的对话历史(按时间正序,仅返回最近 100 条避免过大) // Logan.Li
// GET /api/v1/aiops/chat-history
func (h *LLMHandler) GetChatHistory(c *gin.Context) {
uid := middleware.GetUserID(c)
var rows []models.ChatHistory
// 子查询取最近 100 条后再正序返回,保证前端渲染顺序正确 // Logan.Li
h.db.Where("user_id = ?", uid).
Order("id DESC").
Limit(100).
Find(&rows)
// 反转为时间正序(最早在前)
for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 {
rows[i], rows[j] = rows[j], rows[i]
}
c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{
"list": rows,
"total": len(rows),
}})
}
// ClearChatHistory 清空当前用户的对话历史 // Logan.Li
// DELETE /api/v1/aiops/chat-history
func (h *LLMHandler) ClearChatHistory(c *gin.Context) {
uid := middleware.GetUserID(c)
if err := h.db.Where("user_id = ?", uid).Delete(&models.ChatHistory{}).Error; err != nil {
c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "清除失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "对话历史已清空"})
}
+2
View File
@@ -421,6 +421,8 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config) {
aiopsGroup.PUT("/llm-config", llmHandler.SaveLLMConfig)
aiopsGroup.POST("/llm-config/test", llmHandler.TestLLMConnection)
aiopsGroup.POST("/chat", llmHandler.Chat)
aiopsGroup.GET("/chat-history", llmHandler.GetChatHistory)
aiopsGroup.DELETE("/chat-history", llmHandler.ClearChatHistory)
}
// 启动告警引擎(每 30 秒检查一次)