perf: 流响应

This commit is contained in:
Archer
2023-03-14 14:58:35 +08:00
parent e12f97a73b
commit 6244f6c1fb
7 changed files with 160 additions and 167 deletions

View File

@@ -36,28 +36,10 @@ export const postGPT3SendPrompt = ({
});
/**
* 预发 prompt 进行存储
* 存储一轮对话
*/
export const postChatGptPrompt = ({
prompt,
windowId,
chatId
}: {
prompt: ChatSiteItemType;
windowId: string;
chatId: string;
}) =>
POST<string>(`/chat/preChat`, {
windowId,
prompt: {
obj: prompt.obj,
value: prompt.value
},
chatId
});
/* 获取 Chat 的 Event 对象,进行持续通信 */
export const getChatGPTSendEvent = (chatId: string, windowId: string) =>
new EventSource(`/api/chat/chatGpt?chatId=${chatId}&windowId=${windowId}&date=${Date.now()}`);
export const postSaveChat = (data: { windowId: string; prompts: ChatItemType[] }) =>
POST('/chat/saveChat', data);
/**
* 删除最后一句

47
src/api/fetch.ts Normal file
View File

@@ -0,0 +1,47 @@
interface StreamFetchProps {
url: string;
data: any;
onMessage: (text: string) => void;
}
export const streamFetch = ({ url, data, onMessage }: StreamFetchProps) =>
new Promise(async (resolve, reject) => {
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const reader = res.body?.getReader();
if (!reader) return;
const decoder = new TextDecoder();
let responseText = '';
const read = async () => {
const { done, value } = await reader?.read();
if (done) {
if (res.status === 200) {
resolve(responseText);
} else {
try {
const parseError = JSON.parse(responseText);
reject(parseError?.message || '请求异常');
} catch (err) {
reject('请求异常');
}
}
return;
}
const text = decoder.decode(value).replace(/<br\/>/g, '\n');
res.status === 200 && onMessage(text);
responseText += text;
read();
};
read();
} catch (err: any) {
console.log(err, '====');
reject(typeof err === 'string' ? err : err?.message || '请求异常');
}
});