import { GGUF_SPLIT_CONFIG } from './gguf-split'; import { ProxyToWorker, type RpcInitOptions, type WllamaWorkerResources, } from './worker'; import { absoluteUrl, canUseAsyncFileRead, cbToAsyncIter, checkEnvironmentCompatible, isFirefox, isString, isSupportJSPI, isSupportRelaxedSIMD, isSupportMultiThread, isSupportWebGPU, MAX_RPC_WORKERS, DRAFT_FILE_NAME, MMPROJ_FILE_NAME, needCompat, prepareBlobs, RPC_CONFIG, } from './utils'; import CacheManager, { type DownloadOptions } from './cache-manager'; import { ModelManager, Model, type ModelSource } from './model-manager'; import type { GlueMsgCancelRes, GlueMsgCompletionRes, GlueMsgDetokenizeRes, GlueMsgEmbeddingRes, GlueMsgRealtimeSendRes, GlueMsgRealtimeStartRes, GlueMsgRerankRes, GlueMsgSlotRestoreRes, GlueMsgSlotSaveRes, GlueMsgSystemoneRes, GlueMsgGetResultRes, GlueMsgLoadRes, GlueMsgTestBackendOpsRes, GlueMsgTokenizeRes, GlueMsgTtsRes, } from './glue/messages'; import { LIBLLAMA_VERSION } from './workers-code/generated'; import type { LoadedContextInfo, LoadModelParams, StreamParams, } from './types/types'; import type { ChatCompletionChunk, ChatCompletionParams, ChatCompletionResponse, ChatCompletionUserMessage, CreateEmbeddingResponse, EmbeddingContent, EmbeddingCreateParams, RealtimeEvent, RealtimeSessionParams, RawCompletionChunk, RawCompletionParams, RawCompletionResponse, RerankParams, RerankResponse, SpeechChunk, SpeechParams, SpeechResponse, SystemOneParams, SystemOneResponse, TranscriptionChunk, TranscriptionParams, TranscriptionResponse, ChatCompletionMessageContent, ChatCompletionMessageText, EmbeddingInput, } from './types/oai-compat'; import { LogLevel } from './types/types'; import { getHFModelSource, type HuggingFaceParams } from './huggingface'; import { WasmCompatFromCDN } from './wasm-from-cdn'; export interface WllamaLogger { debug: typeof console.debug; log: typeof console.log; warn: typeof console.warn; error: typeof console.error; } // TODO: bring back useCache export interface WllamaConfig { /** * If true, suppress all log messages from native CPP code */ suppressNativeLog?: boolean; /** * Custom logger functions */ logger?: WllamaLogger; /** * Maximum number of parallel files to be downloaded * * Default: parallelDownloads = 3 */ parallelDownloads?: number; /** * Allow offline mode. If true, the model will be loaded from cache if it's available. * * Default: allowOffline = false */ allowOffline?: boolean; /** * Custom cache manager (only for advanced usage) */ cacheManager?: CacheManager; /** * Custom model manager (only for advanced usage) */ modelManager?: ModelManager; /** * If true, allow a wasm file built from a different llama.cpp version * * Default: skipVersionCheck = false */ skipVersionCheck?: boolean; } export interface WllamaChatMessage { role: 'system' | 'user' | 'assistant'; content: string; } export interface AssetsPathConfig { default: string; 'single-thread/wllama.wasm'?: string; // deprecated, use "default" instead 'multi-thread/wllama.wasm'?: string; // deprecated, use "default" instead } export interface ModelMetadata { hparams: { nVocab: number; nCtxTrain: number; nEmbd: number; nLayer: number; }; meta: Record; } /** * Logger preset with debug messages suppressed */ export const LoggerWithoutDebug = { ...console, debug: () => {}, }; export type WllamaErrorType = | 'model_not_loaded' | 'download_error' | 'load_error' | 'version_mismatch' | 'kv_cache_full' | 'unknown_error' | 'inference_error'; export class WllamaError extends Error { type: WllamaErrorType; constructor(message: string, type: WllamaErrorType = 'unknown_error') { super(message); this.type = type; } } /** * AbortError is thrown when the user wants to abort the current operation. * This is equivalent to AbortError in Fetch API. */ export class WllamaAbortError extends Error { override name: string = 'AbortError'; constructor() { super('Operation aborted'); } } /** * RuntimeError is thrown when there is an error in the WASM runtime, such as stack overflow, OOM, etc. * Stack trace of the error in the WASM runtime can be included in the error object for debugging purpose. */ export class WllamaRuntimeError extends Error { override name: string = 'RuntimeError'; override stack: string; constructor(message: string, stack: string) { super(message); this.stack = stack; } } /** * Set compatibility options for Wllama. * By default, these are set to URL of the latest builds on CDN, which requires internet to download. If you want to use local assets or have your own CDN, follow the instruction from @wllama/wllama-compat package. */ export interface TokenizeOptions { /** Add the special tokens of the model, like BOS (default: false) */ addSpecial?: boolean; /** Parse special tokens written in the text, like `<|im_start|>` (default: true) */ parseSpecial?: boolean; } export interface TokenPiece { id: number; /** The text of the token, or its bytes when it is not valid UTF-8 on its own */ piece: string | number[]; } export interface WllamaCompat { wasm: string; /** Optional, override the JS code embedded inside the wasm file */ worker?: string | { code: string } | undefined; } /** * Encode PCM samples to the base64 PCM16 format of `input_audio_buffer.append`. */ export const encodeRealtimeAudio = (samples: Float32Array): string => { const pcm = new Int16Array(samples.length); for (let i = 0; i < samples.length; i++) { pcm[i] = Math.max(-1, Math.min(1, samples[i])) * 32767; } const bytes = new Uint8Array(pcm.buffer); let binary = ''; for (let i = 0; i < bytes.length; i += 0x8000) { binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); } return btoa(binary); }; /** * Decode the base64 PCM16 audio of a `response.output_audio.delta` event. */ export const decodeRealtimeAudio = (delta: string): Float32Array => { const binary = atob(delta); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } const pcm = new Int16Array(bytes.buffer, 0, bytes.length >> 1); return Float32Array.from(pcm, (v) => v / 32768); }; // polls with no event before the poll loop starts to wait const REALTIME_BUSY_POLLS = 8; const REALTIME_IDLE_MS = 20; /** * A realtime audio session. Events follow the OAI realtime schema, same as the `/v1/realtime` route of llama-server. * Inference runs while `events()` is being read, so keep reading it to get a response. */ export class WllamaRealtimeSession { private closed = false; private pending: RealtimeEvent[] = []; // read from the worker, not yet given to a reader private wakeUp: () => void = () => {}; private sent = false; // a client event was sent since the last poll constructor( private proxy: ProxyToWorker, private reqId: number ) {} /** * Send a client event, for example `session.update` or `response.create`. */ async send(event: RealtimeEvent): Promise { const result = await this.proxy.wllamaAction( 'realtime_send', { _name: 'rtsd_req', req_id: this.reqId, data_json: JSON.stringify(event), } ); if (!result.success) { throw new WllamaError('Realtime session is closed', 'inference_error'); } this.sent = true; this.wakeUp(); } /** * Same as sending `input_audio_buffer.append`. * @param samples mono PCM at `LoadedContextInfo.audio_input_rate` */ async appendAudio(samples: Float32Array): Promise { await this.send({ type: 'input_audio_buffer.append', audio: encodeRealtimeAudio(samples), }); } /** * Read the server events. It ends when the session ends. Only one reader at a time. */ async *events(): AsyncGenerator { let nEmpty = 0; while (this.pending.length > 0 || !this.closed) { // a reader that stops early leaves the rest for the next one if (this.pending.length > 0) { yield this.pending.shift()!; continue; } const chunk = await this.proxy.wllamaAction( 'get_result', { _name: 'gres_req', req_id: this.reqId } ); if (!chunk.has_more) { this.closed = true; } // the event may need a few polls of work, poll without waiting again if (this.sent) { this.sent = false; nEmpty = 0; } if (chunk.data_json) { nEmpty = 0; this.pending.push(...(JSON.parse(chunk.data_json) as RealtimeEvent[])); } else if (++nEmpty > REALTIME_BUSY_POLLS) { // nothing to do until the next client event await new Promise((resolve) => { const timer = setTimeout(resolve, REALTIME_IDLE_MS); this.wakeUp = () => { clearTimeout(timer); resolve(); }; }); } } } /** * End the session and free its slot. */ async close(): Promise { if (this.closed) { return; } this.closed = true; this.pending = []; this.wakeUp(); await this.proxy.wllamaAction('cancel', { _name: 'cncl_req', req_id: this.reqId, }); } } export class Wllama { // The CacheManager and ModelManager are singleton, can be accessed by user public cacheManager: CacheManager; public modelManager: ModelManager; private compat: WllamaCompat | null = null; private proxy: ProxyToWorker = null as any; private rpcWorkers: ProxyToWorker[] = []; private exitCount = 0; // number of exit() calls private config: WllamaConfig; private pathConfig: AssetsPathConfig; private useMultiThread: boolean = false; private nbThreads: number = 1; private useEmbeddings: boolean = false; private useRerank: boolean = false; // available when loaded private loadedContextInfo: LoadedContextInfo = null as any; private seed: number | undefined = undefined; private bosToken: number = -1; private eosToken: number = -1; private eotToken: number = -1; private eogTokens: Set = new Set(); private addBosToken: boolean = false; private addEosToken: boolean = false; private mediaMarker?: string; private chatTemplate?: string; private metadata?: ModelMetadata; private hasEncoder: boolean = false; private decoderStartToken: number = -1; // note: we overlay instead of using llama-server default_template_kwargs, because we cannot transfer complex data structure via GLUE // overlay allow mixed data type or nested structure for kwargs private chatTemplateKwargs: Record = {}; constructor(pathConfig: AssetsPathConfig, wllamaConfig: WllamaConfig = {}) { checkEnvironmentCompatible(); if (!pathConfig) throw new WllamaError('AssetsPathConfig is required'); this.pathConfig = pathConfig; this.config = wllamaConfig; this.cacheManager = wllamaConfig.cacheManager ?? new CacheManager(); this.modelManager = wllamaConfig.modelManager ?? new ModelManager({ cacheManager: this.cacheManager, logger: wllamaConfig.logger ?? console, parallelDownloads: wllamaConfig.parallelDownloads, allowOffline: wllamaConfig.allowOffline, }); this.setCompat('default'); } private logger() { return this.config.logger ?? console; } private checkModelLoaded() { if (!this.isModelLoaded()) { throw new WllamaError( 'loadModel() is not yet called', 'model_not_loaded' ); } } /** * Get the libllama version string, e.g. "b6327-4d74393". * * @returns version string embedded at build time. */ static getLibllamaVersion(): string { return LIBLLAMA_VERSION; } /** * Set compatibility options for Wllama. * The compat build is used on browsers without JSPI or wasm relaxed SIMD (e.g. Safari). Firefox only uses it without relaxed SIMD: without JSPI, the main build is faster there. * @param compat Set to null to disable compatibility, or 'default' to use the default compat resources from CDN. * @param _mode @deprecated not used anymore */ setCompat( compat: WllamaCompat | null | 'default', _mode?: 'safari' | 'firefox_safari' ) { this.compat = compat === 'default' ? WasmCompatFromCDN : compat; } /** * Check if the model is loaded via `loadModel()` */ isModelLoaded(): boolean { return !!this.proxy && !!this.metadata; } /** * Get token ID associated to BOS (begin of sentence) token. * * NOTE: This can only being used after `loadModel` is called. * * @returns -1 if the model is not loaded. */ getBOS(): number { return this.bosToken; } /** * Get token ID associated to EOS (end of sentence) token. * * NOTE: This can only being used after `loadModel` is called. * * @returns -1 if the model is not loaded. */ getEOS(): number { return this.eosToken; } /** * Get token ID associated to EOT (end of turn) token. * * NOTE: This can only being used after `loadModel` is called. * * @returns -1 if the model is not loaded. */ getEOT(): number { return this.eotToken; } /** * Check if a given token is end-of-generation token (e.g. EOS, EOT, etc.) * * @param token the token ID to be checked * @returns true if the token is EOS, EOT, or any other end-of-generation tokens */ isTokenEOG(token: number): boolean { return ( token === this.eosToken || token === this.eotToken || this.eogTokens.has(token) ); } /** * Get token ID associated to token used by decoder, to start generating output sequence(only usable for encoder-decoder architecture). In other words, encoder uses normal BOS and decoder uses this token. * * NOTE: This can only being used after `loadModel` is called. * * @returns -1 if the model is not loaded. */ getDecoderStartToken(): number { return this.decoderStartToken; } /** * Get model hyper-parameters and metadata * * NOTE: This can only being used after `loadModel` is called. * * @returns ModelMetadata */ getModelMetadata(): ModelMetadata { this.checkModelLoaded(); return this.metadata!; } /** * Check if we're currently using multi-thread build. * * NOTE: This can only being used after `loadModel` is called. * * @returns true if multi-thread is used. */ isMultithread(): boolean { this.checkModelLoaded(); return this.useMultiThread; } /** * Get number of threads used in the current context. * * NOTE: This can only being used after `loadModel` is called. * * @returns number of threads */ getNumThreads(): number { this.checkModelLoaded(); return this.useMultiThread ? this.nbThreads : 1; } /** * Check if the current model uses encoder-decoder architecture * * NOTE: This can only being used after `loadModel` is called. * * @returns true if multi-thread is used. */ isEncoderDecoderArchitecture(): boolean { this.checkModelLoaded(); return this.hasEncoder; } /** * Must we add BOS token to the tokenized sequence? * * NOTE: This can only being used after `loadModel` is called. * * @returns true if BOS token must be added to the sequence */ mustAddBosToken(): boolean { this.checkModelLoaded(); return this.addBosToken; } /** * Must we add EOS token to the tokenized sequence? * * NOTE: This can only being used after `loadModel` is called. * * @returns true if EOS token must be added to the sequence */ mustAddEosToken(): boolean { this.checkModelLoaded(); return this.addEosToken; } /** * Get the jinja chat template comes with the model. It only available if the original model (before converting to gguf) has the template in `tokenizer_config.json` * * NOTE: This can only being used after `loadModel` is called. * * @returns the jinja template. null if there is no template in gguf */ getChatTemplate(): string | null { this.checkModelLoaded(); return this.chatTemplate ?? null; } /** * Check if WebGPU is supported by the current environment. * @returns true if WebGPU is supported */ isSupportWebGPU(): boolean { return isSupportWebGPU(); } /** * Load model from a given URL (or a list of URLs, in case the model is splitted into smaller files) * - If the model already been downloaded (via `downloadModel()`), then we will use the cached model * - Else, we download the model from internet * @param modelSourceOrURL * @param params */ async loadModelFromUrl( modelSourceOrURL: ModelSource | string, params: LoadModelParams & DownloadOptions & { useCache?: boolean } = {} ): Promise { const source: ModelSource = isString(modelSourceOrURL) ? ({ url: modelSourceOrURL } as ModelSource) : (modelSourceOrURL as ModelSource); const useCache = params.useCache ?? true; const model = useCache ? await this.modelManager.getModelOrDownload(source, params) : await this.modelManager.downloadModel(source, params); return await this.loadModel(model, params); } /** * Load model from a given Hugging Face model ID and file path. * * @param hfOptions * @param params */ async loadModelFromHF( hfOptions: HuggingFaceParams, params: LoadModelParams & DownloadOptions & { useCache?: boolean } = {} ) { const source = await getHFModelSource(hfOptions); return await this.loadModelFromUrl(source, params); } /** * Load model from a given list of Blob. * * You can pass multiple buffers into the function (in case the model contains multiple shards). * * @param ggufBlobsOrModel Can be either list of Blobs (in case you use local file), or a Model object (in case you use ModelManager) * @param params LoadModelParams */ async loadModel( ggufBlobsOrModel: Blob[] | Model, params: LoadModelParams = {} ): Promise { let blobs: Blob[]; if (ggufBlobsOrModel instanceof Model) { const model = ggufBlobsOrModel; blobs = await model.open(); // a draft-simple model looks like any model, so it is passed explicitly const iDraft = model.draftUrl ? model.files.findIndex( (f) => f.metadata.originalURL === model.draftUrl ) : -1; if (iDraft >= 0) { const [draft] = blobs.splice(iDraft, 1); params = { ...params, spec_draft_model: params.spec_draft_model ?? draft, }; } } else { blobs = [...ggufBlobsOrModel]; // copy array } if (blobs.some((b) => b.size === 0)) { throw new WllamaError( 'Input model (or splits) must be non-empty Blob or File', 'load_error' ); } if (!this.pathConfig['default']) { throw new WllamaError( '"default" is missing from pathConfig', 'load_error' ); } if (this.proxy) { throw new WllamaError('Module is already initialized', 'load_error'); } // detect if we can use multi-thread and webgpu const supportMultiThread = await isSupportMultiThread(); const hwConccurency = Math.floor((navigator.hardwareConcurrency || 1) / 2); const nbThreads = params.n_threads ?? hwConccurency; this.nbThreads = nbThreads; this.useMultiThread = supportMultiThread && nbThreads > 1; // before creating the worker, so a bad file does not leave this instance half initialized // a copy: the caller can change it while the files are prepared const loraEntries = (params.lora_adapters ?? []).map((a) => ({ ...a })); const loraBlobs = loraEntries.flatMap((a) => (a.blob ? [a.blob] : [])); let modelFiles: Awaited>; try { modelFiles = await prepareBlobs( blobs, params.spec_draft_model instanceof Blob ? params.spec_draft_model : undefined, loraBlobs ); } catch (e) { throw new WllamaError((e as Error).message, 'load_error'); } // ids follow this order; adapters given with the model files get scale 1, like --lora of llama-server let iLoraBlob = 0; const loraAdapters = [ ...loraEntries.map((a) => { const path = a.blob ? `/models/${modelFiles.loras[iLoraBlob++]!.name}` : a.path; if (!path) { throw new WllamaError( 'A LoRA adapter needs a path or a blob', 'load_error' ); } return { path, scale: a.scale ?? 1 }; }), ...modelFiles.loras .slice(loraBlobs.length) .map((f) => ({ path: `/models/${f.name}`, scale: 1 })), ]; // initialize the worker const workerResources = this.getWorkerResources(); if (params.n_gpu_layers === 0) { // skip WebGPU device initialization when the user asks for CPU-only workerResources.noWebGPU = true; } else if ( isFirefox() && isSupportWebGPU() && (workerResources.compat || isSupportJSPI()) ) { this.logger().warn( 'WebGPU on Firefox is slower than on other browsers, due to a Firefox bug (https://bugzilla.mozilla.org/show_bug.cgi?id=1870699). wllama works around most of it, see https://github.com/ngxson/wllama/issues/296' ); } const nRpcWorkers = this.pickRpcWorkers(params, workerResources); const rpcMemMax = params.rpc_workers === undefined ? this.autoRpcMemMax(modelFiles.llm, workerResources) : undefined; this.proxy = new ProxyToWorker( workerResources, this.useMultiThread ? nbThreads : 0, // 0 means disable pthread this.config.suppressNativeLog ?? false, this.logger() ); let logLevel = params.log_level ?? LogLevel.INFO; if (this.config.suppressNativeLog) { logLevel = 9999 as any; } // this attempt's proxy and rpc workers: exit() can be called meanwhile, and a new load can then own this.proxy const proxy = this.proxy; const ownRpcWorkers: ProxyToWorker[] = []; // terminate the workers of this attempt, so this instance can load again const exitWorkers = async () => { if (this.proxy === proxy) { await this.exit(); } else { await proxy.wllamaExit(); for (const w of ownRpcWorkers) await w.wllamaExit(); } }; let loadResult: GlueMsgLoadRes; try { const rpc = await this.startRpcWorkers( nRpcWorkers, workerResources, ownRpcWorkers ); await proxy.moduleInit(modelFiles.all, rpc); // run it this.logger().debug('Calling wllamaStart...'); const startResult: any = await proxy.wllamaStart(); if (!startResult.success) { throw new WllamaError( `Error while calling start function, result = ${startResult}` ); } await this.checkWasmVersion(startResult.version); // load the model this.logger().debug('Loading model...'); loadResult = await proxy.wllamaAction('load', { _name: 'load_req', log_level: logLevel, // if async read is not supported, use mmap; refer to README-dev.md for more details use_mmap: !canUseAsyncFileRead(workerResources.compat), use_mlock: false, n_gpu_layers: params.n_gpu_layers ?? 99999, token_embd_on_gpu: params.token_embd_on_gpu ?? true, rpc_mem_max: rpcMemMax, n_ctx: params.n_ctx ?? 1024, n_threads: this.useMultiThread ? nbThreads : 1, n_ctx_auto: false, // not supported for now mmproj_path: modelFiles.mmproj ? `/models/${MMPROJ_FILE_NAME}` : undefined, model_paths: modelFiles.llm.map((f) => `models/${f.name}`), embeddings: params.embeddings, offload_kqv: params.offload_kqv, n_batch: params.n_batch, n_ubatch: params.n_ubatch, pooling_type: params.pooling_type as string, rope_scaling_type: params.rope_scaling_type as string, rope_freq_base: params.rope_freq_base, rope_freq_scale: params.rope_freq_scale, yarn_ext_factor: params.yarn_ext_factor, yarn_attn_factor: params.yarn_attn_factor, yarn_beta_fast: params.yarn_beta_fast, yarn_beta_slow: params.yarn_beta_slow, yarn_orig_ctx: params.yarn_orig_ctx, cache_type_k: params.cache_type_k as string, cache_type_v: params.cache_type_v as string, // with unified KV, all sequences share one n_ctx cache, so each request can still use the full context n_parallel: params.n_parallel ?? 4, kv_unified: params.kv_unified ?? true, flash_attn: params.flash_attn, swa_full: params.swa_full, chat_template: params.chat_template, jinja: params.jinja, reasoning: params.reasoning, image_min_tokens: params.image_min_tokens, image_max_tokens: params.image_max_tokens, warmup: params.warmup, no_kv_offload: params.no_kv_offload, mmproj_offload: params.mmproj_offload, cont_batching: params.cont_batching, n_keep: params.n_keep, ctx_shift: params.ctx_shift, cache_idle_slots: params.cache_idle_slots, n_cache_reuse: params.n_cache_reuse, lora_paths: loraAdapters.length ? loraAdapters.map((a) => a.path) : undefined, lora_scales: loraAdapters.length ? loraAdapters.map((a) => a.scale ?? 1.0) : undefined, lora_init_without_apply: params.lora_init_without_apply, spec_draft_model: modelFiles.draft ? `/models/${DRAFT_FILE_NAME}` : (params.spec_draft_model as string | undefined), spec_draft_ngl: params.spec_draft_ngl, spec_draft_n_max: params.spec_draft_n_max, spec_draft_n_min: params.spec_draft_n_min, spec_draft_p_min: params.spec_draft_p_min, spec_draft_threads: params.spec_draft_threads, spec_draft_threads_batch: params.spec_draft_threads_batch, spec_type: params.spec_type ?? modelFiles.draft?.spec_type, spec_ngram_simple_size_n: params.spec_ngram_simple_size_n, spec_ngram_simple_size_m: params.spec_ngram_simple_size_m, spec_ngram_simple_min_hits: params.spec_ngram_simple_min_hits, spec_ngram_mod_n_min: params.spec_ngram_mod_n_min, spec_ngram_mod_n_max: params.spec_ngram_mod_n_max, spec_ngram_mod_n_match: params.spec_ngram_mod_n_match, kv_overrides_keys: params.kv_overrides ? Object.keys(params.kv_overrides) : undefined, kv_overrides_vals: params.kv_overrides ? Object.values(params.kv_overrides) : undefined, reasoning_budget_tokens: params.reasoning_budget_tokens, reasoning_budget_message: params.reasoning_budget_message, reasoning_format: params.reasoning_format, skip_chat_parsing: params.skip_chat_parsing, prefill_assistant: params.prefill_assistant, }); if (!loadResult.success && !loadResult.n_rpc_workers) { throw new WllamaError('Failed to load model', 'load_error'); } } catch (e) { await exitWorkers(); throw e; } if (!loadResult.success) { // the part of the model on the CPU does not fit in this wasm instance: load again with rpc workers this.logger().debug( `The model does not fit in one wasm instance, using ${loadResult.n_rpc_workers} rpc workers` ); const exitCount = this.exitCount; await exitWorkers(); // exitWorkers() calls exit() once, or not at all if exit() was called before if (this.exitCount !== exitCount + 1) { throw new WllamaError( 'exit() was called while the model was loading', 'load_error' ); } return await this.loadModel(blobs, { ...params, rpc_workers: loadResult.n_rpc_workers, }); } const loadedCtxInfo: LoadedContextInfo & GlueMsgLoadRes = { ...loadResult, metadata: {}, }; for (let i = 0; i < loadResult.metadata_key.length; i++) { loadedCtxInfo.metadata[loadResult.metadata_key[i]] = loadResult.metadata_val[i]; } this.seed = params.seed; this.bosToken = loadedCtxInfo.token_bos; this.eosToken = loadedCtxInfo.token_eos; this.eotToken = loadedCtxInfo.token_eot; this.useEmbeddings = !!params.embeddings; this.useRerank = params.pooling_type == 'rank'; this.metadata = { hparams: { nVocab: loadedCtxInfo.n_vocab, nCtxTrain: loadedCtxInfo.n_ctx_train, nEmbd: loadedCtxInfo.n_embd, nLayer: loadedCtxInfo.n_layer, }, meta: loadedCtxInfo.metadata, }; this.hasEncoder = !!loadedCtxInfo.has_encoder; this.decoderStartToken = loadedCtxInfo.token_decoder_start; this.addBosToken = loadedCtxInfo.add_bos_token; this.addEosToken = loadedCtxInfo.add_eos_token; this.chatTemplate = loadedCtxInfo.metadata['tokenizer.chat_template']; this.loadedContextInfo = loadedCtxInfo; this.eogTokens = new Set(loadedCtxInfo.list_tokens_eog); this.mediaMarker = loadedCtxInfo.media_marker; this.chatTemplateKwargs = params.default_template_kwargs ?? {}; this.logger().debug({ loadedCtxInfo }); } getLoadedContextInfo(): LoadedContextInfo { this.checkModelLoaded(); if (!this.loadedContextInfo) { throw new WllamaError('Loaded context info is not available'); } // copy object return { ...this.loadedContextInfo }; } ////////////////////////////////////////////// // High level API /** * Calculate embedding vector for a given text or multimodal input. * By default, BOS and EOS tokens will be added automatically. You can use the "skipBOS" and "skipEOS" option to disable it. * @param options OAI-compatible embedding creation options * @returns OAI-compatible embedding response */ async createEmbedding( options: EmbeddingCreateParams ): Promise { this.checkModelLoaded(); if (!this.useEmbeddings) { throw new WllamaError( 'Embeddings is not enabled. Please set it via LoadModelParams.embeddings' ); } if ( options.embd_normalize !== undefined && (!Number.isInteger(options.embd_normalize) || options.embd_normalize < -1) ) { throw new WllamaError( 'embd_normalize must be an integer >= -1', 'inference_error' ); } const { input, files } = this.prepareEmbeddingInput(options.input); const result = await this.proxy.wllamaAction( 'embedding', { _name: 'embd_req', data_json: JSON.stringify({ ...options, input }), files: files.map((f) => new Uint8Array(f)), } ); if (!result.success) { throw new WllamaError( result.message || 'Model failed to start inference', 'inference_error' ); } return await this.getResponse(options as any, false, result.req_id); } /** * Rerank a list of documents against a query. * Requires the model to be loaded with embeddings: true and pooling_type: 'rank'. * @param options Reranking options (query, documents, top_n) * @returns Reranking response with relevance scores sorted highest first */ async createRerank(options: RerankParams): Promise { this.checkModelLoaded(); if (!this.useEmbeddings || !this.useRerank) { throw new WllamaError( 'Rerank is not enabled. Please set it via LoadModelParams: embeddings = true and pooling_type = rank' ); } const top_n = options.top_n ?? options.documents.length; let totalTokens = 0; const rawResults: Array<{ index: number; score: number }> = []; for (let i = 0; i < options.documents.length; i++) { const result = await this.proxy.wllamaAction('rerank', { _name: 'rrnk_req', data_json: JSON.stringify({ query: options.query, document: options.documents[i], }), }); if (!result.success) { throw new WllamaError( 'Model failed to start reranking', 'inference_error' ); } const { score, tokens_evaluated } = await this.getSingleResult<{ score: number; tokens_evaluated: number; }>(result.req_id, 'reranking'); totalTokens += tokens_evaluated; rawResults.push({ index: i, score }); } rawResults.sort((a, b) => b.score - a.score); return { model: this.getModelMetadata().meta['general.name'] ?? '', object: 'list', usage: { prompt_tokens: totalTokens, total_tokens: totalTokens }, results: rawResults.slice(0, top_n).map(({ index, score }) => ({ index, relevance_score: score, })), }; } /** * Answer typed questions about a state, using a decision model (TypeSafe-compatible System One API). * Image input is not supported yet. * @param options The state and the questions * @returns The answer of each question */ async createSystemOne(options: SystemOneParams): Promise { this.checkModelLoaded(); const result = await this.proxy.wllamaAction( 'systemone', { _name: 'sys1_req', data_json: JSON.stringify(options), } ); if (!result.success) { throw new WllamaError( 'Model failed to start systemone', 'inference_error' ); } return await this.getSingleResult( result.req_id, 'systemone' ); } /** * Generate speech from text. The model must have audio output, see `LoadedContextInfo.has_audio_output`. * @param options speech options * @returns the whole audio (stream=false) or an async iterator of audio chunks (stream=true). A stream starts its request on the first read, so errors come from the iterator */ async createSpeech( options: SpeechParams & { stream?: false } ): Promise; async createSpeech( options: SpeechParams & { stream: true } ): Promise>; async createSpeech( options: SpeechParams & { stream?: boolean } ): Promise> { this.checkModelLoaded(); // a stream starts its request on the first read, so an unread one costs nothing // it belongs to the model loaded now, so take its worker here const chunks = this.getSpeechChunks(options, this.proxy); if (options.stream) { return chunks; } for await (const chunk of chunks) { if (chunk.final) { return { audio: chunk.audio, sample_rate: chunk.sample_rate }; } } throw new WllamaError('No speech result received', 'inference_error'); } /** * Transcribe an audio file. The model must have audio input, see `supportInputModality()`. * @param options OAI-compatible transcription options * @returns OAI-compatible transcription response (stream=false), void when done (stream=true + onData), or async iterator (stream=true, no onData) */ async createTranscription( options: TranscriptionParams & { stream?: false } ): Promise; async createTranscription( options: TranscriptionParams & StreamParams ): Promise; async createTranscription( options: TranscriptionParams & { stream: true } ): Promise>; async createTranscription( options: TranscriptionParams ): Promise> { this.checkModelLoaded(); if (!this.supportInputModality('audio')) { throw new WllamaError( 'Audio input is not supported by the loaded model', 'inference_error' ); } if (options.stream && (options as any).onData) { await this.createCompletionImpl(options); } else if (options.stream) { return await this.createCompletionGenerator(options); } else { return await this.createCompletionImpl({ ...options, stream: false }); } } /** * Start a realtime audio session. The model must support it, see `LoadedContextInfo.has_audio_stream`. * It holds one slot until `close()` is called. * @param options session options * @returns the session */ async createRealtimeSession( options: RealtimeSessionParams = {} ): Promise { this.checkModelLoaded(); const customOpt = this.seed !== undefined ? { seed: this.seed } : {}; const result = await this.proxy.wllamaAction( 'realtime_start', { _name: 'rtst_req', data_json: JSON.stringify({ ...customOpt, ...options }), } ); if (!result.success) { throw new WllamaError( result.message || 'Model failed to start realtime session', 'inference_error' ); } return new WllamaRealtimeSession(this.proxy, result.req_id); } /** * Make chat completion for a given chat messages. * @param options OAI-compatible chat completion options * @returns OAI-compatible chat completion response (only the final result when stream=false) or an async iterator of completion chunks (when stream=true) */ async createChatCompletion( options: ChatCompletionParams & { stream?: false } ): Promise; async createChatCompletion( options: ChatCompletionParams & StreamParams ): Promise; async createChatCompletion( options: ChatCompletionParams & { stream: true } ): Promise>; async createChatCompletion( options: ChatCompletionParams ): Promise< ChatCompletionResponse | void | AsyncIterable > { // first, try to overlay chatTemplateKwargs if (Object.keys(this.chatTemplateKwargs).length > 0) { options = { ...options, chat_template_kwargs: { ...this.chatTemplateKwargs, ...(options.chat_template_kwargs ?? {}), }, }; } // then, call the corresponding overloaded function if (options.stream && (options as any).onData) { await this.createCompletionImpl(options); } else if (options.stream) { return await this.createCompletionGenerator(options); } else { return await this.createCompletionImpl({ ...options, stream: false }); } } /** * Make (raw) completion for a given text. * @param options OAI-compatible completion options * @returns OAI-compatible completion response (stream=false), void when done (stream=true + onData), or async iterator (stream=true, no onData) */ async createCompletion( options: RawCompletionParams & { stream?: false } ): Promise; async createCompletion( options: RawCompletionParams & StreamParams ): Promise; async createCompletion( options: RawCompletionParams & { stream: true } ): Promise>; async createCompletion( options: RawCompletionParams ): Promise> { if (options.stream && (options as any).onData) { await this.createCompletionImpl(options); } else if (options.stream) { return await this.createCompletionGenerator(options); } else { return await this.createCompletionImpl({ ...options, stream: false }); } } /** * Private implementation of createCompletion */ private async createCompletionImpl( options: TOpt ): Promise { this.checkModelLoaded(); const isStream = !!(options as any).stream; const isChat = !!(options as any).messages; const isAsr = !!(options as any).file; const customOpt: any = {}; if (this.seed !== undefined) { customOpt.seed = this.seed; } let files: ArrayBuffer[] = []; if (isAsr) { const { file, ...rest } = options as any as TranscriptionParams; files = [file]; // upstream reads these as form fields, so they must be strings const formFields: Record = {}; for (const key of ['stream', 'max_tokens', 'temperature'] as const) { if (rest[key] !== undefined) { formFields[key] = String(rest[key]); } } options = { ...rest, ...formFields } as any; } if (isChat) { const tmp = this.prepareMultimodalInput( options as any as ChatCompletionParams ); options = tmp.params as any; files = tmp.files; } const result = await this.proxy.wllamaAction( 'completion', { _name: 'cmpl_req', is_chat: isChat, is_asr: isAsr, data_json: JSON.stringify({ ...options, ...customOpt }), files: files.map((f) => new Uint8Array(f)), } ); if (!result.success) { throw new WllamaError( 'Model failed to start inference', 'inference_error' ); } return await this.getResponse( options as StreamParams & { abortSignal?: AbortSignal }, isStream, result.req_id ); } /** * Same with `createCompletion`, but returns an async iterator instead. * Only called when stream=true and no onData is provided. */ private createCompletionGenerator( options: TOpt ): Promise> { return new Promise((resolve) => { const createGenerator = cbToAsyncIter( (callback: (val?: TChunk, done?: boolean, err?: Error) => void) => { this.createCompletionImpl({ ...options, onData: (chunk: TChunk) => callback(chunk), }) .then(() => callback(undefined, true)) .catch((err) => callback(undefined, false, err)); } ); resolve(createGenerator()); }); } /** * Whether the currently loaded model supports a specific input modality (e.g. image or audio). * @param modality * @returns */ supportInputModality(modality: 'image' | 'audio' | 'video'): boolean { this.checkModelLoaded(); if (modality === 'image') { return !!this.loadedContextInfo.has_image_input; } else if (modality === 'audio') { return !!this.loadedContextInfo.has_audio_input; } else if (modality === 'video') { return !!this.loadedContextInfo.has_video_input; } else { throw new WllamaError( 'Unsupported modality: ' + modality, 'unknown_error' ); } } /** * Save the state of a slot (the processed prompt), to restore it later with `restoreSlotState()`. * * The state can only be restored with the same model and the same wllama version. * * @param idSlot ID of the slot, between 0 and `n_parallel - 1` * @returns the state, you can store it (for example in OPFS) */ async saveSlotState(idSlot: number = 0): Promise { this.checkModelLoaded(); const result = await this.proxy.wllamaAction( 'slot_save', { _name: 'slsv_req', id_slot: idSlot, } ); if (!result.success) { throw new WllamaError( result.message || 'Failed to save slot state', 'inference_error' ); } return result.data; } /** * Restore the state of a slot from the output of `saveSlotState()`. * * The next request that starts with the same prompt reuses it. * * @param data The saved state * @param idSlot ID of the slot, between 0 and `n_parallel - 1` * @returns number of tokens in the restored prompt */ async restoreSlotState( data: Uint8Array, idSlot: number = 0 ): Promise { this.checkModelLoaded(); const result = await this.proxy.wllamaAction( 'slot_restore', { _name: 'slrs_req', id_slot: idSlot, data, } ); if (!result.success) { throw new WllamaError( result.message || 'Failed to restore slot state', 'inference_error' ); } return result.n_tokens; } /** * Convert text to tokens, like the `/tokenize` route of llama-server. * * @param content The text, or an array mixing text and token IDs * @param options.addSpecial Add the special tokens of the model, like BOS (default: false) * @param options.parseSpecial Parse special tokens written in the text, like `<|im_start|>` (default: true) * @param options.withPieces Also return the text of each token. A piece that is not valid UTF-8 on its own (part of a multi-byte character) is returned as its bytes * @returns the token IDs, or with `withPieces`, the token IDs with their pieces */ async tokenize( content: string | (string | number)[], options?: TokenizeOptions & { withPieces?: false } ): Promise; async tokenize( content: string | (string | number)[], options: TokenizeOptions & { withPieces: true } ): Promise; async tokenize( content: string | (string | number)[], options: TokenizeOptions & { withPieces?: boolean } = {} ): Promise { this.checkModelLoaded(); const result = await this.proxy.wllamaAction( 'tokenize', { _name: 'tokn_req', data_json: JSON.stringify({ content, add_special: options.addSpecial ?? false, parse_special: options.parseSpecial ?? true, with_pieces: options.withPieces ?? false, }), } ); return JSON.parse(result.data_json).tokens; } /** * Convert tokens to text, like the `/detokenize` route of llama-server. * * @param tokens The token IDs * @returns the text */ async detokenize(tokens: number[]): Promise { this.checkModelLoaded(); const result = await this.proxy.wllamaAction( 'detokenize', { _name: 'dtkn_req', data_json: JSON.stringify({ tokens }), } ); return JSON.parse(result.data_json).content; } /** * Unload the model and free all memory. * * Note: This function will NOT crash if model is not yet loaded */ async exit(): Promise { // detach them first: a new load can start while this one is shutting down this.exitCount++; const proxy = this.proxy; const rpcWorkers = this.rpcWorkers; this.proxy = null as any; this.rpcWorkers = []; await proxy?.wllamaExit(); // rpc workers are blocked in the wasm, terminate them for (const w of rpcWorkers) await w.wllamaExit(); } // without async file reads (no JSPI, not compat), the whole model is copied into the main wasm (mmap), so rpc workers cannot help private static RPC_NEEDS_ASYNC_READ = 'The model does not fit in one wasm instance (4GB): rpc workers need a browser with JSPI, or the compat build (see setCompat)'; private pickRpcWorkers( params: LoadModelParams, resources: WllamaWorkerResources ): number { if (params.rpc_workers !== undefined) { const n = params.rpc_workers; if (!Number.isInteger(n) || n < 0 || n > MAX_RPC_WORKERS) { throw new WllamaError( `rpc_workers must be an integer from 0 to ${MAX_RPC_WORKERS}`, 'load_error' ); } if (params.rpc_workers > 0 && !this.useMultiThread) { throw new WllamaError( 'rpc_workers needs multi-thread, see the Cross-Origin headers in README', 'load_error' ); } if (params.rpc_workers > 0 && !canUseAsyncFileRead(resources.compat)) { throw new WllamaError(Wllama.RPC_NEEDS_ASYNC_READ, 'load_error'); } return params.rpc_workers; } return 0; } // by default, the wasm measures the part of the model on the CPU, and asks for rpc workers if it is over this limit (MiB) // undefined: no measure. It reads the metadata one more time, so small files skip it private autoRpcMemMax( files: { blob: Blob }[], resources: WllamaWorkerResources ): number | undefined { const size = files.reduce((sum, f) => sum + f.blob.size, 0); if (size < RPC_CONFIG.autoMinSize) return undefined; if (!canUseAsyncFileRead(resources.compat)) { if (size >= GGUF_SPLIT_CONFIG.maxFileSize) { throw new WllamaError(Wllama.RPC_NEEDS_ASYNC_READ, 'load_error'); } return undefined; } // the main wasm does the rpc I/O in its own threads return this.useMultiThread ? RPC_CONFIG.mainMemMax : undefined; } // spawn wasm instances that each hold a part of the model in their own 4GB memory private async startRpcWorkers( n: number, resources: WllamaWorkerResources, started: ProxyToWorker[] ): Promise { if (n <= 0) return undefined; const RING_BYTES = 16 * 1024 * 1024; // power of 2 const HEADER_BYTES = 64; // same as RPC_HEADER_BYTES in rpc-transport.js const nThreads = this.useMultiThread ? this.nbThreads : 0; const channels: RpcInitOptions['channels'] = []; for (let i = 0; i < n; i++) { const port = 5001 + i; const sab = new SharedArrayBuffer(HEADER_BYTES + 2 * RING_BYTES); const server = new ProxyToWorker( { ...resources, noWebGPU: true }, nThreads, this.config.suppressNativeLog ?? false, this.logger() ); this.rpcWorkers.push(server); started.push(server); await server.moduleInit([], { env: {}, channels: [{ port, sab, role: 'server' }], }); await server.rpcServe(port, Math.max(nThreads, 1)); channels.push({ port, sab, role: 'client' }); } const servers = channels.map((c) => `127.0.0.1:${c.port}`).join(','); return { env: { WLLAMA_RPC_SERVERS: servers }, channels }; } /** * [FOR DEBUGGING ONLY] Run ggml backend ops tests without loading any model. * * Initializes the wasm runtime, executes `test-backend-ops` with the given args, then shuts down. * * For more info, please refer to guides/debug.md * * @param args Arguments forwarded to test-backend-ops (e.g. ["-o", "ADD"]) * @returns retcode (0 = all tests passed) and success flag */ async testBackendOps( args: string[] = [] ): Promise<{ retcode: number; success: boolean }> { if (!this.pathConfig['default']) { throw new WllamaError( '"default" is missing from pathConfig', 'load_error' ); } if (!(await isSupportMultiThread())) { throw new WllamaError( 'Multi-threading is required to run backend ops tests, but it is not supported in the current environment.' ); } const tmpProxy = new ProxyToWorker( this.getWorkerResources(), 0, // single-thread; no model needed this.config.suppressNativeLog ?? false, this.logger() ); try { await tmpProxy.moduleInit([]); const startResult: any = await tmpProxy.wllamaStart(); if (!startResult.success) { throw new WllamaError( `Error while calling start function, result = ${startResult}` ); } const result = await tmpProxy.wllamaAction( 'test_backend_ops', { _name: 'tbop_req', args: ['test-backend-ops', ...args] } ); return { retcode: result.retcode, success: result.success }; } finally { await tmpProxy.wllamaExit(); } } ////////////////////////////////////////////// // Low level API // TODO: add back /** * get debug info */ async _getDebugInfo(): Promise { this.checkModelLoaded(); return await this.proxy.wllamaDebug(); } ////////////////////////////////////////////// // Utils private jsonDecode(data_json: string) { try { return JSON.parse(data_json); } catch (e) { this.logger().error('Failed to parse JSON:', data_json); throw new WllamaError('Failed to parse model output', 'inference_error'); } } private replaceMedia( content: ChatCompletionMessageContent[], files: ArrayBuffer[] ): ChatCompletionMessageText[] { return content.map((c) => { if (c.type === 'text') { return c; } if (!this.mediaMarker) { throw new WllamaError('Media marker is undefined', 'inference_error'); } files.push(c.data); return { type: 'text', text: this.mediaMarker }; }); } private prepareMultimodalInput(params: ChatCompletionParams): { params: ChatCompletionParams; files: ArrayBuffer[]; } { const msg = params.messages; const msgNew: typeof msg = []; const files: ArrayBuffer[] = []; for (const m of msg) { if (Array.isArray(m.content)) { msgNew.push({ ...m, content: this.replaceMedia(m.content, files), } as ChatCompletionUserMessage); } else { // no transform for non-typed content msgNew.push(m); } } return { params: { ...params, messages: msgNew, }, files, }; } private prepareEmbeddingInput(input: EmbeddingInput): { input: EmbeddingInput; files: ArrayBuffer[]; } { const files: ArrayBuffer[] = []; const isContentPart = (entry: unknown): entry is EmbeddingContent => typeof entry === 'object' && entry !== null && 'type' in entry && (entry.type === 'text' || entry.type === 'image'); const isContent = (entry: unknown): entry is EmbeddingContent[] => Array.isArray(entry) && entry.length > 0 && entry.every(isContentPart); const toText = (content: EmbeddingContent[]): string => { if ( content.some((c) => c.type === 'text' && typeof c.text !== 'string') ) { throw new WllamaError( 'Text input must contain a string in "text"', 'inference_error' ); } const text = this.replaceMedia(content, files) .map((c) => c.text) .join(''); if (text.length === 0) { throw new WllamaError( 'Input content cannot be empty', 'inference_error' ); } return text; }; let prepared = input; if (isContent(input)) { prepared = toText(input); } else if ( Array.isArray(input) && input.length > 0 && (input as unknown[]).every(isContent) ) { prepared = (input as EmbeddingContent[][]).map(toText); } if (files.length > 0 && !this.supportInputModality('image')) { throw new WllamaError( 'Image input is not supported by the loaded model', 'inference_error' ); } return { input: prepared, files }; } // release the slot occupied by the request; cancelling an already-finished request is a no-op private async cancelRequest(reqId: number): Promise { try { await this.proxy.wllamaAction('cancel', { _name: 'cncl_req', req_id: reqId, }); } catch (e) { this.logger().warn('Failed to cancel request', reqId, e); } } private async *getSpeechChunks( options: SpeechParams & { stream?: boolean }, proxy: ProxyToWorker ): AsyncGenerator { const { speaker_ref, abortSignal, ...params } = options; if (abortSignal?.aborted) { throw new WllamaAbortError(); } // request ids start again in a new worker, so only talk to the worker that has the request if (this.proxy !== proxy) { throw new WllamaError( 'The model of this speech stream is not loaded anymore', 'inference_error' ); } const customOpt = this.seed !== undefined ? { seed: this.seed } : {}; const result = await proxy.wllamaAction('tts', { _name: 'tts__req', data_json: JSON.stringify({ ...customOpt, ...params }), files: speaker_ref ? [new Uint8Array(speaker_ref)] : [], }); if (!result.success) { throw new WllamaError( result.message || 'Model failed to start speech generation', 'inference_error' ); } const reqId = result.req_id; const cancel = async () => { if (this.proxy === proxy) { await this.cancelRequest(reqId); } }; // also cancel while the reader waits between chunks const onAbort = () => void cancel(); abortSignal?.addEventListener('abort', onAbort, { once: true }); let completed = false; try { while (true) { if (abortSignal?.aborted) { throw new WllamaAbortError(); } const chunk = await proxy.wllamaAction( 'get_result', { _name: 'gres_req', req_id: reqId } ); if (abortSignal?.aborted) { throw new WllamaAbortError(); } completed = !chunk.has_more; if (chunk.data_json) { const data = this.jsonDecode(chunk.data_json); if (chunk.is_error) { throw new WllamaError( data.message || 'Unknown speech error', 'inference_error' ); } yield { audio: chunk.data_raw.slice().buffer as ArrayBuffer, sample_rate: data.sample_rate, final: data.final, }; } if (completed) { return; } } } finally { // covers a consumer that stops reading too abortSignal?.removeEventListener('abort', onAbort); if (!completed) { await cancel(); } } } private async getSingleResult(reqId: number, task: string): Promise { let completed = false; try { while (true) { const chunk = await this.proxy.wllamaAction( 'get_result', { _name: 'gres_req', req_id: reqId } ); const jsonString = chunk.data_json; if (jsonString && jsonString.length > 0) { if (chunk.is_error) { const jsonData = this.jsonDecode(jsonString); throw new WllamaError( jsonData.message || `Unknown ${task} error`, 'inference_error' ); } completed = true; return this.jsonDecode(jsonString); } if (!chunk.has_more) { completed = true; break; } } throw new WllamaError(`No ${task} result received`, 'inference_error'); } finally { if (!completed) { await this.cancelRequest(reqId); } } } private async getResponse( options: StreamParams & { abortSignal?: AbortSignal }, isStream: boolean, reqId: number ) { let finalResult: any = null; let completed = false; try { while (true) { if (options.abortSignal?.aborted) { throw new WllamaAbortError(); } const result_chunk = await this.proxy.wllamaAction( 'get_result', { _name: 'gres_req', req_id: reqId, } ); const jsonString = result_chunk.data_json; if (!jsonString || jsonString.length === 0) { if (!result_chunk.has_more) { completed = true; break; } else { continue; } } if (jsonString == 'null') { continue; // this is the "is_begin = true" chunk on server side, we can ignore it } let jsonData = this.jsonDecode(jsonString); finalResult = jsonData; if (result_chunk.is_error) { this.logger().error('Model returned an error:', jsonData); throw new WllamaError( jsonData.message || 'Unknown inference error', 'inference_error' ); } if (isStream) { if (!Array.isArray(jsonData)) { jsonData = [jsonData]; } for (const chunk of jsonData) { options.onData?.(chunk); finalResult = chunk; } } if (!result_chunk.has_more) { completed = true; break; } } } finally { // any exit before the final chunk (abort, decode error, onData throw) must free the slot if (!completed) { await this.cancelRequest(reqId); } } return finalResult; } private async checkWasmVersion(wasmVersion?: string) { // compare the commit only, the build number is wrong in a shallow clone const getCommit = (version?: string) => version?.split('-').pop(); if (getCommit(wasmVersion) === getCommit(LIBLLAMA_VERSION)) { return; } const message = `wasm file version (${wasmVersion ?? 'unknown'}) does not match the expected version (${LIBLLAMA_VERSION})`; if (this.config.skipVersionCheck) { this.logger().warn(message); return; } await this.exit(); throw new WllamaError( `${message}. Use the wasm file from the same release, or set skipVersionCheck to ignore this error`, 'version_mismatch' ); } getWorkerResources(): WllamaWorkerResources { const workerResources: WllamaWorkerResources = { wasmPath: absoluteUrl(this.pathConfig['default']), compat: false, }; // compat is very slow on Firefox: without JSPI, the main build runs too (on CPU only) if (isFirefox() ? !isSupportRelaxedSIMD() : needCompat()) { if (!this.compat) { this.logger().warn( 'Not using compat mode, the browser does not support JSPI or wasm relaxed SIMD: WebGPU and models over 4GB are disabled' ); } else { const isUsingDefault = this.compat.wasm === WasmCompatFromCDN.wasm; if (isUsingDefault) { this.logger().warn( 'Compatibility mode is activated, using resources from CDN. To use local resources, please refer to @wllama/wllama-compat package.' ); this.logger().warn( 'IMPORTANT: Performance will be significantly degraded in compatibility mode.' ); } workerResources.wasmPath = absoluteUrl(this.compat.wasm); workerResources.jsPath = this.compat.worker; workerResources.compat = true; } } if (isFirefox() && !isSupportJSPI()) { this.logger().warn( 'This version of Firefox does not support JSPI, WebGPU and models over 4GB are disabled. Consider updating it, or enabling "javascript.options.wasm_js_promise_integration" in "about:config".' ); } return workerResources; } }