修改完善通用交互

This commit is contained in:
junleea 2025-03-26 18:08:51 +08:00
parent 6117d92034
commit 44e29ee6f3
8 changed files with 5020 additions and 243 deletions

File diff suppressed because one or more lines are too long

1
components.d.ts vendored
View File

@ -46,6 +46,7 @@ declare module '@vue/runtime-core' {
ElRate: typeof import('element-plus/es')['ElRate'] ElRate: typeof import('element-plus/es')['ElRate']
ElResult: typeof import('element-plus/es')['ElResult'] ElResult: typeof import('element-plus/es')['ElResult']
ElRow: typeof import('element-plus/es')['ElRow'] ElRow: typeof import('element-plus/es')['ElRow']
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
ElSelect: typeof import('element-plus/es')['ElSelect'] ElSelect: typeof import('element-plus/es')['ElSelect']
ElSlider: typeof import('element-plus/es')['ElSlider'] ElSlider: typeof import('element-plus/es')['ElSlider']
ElSpace: typeof import('element-plus/es')['ElSpace'] ElSpace: typeof import('element-plus/es')['ElSpace']

2689
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -21,9 +21,14 @@
"element-plus": "^2.6.3", "element-plus": "^2.6.3",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"js-md5": "^0.8.3", "js-md5": "^0.8.3",
"katex": "^0.16.21",
"markdown-it": "^14.1.0", "markdown-it": "^14.1.0",
"markdown-it-katex": "^2.0.3",
"markdown-it-mermaid": "^0.2.5",
"marked": "^15.0.7", "marked": "^15.0.7",
"md-editor-v3": "^2.11.2", "md-editor-v3": "^2.11.2",
"mermaid": "^11.6.0",
"mermaid-it-markdown": "^1.0.8",
"nprogress": "^0.2.0", "nprogress": "^0.2.0",
"pinia": "^2.1.7", "pinia": "^2.1.7",
"vue": "^3.4.5", "vue": "^3.4.5",

View File

@ -63,7 +63,7 @@ const routes: RouteRecordRaw[] = [
path: '/gen-chat', path: '/gen-chat',
name: 'gen-chat', name: 'gen-chat',
meta: { meta: {
title: '人机对话', title: '通用智能交互',
permiss: '53', permiss: '53',
}, },
component: () => import(/* webpackChunkName: "gen-chat" */ '../views/system/gen-chat.vue'), component: () => import(/* webpackChunkName: "gen-chat" */ '../views/system/gen-chat.vue'),

View File

@ -1,5 +1,48 @@
<template> <template>
<div class="chat-app">
<!-- 历史会话侧边栏 -->
<div class="history-sessions" v-if="sessionIsShow">
<el-card class="session-card">
<template #header>
<h3>当前会话</h3>
</template>
<ul>
<li>{{ getShortenedName(sessionName) }}</li>
</ul>
</el-card>
<el-card class="session-card2">
<template #header>
<h3>历史会话</h3>
</template>
<el-scrollbar style="height: 400px; scrollbar-width: none">
<ul>
<li
v-for="(session, index) in historySessions"
:key="index"
@click="loadSession(session.ID)"
>
{{ getShortenedName(session.Name) }}
</li>
</ul>
</el-scrollbar>
</el-card>
</div>
<!-- 原有的聊天区域 -->
<div class="chat-container"> <div class="chat-container">
<div>
<div @click="showSession" style="cursor: pointer">
<el-icon v-if="sessionIsShow">
<Expand />
</el-icon>
<el-icon v-else>
<Fold />
</el-icon>
</div>
<div>
<el-button type="primary" @click="clearCurrent">新会话</el-button>
</div>
</div>
<!-- 消息列表 --> <!-- 消息列表 -->
<el-card class="chat-messages" shadow="never" ref="messagesContainer"> <el-card class="chat-messages" shadow="never" ref="messagesContainer">
<div <div
@ -30,12 +73,13 @@
@keyup.enter="sendMessage" @keyup.enter="sendMessage"
/> />
</el-col> </el-col>
<el-col :span="4" style="text-align: center;" > <el-col :span="4" style="text-align: center">
<el-button type="primary" @click="sendMessage">Send</el-button> <el-button type="primary" @click="sendMessage">发送</el-button>
</el-col> </el-col>
</el-row> </el-row>
</el-card> </el-card>
</div> </div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@ -45,8 +89,11 @@ import { WSMessage, AIQMessage, OllamaMessage } from "@/types/im";
import { ElMessage } from "element-plus"; import { ElMessage } from "element-plus";
import { GetMessageService } from "@/api/im"; import { GetMessageService } from "@/api/im";
import MarkdownIt from "markdown-it"; import MarkdownIt from "markdown-it";
import markdownItMermaid from "markdown-it-mermaid";
import hljs from "highlight.js"; import hljs from "highlight.js";
import { Session } from "@/types/session";
import bash from "highlight.js/lib/languages/bash"; import bash from "highlight.js/lib/languages/bash";
import { FindSessionService } from "@/api/session";
import javascript from "highlight.js/lib/languages/javascript"; import javascript from "highlight.js/lib/languages/javascript";
import typescript from "highlight.js/lib/languages/typescript"; import typescript from "highlight.js/lib/languages/typescript";
import java from "highlight.js/lib/languages/java"; import java from "highlight.js/lib/languages/java";
@ -56,11 +103,13 @@ import json from "highlight.js/lib/languages/json";
import yaml from "highlight.js/lib/languages/yaml"; import yaml from "highlight.js/lib/languages/yaml";
import xml from "highlight.js/lib/languages/xml"; import xml from "highlight.js/lib/languages/xml";
import shell from "highlight.js/lib/languages/shell"; import shell from "highlight.js/lib/languages/shell";
import "katex/dist/katex.min.css";
interface Message { interface Message {
role: "user" | "assistant"; role: "user" | "assistant";
content: string; content: string;
finished?: boolean; finished?: boolean;
} }
hljs.registerLanguage("bash", bash); hljs.registerLanguage("bash", bash);
hljs.registerLanguage("javascript", javascript); hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("typescript", typescript); hljs.registerLanguage("typescript", typescript);
@ -71,30 +120,25 @@ hljs.registerLanguage("json", json);
hljs.registerLanguage("yaml", yaml); hljs.registerLanguage("yaml", yaml);
hljs.registerLanguage("xml", xml); hljs.registerLanguage("xml", xml);
hljs.registerLanguage("shell", shell); hljs.registerLanguage("shell", shell);
const md = new MarkdownIt({ const md = new MarkdownIt({
html: true, html: true,
linkify: true, linkify: true,
breaks: true, breaks: true,
xhtmlOut: true, xhtmlOut: true,
typographer: true, typographer: true,
highlight: function (str, lang) { highlight: (str, lang) => {
if (lang && hljs.getLanguage(lang)) { if (lang && hljs.getLanguage(lang)) {
try { try {
return ( return `<pre class="hljs"><code>${
'<pre class="hljs"><code>' + hljs.highlight(str, { language: lang, ignoreIllegals: true }).value
hljs.highlight(lang, str, true).value + }</code></pre>`;
"</code></pre>"
);
} catch (__) {} } catch (__) {}
} }
return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
return (
'<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
);
}, },
}); });
const historySessions = ref<Session[]>([]);
const loading = ref(false); const loading = ref(false);
const isUserScrolling = ref<boolean>(false); const isUserScrolling = ref<boolean>(false);
const messages = reactive([]); const messages = reactive([]);
@ -103,20 +147,23 @@ const socket = ref(null);
const currentAIMessage = ref(""); const currentAIMessage = ref("");
const sessionID = ref(0); const sessionID = ref(0);
const messagesContainer = ref<HTMLDivElement | null>(null); const messagesContainer = ref<HTMLDivElement | null>(null);
const sessionIsShow = ref(false);
const sessionName = ref("");
const renderMarkdown = (content: string) => { const renderMarkdown = (content: string) => {
return md.render(content); return md.render(content);
}; };
const scrollToBottom = () => { const scrollToBottom = () => {
nextTick(() => { let x = document.getElementsByClassName("chat-messages")[0];
if (messagesContainer.value) { x.scrollTop = x.scrollHeight; //
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
}
});
}; };
onMounted(() => { onMounted(() => {
// if (typeof window !== 'undefined') {
// //
// md.use(markdownItMermaid);
// }
let url = let url =
"wss://pm.ljsea.top/im/ai_chat_ws?" + "wss://pm.ljsea.top/im/ai_chat_ws?" +
"token=" + "token=" +
@ -126,6 +173,7 @@ onMounted(() => {
console.log("WebSocket 连接已建立"); console.log("WebSocket 连接已建立");
ElMessage.success("连接成功"); ElMessage.success("连接成功");
}; };
getMessage(125);
messagesContainer.value = document.querySelector(".chat-messages"); messagesContainer.value = document.querySelector(".chat-messages");
socket.value.onmessage = (event) => { socket.value.onmessage = (event) => {
@ -144,7 +192,7 @@ onMounted(() => {
finished: false, finished: false,
}); });
} }
console.log("resp:", msg); //console.log("resp:", msg);
sessionID.value = msg.session_id; sessionID.value = msg.session_id;
currentAIMessage.value += msg.msg.msg.response; currentAIMessage.value += msg.msg.msg.response;
if (msg.msg.msg.done) { if (msg.msg.msg.done) {
@ -174,32 +222,87 @@ onUnmounted(() => {
}); });
const sendMessage = () => { const sendMessage = () => {
if (inputMessage.value.trim() === "") {
ElMessage.warning("消息不能为空");
return;
}
let msg = { let msg = {
msg: inputMessage.value, msg: inputMessage.value,
type: "ollama", type: "ollama",
function: "gen-ai-chat", function: "gen-ai-chat",
session_id: sessionID.value, session_id: sessionID.value,
}; };
if (inputMessage.value.trim() === "") return;
messages.push({ role: "user", content: inputMessage.value, finished: true }); messages.push({ role: "user", content: inputMessage.value, finished: true });
socket.value.send(JSON.stringify(msg)); socket.value.send(JSON.stringify(msg));
inputMessage.value = ""; inputMessage.value = "";
scrollToBottom(); scrollToBottom();
loading.value = true; loading.value = true;
//getMessage(); if (sessionID.value == 0) {
sessionName.value = msg.msg;
}
}; };
const loadSession = async (session_id: number) => {
sessionID.value = session_id;
messages.length = 0; //
sessionName.value = historySessions.value.find(
(session) => session.ID == session_id
)?.Name;
await getMessage(session_id);
};
const getMessage = async () => { const clearCurrent = () => {
sessionID.value = 0;
messages.length = 0; //
sessionName.value = "新会话";
ElMessage.success("新会话已创建!可以开始聊天了");
};
const showSession = async () => {
//
let req = {
token: localStorage.getItem("token"),
type: "UserID",
};
let result = await FindSessionService(req);
historySessions.value = result.data;
sessionIsShow.value = !sessionIsShow.value;
};
const getShortenedName = (name: string) => {
if (name.length > 10) {
return name.slice(0, 10) + "...";
}
return name;
};
const getMessage = async (session_id: number) => {
let result = {}; let result = {};
try { try {
let req = { let req = {
token: localStorage.getItem("token"), token: localStorage.getItem("token"),
session_id: sessionID.value, session_id: session_id,
}; };
result = await GetMessageService(req); result = await GetMessageService(req);
if (result["code"] === 0) { if (result["code"] === 0) {
console.log(result["data"]); console.log(result["data"]);
let data = result["data"];
for (let i = 0; i < data.length; i++) {
if (data[i]["Type"] === 3) {
messages.push({
role: "user",
content: data[i]["Msg"],
finished: true,
});
} else if (data[i]["Type"] === 4) {
messages.push({
role: "assistant",
content: data[i]["Msg"],
finished: true,
});
} else {
console.log("未知消息类型");
}
}
} }
} catch (e) { } catch (e) {
console.log(e); console.log(e);
@ -207,12 +310,40 @@ const getMessage = async () => {
return {}; return {};
}; };
</script> </script>
<style scoped> <style scoped>
.chat-app {
display: flex;
height: 100%;
}
.history-sessions {
width: 15%;
padding: 20px;
height: 100%;
overflow-y: auto;
border-right: 1px solid #e1e1e1;
scrollbar-width: none;
}
.history-sessions ul {
list-style-type: none;
padding: 0;
}
.history-sessions li {
cursor: pointer;
padding: 10px;
border-bottom: 1px solid #e1e1e1;
}
.history-sessions li:hover {
background-color: #f0f0f0;
}
.chat-container { .chat-container {
flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100%;
padding: 20px; padding: 20px;
box-sizing: border-box; box-sizing: border-box;
} }
@ -285,4 +416,34 @@ const getMessage = async () => {
.el-input { .el-input {
width: 100%; width: 100%;
} }
.session-card {
margin-bottom: 20px;
height: 20%;
}
.session-card2 {
margin-bottom: 20px;
height: 70%;
}
.session-card ul {
list-style-type: none;
padding: 0;
margin: 0;
}
.session-card li {
cursor: pointer;
padding: 10px;
border-bottom: 1px solid #e1e1e1;
}
.session-card li:hover {
background-color: #f0f0f0;
}
.scroll-wrapper {
height: 100%;
overflow-y: auto;
}
</style> </style>

View File

@ -0,0 +1,296 @@
<template>
<div @click="sessionIsShow = !sessionIsShow" style="cursor: pointer;">
<el-icon v-if="sessionIsShow" >
<Expand />
</el-icon>
<el-icon v-else>
<Fold />
</el-icon>
</div>
<div class="chat-container">
<!-- 消息列表 -->
<el-card class="chat-messages" shadow="never" ref="messagesContainer">
<div
v-for="(message, index) in messages"
:key="index"
:class="['message', message.role]"
>
<div class="message-avatar">
<span v-if="message.role === 'assistant'">💬</span>
<span v-else>👤</span>
</div>
<div class="message-content">
<div v-html="renderMarkdown(message.content)"></div>
</div>
</div>
<div v-if="loading" class="loading-indicator">Loading...</div>
</el-card>
<!-- 输入区域 -->
<el-card class="chat-input" shadow="never">
<el-row :gutter="10">
<el-col :span="20">
<el-input
v-model="inputMessage"
type="textarea"
:rows="2"
placeholder="输入消息..."
@keyup.enter="sendMessage"
/>
</el-col>
<el-col :span="4" style="text-align: center;" >
<el-button type="primary" @click="sendMessage" >发送</el-button>
</el-col>
</el-row>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive, nextTick } from "vue";
import { ElCard, ElInput, ElButton } from "element-plus";
import { WSMessage, AIQMessage, OllamaMessage } from "@/types/im";
import { ElMessage } from "element-plus";
import { GetMessageService } from "@/api/im";
import MarkdownIt from "markdown-it";
import markdownItMermaid from "markdown-it-mermaid";
import hljs from "highlight.js";
import bash from "highlight.js/lib/languages/bash";
import javascript from "highlight.js/lib/languages/javascript";
import typescript from "highlight.js/lib/languages/typescript";
import java from "highlight.js/lib/languages/java";
import sql from "highlight.js/lib/languages/sql";
import nginx from "highlight.js/lib/languages/nginx";
import json from "highlight.js/lib/languages/json";
import yaml from "highlight.js/lib/languages/yaml";
import xml from "highlight.js/lib/languages/xml";
import shell from "highlight.js/lib/languages/shell";
import 'katex/dist/katex.min.css';
interface Message {
role: "user" | "assistant";
content: string;
finished?: boolean;
}
hljs.registerLanguage("bash", bash);
hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("typescript", typescript);
hljs.registerLanguage("java", java);
hljs.registerLanguage("sql", sql);
hljs.registerLanguage("nginx", nginx);
hljs.registerLanguage("json", json);
hljs.registerLanguage("yaml", yaml);
hljs.registerLanguage("xml", xml);
hljs.registerLanguage("shell", shell);
const md = new MarkdownIt({
html: true,
linkify: true,
breaks: true,
xhtmlOut: true,
typographer: true,
highlight: (str, lang) => {
if (lang && hljs.getLanguage(lang)) {
try {
return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
} catch (__) {}
}
return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
},
});
const loading = ref(false);
const isUserScrolling = ref<boolean>(false);
const messages = reactive([]);
const inputMessage = ref("");
const socket = ref(null);
const currentAIMessage = ref("");
const sessionID = ref(0);
const messagesContainer = ref<HTMLDivElement | null>(null);
const sessionIsShow = ref(false);
const renderMarkdown = (content: string) => {
return md.render(content);
};
const scrollToBottom = () => {
let x=document.getElementsByClassName("chat-messages")[0]
x.scrollTop=x.scrollHeight //
};
onMounted(() => {
// if (typeof window !== 'undefined') {
// //
// md.use(markdownItMermaid);
// }
let url =
"wss://pm.ljsea.top/im/ai_chat_ws?" +
"token=" +
localStorage.getItem("token");
socket.value = new WebSocket(url);
socket.value.onopen = () => {
console.log("WebSocket 连接已建立");
ElMessage.success("连接成功");
};
getMessage(125);
messagesContainer.value = document.querySelector(".chat-messages");
socket.value.onmessage = (event) => {
let msg: WSMessage = JSON.parse(event.data);
const existingMessage = messages.find(
(msg) => msg.role === "assistant" && !msg.finished
);
if (existingMessage) {
//
existingMessage.content += msg.msg.msg.response;
} else {
//
messages.push({
role: "assistant",
content: msg.msg.msg.response,
finished: false,
});
}
console.log("resp:", msg);
sessionID.value = msg.session_id;
currentAIMessage.value += msg.msg.msg.response;
if (msg.msg.msg.done) {
const assistantMessage = messages[messages.length - 1];
assistantMessage.finished = true;
loading.value = false;
}
nextTick(() => {
scrollToBottom(); //
});
};
socket.value.onclose = () => {
console.log("WebSocket 连接已关闭");
ElMessage.error("连接已关闭");
};
socket.value.onerror = (error) => {
console.error("WebSocket 发生错误:", error);
};
});
onUnmounted(() => {
if (socket.value) {
socket.value.close();
}
});
const sendMessage = () => {
let msg = {
msg: inputMessage.value,
type: "ollama",
function: "gen-ai-chat",
session_id: sessionID.value,
};
if (inputMessage.value.trim() === "") return;
messages.push({ role: "user", content: inputMessage.value, finished: true });
socket.value.send(JSON.stringify(msg));
inputMessage.value = "";
scrollToBottom();
loading.value = true;
};
const getMessage = async (session_id:number) => {
let result = {};
try {
let req = {
token: localStorage.getItem("token"),
session_id: session_id,
};
result = await GetMessageService(req);
if (result["code"] === 0) {
console.log(result["data"]);
}
} catch (e) {
console.log(e);
}
return {};
};
</script>
<style scoped>
.chat-container {
display: flex;
flex-direction: column;
height: 100%;
padding: 20px;
box-sizing: border-box;
}
.chat-messages {
flex: 1;
overflow-y: auto; /* 允许垂直滚动 */
padding: 10px;
margin-bottom: 20px;
position: relative;
display: flex;
flex-direction: column;
}
.messages-wrapper {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto; /* 确保内部可以滚动 */
height: 100%;
}
.message {
display: flex;
margin-bottom: 15px;
}
.message.user {
justify-content: flex-end;
}
.message-avatar {
width: 40px;
text-align: center;
line-height: 40px;
font-size: 20px;
margin-right: 10px;
}
.message.assistant .message-avatar {
margin-right: 0;
margin-left: 10px;
}
.message-content {
background-color: #f0f9eb;
border: 1px solid #e1f3d8;
border-radius: 4px;
padding: 10px 15px;
white-space: pre-wrap;
max-width: 70%;
}
.message.assistant .message-content {
background-color: #f3f4f6;
border: 1px solid #dce4eb;
max-width: 70%;
}
.loading-indicator {
text-align: center;
color: #999;
font-size: 16px;
}
.chat-input {
width: 100%;
}
.el-input {
width: 100%;
}
</style>

1879
yarn.lock

File diff suppressed because it is too large Load Diff