Files
zhxg_app/utils/ai_stream.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2025-08-14 00:36:04 +08:00
// src/utils/ai_stream.js
2025-08-13 09:19:28 +08:00
import {
getToken
} from '@/utils/auth';
const BASE_URL = (() => {
// #ifdef H5
return 'http://localhost:8088';
// #endif
// #ifndef H5
// return 'http://192.168.x.x:8088'; // 换成你的电脑 IP
// #endif
})();
export function createChatStream(params) {
const requestId = `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const url = `${BASE_URL}/aitutor/aichat/stream`;
const token = getToken();
if (!token) throw new Error('请先登录');
const controller = new AbortController();
const fetchPromise = fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'X-Request-ID': requestId
},
body: JSON.stringify({
query: params.prompt,
user_id: params.userId,
user_name: params.userName,
2025-08-14 00:36:04 +08:00
user_token: params.user_token || '123',
2025-08-13 09:19:28 +08:00
user_role: 'student',
2025-08-14 00:36:04 +08:00
conversation_id: params.conversationId || null,
2025-08-13 09:19:28 +08:00
}),
signal: controller.signal
})
2025-08-14 00:36:04 +08:00
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
if (!response.body) throw new Error('Response body is null');
return {
reader: response.body.getReader(),
decoder: new TextDecoder('utf-8')
};
2025-08-13 09:19:28 +08:00
});
2025-08-14 00:36:04 +08:00
return {
stream: fetchPromise,
cancel: (reason) => {
if (!controller.signal.aborted) {
controller.abort(reason);
}
}
};
2025-08-13 09:19:28 +08:00
}