57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
// src/utils/ai_stream.js (H5 优化版)
|
|
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: {
|
|
'Accept': 'text/event-stream',
|
|
'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,
|
|
user_token: params.user_token || '123',
|
|
user_role: 'student',
|
|
conversation_id: params.conversationId || null,
|
|
}),
|
|
signal: controller.signal
|
|
})
|
|
.then(resp => {
|
|
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
|
if (!resp.body) throw new Error('Response body is null');
|
|
return resp.body;
|
|
});
|
|
|
|
return fetchPromise.then(body => ({
|
|
stream: Promise.resolve({
|
|
reader: body.getReader(),
|
|
decoder: new TextDecoder('utf-8')
|
|
}),
|
|
cancel: reason => !controller.signal.aborted && controller.abort(reason)
|
|
})).catch(err => ({
|
|
stream: Promise.reject(err),
|
|
cancel: () => {}
|
|
}));
|
|
} |