2023-09-26 11:35:52 +03:00
|
|
|
import { useChatContext } from "@/lib/context";
|
|
|
|
|
|
|
|
import { ChatMessage } from "../types";
|
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
|
|
export const useHandleStream = () => {
|
|
|
|
const { updateStreamingHistory } = useChatContext();
|
|
|
|
|
|
|
|
const handleStream = async (
|
2023-11-30 14:49:04 +03:00
|
|
|
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
|
|
onFirstChunk: () => void
|
2023-09-26 11:35:52 +03:00
|
|
|
): Promise<void> => {
|
|
|
|
const decoder = new TextDecoder("utf-8");
|
2023-11-30 14:49:04 +03:00
|
|
|
let isFirstChunk = true;
|
2023-09-26 11:35:52 +03:00
|
|
|
|
|
|
|
const handleStreamRecursively = async () => {
|
|
|
|
const { done, value } = await reader.read();
|
|
|
|
|
|
|
|
if (done) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-11-30 14:49:04 +03:00
|
|
|
if (isFirstChunk) {
|
|
|
|
isFirstChunk = false;
|
|
|
|
onFirstChunk();
|
|
|
|
}
|
|
|
|
|
2023-09-26 11:35:52 +03:00
|
|
|
const dataStrings = decoder
|
|
|
|
.decode(value)
|
|
|
|
.trim()
|
|
|
|
.split("data: ")
|
|
|
|
.filter(Boolean);
|
|
|
|
|
|
|
|
dataStrings.forEach((data) => {
|
|
|
|
const parsedData = JSON.parse(data) as ChatMessage;
|
|
|
|
updateStreamingHistory(parsedData);
|
|
|
|
});
|
|
|
|
|
|
|
|
await handleStreamRecursively();
|
|
|
|
};
|
|
|
|
|
|
|
|
await handleStreamRecursively();
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
handleStream,
|
|
|
|
};
|
|
|
|
};
|