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
3import { oai_settings } from '../openai.js';3import { oai_settings } from '../openai.js';
4import { SECRET_KEYS, secret_state } from '../secrets.js';4import { SECRET_KEYS, secret_state } from '../secrets.js';
5import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js';5import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js';
6import { getTokenCountAsync } from '../tokenizers.js';
6import { createThumbnail, isValidUrl } from '../utils.js';7import { createThumbnail, isValidUrl } from '../utils.js';
78
8/**9/**
@@ -235,6 +236,7 @@ export async function generateWebLlmChatPrompt(messages, params = {}) {
235236
236/**237/**
237 * Counts the number of tokens in the provided text using WebLLM's default model.238 * 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.
238 * @param {string} text Text to count tokens in240 * @param {string} text Text to count tokens in
239 * @returns {Promise<number>} Number of tokens in the text241 * @returns {Promise<number>} Number of tokens in the text
240 */242 */
@@ -243,9 +245,14 @@ export async function countWebLlmTokens(text) {
243 throw new Error('WebLLM extension is not installed.');245 throw new Error('WebLLM extension is not installed.');
244 }246 }
245247
246 const engine = SillyTavern.llm;248 try {
247 const response = await engine.countTokens(text);249 const engine = SillyTavern.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 }
249}256}
250257
251/**258/**