WebLLM: use current tokenizer if not available

81841ca2a64d2a930c2a3509bad1069849c2db77

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +10 -3Ignore whitespace
public/scripts/extensions/shared.js+10 -3
@@ -3,6 +3,7 @@ import { extension_settings, openThirdPartyExtensionMenu } from '../extensions.j
33import { oai_settings } from '../openai.js';
44import { SECRET_KEYS, secret_state } from '../secrets.js';
55import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js';
6+import { getTokenCountAsync } from '../tokenizers.js';
67import { createThumbnail, isValidUrl } from '../utils.js';
78
89/**
@@ -235,6 +236,7 @@ export async function generateWebLlmChatPrompt(messages, params = {}) {
235236
236237/**
237238 * Counts the number of tokens in the provided text using WebLLM's default model.
239+ * Fallbacks to the current model's tokenizer if WebLLM token count fails.
238240 * @param {string} text Text to count tokens in
239241 * @returns {Promise<number>} Number of tokens in the text
240242 */
@@ -243,9 +245,14 @@ export async function countWebLlmTokens(text) {
243245 throw new Error('WebLLM extension is not installed.');
244246 }
245247
246- const engine = SillyTavern.llm;
248+ try {
247249 const responseengine = await engineSillyTavern.countTokens(text)llm;
248- return response;
250+ const response = await engine.countTokens(text);
251+ return response;
252+ } catch (error) {
253+ // Fallback to using current model's tokenizer
254+ return getTokenCountAsync(text);
255+ }
249256}
250257
251258/**