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;
|
2024-01-26 05:03:08 +03:00
|
|
|
let incompleteData = "";
|
2023-09-26 11:35:52 +03:00
|
|
|
|
|
|
|
const handleStreamRecursively = async () => {
|
|
|
|
const { done, value } = await reader.read();
|
|
|
|
|
|
|
|
if (done) {
|
2024-01-27 03:06:01 +03:00
|
|
|
if (incompleteData !== "") {
|
2024-01-26 05:03:08 +03:00
|
|
|
// Try to parse any remaining incomplete data
|
|
|
|
|
|
|
|
try {
|
|
|
|
const parsedData = JSON.parse(incompleteData) as ChatMessage;
|
|
|
|
updateStreamingHistory(parsedData);
|
|
|
|
} catch (e) {
|
|
|
|
console.error("Error parsing incomplete data", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-26 11:35:52 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-11-30 14:49:04 +03:00
|
|
|
if (isFirstChunk) {
|
|
|
|
isFirstChunk = false;
|
|
|
|
onFirstChunk();
|
|
|
|
}
|
|
|
|
|
2024-01-26 05:03:08 +03:00
|
|
|
// Concatenate incomplete data with new chunk
|
|
|
|
const rawData = incompleteData + decoder.decode(value, { stream: true });
|
|
|
|
|
2024-01-27 03:06:01 +03:00
|
|
|
const dataStrings = rawData.trim().split("data: ").filter(Boolean);
|
2023-09-26 11:35:52 +03:00
|
|
|
|
2024-01-26 05:03:08 +03:00
|
|
|
dataStrings.forEach((data, index, array) => {
|
|
|
|
if (index === array.length - 1 && !data.endsWith("\n")) {
|
|
|
|
// Last item and does not end with a newline, save as incomplete
|
|
|
|
incompleteData = data;
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const parsedData = JSON.parse(data) as ChatMessage;
|
|
|
|
updateStreamingHistory(parsedData);
|
|
|
|
} catch (e) {
|
|
|
|
console.error("Error parsing data string", e);
|
|
|
|
}
|
2023-09-26 11:35:52 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
await handleStreamRecursively();
|
|
|
|
};
|
|
|
|
|
|
|
|
await handleStreamRecursively();
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
handleStream,
|
|
|
|
};
|
|
|
|
};
|