///
///
import { ProxyToWorker, type WllamaWorkerResources } from './worker.js';
import CacheManager, { type DownloadOptions } from './cache-manager.js';
import { ModelManager, Model, type ModelSource } from './model-manager.js';
import type { LoadedContextInfo, LoadModelParams, StreamParams } from './types/types.js';
import type { ChatCompletionChunk, ChatCompletionParams, ChatCompletionResponse, CreateEmbeddingResponse, EmbeddingCreateParams, RealtimeEvent, RealtimeSessionParams, RawCompletionChunk, RawCompletionParams, RawCompletionResponse, RerankParams, RerankResponse, SpeechChunk, SpeechParams, SpeechResponse, SystemOneParams, SystemOneResponse, TranscriptionChunk, TranscriptionParams, TranscriptionResponse } from './types/oai-compat.js';
import { type HuggingFaceParams } from './huggingface.js';
export interface WllamaLogger {
debug: typeof console.debug;
log: typeof console.log;
warn: typeof console.warn;
error: typeof console.error;
}
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;
'multi-thread/wllama.wasm'?: string;
}
export interface ModelMetadata {
hparams: {
nVocab: number;
nCtxTrain: number;
nEmbd: number;
nLayer: number;
};
meta: Record;
}
/**
* Logger preset with debug messages suppressed
*/
export declare const LoggerWithoutDebug: {
debug: () => void;
assert(condition?: boolean | undefined, ...data: any[]): void;
assert(value: any, message?: string | undefined, ...optionalParams: any[]): void;
clear(): void;
clear(): void;
count(label?: string | undefined): void;
count(label?: string | undefined): void;
countReset(label?: string | undefined): void;
countReset(label?: string | undefined): void;
dir(item?: any, options?: any): void;
dir(obj: any, options?: import("util").InspectOptions | undefined): void;
dirxml(...data: any[]): void;
dirxml(...data: any[]): void;
error(...data: any[]): void;
error(message?: any, ...optionalParams: any[]): void;
group(...data: any[]): void;
group(...label: any[]): void;
groupCollapsed(...data: any[]): void;
groupCollapsed(...label: any[]): void;
groupEnd(): void;
groupEnd(): void;
info(...data: any[]): void;
info(message?: any, ...optionalParams: any[]): void;
log(...data: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
table(tabularData?: any, properties?: string[] | undefined): void;
table(tabularData: any, properties?: readonly string[] | undefined): void;
time(label?: string | undefined): void;
time(label?: string | undefined): void;
timeEnd(label?: string | undefined): void;
timeEnd(label?: string | undefined): void;
timeLog(label?: string | undefined, ...data: any[]): void;
timeLog(label?: string | undefined, ...data: any[]): void;
timeStamp(label?: string | undefined): void;
timeStamp(label?: string | undefined): void;
trace(...data: any[]): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(...data: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
Console: console.ConsoleConstructor;
profile(label?: string | undefined): void;
profileEnd(label?: string | undefined): void;
};
export type WllamaErrorType = 'model_not_loaded' | 'download_error' | 'load_error' | 'version_mismatch' | 'kv_cache_full' | 'unknown_error' | 'inference_error';
export declare class WllamaError extends Error {
type: WllamaErrorType;
constructor(message: string, type?: WllamaErrorType);
}
/**
* AbortError is thrown when the user wants to abort the current operation.
* This is equivalent to AbortError in Fetch API.
*/
export declare class WllamaAbortError extends Error {
name: string;
constructor();
}
/**
* 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 declare class WllamaRuntimeError extends Error {
name: string;
stack: string;
constructor(message: string, stack: string);
}
/**
* 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 declare const encodeRealtimeAudio: (samples: Float32Array) => string;
/**
* Decode the base64 PCM16 audio of a `response.output_audio.delta` event.
*/
export declare const decodeRealtimeAudio: (delta: string) => Float32Array;
/**
* 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 declare class WllamaRealtimeSession {
private proxy;
private reqId;
private closed;
private pending;
private wakeUp;
private sent;
constructor(proxy: ProxyToWorker, reqId: number);
/**
* Send a client event, for example `session.update` or `response.create`.
*/
send(event: RealtimeEvent): Promise;
/**
* Same as sending `input_audio_buffer.append`.
* @param samples mono PCM at `LoadedContextInfo.audio_input_rate`
*/
appendAudio(samples: Float32Array): Promise;
/**
* Read the server events. It ends when the session ends. Only one reader at a time.
*/
events(): AsyncGenerator;
/**
* End the session and free its slot.
*/
close(): Promise;
}
export declare class Wllama {
cacheManager: CacheManager;
modelManager: ModelManager;
private compat;
private proxy;
private rpcWorkers;
private exitCount;
private config;
private pathConfig;
private useMultiThread;
private nbThreads;
private useEmbeddings;
private useRerank;
private loadedContextInfo;
private seed;
private bosToken;
private eosToken;
private eotToken;
private eogTokens;
private addBosToken;
private addEosToken;
private mediaMarker?;
private chatTemplate?;
private metadata?;
private hasEncoder;
private decoderStartToken;
private chatTemplateKwargs;
constructor(pathConfig: AssetsPathConfig, wllamaConfig?: WllamaConfig);
private logger;
private checkModelLoaded;
/**
* Get the libllama version string, e.g. "b6327-4d74393".
*
* @returns version string embedded at build time.
*/
static getLibllamaVersion(): string;
/**
* 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'): void;
/**
* Check if the model is loaded via `loadModel()`
*/
isModelLoaded(): boolean;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* Get model hyper-parameters and metadata
*
* NOTE: This can only being used after `loadModel` is called.
*
* @returns ModelMetadata
*/
getModelMetadata(): ModelMetadata;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* Check if WebGPU is supported by the current environment.
* @returns true if WebGPU is supported
*/
isSupportWebGPU(): boolean;
/**
* 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
*/
loadModelFromUrl(modelSourceOrURL: ModelSource | string, params?: LoadModelParams & DownloadOptions & {
useCache?: boolean;
}): Promise;
/**
* Load model from a given Hugging Face model ID and file path.
*
* @param hfOptions
* @param params
*/
loadModelFromHF(hfOptions: HuggingFaceParams, params?: LoadModelParams & DownloadOptions & {
useCache?: boolean;
}): Promise;
/**
* 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
*/
loadModel(ggufBlobsOrModel: Blob[] | Model, params?: LoadModelParams): Promise;
getLoadedContextInfo(): LoadedContextInfo;
/**
* 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
*/
createEmbedding(options: EmbeddingCreateParams): Promise;
/**
* 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
*/
createRerank(options: RerankParams): Promise;
/**
* 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
*/
createSystemOne(options: SystemOneParams): Promise;
/**
* 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
*/
createSpeech(options: SpeechParams & {
stream?: false;
}): Promise;
createSpeech(options: SpeechParams & {
stream: true;
}): Promise>;
/**
* 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)
*/
createTranscription(options: TranscriptionParams & {
stream?: false;
}): Promise;
createTranscription(options: TranscriptionParams & StreamParams): Promise;
createTranscription(options: TranscriptionParams & {
stream: true;
}): Promise>;
/**
* 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
*/
createRealtimeSession(options?: RealtimeSessionParams): Promise;
/**
* 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)
*/
createChatCompletion(options: ChatCompletionParams & {
stream?: false;
}): Promise;
createChatCompletion(options: ChatCompletionParams & StreamParams): Promise;
createChatCompletion(options: ChatCompletionParams & {
stream: true;
}): Promise>;
/**
* 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)
*/
createCompletion(options: RawCompletionParams & {
stream?: false;
}): Promise;
createCompletion(options: RawCompletionParams & StreamParams): Promise;
createCompletion(options: RawCompletionParams & {
stream: true;
}): Promise>;
/**
* Private implementation of createCompletion
*/
private createCompletionImpl;
/**
* Same with `createCompletion`, but returns an async iterator instead.
* Only called when stream=true and no onData is provided.
*/
private createCompletionGenerator;
/**
* Whether the currently loaded model supports a specific input modality (e.g. image or audio).
* @param modality
* @returns
*/
supportInputModality(modality: 'image' | 'audio' | 'video'): boolean;
/**
* 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)
*/
saveSlotState(idSlot?: number): Promise;
/**
* 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
*/
restoreSlotState(data: Uint8Array, idSlot?: number): Promise;
/**
* 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
*/
tokenize(content: string | (string | number)[], options?: TokenizeOptions & {
withPieces?: false;
}): Promise;
tokenize(content: string | (string | number)[], options: TokenizeOptions & {
withPieces: true;
}): Promise;
/**
* Convert tokens to text, like the `/detokenize` route of llama-server.
*
* @param tokens The token IDs
* @returns the text
*/
detokenize(tokens: number[]): Promise;
/**
* Unload the model and free all memory.
*
* Note: This function will NOT crash if model is not yet loaded
*/
exit(): Promise;
private static RPC_NEEDS_ASYNC_READ;
private pickRpcWorkers;
private autoRpcMemMax;
private startRpcWorkers;
/**
* [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
*/
testBackendOps(args?: string[]): Promise<{
retcode: number;
success: boolean;
}>;
/**
* get debug info
*/
_getDebugInfo(): Promise;
private jsonDecode;
private replaceMedia;
private prepareMultimodalInput;
private prepareEmbeddingInput;
private cancelRequest;
private getSpeechChunks;
private getSingleResult;
private getResponse;
private checkWasmVersion;
getWorkerResources(): WllamaWorkerResources;
}