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

Throttle onUpdate to 50ms #2182

Closed
wants to merge 1 commit into from
Closed
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
11 changes: 7 additions & 4 deletions packages/react/src/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '@ai-sdk/ui-utils';
import { useCallback, useEffect, useId, useRef, useState } from 'react';
import useSWR, { KeyedMutator } from 'swr';
import { throttle } from 'lodash';

export type { CreateMessage, Message, UseChatOptions };

Expand Down Expand Up @@ -129,6 +130,11 @@ const getStreamedResponse = async (
}),
);

const onUpdate = throttle((merged, data) => {
mutate([...chatRequest.messages, ...merged], false);
mutateStreamData([...(existingData || []), ...(data || [])], false);
}, 50);

return await callChatApi({
api,
body: experimental_prepareRequestBody?.({
Expand Down Expand Up @@ -164,10 +170,7 @@ const getStreamedResponse = async (
mutate(previousMessages, false);
},
onResponse,
onUpdate(merged, data) {
mutate([...chatRequest.messages, ...merged], false);
mutateStreamData([...(existingData || []), ...(data || [])], false);
},
onUpdate,
onToolCall,
onFinish,
generateId,
Expand Down