57 lines
1.4 KiB
JavaScript
57 lines
1.4 KiB
JavaScript
// src/utils/ai_stream.js
|
|
import {
|
|
getToken
|
|
} from '@/utils/auth';
|
|
import config from '@/config'
|
|
const BASE_URL = (() => {
|
|
// #ifdef H5
|
|
return config.baseUrl;
|
|
// #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,
|
|
user_token: params.user_token || '123',
|
|
user_role: 'student',
|
|
conversation_id: params.conversationId || null,
|
|
}),
|
|
signal: controller.signal
|
|
})
|
|
.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')
|
|
};
|
|
});
|
|
|
|
return {
|
|
stream: fetchPromise,
|
|
cancel: (reason) => {
|
|
if (!controller.signal.aborted) {
|
|
controller.abort(reason);
|
|
}
|
|
}
|
|
};
|
|
} |