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

alternative requestAnimationFrame fix #640

Merged
merged 5 commits into from
May 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 24 additions & 3 deletions src/lib/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,11 @@ ${func.name}(${JSON.stringify(data, null, 2)})\n\`\`\`\n`;
};

const buffer: string[] = [];
let functionName: string = "";
let functionArgs: string = "";
const pendingTokens: string[] = [];
let functionName = "";
let functionArgs = "";
let uiRenderPromise: Promise<void> | null = null;

const streamOpenAIResponse = async (token: string, func: string, args: string) => {
if (func || args) {
functionName += func;
Expand All @@ -203,8 +206,23 @@ ${func.name}(${JSON.stringify(data, null, 2)})\n\`\`\`\n`;
}
} else if (token) {
buffer.push(token);

if (onData && !isPaused) {
onData({ token, currentText: buffer.join("") });
pendingTokens.push(token);

// We need to render this new content, so we'll schedule a UI render
// when the main thread is ready before before proceeding so we don't
// swamp it with too many concurrent updates.
if (!uiRenderPromise) {
uiRenderPromise = new Promise((resolve) => {
requestAnimationFrame(() => {
onData({ token: pendingTokens.join(""), currentText: buffer.join("") });
pendingTokens.length = 0;
uiRenderPromise = null;
resolve();
});
});
}
}
}

Expand Down Expand Up @@ -276,6 +294,9 @@ ${func.name}(${JSON.stringify(data, null, 2)})\n\`\`\`\n`;
);
}

if (uiRenderPromise) {
await uiRenderPromise;
}
const content = buffer.join("");
return handleOpenAIResponse(content, functionName, functionArgs);
};
Expand Down