WebLLM: use current tokenizer if not available
| @@ -3,6 +3,7 @@ import { extension_settings, openThirdPartyExtensionMenu } from '../extensions.j | |||
| 3 | import { oai_settings } from '../openai.js'; | 3 | import { oai_settings } from '../openai.js'; |
| 4 | import { SECRET_KEYS, secret_state } from '../secrets.js'; | 4 | import { SECRET_KEYS, secret_state } from '../secrets.js'; |
| 5 | import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js'; | 5 | import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js'; |
| 6 | import { getTokenCountAsync } from '../tokenizers.js'; | ||
| 6 | import { createThumbnail, isValidUrl } from '../utils.js'; | 7 | import { createThumbnail, isValidUrl } from '../utils.js'; |
| 7 | 8 | ||
| 8 | /** | 9 | /** |
| @@ -235,6 +236,7 @@ export async function generateWebLlmChatPrompt(messages, params = {}) { | |||
| 235 | 236 | ||
| 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 in | 240 | * @param {string} text Text to count tokens in |
| 239 | * @returns {Promise<number>} Number of tokens in the text | 241 | * @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 | } |
| 245 | 247 | ||
| 248 | try { | ||
| 246 | const engine = SillyTavern.llm; | 249 | const engine = SillyTavern.llm; |
| 247 | const response = await engine.countTokens(text); | 250 | const response = await engine.countTokens(text); |
| 248 | return response; | 251 | return response; |
| 252 | } catch (error) { | ||
| 253 | // Fallback to using current model's tokenizer | ||
| 254 | return getTokenCountAsync(text); | ||
| 255 | } | ||
| 249 | } | 256 | } |
| 250 | 257 | ||
| 251 | /** | 258 | /** |