mirror of
https://github.com/StanGirard/quivr.git
synced 2024-12-22 19:01:49 +03:00
13b174b202
Demo: https://github.com/StanGirard/quivr/assets/63923024/3aecb83f-3acd-46d4-900d-a042814c6638 Issue: https://github.com/StanGirard/quivr/issues/1753
49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
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 (
|
|
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
onFirstChunk: () => void
|
|
): Promise<void> => {
|
|
const decoder = new TextDecoder("utf-8");
|
|
let isFirstChunk = true;
|
|
|
|
const handleStreamRecursively = async () => {
|
|
const { done, value } = await reader.read();
|
|
|
|
if (done) {
|
|
return;
|
|
}
|
|
|
|
if (isFirstChunk) {
|
|
isFirstChunk = false;
|
|
onFirstChunk();
|
|
}
|
|
|
|
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,
|
|
};
|
|
};
|