feat: 对网络请求的调整优化处理
This commit is contained in:
79
request/api/AgentChatStream.js
Normal file
79
request/api/AgentChatStream.js
Normal file
@@ -0,0 +1,79 @@
|
||||
import { BASE_URL } from "../../constant/base";
|
||||
|
||||
/// 请求流式数据的API
|
||||
const API = '/agent/assistant/chat';
|
||||
|
||||
/**
|
||||
* 获取AI聊天流式信息(仅微信小程序支持)
|
||||
* @param {Object} params 请求参数
|
||||
* @param {Function} onChunk 回调,每收到一段数据触发
|
||||
* @returns {Promise}
|
||||
*/
|
||||
function agentChatStream(params, onChunk) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = uni.getStorageSync('token');
|
||||
|
||||
console.log("发送请求内容: ", params)
|
||||
// #ifdef MP-WEIXIN
|
||||
const requestTask = uni.request({
|
||||
url: BASE_URL + API, // 替换为你的接口地址
|
||||
method: 'POST',
|
||||
data: params,
|
||||
enableChunked: true,
|
||||
header: {
|
||||
Accept: 'text/event-stream',
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`, // 如需token可加
|
||||
},
|
||||
responseType: 'arraybuffer',
|
||||
success(res) {
|
||||
resolve(res.data);
|
||||
},
|
||||
fail(err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
|
||||
requestTask.onHeadersReceived(res => {
|
||||
console.log('onHeadersReceived', res);
|
||||
});
|
||||
|
||||
requestTask.onChunkReceived(res => {
|
||||
const base64 = uni.arrayBufferToBase64(res.data);
|
||||
let data = '';
|
||||
try {
|
||||
data = decodeURIComponent(escape(atob(base64)));
|
||||
} catch (e) {
|
||||
// 某些平台可能不支持 atob,可以直接用 base64
|
||||
data = base64;
|
||||
}
|
||||
const messages = parseSSEChunk(data);
|
||||
messages.forEach(msg => {
|
||||
if (onChunk) onChunk(msg);
|
||||
});
|
||||
});
|
||||
// #endif
|
||||
});
|
||||
}
|
||||
|
||||
// 解析SSE分段数据
|
||||
function parseSSEChunk(raw) {
|
||||
// 拆分为多段
|
||||
const lines = raw.split('\n\n');
|
||||
const results = [];
|
||||
lines.forEach(line => {
|
||||
// 只处理包含 data: 的行
|
||||
const dataMatch = line.match(/data:(\{.*\})/);
|
||||
if (dataMatch && dataMatch[1]) {
|
||||
try {
|
||||
const obj = JSON.parse(dataMatch[1]);
|
||||
results.push(obj);
|
||||
} catch (e) {
|
||||
// 解析失败忽略
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
||||
export { agentChatStream }
|
||||
Reference in New Issue
Block a user