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)
|
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.PUT("/config", middleware.AdminAuth(), aiCtrl.SaveConfig)
|
||||||
ai.POST("/config/test", middleware.AdminAuth(), aiCtrl.TestConfig)
|
ai.POST("/config/test", middleware.AdminAuth(), aiCtrl.TestConfig)
|
||||||
ai.POST("/analyze", middleware.RequirePro(), aiCtrl.Analyze)
|
ai.POST("/analyze", middleware.RequirePro(), aiCtrl.Analyze)
|
||||||
|
ai.POST("/chat", middleware.RequirePro(), aiCtrl.Chat)
|
||||||
ai.GET("/runs", aiCtrl.ListRuns)
|
ai.GET("/runs", aiCtrl.ListRuns)
|
||||||
ai.GET("/runs/:id", aiCtrl.GetRun)
|
ai.GET("/runs/:id", aiCtrl.GetRun)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"lokistack/repository"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -126,3 +127,70 @@ func TestAIConnection(cfg models.AIConfig) (string, error) {
|
|||||||
}
|
}
|
||||||
return strings.TrimSpace(reply), nil
|
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
|
||||||
|
}
|
||||||
@@ -91,4 +91,7 @@ export const aiApi = {
|
|||||||
`/ai/runs?page=${page}&pageSize=${pageSize}`,
|
`/ai/runs?page=${page}&pageSize=${pageSize}`,
|
||||||
),
|
),
|
||||||
run: (id: number) => http.get<AIRun>(`/ai/runs/${id}`),
|
run: (id: number) => http.get<AIRun>(`/ai/runs/${id}`),
|
||||||
|
|
||||||
|
chat: (data: { sourceId?: number; history: Array<{ role: 'user' | 'assistant'; content: string }>; page?: string; rangeMinutes?: number }) =>
|
||||||
|
http.post<{ reply: string }>('/ai/chat', data),
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { memo, useEffect, useRef, useState } from 'react'
|
||||||
|
import { useLocation } from 'react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { Loader2, Send, Sparkles, X } from 'lucide-react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { aiApi } from '@/api/ai'
|
||||||
|
import { getUser } from '@/lib/auth-storage'
|
||||||
|
import { useLicense } from '@/hooks/useLicense'
|
||||||
|
|
||||||
|
interface Msg { role: 'user' | 'assistant'; content: string }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全站 AI 助手浮窗(参考 FlowStack 右下角浮空设计):
|
||||||
|
* 仅管理员 + Pro 生效时渲染;对话自动携带当前页面路径作为上下文,
|
||||||
|
* 后端按需注入当前数据源的日志摘要,让"现在这个报错是什么"有数据依据。
|
||||||
|
*/
|
||||||
|
export const AiAssistant = memo(function AiAssistant() {
|
||||||
|
const { t } = useTranslation('aiops')
|
||||||
|
const location = useLocation()
|
||||||
|
const { pro } = useLicense()
|
||||||
|
const isAdmin = getUser()?.role === 'admin'
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const [messages, setMessages] = useState<Msg[]>([])
|
||||||
|
const [input, setInput] = useState('')
|
||||||
|
const [sending, setSending] = useState(false)
|
||||||
|
const listRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight
|
||||||
|
}, [messages, sending])
|
||||||
|
|
||||||
|
if (!isAdmin || !pro) return null
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
const text = input.trim()
|
||||||
|
if (!text || sending) return
|
||||||
|
const next: Msg[] = [...messages, { role: 'user', content: text }]
|
||||||
|
setMessages(next)
|
||||||
|
setInput('')
|
||||||
|
setSending(true)
|
||||||
|
try {
|
||||||
|
const res = await aiApi.chat({
|
||||||
|
history: next.slice(-20),
|
||||||
|
page: location.pathname,
|
||||||
|
rangeMinutes: 15,
|
||||||
|
})
|
||||||
|
setMessages(current => [...current, { role: 'assistant', content: res.reply }])
|
||||||
|
} catch (err) {
|
||||||
|
setMessages(current => [...current, { role: 'assistant', content: err instanceof Error ? err.message : t('assistant.error') }])
|
||||||
|
} finally {
|
||||||
|
setSending(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={open ? t('assistant.close') : t('assistant.open')}
|
||||||
|
onClick={() => setOpen(!open)}
|
||||||
|
className="fixed bottom-6 right-6 z-50 flex size-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-105"
|
||||||
|
>
|
||||||
|
{open ? <X className="size-5" /> : <Sparkles className="size-5" />}
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
className="fixed bottom-20 right-6 z-50 flex h-[520px] w-[min(92vw,400px)] flex-col overflow-hidden rounded-xl border bg-card shadow-2xl"
|
||||||
|
role="dialog"
|
||||||
|
aria-label={t('assistant.title')}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between border-b px-4 py-2.5">
|
||||||
|
<span className="flex items-center gap-2 text-sm font-semibold">
|
||||||
|
<Sparkles className="size-4 text-primary" />
|
||||||
|
{t('assistant.title')}
|
||||||
|
</span>
|
||||||
|
<button type="button" aria-label={t('assistant.close')} onClick={() => setOpen(false)} className="rounded p-1 text-muted-foreground hover:bg-muted">
|
||||||
|
<X className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div ref={listRef} className="flex-1 space-y-3 overflow-y-auto p-4 text-sm">
|
||||||
|
{messages.length === 0 && (
|
||||||
|
<p className="py-8 text-center text-xs text-muted-foreground">{t('assistant.emptyHint')}</p>
|
||||||
|
)}
|
||||||
|
{messages.map((m, i) => (
|
||||||
|
<div key={i} className={m.role === 'user' ? 'flex justify-end' : 'flex justify-start'}>
|
||||||
|
<div className={
|
||||||
|
m.role === 'user'
|
||||||
|
? 'max-w-[85%] rounded-lg bg-primary px-3 py-2 text-primary-foreground'
|
||||||
|
: 'max-w-[85%] whitespace-pre-wrap rounded-lg bg-muted px-3 py-2'
|
||||||
|
}>
|
||||||
|
{m.content}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{sending && (
|
||||||
|
<div className="flex justify-start">
|
||||||
|
<div className="flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-xs text-muted-foreground">
|
||||||
|
<Loader2 className="size-3.5 animate-spin" />
|
||||||
|
{t('assistant.thinking')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-end gap-2 border-t p-3">
|
||||||
|
<Textarea
|
||||||
|
rows={1}
|
||||||
|
value={input}
|
||||||
|
onChange={e => setInput(e.target.value)}
|
||||||
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send() }
|
||||||
|
}}
|
||||||
|
placeholder={t('assistant.placeholder')}
|
||||||
|
className="max-h-28 min-h-9 resize-none text-sm"
|
||||||
|
/>
|
||||||
|
<Button size="sm" onClick={() => void send()} disabled={sending || !input.trim()} aria-label={t('assistant.send')}>
|
||||||
|
<Send className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -22,6 +22,7 @@ import { cn } from '@/lib/utils'
|
|||||||
import { useIsMobile } from '@/hooks/use-mobile'
|
import { useIsMobile } from '@/hooks/use-mobile'
|
||||||
import { menuItems, findRouteMeta, findGroupKey } from '@/router/routes'
|
import { menuItems, findRouteMeta, findGroupKey } from '@/router/routes'
|
||||||
import { useLicense } from '@/hooks/useLicense'
|
import { useLicense } from '@/hooks/useLicense'
|
||||||
|
import { AiAssistant } from '@/components/AiAssistant'
|
||||||
import { Lock } from 'lucide-react'
|
import { Lock } from 'lucide-react'
|
||||||
import { GroupTabs } from './GroupTabs'
|
import { GroupTabs } from './GroupTabs'
|
||||||
import { getUser, clearAuth } from '@/lib/auth-storage'
|
import { getUser, clearAuth } from '@/lib/auth-storage'
|
||||||
@@ -265,9 +266,10 @@ const Layout = memo(function Layout({ children }: { children: React.ReactNode })
|
|||||||
<main className="flex-1 overflow-auto p-4 md:p-6">
|
<main className="flex-1 overflow-auto p-4 md:p-6">
|
||||||
<Suspense fallback={<PageSkeleton />}>{children}</Suspense>
|
<Suspense fallback={<PageSkeleton />}>{children}</Suspense>
|
||||||
</main>
|
</main>
|
||||||
|
<AiAssistant />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
export default Layout
|
export default Layout
|
||||||
@@ -1,4 +1,15 @@
|
|||||||
export default {
|
export default {
|
||||||
|
assistant: {
|
||||||
|
title: 'AI Assistant',
|
||||||
|
open: 'Open AI assistant',
|
||||||
|
close: 'Close',
|
||||||
|
send: 'Send',
|
||||||
|
thinking: 'Thinking…',
|
||||||
|
error: 'Request failed',
|
||||||
|
placeholder: 'Ask about logs, e.g. anything unusual now?',
|
||||||
|
emptyHint: 'Just ask; I can see the page you are viewing and the last 15 minutes of logs.',
|
||||||
|
},
|
||||||
|
|
||||||
title: 'AIOps',
|
title: 'AIOps',
|
||||||
subtitle: 'Let a model read log signals: statistics first, conclusions second — raw logs never leave the platform',
|
subtitle: 'Let a model read log signals: statistics first, conclusions second — raw logs never leave the platform',
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,15 @@
|
|||||||
export default {
|
export default {
|
||||||
|
assistant: {
|
||||||
|
title: 'AI 助手',
|
||||||
|
open: '打开 AI 助手',
|
||||||
|
close: '关闭',
|
||||||
|
send: '发送',
|
||||||
|
thinking: '思考中…',
|
||||||
|
error: '请求失败',
|
||||||
|
placeholder: '问问日志的事,如:当前有什么异常?',
|
||||||
|
emptyHint: '直接提问;我会参考你当前正在查看的页面与近 15 分钟日志概况。',
|
||||||
|
},
|
||||||
|
|
||||||
title: '智能运维',
|
title: '智能运维',
|
||||||
subtitle: '用大模型解读日志信号:先看统计、再看结论,全程不把日志原文发出去',
|
subtitle: '用大模型解读日志信号:先看统计、再看结论,全程不把日志原文发出去',
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user