newAi.jsx
11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import React, { useState, useEffect, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { AudioOutline } from "antd-mobile-icons";
import './AiChatStyles.less'; // 引入外部样式文件
const ChatInterface = () => {
// ==================== 状态管理 ====================
const [sessionId, setSessionId] = useState('');
const [sUserId] = useState('user-001');
const [sUserType] = useState('sysadmin');
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [currentModel, setCurrentModel] = useState('general');
const [chatHistory, setChatHistory] = useState([]);
const [welcomeContent, setWelcomeContent] = useState('');
const messagesEndRef = useRef(null);
const inputRef = useRef(null);
// ==================== 配置 ====================
const CONFIG = {
backendUrl: 'http://localhost:8099/xlyAi',
endpoints: {
chat: '/api/v1/chat/query',
process: '/api/v1/chat/query',
},
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
maxHistory: 20,
};
// ==================== 工具函数 ====================
const getCurrentTime = () => {
const now = new Date();
return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};
const generateRandomString = (length) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
};
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// ==================== 初始化 ====================
useEffect(() => {
setMessages([
{
id: 'welcome',
type: 'ai',
content: '',
time: getCurrentTime(),
isWelcome: true
}
]);
const initSession = async () => {
try {
const initUrl = `${CONFIG.backendUrl}/api/v1/chat/init?sUserId=${sUserId}&sUserType=${sUserType}`;
const response = await fetch(initUrl, {
method: 'POST',
headers: CONFIG.headers,
body: JSON.stringify({})
});
const data = await response.json();
if (data.data) {
setWelcomeContent(data.data);
setMessages(prev => prev.map(msg =>
msg.id === 'welcome' ? { ...msg, content: data.data } : msg
));
}
} catch (error) {
console.error('初始化失败:', error);
}
};
initSession();
inputRef.current?.focus();
const handleKeyDown = (e) => {
if (e.ctrlKey && e.key === 'Enter') {
handleSendMessage();
}
if (e.key === 'Escape') {
setInputValue('');
}
if (e.key === 'ArrowUp' && inputValue === '') {
const lastUserMessage = chatHistory
.filter(item => item.role === 'user')
.pop();
if (lastUserMessage) {
setInputValue(lastUserMessage.content);
e.preventDefault();
}
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []);
useEffect(() => {
scrollToBottom();
}, [messages, isLoading]);
// ==================== 消息处理 ====================
const addMessage = (content, type, isError = false) => {
const newMessage = {
id: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
type,
content,
time: getCurrentTime(),
isError
};
setMessages(prev => [...prev, newMessage]);
return newMessage.id;
};
const handleSendMessage = async () => {
const message = inputValue.trim();
if (!message || isLoading) return;
let currentSessionId = sessionId;
if (!currentSessionId) {
currentSessionId = generateRandomString(20);
setSessionId(currentSessionId);
}
setInputValue('');
setIsLoading(true);
addMessage(message, 'user');
const newHistoryItem = { role: 'user', content: message, timestamp: Date.now() };
setChatHistory(prev => {
const updated = [...prev, newHistoryItem];
return updated.length > CONFIG.maxHistory ? updated.slice(-CONFIG.maxHistory) : updated;
});
try {
const endpoint = currentModel === 'process' ? CONFIG.endpoints.process : CONFIG.endpoints.chat;
const requestData = {
message,
modelType: currentModel,
sUserId,
sUserType,
sessionId: currentSessionId
};
const response = await fetch(`${CONFIG.backendUrl}${endpoint}`, {
method: 'POST',
headers: CONFIG.headers,
body: JSON.stringify(requestData)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (data.data) {
addMessage(data.data, 'ai');
setChatHistory(prev => {
const updated = [...prev, { role: 'assistant', content: data.data, timestamp: Date.now() }];
return updated.length > CONFIG.maxHistory ? updated.slice(-CONFIG.maxHistory) : updated;
});
}
} catch (error) {
console.error('请求失败:', error);
const errorMessage = `
抱歉,请求出现错误:${error.message}
**可能的原因:**
1. Spring Boot 后端服务未启动
2. API 接口路径不正确
3. 网络连接问题
**检查步骤:**
1. 确保后端服务在端口 8099 运行
2. 检查浏览器控制台查看详细错误
3. 刷新页面重试
`;
addMessage(errorMessage, 'ai', true);
} finally {
setIsLoading(false);
inputRef.current?.focus();
}
};
const handleClearChat = () => {
if (window.confirm('确定要清空当前对话吗?')) {
setMessages([
{
id: 'cleared',
type: 'ai',
content: '对话已清空,请开始新的对话。',
time: getCurrentTime(),
}
]);
setChatHistory([]);
setSessionId('');
}
};
const handleCopyMessage = (content) => {
navigator.clipboard.writeText(content).then(() => {
alert('已复制到剪贴板');
});
};
const handleRegenerateMessage = (messageId, content) => {
setChatHistory(prev => prev.filter(item =>
!(item.role === 'assistant' && item.content === content)
));
setMessages(prev => prev.filter(msg => msg.id !== messageId));
setInputValue(content);
setTimeout(() => handleSendMessage(), 100);
};
const handleModelChange = (e) => {
setCurrentModel(e.target.value);
};
// ==================== 渲染 ====================
return (
<div className="ai-chat-container">
{/* 头部 */}
<div className="chat-header">
<div className="header-left">
<h1>小羚羊Ai-agent智能体</h1>
<p>AI 印刷助手</p>
</div>
<div className="header-right">
<select
className="model-selector"
value={currentModel}
onChange={handleModelChange}
>
<option value="process">小羚羊印刷行业大模型</option>
<option value="general">qwen2.5:14b</option>
</select>
<button
className="model-selectors"
onClick={handleClearChat}
>
清空对话
</button>
</div>
</div>
{/* 主体 */}
<div className="chat-body">
<div className="chat-main">
{/* 消息区域 */}
<div className="messages-container">
{messages.map((msg) => (
<div
key={msg.id}
className={`message ${msg.type}-message`}
>
<div className={`message-bubble ${msg.type}-bubble`}>
<div className="message-content">
{msg.type === 'ai' ? (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code: ({ node, inline, className, children, ...props }) => (
inline ? (
<code className="inline-code" {...props}>
{children}
</code>
) : (
<pre className="code-block">
<code {...props}>{children}</code>
</pre>
)
)
}}
>
{msg.content || welcomeContent}
</ReactMarkdown>
) : (
msg.content
)}
</div>
<div className="message-meta">
<span className="message-time">{msg.time}</span>
{msg.type === 'ai' && !msg.isWelcome && (
<div className="message-actions">
<button
className="action-btn"
onClick={() => handleCopyMessage(msg.content)}
>
复制
</button>
<button
className="action-btn"
onClick={() => handleRegenerateMessage(msg.id, msg.content)}
>
重新生成
</button>
</div>
)}
</div>
</div>
</div>
))}
{/* 打字机效果 */}
{isLoading && (
<div className="message ai-message">
<div className="typing-indicator">
<div className="typing-dot"></div>
<div className="typing-dot" style={{ animationDelay: '0.2s' }}></div>
<div className="typing-dot" style={{ animationDelay: '0.4s' }}></div>
<span className="typing-text">正在思考...</span>
</div>
</div>
)}
<div ref={messagesEndRef} className="bottom-spacer" />
</div>
{/* 输入区域 */}
<div className="input-section">
<div className="input-wrapper">
<input
ref={inputRef}
type="text"
className="message-input"
placeholder="输入您的问题..."
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
}}
disabled={isLoading}
/>
<AudioOutline className='message-icon'/>
<button
className={`send-button ${isLoading ? 'disabled' : ''}`}
onClick={handleSendMessage}
disabled={isLoading}
>
发送
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default ChatInterface;