Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smooth chat streaming output #510

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions src/hooks/useSubmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,34 @@ const useSubmit = () => {
);
}

if (stream) {
let messageQueue = [];
let streamProcessingCompleted = false;
async function processMessageQueue() {
while (!streamProcessingCompleted || messageQueue.length > 0) {
if (messageQueue.length > 0) {
let messageContent = messageQueue.shift();
const messageLen = messageContent.length;
let curChars = '';
let speed = streamProcessingCompleted
? messageLen
: Math.max(3, Math.round(messageLen / 30));
while (messageContent) {
curChars = messageContent.slice(0, speed);
const updatedChats = JSON.parse(
JSON.stringify(useStore.getState().chats)
);
const updatedMessages = updatedChats[currentChatIndex].messages;
updatedMessages[updatedMessages.length - 1].content += curChars;
setChats(updatedChats);
messageContent = messageContent.slice(speed);
await new Promise((resolve) => setTimeout(resolve, 50));
}
} else {
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
}
async function readStream(stream) {
if (stream.locked)
throw new Error(
'Oops, the stream is locked right now. Please try again'
Expand All @@ -127,13 +154,7 @@ const useSubmit = () => {
}
return output;
}, '');

const updatedChats: ChatInterface[] = JSON.parse(
JSON.stringify(useStore.getState().chats)
);
const updatedMessages = updatedChats[currentChatIndex].messages;
updatedMessages[updatedMessages.length - 1].content += resultString;
setChats(updatedChats);
messageQueue.push(resultString);
}
}
if (useStore.getState().generating) {
Expand All @@ -143,6 +164,11 @@ const useSubmit = () => {
}
reader.releaseLock();
stream.cancel();
streamProcessingCompleted = true;
}

if (stream) {
await Promise.all([readStream(stream), processMessageQueue()]);
}

// update tokens used in chatting
Expand Down