实现 AI Agent 对话功能(Task 15)
后端实现: - 集成 Vercel AI SDK 实现流式对话 - 实现工具系统(文章搜索、报告分析、网络搜索) - 实现上下文加载和提示词构建 - 实现对话管理和消息存储 - 添加 Agent API 路由(流式对话、历史记录) 前端实现: - 实现聊天界面(配置选择、消息展示、历史记录) - 支持 Markdown 渲染和代码高亮 - 实现流式响应解析和展示 - 优化布局(单侧边栏 + 可折叠历史面板) - 修复 API 路径和 CORS 问题 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb54568b22
commit
e6a434e516
27 files changed
+8734
-19
No files matched your search
Generated
+12
-11
@@ -13,6 +13,7 @@
|
||||
"axios": "^1.13.4",
|
||||
"echarts": "^6.0.0",
|
||||
"element-plus": "^2.13.2",
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.24",
|
||||
@@ -957,7 +958,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
|
||||
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/lodash": "*"
|
||||
}
|
||||
@@ -984,7 +984,6 @@
|
||||
"integrity": "sha512-ne4A0IpG3+2ETuREInjPNhUGis1SFjv1d5asp8MzEAGtOZeTeHVDOYqOgqfhvseqg/iXty2hjBf1zAOb7RNiNw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
@@ -1422,7 +1421,6 @@
|
||||
"resolved": "https://registry.npmjs.org/echarts/-/echarts-6.0.0.tgz",
|
||||
"integrity": "sha512-Tte/grDQRiETQP4xz3iZWSvoHrkCQtwqd6hs+mifXcjrCuo2iKWbajFObuLJVBlDIJlOzgQPd1hsaKt/3+OMkQ==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0",
|
||||
"zrender": "6.0.0"
|
||||
@@ -1724,6 +1722,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/highlight.js": {
|
||||
"version": "11.11.1",
|
||||
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.11.1.tgz",
|
||||
"integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/hookable": {
|
||||
"version": "5.5.3",
|
||||
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
|
||||
@@ -1755,15 +1762,13 @@
|
||||
"version": "4.17.23",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
|
||||
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash-es": {
|
||||
"version": "4.17.23",
|
||||
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",
|
||||
"integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash-unified": {
|
||||
"version": "1.0.3",
|
||||
@@ -1918,7 +1923,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -2100,7 +2104,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -2128,7 +2131,6 @@
|
||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.27.0",
|
||||
"fdir": "^6.5.0",
|
||||
@@ -2210,7 +2212,6 @@
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.27.tgz",
|
||||
"integrity": "sha512-aJ/UtoEyFySPBGarREmN4z6qNKpbEguYHMmXSiOGk69czc+zhs0NF6tEFrY8TZKAl8N/LYAkd4JHVd5E/AsSmw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.27",
|
||||
"@vue/compiler-sfc": "3.5.27",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"axios": "^1.13.4",
|
||||
"echarts": "^6.0.0",
|
||||
"element-plus": "^2.13.2",
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.24",
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<template>
|
||||
<MainLayout />
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import MainLayout from '@/layouts/MainLayout.vue'
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import request from './request'
|
||||
|
||||
export interface ChatParams {
|
||||
conversationId?: number
|
||||
reportId?: number
|
||||
articleId?: number
|
||||
topicId: number
|
||||
message: string
|
||||
llmConfigId: number
|
||||
userId?: number
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
role: string
|
||||
content: string
|
||||
toolCalls?: any
|
||||
createdAt?: string
|
||||
}
|
||||
|
||||
export interface Conversation {
|
||||
id: number
|
||||
topicId: number
|
||||
reportId?: number
|
||||
articleId?: number
|
||||
userId?: number
|
||||
messages: Message[]
|
||||
messageCount?: number
|
||||
lastMessage?: {
|
||||
role: string
|
||||
content: string
|
||||
createdAt: string
|
||||
}
|
||||
topic?: {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
report?: {
|
||||
id: number
|
||||
title: string
|
||||
}
|
||||
article?: {
|
||||
id: number
|
||||
title: string
|
||||
}
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式对话
|
||||
*/
|
||||
export async function streamChat(params: ChatParams): Promise<Response> {
|
||||
const response = await fetch('/api/v1/agent/chat', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
throw new Error(error.error || '请求失败')
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对话详情
|
||||
*/
|
||||
export async function getConversation(id: number): Promise<Conversation> {
|
||||
return request.get(`/agent/conversations/${id}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对话列表
|
||||
*/
|
||||
export async function getConversations(params?: {
|
||||
userId?: number
|
||||
topicId?: number
|
||||
}): Promise<Conversation[]> {
|
||||
return request.get('/agent/conversations', { params })
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除对话
|
||||
*/
|
||||
export async function deleteConversation(id: number): Promise<void> {
|
||||
return request.delete(`/agent/conversations/${id}`)
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
<template>
|
||||
<div :class="['message-item', message.role]">
|
||||
<div class="message-avatar">
|
||||
<el-avatar v-if="message.role === 'user'" :size="36">
|
||||
<el-icon><User /></el-icon>
|
||||
</el-avatar>
|
||||
<el-avatar v-else :size="36" style="background-color: #409eff">
|
||||
<el-icon><ChatDotRound /></el-icon>
|
||||
</el-avatar>
|
||||
</div>
|
||||
|
||||
<div class="message-content-wrapper">
|
||||
<div class="message-meta">
|
||||
<span class="message-role">{{ roleLabel }}</span>
|
||||
<span class="message-time">{{ formattedTime }}</span>
|
||||
</div>
|
||||
|
||||
<div class="message-content">
|
||||
<!-- Markdown 渲染 -->
|
||||
<div
|
||||
v-if="message.role === 'assistant'"
|
||||
v-html="renderedContent"
|
||||
class="markdown-body"
|
||||
/>
|
||||
|
||||
<!-- 用户消息 -->
|
||||
<div v-else class="user-message">{{ message.content }}</div>
|
||||
|
||||
<!-- 流式输出指示器 -->
|
||||
<span v-if="streaming" class="streaming-cursor">▊</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { User, ChatDotRound } from '@element-plus/icons-vue'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import hljs from 'highlight.js'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
interface Props {
|
||||
message: {
|
||||
role: string
|
||||
content: string
|
||||
toolCalls?: any
|
||||
createdAt?: string
|
||||
}
|
||||
streaming?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
// Markdown 渲染器
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true,
|
||||
highlight: (str: string, lang: string) => {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(str, { language: lang }).value
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return ''
|
||||
},
|
||||
})
|
||||
|
||||
const roleLabel = computed(() => {
|
||||
const labels: Record<string, string> = {
|
||||
user: '你',
|
||||
assistant: 'AI 助手',
|
||||
system: '系统',
|
||||
tool: '工具',
|
||||
}
|
||||
return labels[props.message.role] || props.message.role
|
||||
})
|
||||
|
||||
const formattedTime = computed(() => {
|
||||
if (!props.message.createdAt) return ''
|
||||
const date = new Date(props.message.createdAt)
|
||||
return date.toLocaleTimeString('zh-CN', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
})
|
||||
|
||||
const renderedContent = computed(() => {
|
||||
return md.render(props.message.content || '')
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.message-item {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-bottom: 20px;
|
||||
animation: fadeIn 0.3s ease-in;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.message-avatar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.message-content-wrapper {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
.message-item.user .message-content-wrapper {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.message-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.message-role {
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
position: relative;
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
background-color: #f5f7fa;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.message-item.user .message-content {
|
||||
background-color: #409eff;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.user-message {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.markdown-body {
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h1),
|
||||
.markdown-body :deep(h2),
|
||||
.markdown-body :deep(h3) {
|
||||
margin-top: 16px;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h1) {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h2) {
|
||||
font-size: 1.3em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(h3) {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.markdown-body :deep(p) {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.markdown-body :deep(p:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown-body :deep(code) {
|
||||
padding: 2px 6px;
|
||||
background-color: rgba(0, 0, 0, 0.06);
|
||||
border-radius: 3px;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.markdown-body :deep(pre) {
|
||||
padding: 12px;
|
||||
background-color: #f6f8fa;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.markdown-body :deep(pre code) {
|
||||
padding: 0;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.markdown-body :deep(ul),
|
||||
.markdown-body :deep(ol) {
|
||||
padding-left: 24px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.markdown-body :deep(li) {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.markdown-body :deep(blockquote) {
|
||||
padding-left: 12px;
|
||||
border-left: 4px solid #dfe2e5;
|
||||
color: #6a737d;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.markdown-body :deep(a) {
|
||||
color: #409eff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdown-body :deep(a:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.markdown-body :deep(strong) {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.streaming-cursor {
|
||||
display: inline-block;
|
||||
animation: blink 1s infinite;
|
||||
margin-left: 2px;
|
||||
color: #409eff;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
0%,
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
51%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,135 @@
|
||||
import { ref } from 'vue'
|
||||
import { streamChat, type ChatParams, type Message } from '@/api/agent'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
export function useAgentChat() {
|
||||
const messages = ref<Message[]>([])
|
||||
const isLoading = ref(false)
|
||||
const currentStreamContent = ref('')
|
||||
const conversationId = ref<number | undefined>()
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*/
|
||||
async function sendMessage(params: Omit<ChatParams, 'conversationId'>) {
|
||||
if (isLoading.value) return
|
||||
|
||||
isLoading.value = true
|
||||
currentStreamContent.value = ''
|
||||
|
||||
// 添加用户消息
|
||||
messages.value.push({
|
||||
role: 'user',
|
||||
content: params.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await streamChat({
|
||||
...params,
|
||||
conversationId: conversationId.value,
|
||||
})
|
||||
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('无法获取响应流')
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let assistantContent = ''
|
||||
|
||||
// 添加助手消息占位
|
||||
const assistantMessage: Message = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
messages.value.push(assistantMessage)
|
||||
|
||||
// 读取流
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
|
||||
if (done) {
|
||||
break
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value)
|
||||
const lines = chunk.split('\n')
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const data = line.slice(6)
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data)
|
||||
|
||||
// 处理 conversationId
|
||||
if (parsed.type === 'conversation-id') {
|
||||
conversationId.value = parsed.conversationId
|
||||
}
|
||||
|
||||
// 处理文本流
|
||||
if (parsed.type === 'text-delta') {
|
||||
assistantContent += parsed.textDelta
|
||||
currentStreamContent.value = assistantContent
|
||||
// 更新最后一条消息
|
||||
messages.value[messages.value.length - 1].content = assistantContent
|
||||
}
|
||||
|
||||
// 处理完成
|
||||
if (parsed.type === 'done') {
|
||||
currentStreamContent.value = ''
|
||||
}
|
||||
|
||||
// 处理错误
|
||||
if (parsed.type === 'error') {
|
||||
throw new Error(parsed.error)
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略 JSON 解析错误
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Chat error:', error)
|
||||
ElMessage.error(error.message || '发送消息失败')
|
||||
|
||||
// 移除失败的助手消息
|
||||
if (messages.value[messages.value.length - 1]?.role === 'assistant') {
|
||||
messages.value.pop()
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
currentStreamContent.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空消息
|
||||
*/
|
||||
function clearMessages() {
|
||||
messages.value = []
|
||||
conversationId.value = undefined
|
||||
currentStreamContent.value = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载历史消息
|
||||
*/
|
||||
function loadMessages(historyMessages: Message[], convId?: number) {
|
||||
messages.value = historyMessages
|
||||
conversationId.value = convId
|
||||
}
|
||||
|
||||
return {
|
||||
messages,
|
||||
isLoading,
|
||||
currentStreamContent,
|
||||
conversationId,
|
||||
sendMessage,
|
||||
clearMessages,
|
||||
loadMessages,
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,11 @@
|
||||
<el-icon><Monitor /></el-icon>
|
||||
<template #title>采集监控</template>
|
||||
</el-menu-item>
|
||||
|
||||
<el-menu-item index="/agent">
|
||||
<el-icon><ChatDotRound /></el-icon>
|
||||
<template #title>AI 对话</template>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-aside>
|
||||
|
||||
@@ -92,6 +97,7 @@ import {
|
||||
Monitor,
|
||||
Expand,
|
||||
Fold,
|
||||
ChatDotRound,
|
||||
} from '@element-plus/icons-vue'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
@@ -64,6 +64,12 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('@/views/monitoring/Monitoring.vue'),
|
||||
meta: { title: '采集监控' },
|
||||
},
|
||||
{
|
||||
path: 'agent',
|
||||
name: 'AgentChat',
|
||||
component: () => import('@/views/agent/AgentChat.vue'),
|
||||
meta: { title: 'AI 对话' },
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
<template>
|
||||
<div class="agent-chat">
|
||||
<!-- 主聊天区域 -->
|
||||
<div class="chat-main">
|
||||
<!-- 顶部配置栏 -->
|
||||
<div class="config-bar">
|
||||
<div class="config-left">
|
||||
<el-select
|
||||
v-model="selectedTopicId"
|
||||
placeholder="选择主题"
|
||||
size="default"
|
||||
style="width: 150px"
|
||||
>
|
||||
<el-option
|
||||
v-for="topic in topics"
|
||||
:key="topic.id"
|
||||
:label="topic.name"
|
||||
:value="topic.id"
|
||||
/>
|
||||
</el-select>
|
||||
|
||||
<el-select
|
||||
v-model="selectedLlmConfigId"
|
||||
placeholder="选择 LLM"
|
||||
size="default"
|
||||
style="width: 180px"
|
||||
>
|
||||
<el-option
|
||||
v-for="config in llmConfigs"
|
||||
:key="config.id"
|
||||
:label="`${config.name} (${config.model})`"
|
||||
:value="config.id"
|
||||
/>
|
||||
</el-select>
|
||||
|
||||
<el-select
|
||||
v-model="selectedReportId"
|
||||
placeholder="关联报告(可选)"
|
||||
size="default"
|
||||
style="width: 200px"
|
||||
clearable
|
||||
>
|
||||
<el-option
|
||||
v-for="report in reports"
|
||||
:key="report.id"
|
||||
:label="report.title"
|
||||
:value="report.id"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<div class="config-right">
|
||||
<el-button size="default" @click="handleNewChat">
|
||||
<el-icon><Plus /></el-icon>
|
||||
新建对话
|
||||
</el-button>
|
||||
<el-button
|
||||
size="default"
|
||||
:icon="showHistory ? 'ArrowRight' : 'Clock'"
|
||||
@click="showHistory = !showHistory"
|
||||
>
|
||||
{{ showHistory ? '隐藏历史' : '历史对话' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 消息列表 -->
|
||||
<div ref="messageListRef" class="message-list">
|
||||
<el-empty v-if="messages.length === 0" description="开始一段新对话吧">
|
||||
<template #image>
|
||||
<el-icon :size="60" color="#909399"><ChatDotRound /></el-icon>
|
||||
</template>
|
||||
</el-empty>
|
||||
|
||||
<MessageItem
|
||||
v-for="(message, index) in messages"
|
||||
:key="index"
|
||||
:message="message"
|
||||
:streaming="isLoading && index === messages.length - 1 && message.role === 'assistant'"
|
||||
/>
|
||||
|
||||
<!-- 加载指示器 -->
|
||||
<div v-if="isLoading && (!messages.length || messages[messages.length - 1]?.role !== 'assistant')" class="loading-indicator">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
<span>AI 正在思考...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 输入区域 -->
|
||||
<div class="input-area">
|
||||
<el-input
|
||||
v-model="inputMessage"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
placeholder="输入你的问题... (Ctrl+Enter 发送)"
|
||||
:disabled="isLoading"
|
||||
@keydown.ctrl.enter="handleSendMessage"
|
||||
/>
|
||||
<div class="input-actions">
|
||||
<span class="input-hint">Ctrl + Enter 发送</span>
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="isLoading"
|
||||
:disabled="!inputMessage.trim() || !selectedLlmConfigId || !selectedTopicId"
|
||||
@click="handleSendMessage"
|
||||
>
|
||||
发送
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 历史对话侧边栏(可折叠) -->
|
||||
<transition name="slide">
|
||||
<div v-show="showHistory" class="history-panel">
|
||||
<div class="history-header">
|
||||
<span>历史对话</span>
|
||||
<el-button size="small" text @click="loadConversations">
|
||||
<el-icon><Refresh /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="history-list">
|
||||
<div
|
||||
v-for="conv in conversations"
|
||||
:key="conv.id"
|
||||
:class="['history-item', { active: conv.id === conversationId }]"
|
||||
@click="loadConversation(conv)"
|
||||
>
|
||||
<div class="history-item-header">
|
||||
<span class="history-title">{{ conv.topic?.name || '未知主题' }}</span>
|
||||
<el-button
|
||||
size="small"
|
||||
type="danger"
|
||||
text
|
||||
@click.stop="handleDeleteConversation(conv.id)"
|
||||
>
|
||||
<el-icon><Delete /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="history-preview">
|
||||
{{ conv.lastMessage?.content || '暂无消息' }}
|
||||
</div>
|
||||
<div class="history-time">
|
||||
{{ formatTime(conv.updatedAt) }}
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-if="conversations.length === 0" description="暂无历史对话" :image-size="60" />
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, nextTick, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Loading, ChatDotRound, Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||
import MessageItem from '@/components/agent/MessageItem.vue'
|
||||
import { useAgentChat } from '@/composables/useAgentChat'
|
||||
import {
|
||||
getConversations,
|
||||
getConversation,
|
||||
deleteConversation,
|
||||
type Conversation,
|
||||
} from '@/api/agent'
|
||||
import request from '@/api/request'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
// 配置数据
|
||||
const topics = ref<any[]>([])
|
||||
const llmConfigs = ref<any[]>([])
|
||||
const reports = ref<any[]>([])
|
||||
const conversations = ref<Conversation[]>([])
|
||||
|
||||
// 选中的配置
|
||||
const selectedTopicId = ref<number>()
|
||||
const selectedLlmConfigId = ref<number>()
|
||||
const selectedReportId = ref<number>()
|
||||
|
||||
// UI 状态
|
||||
const showHistory = ref(false)
|
||||
const inputMessage = ref('')
|
||||
const messageListRef = ref<HTMLElement>()
|
||||
|
||||
// 使用 composable
|
||||
const {
|
||||
messages,
|
||||
isLoading,
|
||||
conversationId,
|
||||
sendMessage,
|
||||
clearMessages,
|
||||
loadMessages,
|
||||
} = useAgentChat()
|
||||
|
||||
// 初始化
|
||||
onMounted(async () => {
|
||||
await Promise.all([
|
||||
loadTopics(),
|
||||
loadLlmConfigs(),
|
||||
loadReports(),
|
||||
loadConversations(),
|
||||
])
|
||||
|
||||
// 从路由参数初始化
|
||||
if (route.query.topicId) {
|
||||
selectedTopicId.value = Number(route.query.topicId)
|
||||
}
|
||||
if (route.query.llmConfigId) {
|
||||
selectedLlmConfigId.value = Number(route.query.llmConfigId)
|
||||
}
|
||||
if (route.query.reportId) {
|
||||
selectedReportId.value = Number(route.query.reportId)
|
||||
}
|
||||
if (route.query.conversationId) {
|
||||
const conv = await getConversation(Number(route.query.conversationId))
|
||||
if (conv) {
|
||||
loadConversation(conv)
|
||||
}
|
||||
}
|
||||
|
||||
// 默认选择第一个
|
||||
if (!selectedTopicId.value && topics.value.length > 0) {
|
||||
selectedTopicId.value = topics.value[0].id
|
||||
}
|
||||
if (!selectedLlmConfigId.value && llmConfigs.value.length > 0) {
|
||||
selectedLlmConfigId.value = llmConfigs.value[0].id
|
||||
}
|
||||
})
|
||||
|
||||
// 自动滚动到底部
|
||||
watch([messages, isLoading], () => {
|
||||
nextTick(() => {
|
||||
if (messageListRef.value) {
|
||||
messageListRef.value.scrollTop = messageListRef.value.scrollHeight
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// 加载主题列表
|
||||
async function loadTopics() {
|
||||
try {
|
||||
const res = await request.get('/topics')
|
||||
topics.value = res.data || res
|
||||
} catch (error) {
|
||||
console.error('加载主题失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载 LLM 配置列表
|
||||
async function loadLlmConfigs() {
|
||||
try {
|
||||
const res = await request.get('/llm-configs')
|
||||
llmConfigs.value = res.data || res
|
||||
} catch (error) {
|
||||
console.error('加载 LLM 配置失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载报告列表
|
||||
async function loadReports() {
|
||||
try {
|
||||
const res = await request.get('/reports', {
|
||||
params: { status: 'completed', limit: 20 },
|
||||
})
|
||||
reports.value = res.data || res
|
||||
} catch (error) {
|
||||
console.error('加载报告失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载对话列表
|
||||
async function loadConversations() {
|
||||
try {
|
||||
conversations.value = await getConversations()
|
||||
} catch (error) {
|
||||
console.error('加载对话列表失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载对话
|
||||
function loadConversation(conv: Conversation) {
|
||||
selectedTopicId.value = conv.topicId
|
||||
selectedReportId.value = conv.reportId
|
||||
loadMessages(conv.messages || [], conv.id)
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
async function handleSendMessage() {
|
||||
if (!inputMessage.value.trim() || isLoading.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!selectedTopicId.value) {
|
||||
ElMessage.warning('请先选择主题')
|
||||
return
|
||||
}
|
||||
|
||||
if (!selectedLlmConfigId.value) {
|
||||
ElMessage.warning('请先选择 LLM 配置')
|
||||
return
|
||||
}
|
||||
|
||||
const message = inputMessage.value
|
||||
inputMessage.value = ''
|
||||
|
||||
await sendMessage({
|
||||
topicId: selectedTopicId.value,
|
||||
llmConfigId: selectedLlmConfigId.value,
|
||||
reportId: selectedReportId.value,
|
||||
message,
|
||||
})
|
||||
|
||||
// 刷新对话列表
|
||||
await loadConversations()
|
||||
}
|
||||
|
||||
// 新建对话
|
||||
function handleNewChat() {
|
||||
clearMessages()
|
||||
selectedReportId.value = undefined
|
||||
inputMessage.value = ''
|
||||
}
|
||||
|
||||
// 删除对话
|
||||
async function handleDeleteConversation(id: number) {
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要删除这个对话吗?', '提示', {
|
||||
type: 'warning',
|
||||
})
|
||||
|
||||
await deleteConversation(id)
|
||||
ElMessage.success('删除成功')
|
||||
|
||||
// 如果删除的是当前对话,清空消息
|
||||
if (id === conversationId.value) {
|
||||
handleNewChat()
|
||||
}
|
||||
|
||||
await loadConversations()
|
||||
} catch (error: any) {
|
||||
if (error !== 'cancel') {
|
||||
ElMessage.error('删除失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化时间
|
||||
function formatTime(time: string): string {
|
||||
const date = new Date(time)
|
||||
const now = new Date()
|
||||
const diff = now.getTime() - date.getTime()
|
||||
|
||||
const minutes = Math.floor(diff / 60000)
|
||||
const hours = Math.floor(diff / 3600000)
|
||||
const days = Math.floor(diff / 86400000)
|
||||
|
||||
if (minutes < 1) return '刚刚'
|
||||
if (minutes < 60) return `${minutes}分钟前`
|
||||
if (hours < 24) return `${hours}小时前`
|
||||
if (days < 7) return `${days}天前`
|
||||
|
||||
return date.toLocaleDateString('zh-CN')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.agent-chat {
|
||||
display: flex;
|
||||
height: calc(100vh - 100px);
|
||||
background-color: #fff;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.chat-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* 顶部配置栏 */
|
||||
.config-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
background-color: #fafafa;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.config-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.config-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* 消息列表 */
|
||||
.message-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.loading-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: #909399;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
/* 输入区域 */
|
||||
.input-area {
|
||||
border-top: 1px solid #e6e6e6;
|
||||
padding: 16px;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.input-actions {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
/* 历史对话面板 */
|
||||
.history-panel {
|
||||
width: 280px;
|
||||
border-left: 1px solid #e6e6e6;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.history-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.history-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
padding: 10px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
margin-bottom: 8px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #e6e6e6;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.history-item:hover {
|
||||
border-color: #409eff;
|
||||
}
|
||||
|
||||
.history-item.active {
|
||||
border-color: #409eff;
|
||||
background-color: #ecf5ff;
|
||||
}
|
||||
|
||||
.history-item-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.history-title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.history-preview {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
font-size: 11px;
|
||||
color: #c0c4cc;
|
||||
}
|
||||
|
||||
/* 过渡动画 */
|
||||
.slide-enter-active,
|
||||
.slide-leave-active {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.slide-enter-from,
|
||||
.slide-leave-to {
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user