mirror of
https://github.com/labring/FastGPT.git
synced 2025-10-20 10:45:52 +00:00
perf: 流响应
This commit is contained in:
@@ -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
47
src/api/fetch.ts
Normal 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 || '请求异常');
|
||||
}
|
||||
});
|
Reference in New Issue
Block a user