Skip to content

Commit

Permalink
fix(chat): fix settings modal opening delay (Issue #2863) (#2864)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander-Kezik authored Dec 23, 2024
1 parent d941e1c commit d98273c
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions apps/chat/src/hooks/useTokenizer.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef } from 'react';

import { DialAIEntityModel } from '../types/models';

import { Tiktoken, get_encoding } from 'tiktoken';

export const useTokenizer = (tokenizer: DialAIEntityModel['tokenizer']) => {
const [encoding, setEncoding] = useState<Tiktoken | undefined>(undefined);
const encodingRef = useRef<Tiktoken | null>(null);

useEffect(() => {
if (tokenizer?.encoding) {
setEncoding(get_encoding(tokenizer.encoding));
// clean up if tokenizer changed
if (encodingRef.current) {
encodingRef.current.free();
encodingRef.current = null;
}

// use microtask to not block the thread and isMounted variable to prevent task execution if component unmounted
let isMounted = true;
Promise.resolve().then(() => {
if (isMounted && tokenizer?.encoding) {
encodingRef.current = get_encoding(tokenizer.encoding);
}
});

return () => {
isMounted = false;
if (encodingRef.current) {
encodingRef.current.free();
encodingRef.current = null;
}
};
}, [tokenizer]);

useEffect(() => {
return () => encoding?.free();
const getTokensLength = useCallback((str: string) => {
return encodingRef.current?.encode(str).length ?? new Blob([str]).size;
}, []);

const getTokensLength = useCallback(
(str: string) => {
return encoding?.encode(str).length ?? new Blob([str]).size;
},
[encoding],
);

return {
getTokensLength,
};
Expand Down

0 comments on commit d98273c

Please sign in to comment.