feat(ai): 全站 AI 助手浮窗(参考 FlowStack 右下角浮空设计)
- POST /ai/chat:多轮对话(messages 透传)+ 页面上下文注入 —— 前端带当前路径, 后端自动附加该数据源近 15 分钟轻量日志摘要(总量/Top3 应用/告警命中), 追问「这个报错什么原因」有数据依据;脱敏/每日配额/Pro 闸门与整页分析共用 - AiAssistant 浮球+浮窗挂 Layout:仅 admin+Pro 渲染;消息气泡、Enter 发送、 上下文随路由自动采集;免费版不显示
This commit is contained in:
1 parent
b81b31f322
commit
f457d6da09
8 files changed
+249
-1
No files matched your search
@@ -153,3 +153,31 @@ func (ctrl *AIController) GetRun(c *gin.Context) {
|
||||
}
|
||||
utils.Success(c, run)
|
||||
}
|
||||
|
||||
// Chat 全站 AI 助手浮窗(多轮对话 + 页面上下文注入;Pro 闸门)
|
||||
func (ctrl *AIController) Chat(c *gin.Context) {
|
||||
var req struct {
|
||||
SourceID uint `json:"sourceId"`
|
||||
History []services.ChatMessage `json:"history" binding:"required,min=1,max=40"`
|
||||
Page string `json:"page"`
|
||||
RangeMinutes int `json:"rangeMinutes"`
|
||||
}
|
||||
if !utils.BindAndValidate(c, &req) {
|
||||
return
|
||||
}
|
||||
cfg := services.GetAIConfig()
|
||||
var src *models.LogSource
|
||||
if req.SourceID > 0 {
|
||||
src = services.GetLogSource(req.SourceID)
|
||||
}
|
||||
rangeMinutes := req.RangeMinutes
|
||||
if rangeMinutes <= 0 || rangeMinutes > 120 {
|
||||
rangeMinutes = 15
|
||||
}
|
||||
reply, err := services.RunAIChat(c.Request.Context(), cfg, src, c.GetUint("userId"), c.GetString("role") == "admin", req.History, req.Page, rangeMinutes)
|
||||
if err != nil {
|
||||
utils.Error(c, 400, err.Error())
|
||||
return
|
||||
}
|
||||
utils.Success(c, gin.H{"reply": reply})
|
||||
}
|
||||
@@ -131,6 +131,7 @@ func SetupRouter() *gin.Engine {
|
||||
ai.PUT("/config", middleware.AdminAuth(), aiCtrl.SaveConfig)
|
||||
ai.POST("/config/test", middleware.AdminAuth(), aiCtrl.TestConfig)
|
||||
ai.POST("/analyze", middleware.RequirePro(), aiCtrl.Analyze)
|
||||
ai.POST("/chat", middleware.RequirePro(), aiCtrl.Chat)
|
||||
ai.GET("/runs", aiCtrl.ListRuns)
|
||||
ai.GET("/runs/:id", aiCtrl.GetRun)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"lokistack/repository"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -126,3 +127,70 @@ func TestAIConnection(cfg models.AIConfig) (string, error) {
|
||||
}
|
||||
return strings.TrimSpace(reply), nil
|
||||
}
|
||||
|
||||
// ChatMessage 浮窗助手的多轮消息(user/assistant 交替)
|
||||
type ChatMessage struct {
|
||||
Role string `json:"role" binding:"required,oneof=user assistant"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
|
||||
// RunAIChat 全站 AI 助手浮窗:多轮对话 + 当前页面上下文注入(轻量信号摘要)。
|
||||
// 与整页分析共享配置/配额/脱敏/Pro 闸门;context 里的 sourceId 可选,带了就注入日志摘要。
|
||||
func RunAIChat(ctx context.Context, cfg models.AIConfig, src *models.LogSource, userID uint, admin bool, history []ChatMessage, page string, rangeMinutes int) (string, error) {
|
||||
if !cfg.Enabled {
|
||||
return "", fmt.Errorf("AI 未启用:请先在「智能运维 → 模型配置」中开启并保存")
|
||||
}
|
||||
if cfg.DailyTokenCap > 0 && AITokenUsedToday(userID) >= cfg.DailyTokenCap {
|
||||
return "", fmt.Errorf("今日 AI 用量已达上限,明天再试或调整上限")
|
||||
}
|
||||
|
||||
system := "你是 LokiStack 日志平台的运维助手。回答简明、面向排查行动;不确定就说不确定。"
|
||||
if src != nil && rangeMinutes > 0 {
|
||||
end := time.Now()
|
||||
from := end.Add(-time.Duration(rangeMinutes) * time.Minute)
|
||||
if bundle, err := CollectAISignals(ctx, src, userID, admin, from, end, ""); err == nil {
|
||||
system += "\n\n当前用户正在查看 " + page + " 页,近 " + fmt.Sprintf("%d", rangeMinutes) + " 分钟的日志概况:总量 " +
|
||||
fmt.Sprintf("%d", bundle.TotalEntries) + " 条(估算)"
|
||||
if len(bundle.Apps) > 0 {
|
||||
system += ",Top 应用:"
|
||||
for i, a := range bundle.Apps {
|
||||
if i >= 3 {
|
||||
break
|
||||
}
|
||||
system += fmt.Sprintf(" %s(%d)", a.App, a.Entries)
|
||||
}
|
||||
}
|
||||
if len(bundle.Alerts) > 0 {
|
||||
system += ";存在告警命中"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
msgs := []aiMessage{{Role: "system", Content: system}}
|
||||
for _, m := range history {
|
||||
msgs = append(msgs, aiMessage{Role: m.Role, Content: m.Content})
|
||||
}
|
||||
// 脱敏:用户消息里的敏感串同样替换
|
||||
if cfg.RedactExtra != nil {
|
||||
for i := range msgs {
|
||||
msgs[i].Content = RedactTextOnly(msgs[i].Content, cfg.RedactExtra)
|
||||
}
|
||||
}
|
||||
reply, promptTokens, completionTokens, err := aiChat(ctx, cfg, msgs)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 计入每日配额:落一条 chat 类型用量记录
|
||||
db := repository.GetDB()
|
||||
if db != nil {
|
||||
db.Lock()
|
||||
db.AIAnalysisRuns = append(db.AIAnalysisRuns, models.AIAnalysisRun{
|
||||
UserID: userID, Username: "chat", SourceID: 0, SourceName: page,
|
||||
Status: "chat", PromptTokens: promptTokens, CompletionTokens: completionTokens,
|
||||
CreatedAt: time.Now(),
|
||||
})
|
||||
db.RequestSave()
|
||||
db.Unlock()
|
||||
}
|
||||
return reply, nil
|
||||
}
|
||||
Reference in new issue
Block a user