Skip to content

Commit

Permalink
feat: animate streaming response to make more smooth
Browse files Browse the repository at this point in the history
  • Loading branch information
Yidadaa committed Nov 19, 2023
1 parent 9876a1a commit 536ace8
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions app/client/platforms/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,33 @@ export class ChatGPTApi implements LLMApi {

if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;

// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
return;
}

if (remainText.length > 0) {
responseText += remainText[0];
remainText = remainText.slice(1);
options.onUpdate?.(responseText, remainText[0]);
}

requestAnimationFrame(animateResponseText);
}

// start animaion
animateResponseText();

const finish = () => {
if (!finished) {
options.onFinish(responseText);
finished = true;
options.onFinish(responseText + remainText);
}
};

Expand Down Expand Up @@ -183,8 +204,7 @@ export class ChatGPTApi implements LLMApi {
};
const delta = json.choices[0]?.delta?.content;
if (delta) {
responseText += delta;
options.onUpdate?.(responseText, delta);
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text);
Expand Down

0 comments on commit 536ace8

Please sign in to comment.