修复:AI问答模块

This commit is contained in:
2025-07-09 12:39:29 +08:00
parent 5deb2e96b5
commit 6b36f83861
10 changed files with 247 additions and 57 deletions

View File

@@ -11,6 +11,7 @@ export interface AiChatMessage {
conversationId?: string; conversationId?: string;
type?: string; type?: string;
requestType?: number; requestType?: number;
aiToken?: string;
} }
/** /**
@@ -48,3 +49,5 @@ export async function stopAiMessage(data: { taskId: string; type?: string }) {
} }
return Promise.reject(new Error(res.message)); return Promise.reject(new Error(res.message));
} }

View File

@@ -25,7 +25,7 @@ const Index = () => {
// 二级栏目 // 二级栏目
const childCateogry = await pageCmsNavigation({parentId: categoryId}); const childCateogry = await pageCmsNavigation({parentId: categoryId});
// 终极新闻列表 // 终极新闻列表
const articles = await pageCmsArticle({categoryId}); const articles = await pageCmsArticle({categoryId,limit: 50});
// 当前栏目信息 // 当前栏目信息
if (navs) { if (navs) {

View File

@@ -22,7 +22,7 @@ const Index = () => {
// 当前栏目信息 // 当前栏目信息
const navs = await getCmsNavigation(categoryId); const navs = await getCmsNavigation(categoryId);
// 终极新闻列表 // 终极新闻列表
const articles = await pageCmsArticle({categoryId}); const articles = await pageCmsArticle({categoryId,limit: 50});
// 当前栏目信息 // 当前栏目信息
if (navs) { if (navs) {

View File

@@ -25,7 +25,7 @@ const Index = () => {
// 二级栏目 // 二级栏目
const childCateogry = await pageCmsNavigation({parentId: categoryId}); const childCateogry = await pageCmsNavigation({parentId: categoryId});
// 终极新闻列表 // 终极新闻列表
const articles = await pageCmsArticle({categoryId}); const articles = await pageCmsArticle({categoryId,limit: 50});
// 当前栏目信息 // 当前栏目信息
if (navs) { if (navs) {

View File

@@ -22,7 +22,7 @@ const List = () => {
// 当前栏目信息 // 当前栏目信息
const navs = await getCmsNavigation(categoryId); const navs = await getCmsNavigation(categoryId);
// 终极新闻列表 // 终极新闻列表
const articles = await pageCmsArticle({categoryId}); const articles = await pageCmsArticle({categoryId,limit: 50});
// 当前栏目信息 // 当前栏目信息
if (navs) { if (navs) {

View File

@@ -23,11 +23,40 @@ html {
color: white; color: white;
padding: 16px; padding: 16px;
text-align: center; text-align: center;
font-size: 1.2rem; // 使用 rem 单位 font-size: 1rem; // 使用 rem 单位
font-weight: bold; font-weight: bold;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
} }
.connection-status {
background: #fff3cd;
border-bottom: 1px solid #ffeaa7;
padding: 8px 16px;
text-align: center;
.status-indicator {
font-size: 0.9rem;
color: #856404;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
&.offline::before {
content: '⚠️';
font-size: 1rem;
}
.reconnect-button {
margin-left: 12px;
height: 28px;
padding: 0 12px;
font-size: 0.8rem;
border-radius: 14px;
}
}
}
.chat-container { .chat-container {
flex: 1; flex: 1;
display: flex; display: flex;
@@ -111,8 +140,23 @@ html {
border-radius: 18px; border-radius: 18px;
word-wrap: break-word; word-wrap: break-word;
line-height: 1.5; line-height: 1.5;
font-size: 1rem; // 使用 rem 单位 font-size: .8rem; // 使用 rem 单位
position: relative; position: relative;
display: flex;
align-items: flex-end;
gap: 4px;
.message-text {
flex: 1;
white-space: pre-wrap;
}
.typing-cursor {
color: #666;
font-weight: bold;
animation: blink 1s infinite;
margin-left: 2px;
}
.typing-indicator { .typing-indicator {
display: flex; display: flex;
@@ -139,7 +183,7 @@ html {
padding: 16px; padding: 16px;
border-top: 1px solid #e0e0e0; border-top: 1px solid #e0e0e0;
display: flex; display: flex;
align-items: flex-end; align-items: center;
gap: 12px; gap: 12px;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1); box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
@@ -155,7 +199,7 @@ html {
padding: 10px 16px; padding: 10px 16px;
border: 1px solid #e0e0e0; border: 1px solid #e0e0e0;
border-radius: 20px; border-radius: 20px;
font-size: 1.2rem; // 使用 rem 单位 font-size: 1rem; // 使用 rem 单位
line-height: 1.8; line-height: 1.8;
resize: none; resize: none;
outline: none; outline: none;
@@ -202,6 +246,32 @@ html {
box-shadow: none; box-shadow: none;
} }
} }
.stop-button {
min-width: 60px;
height: 40px;
border-radius: 20px;
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
border: none;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.3s ease;
flex-shrink: 0;
font-size: 0.8rem;
padding: 0 12px;
&:hover {
transform: scale(1.05);
box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}
&:active {
transform: scale(0.95);
}
}
} }
.quick-questions { .quick-questions {
@@ -210,7 +280,7 @@ html {
border-top: 1px solid #e0e0e0; border-top: 1px solid #e0e0e0;
.quick-title { .quick-title {
font-size: 1rem; // 使用 rem 单位 font-size: .8rem; // 使用 rem 单位
color: #666; color: #666;
margin-bottom: 12px; margin-bottom: 12px;
display: flex; display: flex;
@@ -228,7 +298,7 @@ html {
background: #f9f9f9; background: #f9f9f9;
border: 1px solid #e0e0e0; border: 1px solid #e0e0e0;
border-radius: 12px; border-radius: 12px;
font-size: 1rem; // 使用 rem 单位 font-size: .8rem; // 使用 rem 单位
color: #333; color: #333;
cursor: pointer; cursor: pointer;
transition: all 0.3s ease; transition: all 0.3s ease;
@@ -259,7 +329,7 @@ html {
text-align: center; text-align: center;
.empty-icon { .empty-icon {
font-size: 4rem; // 使用 rem 单位 font-size: 3rem; // 使用 rem 单位
margin-bottom: 16px; margin-bottom: 16px;
opacity: 0.5; opacity: 0.5;
} }
@@ -272,7 +342,7 @@ html {
} }
.empty-desc { .empty-desc {
font-size: 1rem; // 使用 rem 单位 font-size: .8rem; // 使用 rem 单位
color: #666; color: #666;
line-height: 1.5; line-height: 1.5;
} }
@@ -300,3 +370,12 @@ html {
opacity: 1; opacity: 1;
} }
} }
@keyframes blink {
0%, 50% {
opacity: 1;
}
51%, 100% {
opacity: 0;
}
}

View File

@@ -5,8 +5,8 @@ import {Button} from '@nutui/nutui-react-taro';
import {User, ArrowUp} from '@nutui/icons-react-taro'; import {User, ArrowUp} from '@nutui/icons-react-taro';
import {sendAiMessage, stopAiMessage} from '@/api/ai'; import {sendAiMessage, stopAiMessage} from '@/api/ai';
import {createWebSocket} from '@/utils/websocket'; import {createWebSocket} from '@/utils/websocket';
import {getAiToken} from '@/utils/aiToken';
import './index.scss'; import './index.scss';
import Header from "../index/Header";
import {WSS_API_URL} from "@/utils/server"; import {WSS_API_URL} from "@/utils/server";
// 消息类型 // 消息类型
@@ -28,6 +28,7 @@ const AiChat = () => {
const [inputValue, setInputValue] = useState(''); const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [currentTaskId, setCurrentTaskId] = useState<string>(''); const [currentTaskId, setCurrentTaskId] = useState<string>('');
const [wsConnected, setWsConnected] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null); const messagesEndRef = useRef<HTMLDivElement>(null);
const wsRef = useRef<any>(null); const wsRef = useRef<any>(null);
@@ -39,19 +40,16 @@ const AiChat = () => {
"请问您还有什么问题吗?" "请问您还有什么问题吗?"
]; ];
// 检查并获取AI Token
const checkAiToken = () => {
return getAiToken();
};
// 滚动到底部 // 滚动到底部
const scrollToBottom = () => { const scrollToBottom = () => {
if (!Taro.getStorageSync('UserId')) { // 检查并确保AI_TOKEN存在
Taro.showToast({ checkAiToken();
title: '请先登录',
icon: 'none',
duration: 2000
});
Taro.navigateTo({
url: '/passport/sms-login',
})
return false;
}
setTimeout(() => { setTimeout(() => {
messagesEndRef.current?.scrollIntoView({behavior: 'smooth'}); messagesEndRef.current?.scrollIntoView({behavior: 'smooth'});
}, 100); }, 100);
@@ -59,9 +57,7 @@ const AiChat = () => {
// 初始化WebSocket连接 // 初始化WebSocket连接
const initWebSocket = () => { const initWebSocket = () => {
// const wsUrl = APP_API_URL.replace('http', 'ws') + '/chat/' + Taro.getStorageSync('UserId') || 'token'; wsRef.current = createWebSocket(WSS_API_URL + "/chat/" + Taro.getStorageSync('AI_TOKEN'));
console.log(WSS_API_URL + "/chat/" + Taro.getStorageSync('UserId'), 'wsUrl')
wsRef.current = createWebSocket(WSS_API_URL + "/chat/" + Taro.getStorageSync('UserId'));
wsRef.current.onMessage((data: any) => { wsRef.current.onMessage((data: any) => {
console.log('收到WebSocket消息:', data); console.log('收到WebSocket消息:', data);
@@ -75,52 +71,84 @@ const AiChat = () => {
setIsLoading(false); setIsLoading(false);
setCurrentTaskId(''); setCurrentTaskId('');
} else { } else {
// 更新AI回复消息 // 实时更新AI回复消息
setMessages(prev => { setMessages(prev => {
const lastMessage = prev[prev.length - 1]; const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage && lastMessage.type === 'ai' && lastMessage.isTyping) { if (lastMessage && lastMessage.type === 'ai' && lastMessage.isTyping) {
// 更新最后一条AI消息 // 直接追加内容到现有AI消息
return prev.map((msg, index) => lastMessage.query = (lastMessage.query || '') + data.answer;
index === prev.length - 1
? {...msg, query: msg.query + data.answer}
: msg
);
} else { } else {
// 创建新的AI消息 // 创建新的AI消息
return [...prev, { newMessages.push({
id: Date.now().toString(), id: Date.now().toString(),
type: 'ai', type: 'ai',
query: data.answer, query: data.answer,
timestamp: Date.now(), timestamp: Date.now(),
isTyping: true isTyping: true
}]; });
} }
return newMessages;
}); });
if (data.taskId) { if (data.taskId) {
setCurrentTaskId(data.taskId); setCurrentTaskId(data.taskId);
} }
} }
scrollToBottom();
// 实时滚动到底部
setTimeout(() => {
messagesEndRef.current?.scrollIntoView({behavior: 'smooth'});
}, 50);
} }
}); });
wsRef.current.onOpen(() => { wsRef.current.onOpen(() => {
console.log('WebSocket连接成功'); console.log('WebSocket连接成功');
setWsConnected(true);
}); });
wsRef.current.onError((error: any) => { wsRef.current.onError((error: any) => {
console.error('WebSocket连接错误:', error); console.error('WebSocket连接错误:', error);
setWsConnected(false);
// Taro.showToast({
// title: 'WebSocket连接失败',
// icon: 'none',
// duration: 2000
// });
});
wsRef.current.onClose(() => {
console.log('WebSocket连接关闭');
setWsConnected(false);
// 如果正在加载中,显示连接断开提示
if (isLoading) {
Taro.showToast({
title: '连接已断开,正在重连...',
icon: 'none',
duration: 2000
});
}
}); });
wsRef.current.connect().catch((error: any) => { wsRef.current.connect().catch((error: any) => {
console.error('WebSocket连接失败:', error); console.error('WebSocket连接失败:', error);
// Taro.showToast({
// title: 'WebSocket连接失败',
// icon: 'none',
// duration: 2000
// });
}); });
}; };
useEffect(() => { useEffect(() => {
// 初始化时检查并生成AI Token
checkAiToken();
initWebSocket(); initWebSocket();
Taro.hideTabBar(); Taro.hideTabBar();
return () => { return () => {
if (wsRef.current) { if (wsRef.current) {
wsRef.current.close(); wsRef.current.close();
@@ -136,26 +164,78 @@ const AiChat = () => {
const handleSendMessage = async (content: string) => { const handleSendMessage = async (content: string) => {
if (!content.trim() || isLoading) return; if (!content.trim() || isLoading) return;
// 检查并确保AI Token存在
const aiToken = checkAiToken();
if (!aiToken) {
Taro.showToast({
title: '初始化失败,请重试',
icon: 'none',
duration: 2000
});
return;
}
// 检查WebSocket连接状态
if (!wsConnected) {
Taro.showToast({
title: '连接已断开,请稍后重试',
icon: 'none',
duration: 2000
});
return;
}
const userMessage: Message = { const userMessage: Message = {
id: Date.now().toString(), id: Date.now().toString(),
type: 'user', type: 'user',
query: content.trim(), query: content.trim(),
timestamp: Date.now(), timestamp: Date.now(),
user: `${Taro.getStorageSync('UserId')}` user: `${Taro.getStorageSync('AI_TOKEN')}`
}; };
// 立即添加用户消息
setMessages(prev => [...prev, userMessage]); setMessages(prev => [...prev, userMessage]);
setInputValue(''); setInputValue('');
setIsLoading(true); setIsLoading(true);
// 立即添加一个空的AI消息占位符准备接收流式回复
const aiPlaceholder: Message = {
id: (Date.now() + 1).toString(),
type: 'ai',
query: '',
timestamp: Date.now(),
isTyping: true
};
setMessages(prev => [...prev, aiPlaceholder]);
try { try {
await sendAiMessage({ await sendAiMessage({
query: content.trim(), query: content.trim(),
user: `${Taro.getStorageSync('UserId')}`, user: `${Taro.getStorageSync('AI_TOKEN')}`,
responseMode: 'streaming', responseMode: 'streaming',
aiToken: aiToken, // 包含AI Token
}); });
} catch (error) { } catch (error) {
console.error('发送消息失败:', error); console.error('发送消息失败:', error);
setIsLoading(false); setIsLoading(false);
// 移除AI占位符消息
setMessages(prev => prev.filter(msg => msg.id !== aiPlaceholder.id));
// 添加错误消息
const errorMessage: Message = {
id: (Date.now() + 2).toString(),
type: 'ai',
query: '抱歉,发送消息时出现错误,请检查网络连接后重试。',
timestamp: Date.now(),
isTyping: false
};
setMessages(prev => [...prev, errorMessage]);
Taro.showToast({
title: '发送失败,请重试',
icon: 'none',
duration: 2000
});
} }
}; };
@@ -180,9 +260,31 @@ const AiChat = () => {
handleSendMessage(question); handleSendMessage(question);
}; };
// 手动重连WebSocket
const handleReconnect = () => {
if (wsRef.current) {
wsRef.current.close();
}
initWebSocket();
};
return ( return (
<View className="ai-chat"> <View className="ai-chat">
<Header/> {!wsConnected && (
<View className="connection-status">
<View className="status-indicator offline">
...
<Button
size="small"
type="primary"
onClick={handleReconnect}
className="reconnect-button"
>
</Button>
</View>
</View>
)}
<View className="chat-container"> <View className="chat-container">
<View className="messages-container"> <View className="messages-container">
{messages.length === 0 ? ( {messages.length === 0 ? (
@@ -200,14 +302,11 @@ const AiChat = () => {
{message.type === 'user' ? <User size={20}/> : '🤖'} {message.type === 'user' ? <User size={20}/> : '🤖'}
</View> </View>
<View className="message-content"> <View className="message-content">
{message.isTyping ? ( <View className="message-text">
<View className="typing-indicator"> {message.query || (message.isTyping && message.type === 'ai' ? '正在思考中...' : '')}
<View className="dot"></View>
<View className="dot"></View>
<View className="dot"></View>
</View> </View>
) : ( {message.isTyping && message.type === 'ai' && message.query && (
message.query <View className="typing-cursor">|</View>
)} )}
</View> </View>
</View> </View>
@@ -240,9 +339,10 @@ const AiChat = () => {
<Textarea <Textarea
className="message-input" className="message-input"
value={inputValue} value={inputValue}
placeholder="请输入您的问题..." placeholder={isLoading ? "AI正在回复中..." : "请输入您的问题..."}
onInput={(e) => setInputValue(e.detail.value)} onInput={(e) => setInputValue(e.detail.value)}
onConfirm={() => handleSendMessage(inputValue)} onConfirm={() => handleSendMessage(inputValue)}
disabled={isLoading}
autoHeight autoHeight
maxlength={500} maxlength={500}
/> />
@@ -251,16 +351,18 @@ const AiChat = () => {
{isLoading ? ( {isLoading ? (
<Button <Button
onClick={handleStopMessage} onClick={handleStopMessage}
type="danger" type="primary"
icon={<ArrowUp/>} className="stop-button"
> >
</Button> </Button>
) : ( ) : (
<Button <Button
type="danger" type="primary"
onClick={() => handleSendMessage(inputValue)} onClick={() => handleSendMessage(inputValue)}
// disabled={!inputValue.trim()} disabled={!inputValue.trim()}
icon={<ArrowUp/>} icon={<ArrowUp/>}
className="send-button"
> >
</Button> </Button>
)} )}

View File

@@ -49,7 +49,7 @@ const UserCell = () => {
title={ title={
<div style={{display: 'inline-flex', alignItems: 'center'}}> <div style={{display: 'inline-flex', alignItems: 'center'}}>
<Headphones size={16}/> <Headphones size={16}/>
<span className={'pl-3 text-sm'}></span> <span className={'pl-2 text-xs'}></span>
</div> </div>
} }
align="center" align="center"

View File

@@ -25,7 +25,7 @@ const Index = () => {
// 二级栏目 // 二级栏目
const childCateogry = await pageCmsNavigation({parentId: categoryId}); const childCateogry = await pageCmsNavigation({parentId: categoryId});
// 终极新闻列表 // 终极新闻列表
const articles = await pageCmsArticle({categoryId}); const articles = await pageCmsArticle({categoryId,limit: 50});
// 当前栏目信息 // 当前栏目信息
if (navs) { if (navs) {

View File

@@ -97,10 +97,16 @@ export class WebSocketManager {
setTimeout(() => { setTimeout(() => {
this.connect().catch(error => { this.connect().catch(error => {
console.error('重连失败:', error); console.error('重连失败:', error);
// 继续尝试重连
this.handleReconnect();
}); });
}, this.reconnectInterval); }, this.reconnectInterval * this.reconnectAttempts); // 递增重连间隔
} else { } else {
console.error('WebSocket重连次数已达上限'); console.error('WebSocket重连次数已达上限');
// 重置重连次数,以便后续手动重连
setTimeout(() => {
this.reconnectAttempts = 0;
}, 60000); // 1分钟后重置
} }
} }