From 4c09d01583074ce7c9c8c8c7f235b49473a01381 Mon Sep 17 00:00:00 2001
From: Junjie <DELL@qq.com>
Date: 星期五, 12 十二月 2025 12:43:33 +0800
Subject: [PATCH] #AI
---
src/main/webapp/views/ai/diagnosis.html | 131 +++++++++++++++++++++++++++++---
src/main/java/com/zy/ai/controller/WcsDiagnosisController.java | 68 +++++++++++++++++
src/main/java/com/zy/ai/service/WcsDiagnosisService.java | 35 ++++++++
3 files changed, 222 insertions(+), 12 deletions(-)
diff --git a/src/main/java/com/zy/ai/controller/WcsDiagnosisController.java b/src/main/java/com/zy/ai/controller/WcsDiagnosisController.java
index 45c90e3..41dbf15 100644
--- a/src/main/java/com/zy/ai/controller/WcsDiagnosisController.java
+++ b/src/main/java/com/zy/ai/controller/WcsDiagnosisController.java
@@ -177,6 +177,74 @@
return emitter;
}
+ @GetMapping("/askStream")
+ public SseEmitter askStream(@RequestParam("prompt") String prompt) {
+ SseEmitter emitter = new SseEmitter(0L);
+ new Thread(() -> {
+ try {
+ WcsDiagnosisRequest request = new WcsDiagnosisRequest();
+
+ List<String> logs = AiLogAppender.getRecentLogs(100);
+ request.setLogs(logs);
+
+ List<WrkMast> wrkMasts = wrkMastService.selectList(new EntityWrapper<>());
+ request.setTasks(wrkMasts);
+
+ List<DeviceRealTimeData> deviceRealTimeDataList = new ArrayList<>();
+ List<DeviceConfigsData> deviceConfigsDataList = new ArrayList<>();
+
+ List<BasCrnp> basCrnps = basCrnpService.selectList(new EntityWrapper<>());
+ for (BasCrnp basCrnp : basCrnps) {
+ CrnThread crnThread = (CrnThread) SlaveConnection.get(SlaveType.Crn, basCrnp.getCrnNo());
+ if (crnThread == null) {
+ continue;
+ }
+
+ CrnProtocol protocol = crnThread.getStatus();
+
+ for (StationObjModel stationObjModel : basCrnp.getInStationList$()) {
+ StationThread stationThread = (StationThread) SlaveConnection.get(SlaveType.Devp, stationObjModel.getDeviceNo());
+ if (stationThread == null) {
+ continue;
+ }
+
+ Map<Integer, StationProtocol> map = stationThread.getStatusMap();
+ StationProtocol stationProtocol = map.get(stationObjModel.getStationId());
+ if (stationProtocol == null) {
+ continue;
+ }
+
+ DeviceRealTimeData stationData = new DeviceRealTimeData();
+ stationData.setDeviceNo(stationObjModel.getDeviceNo());
+ stationData.setDeviceType(String.valueOf(SlaveType.Devp));
+ stationData.setDeviceData(stationProtocol);
+ deviceRealTimeDataList.add(stationData);
+ }
+
+ DeviceRealTimeData deviceRealTimeData = new DeviceRealTimeData();
+ deviceRealTimeData.setDeviceNo(basCrnp.getCrnNo());
+ deviceRealTimeData.setDeviceType(String.valueOf(SlaveType.Crn));
+ deviceRealTimeData.setDeviceData(protocol);
+ deviceRealTimeDataList.add(deviceRealTimeData);
+
+ DeviceConfigsData deviceConfigsData = new DeviceConfigsData();
+ deviceConfigsData.setDeviceNo(basCrnp.getCrnNo());
+ deviceConfigsData.setDeviceType(String.valueOf(SlaveType.Crn));
+ deviceConfigsData.setDeviceData(basCrnp);
+ deviceConfigsDataList.add(deviceConfigsData);
+ }
+
+ request.setDeviceRealtimeData(deviceRealTimeDataList);
+ request.setDeviceConfigs(deviceConfigsDataList);
+
+ wcsDiagnosisService.askStream(request, prompt, emitter);
+ } catch (Exception e) {
+ emitter.completeWithError(e);
+ }
+ }).start();
+ return emitter;
+ }
+
/**
* POST /api/ai/diagnose/wcs
*/
diff --git a/src/main/java/com/zy/ai/service/WcsDiagnosisService.java b/src/main/java/com/zy/ai/service/WcsDiagnosisService.java
index 93cecbb..a61d222 100644
--- a/src/main/java/com/zy/ai/service/WcsDiagnosisService.java
+++ b/src/main/java/com/zy/ai/service/WcsDiagnosisService.java
@@ -99,6 +99,41 @@
});
}
+ public void askStream(WcsDiagnosisRequest request, String prompt, SseEmitter emitter) {
+ List<ChatCompletionRequest.Message> messages = new ArrayList<>();
+
+ ChatCompletionRequest.Message system = new ChatCompletionRequest.Message();
+ system.setRole("system");
+ system.setContent(
+ "浣犳槸涓�鍚嶈祫娣� WCS锛堜粨鍌ㄦ帶鍒剁郴缁燂級涓庤嚜鍔ㄥ寲绔嬪簱涓撳锛岀啛鎮夛細鍫嗗灈鏈恒�佽緭閫佺嚎銆佹彁鍗囨満銆佺┛姊溅绛夎澶囩殑浠诲姟鍒嗛厤鍜岃繍琛岄�昏緫锛屼篃鐔熸倝甯歌鐨勭郴缁熷崱姝汇�佷换鍔′笉鎵ц銆佽澶囩┖闂蹭絾鏃犱换鍔$瓑闂妯″紡銆俓n\n" +
+ "鍦ㄥ洖绛旂敤鎴烽棶棰樻椂锛岄渶瑕佺粨鍚堜笅闈㈢粰鍑虹殑绯荤粺褰撳墠涓婁笅鏂囦俊鎭紙浠诲姟銆佽澶囧疄鏃剁姸鎬併�佽澶囬厤缃�佺郴缁熸棩蹇楃瓑锛夛紝浠ョ畝娲併�佹槑纭殑涓枃浣滅瓟锛屽苟鍦ㄩ渶瑕佹椂缁欏嚭鍙墽琛岀殑鎺掓煡寤鸿銆�"
+ );
+ messages.add(system);
+
+ ChatCompletionRequest.Message contextMsg = new ChatCompletionRequest.Message();
+ contextMsg.setRole("user");
+ contextMsg.setContent(buildUserContent(request));
+ messages.add(contextMsg);
+
+ ChatCompletionRequest.Message questionMsg = new ChatCompletionRequest.Message();
+ questionMsg.setRole("user");
+ questionMsg.setContent("銆愮敤鎴锋彁闂�慭n" + (prompt == null ? "" : prompt));
+ messages.add(questionMsg);
+
+ llmChatService.chatStream(messages, 0.2, 2048, s -> {
+ try {
+ String safe = s == null ? "" : s.replace("\r", "").replace("\n", "\\n");
+ if (!safe.isEmpty()) {
+ emitter.send(SseEmitter.event().data(safe));
+ }
+ } catch (Exception ignore) {}
+ }, () -> {
+ try { emitter.complete(); } catch (Exception ignore) {}
+ }, e -> {
+ try { emitter.completeWithError(e); } catch (Exception ignore) {}
+ });
+ }
+
private String buildUserContent(WcsDiagnosisRequest request) {
StringBuilder sb = new StringBuilder();
diff --git a/src/main/webapp/views/ai/diagnosis.html b/src/main/webapp/views/ai/diagnosis.html
index a396fa1..e087e17 100644
--- a/src/main/webapp/views/ai/diagnosis.html
+++ b/src/main/webapp/views/ai/diagnosis.html
@@ -9,13 +9,24 @@
body { background: #f5f7fa; }
.container { max-width: 1100px; margin: 24px auto; }
.actions { display: flex; gap: 12px; align-items: center; }
- .output { min-height: 360px; }
+ .output { height: 65vh; }
.markdown-body { font-size: 14px; line-height: 1.4; white-space: pre-wrap; word-break: break-word; }
.markdown-body p { margin: 4px 0; }
.markdown-body ul, .markdown-body ol { margin: 4px 0 4px 16px; padding: 0; }
.markdown-body h1, .markdown-body h2, .markdown-body h3 { margin-top: 8px; }
.markdown-body pre { background: #f6f8fa; padding: 12px; border-radius: 6px; overflow: auto; }
.status { color: #909399; }
+ .chat { display: flex; flex-direction: column; gap: 10px; height: 100%; overflow-y: auto; padding-right: 8px; }
+ .msg { display: flex; align-items: flex-start; }
+ .msg.user { justify-content: flex-end; }
+ .msg.assistant { justify-content: flex-start; }
+ .bubble { max-width: 72%; padding: 10px 12px; border-radius: 16px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
+ .assistant .bubble { background: #ffffff; border: 1px solid #ebeef5; color: #303133; }
+ .user .bubble { background: #409EFF; color: #ffffff; }
+ .composer { display: flex; gap: 10px; align-items: center; margin-top: 12px; }
+ .avatar { width: 24px; height: 24px; display: flex; align-items: center; margin-right: 8px; }
+ .time { font-size: 12px; color: #909399; text-align: right; margin-top: 6px; }
+ .output .el-card__body { height: 100%; padding: 0; }
</style>
</head>
<body>
@@ -36,8 +47,22 @@
<el-divider></el-divider>
<el-card class="output" shadow="never">
- <div class="markdown-body" v-html="renderedHtml"></div>
+ <div ref="chat" class="chat">
+ <div v-for="(m,i) in messages" :key="i" class="msg" :class="m.role">
+ <div class="avatar" v-html="m.role === 'assistant' ? assistantIcon : userIcon"></div>
+ <div class="bubble">
+ <div v-if="m.role === 'assistant'" class="markdown-body" v-html="m.html"></div>
+ <div v-else v-text="m.text"></div>
+ <div class="time">{{ m.ts }}</div>
+ </div>
+ </div>
+ </div>
</el-card>
+
+ <div class="composer">
+ <el-input v-model="userInput" placeholder="鍚� AI 鍔╂墜鎻愰棶" clearable :disabled="streaming" @keyup.enter.native="ask"></el-input>
+ <el-button type="success" :disabled="sendDisabled" @click="ask">鍙戦��</el-button>
+ </div>
</el-card>
</div>
@@ -52,21 +77,32 @@
breaks: true
});
+ function getUserIconHtml(width, height) {
+ width = width || 24; height = height || 24;
+ return '<svg width="'+width+'" height="'+height+'" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n'
+ + '<circle cx="12" cy="7" r="4" fill="#909399"/>\n'
+ + '<path d="M4 20c0-4 4-6 8-6s8 2 8 6" fill="#909399" opacity="0.35"/>\n'
+ + '</svg>';
+ }
+
new Vue({
el: '#app',
data: function() {
return {
headerIcon: getAiIconHtml(50, 50),
+ assistantIcon: getAiIconHtml(24, 24),
+ userIcon: getUserIconHtml(24, 24),
loading: false,
streaming: false,
source: null,
- markdownBuffer: '',
- renderedHtml: '',
+ messages: [],
pendingText: '',
typingTimer: null,
lastRenderTs: 0,
renderIntervalMs: 120,
- stepChars: 6
+ stepChars: 6,
+ userInput: '',
+ autoScrollThreshold: 80
};
},
computed: {
@@ -74,9 +110,66 @@
if (this.streaming) return '璇婃柇杩涜涓�';
if (this.loading) return '杩炴帴涓�';
return '绌洪棽';
+ },
+ sendDisabled: function() {
+ var t = (this.userInput || '').trim();
+ return this.streaming || t.length === 0;
}
},
methods: {
+ shouldAutoScroll: function() {
+ var el = this.$refs.chat;
+ if (!el) return false;
+ return (el.scrollHeight - el.scrollTop - el.clientHeight) <= this.autoScrollThreshold;
+ },
+ scrollToBottom: function(force) {
+ var el = this.$refs.chat;
+ if (!el) return;
+ if (force || this.streaming || this.shouldAutoScroll()) {
+ el.scrollTop = el.scrollHeight;
+ }
+ },
+ nowStr: function() {
+ var d = new Date();
+ function pad(n) { return (n<10?'0':'') + n; }
+ var y = d.getFullYear();
+ var m = pad(d.getMonth() + 1);
+ var day = pad(d.getDate());
+ var hh = pad(d.getHours());
+ var mm = pad(d.getMinutes());
+ var ss = pad(d.getSeconds());
+ return y + '-' + m + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
+ },
+ ask: function() {
+ if (this.streaming) return;
+ var msg = (this.userInput || '').trim();
+ if (!msg) return;
+ this.loading = true;
+ this.streaming = true;
+ this.messages.push({ role: 'user', text: msg, ts: this.nowStr() });
+ this.messages.push({ role: 'assistant', md: '', html: '', ts: this.nowStr() });
+ this.scrollToBottom(true);
+ var url = baseUrl + '/ai/diagnose/askStream?prompt=' + encodeURIComponent(msg);
+ this.source = new EventSource(url);
+ var self = this;
+ this.source.onopen = function() {
+ self.loading = false;
+ };
+ this.source.onmessage = function(e) {
+ if (!e || !e.data) return;
+ var chunk = (e.data || '').replace(/\\n/g, '\n');
+ if (!chunk) return;
+ var normalized = chunk.replace(/\r/g, '');
+ if (/^\n+$/.test(normalized)) return;
+ self.pendingText += chunk;
+ self.ensureTyping();
+ self.scrollToBottom(true);
+ };
+ this.source.onerror = function() {
+ self.stop();
+ };
+ this.userInput = '';
+ },
start: function() {
if (this.streaming) return;
this.clear();
@@ -84,6 +177,8 @@
this.streaming = true;
var url = baseUrl + '/ai/diagnose/runAiStream';
this.source = new EventSource(url);
+ this.messages.push({ role: 'assistant', md: '', html: '', ts: this.nowStr() });
+ this.scrollToBottom(true);
var self = this;
this.source.onopen = function() {
self.loading = false;
@@ -98,6 +193,7 @@
if (/^\n+$/.test(normalized)) return;
self.pendingText += chunk;
self.ensureTyping();
+ self.scrollToBottom(true);
};
this.source.onerror = function() {
self.stop();
@@ -114,14 +210,22 @@
}
if (self.pendingText.length > 0) {
var n = Math.min(self.stepChars, self.pendingText.length);
- self.markdownBuffer += self.pendingText.slice(0, n);
+ var part = self.pendingText.slice(0, n);
self.pendingText = self.pendingText.slice(n);
+ var last = self.messages.length > 0 ? self.messages[self.messages.length - 1] : null;
+ if (last && last.role === 'assistant') {
+ last.md = (last.md || '') + part;
+ }
}
var now = Date.now();
if (now - self.lastRenderTs > self.renderIntervalMs) {
self.lastRenderTs = now;
- var renderSource = self.markdownBuffer.replace(/\\n/g, '\n');
- self.renderedHtml = DOMPurify.sanitize(marked.parse(renderSource));
+ var last = self.messages.length > 0 ? self.messages[self.messages.length - 1] : null;
+ if (last && last.role === 'assistant') {
+ var renderSource = (last.md || '').replace(/\\n/g, '\n');
+ last.html = DOMPurify.sanitize(marked.parse(renderSource));
+ self.$nextTick(function() { self.scrollToBottom(true); });
+ }
}
}, 50);
},
@@ -136,12 +240,15 @@
clearInterval(this.typingTimer);
this.typingTimer = null;
}
- var renderSource = this.markdownBuffer.replace(/\\n/g, '\n');
- this.renderedHtml = DOMPurify.sanitize(marked.parse(renderSource));
+ var last = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
+ if (last && last.role === 'assistant') {
+ var renderSource = (last.md || '').replace(/\\n/g, '\n');
+ last.html = DOMPurify.sanitize(marked.parse(renderSource));
+ }
+ this.$nextTick(function() { this.scrollToBottom(true); }.bind(this));
},
clear: function() {
- this.markdownBuffer = '';
- this.renderedHtml = '';
+ this.messages = [];
this.pendingText = '';
}
}
--
Gitblit v1.9.1