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