API reference

Generated from the docstrings. For how to use these, see the guides; for what each task accepts and returns, the pipeline task table.

Functions

async lmlite.pipeline(task, model, **options)

Load a Transformers.js task and return a callable Pipeline.

pipeline() is the way to run everything except text generation, embeddings and text classification (see LLM, Embedder and Classifier). The supported tasks are listed in SUPPORTED_TASKS; the pipeline task table in the reference says what each one takes and returns.

Parameters:
  • task – One of SUPPORTED_TASKS, for example "zero-shot-classification", "translation", "automatic-speech-recognition", "object-detection" or "text-to-speech".

  • model – A Hugging Face model ID such as "Xenova/detr-resnet-50", or a short name, which gets the default Xenova/ namespace, or a model hosted with the site.

  • **options – Loading options, as for LLM.create(): backend ("wasm", the default, or "webgpu"), backend_fallback, dtype, dtype_fallbacks, hosted_models_url, auto_detect_local, local_models_path, progress_callback and quiet. image_size is for tasks on images: the number of pixels that the shorter side of the image is resized to before inference, instead of the model’s own (800 for Xenova/detr-resnet-50, so a 640 x 480 camera photo is scaled up first). A smaller size is faster: 480 took a fifth of the time for object-detection with the same detections in a test, and 320 a tenth, with slightly lower scores. Only models whose image processor resizes by the shorter side take it.

Returns:

The loaded Pipeline. Call it with the task’s input, and dispose() it when you are done.

Raises:
  • ValueError – task is not supported, or model is empty, or image_size is not a positive integer.

  • TypeError – options contains a model option such as generator_model; this function loads one task.

Example

classifier = await pipeline("zero-shot-classification", model="mobilebert-uncased-mnli")
await classifier("This notebook runs in a browser", candidate_labels=["technology", "sports"])
await classifier.dispose()
async lmlite.tokenizer(model=None, *, tokenizer_json=None, tokenizer_config=None, hosted_models_url=None)

Load only a tokenizer, with no model weights and no inference pipeline.

Parameters:
  • model – A model ID or name. Its tokenizer.json (and tokenizer_config.json when there is one) come from the hosted files/models/ snapshot first, then from the Hub, as for LLM.create(). Pass this or tokenizer_json, not both.

  • tokenizer_json – An HTTP(S) URL, or a path relative to the JupyterLite site root such as "files/models/org/name/tokenizer.json". Paths in the kernel’s virtual file system are not supported.

  • tokenizer_config – The URL or path of a tokenizer_config.json, only with tokenizer_json.

  • hosted_models_url – An explicit URL of a hosted models directory, as for LLM.create().

Returns:

A Tokenizer. Each call loads an independent handle.

Raises:
  • ValueError – The arguments are wrong (neither or both of model and tokenizer_json, or a config with model).

  • RuntimeError – The kernel cannot call encode() synchronously.

Example

tok = await tokenizer(model="minishlab/potion-multilingual-128M")
tok.encode("sushi right next door to a pharmacy")
tok.close()
async lmlite.model_info(model, task=None, backend='wasm', dtype=None)

Inspect a model’s files, download size and cache status without loading or downloading it.

File sizes come from the cache or from a one-byte range request to the Hub.

Parameters:
  • model – A model ID or name.

  • task – The task you will load it as, such as "text-generation", "feature-extraction", "text-classification" or one of SUPPORTED_TASKS. Without it the model’s Hub pipeline tag is used, which needs the network.

  • backend – "wasm" or "webgpu".

  • dtype – The dtype to inspect. Without it, the first of q8, int8 or fp32 that the model publishes.

Returns:

A ModelInfo.

Example

info = await model_info("HuggingFaceTB/SmolLM2-360M-Instruct", dtype="q4")
info.cache_status, info.download_bytes
async lmlite.model_task(model)

The task a model is tagged with on the Hugging Face Hub.

Parameters:

model – A model ID or name.

Returns:

The pipeline tag, such as "text-generation", or None when offline or when the model has no tag. It makes one Hub request with a 5-second timeout.

async lmlite.hosted_base(model_id, *, hosted_models_url=None)

Where a model would load from: the base URL of the hosted models that serve it, if any.

It uses the discovery of LLM.create(): the site’s files/models/manifest.json, or hosted_models_url. Revisions other than @main are never hosted.

Parameters:
  • model_id – A model ID or name.

  • hosted_models_url – An explicit URL of a models directory that has a manifest.json.

Returns:

The base URL, such as "https://my-site.com/files/models/", or None when the model is not hosted.

Raises:

RuntimeError – hosted_models_url was given and its manifest is missing or invalid.

async lmlite.cached_models()

List the models in the Transformers.js browser cache.

Hosted model files and ZIPs in /drive/models are not included.

Returns:

A list of dicts, or None when the Cache API is unavailable. Each dict has model_id, revision, model_type (from the cached config.json), task (the Hub pipeline tag, None offline), files, file_sizes (file name to size, None if unknown) and size.

async lmlite.clear_cache(model=None)

Clear the browser caches that hold downloaded models.

Parameters:

model – A model ID or name. Without it, every cache is cleared.

Returns:

{"deleted_caches": [...], "deleted_databases": [...]}. With one: {"model_id": ..., "deleted_files": [urls]}, covering all of its revisions.

Return type:

With no model

Language models

class lmlite.LLM(js_instance, models=None)

A large language model for text generation, chat and streaming.

Load it with await LLM.create(generator_model=...). For embeddings use Embedder, for classification Classifier, and for everything else pipeline().

Example

llm = await LLM.create(generator_model="HuggingFaceTB/SmolLM2-360M-Instruct", backend="wasm", dtype="q4")
await llm.chat([{"role": "user", "content": "Explain embeddings in simple terms."}])
async for chunk in llm.chat_stream([{"role": "user", "content": "Hello"}]):
    print(chunk, end="")
await llm.dispose()
async generate(prompt: str)

Generate text from a prompt.

Parameters:

prompt – The text to continue.

Returns:

The prompt followed by the generated text, or only the generated text when the model was loaded with return_full_text=False. If cancel() stopped it, the text so far.

async chat(messages)

Answer a conversation, using the chat template of the loaded model’s tokenizer.

Parameters:

messages – A list of {"role": ..., "content": ...} dicts with string values, such as "system", "user" and "assistant". A model without a chat template gets generic role labels, which does not make a completion model follow instructions.

Returns:

The assistant’s reply, never the prompt, whatever return_full_text is. If cancel() stopped it, the text so far.

Raises:

Exception – A template error, such as a role the template does not support. There is no fallback format.

chat_stream(messages)

Stream the answer to a conversation as it is generated.

Generation starts on the first iteration. Leaving the loop early (break, an exception or a kernel interrupt) cancels it. One generation runs per instance at a time.

Parameters:

messages – As for chat().

Yields:

Text chunks, usually a word with its whitespace. "".join(chunks).strip() is the chat() answer.

Example

async for chunk in llm.chat_stream([{"role": "user", "content": "Explain embeddings simply."}]):
    print(chunk, end="", flush=True)
generate_stream(prompt: str)

Stream newly generated text for a prompt.

Parameters:

prompt – The text to continue.

Yields:

Text chunks, never including the prompt, whatever return_full_text is. Cancellation and concurrency are as for chat_stream().

chat_tokens(messages, alternatives=1)

Stream the answer to a conversation one token at a time, with the probabilities.

Cancellation and concurrency are as for chat_stream().

Parameters:
  • messages – As for chat().

  • alternatives – How many other likely tokens to report at each step (default 1; 0 for none).

Yields:

One dict per token – {"text": str, "prob": float, "alternatives": [{"text": str, "prob": float}, ...]}. The probabilities are those the token picker used, after the repetition penalty and, when sampling, the temperature. The joined text values equal the joined chat_stream() chunks.

Raises:

ValueError – alternatives is not a nonnegative integer.

generate_tokens(prompt: str, alternatives=1)

Like chat_tokens() for a plain prompt. The prompt is never included.

Parameters:
  • prompt – The text to continue.

  • alternatives – How many other likely tokens to report at each step (default 1; 0 for none).

Yields:

Dicts as for chat_tokens().

async cancel()

Stop the running generation after its current token.

A stream ends early without an error, and generate() and chat() return the text so far. The instance stays usable.

Returns:

False if nothing was running.

async classmethod create(progress_callback=None, **overrides)

Load a generator model.

Progress is shown in the notebook cell, with status messages while the model is prepared, loaded and warmed up. The cell stays busy until that finishes.

Parameters:
  • generator_model – A Hugging Face model ID such as "HuggingFaceTB/SmolLM2-360M-Instruct", or a short name, which gets the default Xenova/ namespace.

  • backend – "wasm" (the default) or "webgpu"; "native" runs onnxruntime outside a browser (pip install 'lmlite[native]').

  • backend_fallback – True (the default) loads on "wasm" when backend="webgpu" but the browser has no WebGPU adapter, or the load fails for a reason specific to WebGPU (no adapter, a lost device, a shader or buffer limit such as Firefox’s “Too many storage buffers” for q4). It says so when loading ends; backend and backend_fallback_reason tell which backend ran and why. A pinned dtype stays pinned, so a q4 model that fell back is slow on WASM. A network error, running out of memory or a missing file does not fall back, since WASM would fail the same way. False fails instead; use it when you measure or prove which backend ran.

  • dtype – The weights to load, such as "q4" or "fp32". By default the first of q8, int8 and fp32 that exists. On WebGPU "q4" is the fastest; see the model guide.

  • dtype_fallbacks – Dtypes to try in order; takes precedence over dtype.

  • max_new_tokens – How many tokens to generate at most (default 50).

  • return_full_text – True (the default) makes generate() return the prompt followed by the continuation; False returns only the continuation.

  • temperature – Sampling temperature (default 0.7).

  • top_k – Sampling considers this many most likely tokens (default 50).

  • do_sample – True (the default) samples; False picks the most probable token each time.

  • hosted_models_url – An explicit URL of a models directory that has a manifest.json.

  • auto_detect_local – Look for hosted model files and ZIPs automatically (default True).

  • local_models_path – The directory of ZIP archives to import (default "/drive/models").

  • progress_callback – Called with a dict per loading event (model, status, file, loaded, total); the last event has the status "ready" or "error".

  • quiet – Show no progress bar and no loading messages (default False), for an app that has its own.

Returns:

The loaded LLM; call dispose() when you are done.

property backend

"webgpu", "wasm" or "native". After a fallback from WebGPU (see backend_fallback) it is "wasm", and backend_fallback_reason says why.

Type:

The backend that loaded the models

property backend_fallback_reason

Why WebGPU was given up for WASM, or None if it was not.

async dispose()

Release the loaded models and their inference sessions, including GPU resources, without deleting cached model files.

Await any running call first. Calling it again is safe; if a release fails it raises, and the call can be retried. After a successful dispose the object rejects further inference calls; create a new one to load from the cache again. Memory is reclaimed when the browser decides, which may be later.

async export_models()

Save the configured models from the browser cache as zip files in /drive/models.

The files are named model-<namespace>-<model>@<revision>.zip and can be downloaded from JupyterLite. They can be imported again through the local_models_path option of the create() methods.

Tool calling

class lmlite.ToolRunner(model, tools, *, max_steps=5, timeout=None, tool_timeout=None, max_observation=2000)

Run a model that chooses from registered tools until it answers, with a limit on steps and time.

The observation of a tool goes back to the model as a message labelled as data. It is a note to the model, not a guard: a small model can still be misled by a page that contains instructions.

Example

runner = ToolRunner(llm, [Tool("get_time", "The current time.", lambda: "12:00")])
result = await runner.run("What time is it?")
result.answer, result.steps
async run(question)

Ask the model a question and run the tools it chooses, until it answers or a limit is reached.

Cancelling the task that awaits this stops the model’s generation and raises asyncio.CancelledError.

Parameters:

question – What the user asks.

Returns:

An AgentResult. Whatever the end, steps records every reply and what became of it.

class lmlite.Tool(name: str, description: str, func: object, parameters: dict = <factory>)

A function a model may call.

Parameters:
  • name – What the model calls it.

  • description – What it does and when to use it, shown to the model.

  • func – A function or coroutine function taking the arguments as keywords. A plain function that blocks cannot be stopped by a timeout.

  • parameters – A JSON Schema for the arguments, an object with properties and required. Only type (string, integer, number, boolean, array, object), enum, properties, required and items are checked, and once properties is given, a property that is not listed is refused.

lmlite.model_tool(call, name, description, argument='text')

Make a tool from an async function of one string, such as a Pipeline or Embedder.embed.

Parameters:
  • call – A function or coroutine function taking the string.

  • name – What the model calls it.

  • description – What it does and when to use it.

  • argument – The name of the one string argument.

Returns:

A Tool whose argument is required and is passed to call.

class lmlite.AgentResult(answer: str | None, stopped: str, steps: list = <factory>)

How a run ended.

answer

The model’s final answer, or None if it ran out of steps or time.

Type:

str | None

stopped

"answer", "step_limit" or "timeout".

Type:

str

steps

One dict per model reply, for debugging: step, reply (the raw text), outcome ("answer", "ok", "error" for a tool that failed, "invalid" for a reply that was refused, or "timeout" for the step the run’s timeout cut short), tool and arguments when it named a tool, and detail (the observation, or why it failed). An answer given as plain text after a tool ran also has plain_text: True.

Type:

list

Embeddings and classification

class lmlite.Embedder(js_instance, models=None)

Sentence embeddings and similarity search.

Load it with await Embedder.create(model). The vectors come from attention-mask-weighted mean pooling followed by L2 normalisation, so a dot product of two vectors is their cosine similarity.

Example

embedder = await Embedder.create("all-MiniLM-L6-v2", backend="wasm", dtype="q8")
vector = await embedder.embed("Hello world")
await embedder.similarity_search("Where does JupyterLite run?", docs, k=2)
await embedder.dispose()
property backend

The device the embedding model loaded on, "webgpu" or "wasm", or None when Transformers.js chose it. "native" for the onnxruntime backend.

async classmethod create(model, *, backend=None, dtype=None, progress_callback=None, **options)

Load an embedding model.

Parameters:
  • model – A Hugging Face model ID such as "Xenova/all-MiniLM-L6-v2", or a short name, which gets the default Xenova/ namespace.

  • backend – "wasm" or "webgpu", or "native" for the onnxruntime backend outside a browser. None (the default) leaves the device to Transformers.js. With "webgpu", a failure specific to WebGPU is retried once on "wasm" unless backend_fallback=False (see LLM.create()); any other failure is not retried.

  • dtype – Pins the weights, for example "q8", so the vectors are reproducible. There is no fallback to another dtype. None (the default) keeps the Transformers.js default.

  • progress_callback – Called with a dict per loading event, as for LLM.create().

  • **options – The other loading options of LLM.create(): hosted_models_url, auto_detect_local and local_models_path, backend_fallback and quiet (no progress bar and no loading messages).

Returns:

The loaded Embedder; call dispose() when you are done.

async embed(text: str)

The sentence vector of a text.

Parameters:

text – The text to embed.

Returns:

A flat list of floats, normalised to unit length. Its length is the model’s dimension, 384 for MiniLM.

Rank documents by their cosine similarity to a query.

The query and every document are embedded on each call, in memory; nothing is stored between calls.

Parameters:
  • query – The query text.

  • docs – The documents to search, a list of strings.

  • k – How many results to return. By default, all of them.

Returns:

A list of (doc, score) tuples, the most similar first.

property backend_fallback_reason

Why WebGPU was given up for WASM, or None if it was not.

async dispose()

Release the loaded models and their inference sessions, including GPU resources, without deleting cached model files.

Await any running call first. Calling it again is safe; if a release fails it raises, and the call can be retried. After a successful dispose the object rejects further inference calls; create a new one to load from the cache again. Memory is reclaimed when the browser decides, which may be later.

async export_models()

Save the configured models from the browser cache as zip files in /drive/models.

The files are named model-<namespace>-<model>@<revision>.zip and can be downloaded from JupyterLite. They can be imported again through the local_models_path option of the create() methods.

class lmlite.Classifier(js_instance, models=None)

Text classification.

Load it with await Classifier.create(model). The labels are the model’s own: a sentiment model such as distilbert-base-uncased-finetuned-sst-2-english has POSITIVE and NEGATIVE and no neutral class.

Example

classifier = await Classifier.create("distilbert-base-uncased-finetuned-sst-2-english")
await classifier.classify("I love using lmlite in JupyterLite!", top_k=2)
await classifier.dispose()
async classmethod create(model, *, backend='wasm', dtype=None, dtype_fallbacks=None, progress_callback=None, **options)

Load a text classification model.

Parameters:
  • model – A Hugging Face model ID, or a short name, which gets the default Xenova/ namespace.

  • backend – "wasm" (the default) or "webgpu", or "native" for the onnxruntime backend outside a browser.

  • dtype – The weights to load, such as "fp32". By default the first of q8, int8 and fp32 that exists.

  • dtype_fallbacks – Dtypes to try in order; takes precedence over dtype.

  • progress_callback – Called with a dict per loading event, as for LLM.create().

  • **options – The other loading options of LLM.create(): hosted_models_url, auto_detect_local and local_models_path, backend_fallback and quiet (no progress bar and no loading messages).

Returns:

The loaded Classifier; call dispose() when you are done.

async classify(text: str, top_k=None)

Classify a text.

Parameters:
  • text – The text to classify.

  • top_k – How many labels to return. By default, only the best one.

Returns:

A list of {"label": str, "score": float} dicts, the best first.

property backend

"webgpu", "wasm" or "native". After a fallback from WebGPU (see backend_fallback) it is "wasm", and backend_fallback_reason says why.

Type:

The backend that loaded the models

property backend_fallback_reason

Why WebGPU was given up for WASM, or None if it was not.

async dispose()

Release the loaded models and their inference sessions, including GPU resources, without deleting cached model files.

Await any running call first. Calling it again is safe; if a release fails it raises, and the call can be retried. After a successful dispose the object rejects further inference calls; create a new one to load from the cache again. Memory is reclaimed when the browser decides, which may be later.

async export_models()

Save the configured models from the browser cache as zip files in /drive/models.

The files are named model-<namespace>-<model>@<revision>.zip and can be downloaded from JupyterLite. They can be imported again through the local_models_path option of the create() methods.

Task pipelines

class lmlite.Pipeline(llm, task, model)

A loaded Transformers.js task, created with pipeline().

Call it to run the task on one input (await pipe(input, **options)), or use map() for many.

task

The task name, such as "object-detection".

model

The model ID or name that was loaded.

async __call__(inputs, **kwargs)

Run the task on one input, or on a list of inputs for the tasks that take a list.

Parameters:
  • inputs – What the task takes. Text tasks (zero-shot-classification, translation): a string or a list of strings. Audio tasks (automatic-speech-recognition, audio-classification): an HTTP(S) URL, a path to a PCM WAV file, WAV bytes, or mono samples at 16 kHz. Image tasks: encoded image bytes, an HTTP(S) URL, a file path, a NumPy array of shape (H, W, 3) or (H, W, 4), a PIL image, or a list of these. Text to speech: one string.

  • **kwargs – Task options, forwarded to Transformers.js. They must be JSON-serializable, for example candidate_labels, top_k, threshold or max_new_tokens. The image-output tasks also take as_array=True, which returns NumPy pixels instead of PNG bytes.

Returns:

dicts and lists, Speech for text to speech, PNG bytes (or arrays) for the image-output tasks.

Return type:

The task’s result as plain Python objects

Raises:
  • TypeError – A list was given to text to speech, which takes one string (use map()).

  • ValueError – The input cannot be read, for example bytes that are not an image or a WAV file that is not PCM.

async map(inputs, batch_size=8, progress_callback=None, on_error='raise', **kwargs)

Run the task over many inputs, with the loop in JavaScript so a notebook makes one call.

Parameters:
  • inputs – Any iterable of inputs, each in the form the task takes on its own call.

  • batch_size – How many inputs go to each Transformers.js call; 1 runs them one by one. The audio, image-output and text-to-speech tasks always run one input per call.

  • progress_callback – Called as progress_callback(done, total) after each batch.

  • on_error – "raise" raises the first error; "skip" leaves failed inputs out of the results (so the results can be shorter than the inputs); "return" puts an exception object where a failed input’s result would be. A failed batch is retried input by input.

  • **kwargs – Task options, as for a normal call.

Returns:

The results in input order. If cancel() stopped the run, the results of the inputs that ran.

Raises:
  • ValueError – batch_size is not a positive integer, or on_error is not one of the three values.

  • RuntimeError – Another map() is already running on this pipeline.

async cancel()

Stop a running map() after its current batch.

Returns:

False if nothing was running. The pipeline stays usable.

async dispose()

Release the loaded model without deleting its cached files.

Await any running call first. Calling it again is safe.

async export_models()

Save the model from the browser cache as a zip file in /drive/models, ready to download from JupyterLite.

class lmlite.Speech(samples, sampling_rate)

Synthesised speech, returned by the text-to-speech pipelines.

Evaluating a Speech in a notebook cell shows an audio player.

samples

Mono float32 samples: a NumPy array when NumPy is installed, else an array.array("f").

sampling_rate

Samples per second.

Example

tts = await pipeline("text-to-speech", model="Xenova/mms-tts-eng")
speech = await tts("Hello from the browser.")
speech.duration, speech.sampling_rate
open("hello.wav", "wb").write(speech.to_wav())
property duration

Length in seconds.

to_wav()

The speech as a WAV file.

Returns:

The bytes of a 16-bit PCM mono WAV file at sampling_rate.

class lmlite.Tokenizer(js_tokenizer, source)

A loaded tokenizer, created with tokenizer(). It has no model weights.

encode() and decode() are synchronous, so they can be used in plain loops.

source

The model ID or URL it was loaded from.

vocab_size

The number of tokens in the vocabulary.

encode(text, *, add_special_tokens=False)

The token ids of a text.

Parameters:
  • text – The text to encode.

  • add_special_tokens – Add the tokenizer’s special tokens, such as a start or end token. The default is False, unlike in Transformers.js.

Returns:

A list of ints. Nothing is truncated.

Raises:
  • TypeError – text is not a str.

  • RuntimeError – The tokenizer was closed.

decode(ids)

The text of a sequence of token ids, special tokens included.

Parameters:

ids – The token ids.

Returns:

The decoded string.

close()

Release the loaded tokenizer.

Later encode() and decode() calls raise. Calling it again is safe.

class lmlite.ModelInfo(model_id: str, revision: str, task: str, backend: str, dtype: str | None, cache_status: str, download_bytes: int | None, files: list, error: str | None = None)

What a model needs before it loads, returned by model_info(). The values are best effort.

model_id

The resolved model ID, such as "Xenova/gpt2".

Type:

str

revision

The revision the files come from.

Type:

str

task

The task the model will load as, from the task argument or the model’s Hub pipeline tag.

Type:

str

backend

"wasm" or "webgpu".

Type:

str

dtype

The dtype the files are for. When none was asked for, the first of q8, int8 or fp32 that the model publishes; None for embeddings, which keep the Transformers.js default.

Type:

str | None

cache_status

"cached", "partial", "not_cached" or "unknown". It only reflects the Transformers.js Cache API, not hosted files or ZIPs in local_models_path.

Type:

str

download_bytes

The summed file sizes, or None when any size is unknown. It is the download size, not an estimate of the memory the model needs.

Type:

int | None

files

The files the pipeline will fetch, each a dict with name, size (bytes, or None) and cached.

Type:

list

error

Why the information is incomplete, or None.

Type:

str | None

lmlite.SUPPORTED_TASKS

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

Bare ONNX models

class lmlite.OnnxModel(handle, info, licence=None)

A single .onnx file with no Hugging Face repository around it, run with NumPy in and NumPy out.

Load it with await OnnxModel.load(...). You do the pre- and post-processing in NumPy.

inputs

The model’s inputs, a list of dicts with name, dtype and shape; symbolic dimensions stay strings such as "batch".

outputs

The model’s outputs, in the same form.

Example

model = await OnnxModel.load("models/detector.onnx", backend="wasm", licence="Apache-2.0")
outputs = await model.run({"input": blob.astype(np.float32)})
await model.dispose()
async classmethod load(source, backend='wasm', licence=None, sha256=None, cache=True, hosted_models_url=None, backend_fallback=True)

Load a model.

Parameters:
  • source – A file path, a URL, the model’s bytes, or a hosted model ID such as "lmlite/detector" (listed in the site’s manifest.json, or the one at hosted_models_url; it loads <id>/model.onnx).

  • backend – "wasm" (the default) or "webgpu" in a browser kernel; "native", or any backend outside a browser, runs onnxruntime (pip install 'lmlite[native]'). float16 models on WebGPU need an adapter with shader-f16.

  • licence – A free-form string that model_info() returns.

  • sha256 – A hash the model’s bytes must match.

  • cache – In a browser kernel, keep URLs in the Cache API so a later load of the same URL makes no request.

  • hosted_models_url – An explicit URL of a models directory, for hosted IDs.

  • backend_fallback – True (the default) loads on "wasm" when backend="webgpu" but the browser has no WebGPU adapter, or the session cannot be created for a reason specific to WebGPU (an operator or float16 the adapter lacks). The model then runs on WASM, which can be much slower or run out of memory; model_info() reports the backend that ran and the backend_fallback_reason. False fails instead.

Returns:

The loaded OnnxModel.

Raises:
  • ValueError – The bytes do not match sha256.

  • FileNotFoundError – A path does not exist, or a hosted ID is not listed in the manifest.

model_info()

What is known about the loaded model.

Returns:

A dict with the model’s SHA-256 and size, the backend and execution provider, the cache status, the inputs and outputs, and the licence passed to load().

async run(feeds)

Run the model once.

Each call crosses the browser bridge once, with raw buffers: call it once per image rather than with a large batch, since some detectors return about 1 MB of floats per image.

Parameters:

feeds – A dict from input names to NumPy arrays. The dtypes must be the ones the model declares (no silent casts: use astype()), and the shape must fit; dynamic dimensions accept any size.

Returns:

A dict from output names to NumPy arrays.

Raises:
  • ValueError – An input is missing or unknown, or has the wrong rank or size on a fixed axis.

  • TypeError – An input has the wrong dtype.

async map(feeds, progress_callback=None, on_error='raise')

Run the model over many inputs, one run() each.

The loop is in Python, one bridge call per input.

Parameters:
  • feeds – An iterable, or async iterable, of feed dicts. A generator that preprocesses one image at a time keeps the inputs from being in memory together.

  • progress_callback – Called as progress_callback(done, total) after each input; total is None when feeds has no length.

  • on_error – "raise" raises the first error; "skip" leaves a failed input out of the results; "return" puts an exception object where its outputs would be. It covers errors from run(), such as a wrong dtype or shape. An error raised by feeds itself ends the run.

Returns:

The outputs in input order. If cancel() stopped the run, the outputs so far; the model stays usable.

Raises:
  • ValueError – on_error is not one of the three values.

  • RuntimeError – Another map() is already running on this model.

async cancel()

Stop a running map() after its current input.

Returns:

False if nothing was running.

async dispose()

Release the session.

Notebook widgets

class lmlite.audio.AudioRecorder(*args: t.Any, **kwargs: t.Any)

A Record and Stop button that records the microphone of a laptop or tablet, in a notebook.

Install it with pip install 'lmlite[audio]'. The kernel runs in a Web Worker, which cannot open the microphone, so the widget records on the page and hands the kernel the recording. The page must be on HTTPS (or localhost), and the browser asks for permission the first time.

Tick Raw input to turn off the browser’s echo cancellation, noise suppression and gain control, which can silence a recording on some devices. info describes the last recording: seconds, peak (0 to 1; near 0 means silence), channels, sampleRate, mimeType, and raw and gain for a raw recording.

To ask the user for a recording from code, such as a tool an assistant calls, await recorder.request("Tap Record and say your question", max_seconds=10): the widget shows the question with Record and Cancel buttons, and nothing is recorded until the user taps.

Example

recorder = AudioRecorder()
recorder                      # tap Record, speak, tap Stop
wav = await recorder.wait()   # 16 kHz mono 16-bit WAV bytes
text = (await transcriber(wav))["text"]
property audio

The last recording.

Returns:

The bytes of a 16 kHz mono 16-bit WAV file, or b"" if there is none. Speech recognition and audio classification pipelines take it as input.

async wait()

The last recording, waiting for one if there is none yet.

Returns:

The WAV bytes, as audio.

async request(prompt, timeout=None, max_seconds=None)

Ask the user for a new recording and wait for it.

The widget shows prompt with a Record button and a Cancel button. It records nothing until the user taps Record, and the user taps Stop (or max_seconds pass) to end it. Only a recording made for this request resolves it, not one that was already there. A recording under way when the request arrives is dropped. The microphone is released when the request ends, however it ends.

Parameters:
  • prompt – What the user is asked to do, shown in the widget.

  • timeout – Seconds to wait, including the permission prompt and the recording, or None to wait for ever.

  • max_seconds – Stop the recording by itself after this many seconds, or None to wait for the Stop tap.

Returns:

The WAV bytes, as audio.

Raises:
  • CaptureCancelled – The user tapped Cancel.

  • TimeoutError – There was no complete recording within timeout seconds.

  • PermissionError – The browser did not allow the microphone.

  • RuntimeError – The microphone could not start (none found, in use), or a request is already pending.

Example

wav = await recorder.request("Tap Record and say your question", timeout=60, max_seconds=10)
text = (await transcriber(wav))["text"]
clear()

Forget the recording, so that wait() waits for a new one.

class lmlite.camera.CameraCapture(*args: t.Any, **kwargs: t.Any)

Start camera, Take photo and Stop camera buttons for the camera of a laptop, tablet or phone, in a notebook.

Install it with pip install 'lmlite[camera]'. The kernel runs in a Web Worker, which cannot open the camera, so the widget shows it on the page and hands the kernel a photo. The page must be on HTTPS (or localhost), and the browser asks for permission the first time. “Rear camera” is a preference: a device with one camera uses it. info holds the last photo’s width, height and bytes.

To build an app, turn the buttons off and drive the camera from your own: CameraCapture(controls=False, autostart=True, show_photo=False) shows just the live picture and starts it, take() takes the photo, and image or wait() returns it.

To ask the user for a photo from code, such as a tool an assistant calls, await camera.request("Tap to take a photo of the desk"): the widget shows the question with Take photo and Cancel buttons and the live picture, and nothing is captured until the user taps.

Example

camera = CameraCapture()
camera                        # Start camera, aim, Take photo
jpeg = await camera.wait()
detections = await detector(jpeg, threshold=0.6)
property image

The last photo.

Returns:

The bytes of a JPEG file, at most 1024 pixels on the longer side, or b"" if there is none. Any image pipeline takes it as input.

async wait()

The last photo, waiting for one if there is none yet.

Returns:

The JPEG bytes, as image.

async request(prompt, timeout=None)

Ask the user for a new photo and wait for it.

The widget shows prompt with a live picture, a Take photo button and a Cancel button, and starts the camera if it is not running. It takes nothing until the user taps. Only a photo taken for this request resolves it, not one that was already there. The camera the request started is stopped when it ends, however it ends.

Parameters:
  • prompt – What the user is asked to do, shown in the widget.

  • timeout – Seconds to wait, including the permission prompt, or None to wait for ever.

Returns:

The JPEG bytes, as image.

Raises:
  • CaptureCancelled – The user tapped Cancel.

  • TimeoutError – Nobody took a photo within timeout seconds.

  • PermissionError – The browser did not allow the camera.

  • RuntimeError – The camera could not start (none found, in use), or a request is already pending.

Example

try:
    jpeg = await camera.request("Tap to take a photo of the desk", timeout=60)
except CaptureCancelled:
    ...  # the user declined: answer without a photo
clear()

Forget the photo, so that wait() waits for a new one.

exception lmlite.camera.CaptureCancelled

The user dismissed the request with Cancel. A tool can try another route or answer without the media.

class lmlite.widgets.CacheManager

Widget to list, load and delete models in the Transformers.js browser cache.

Display manager.view and await manager.refresh() to fill it. Each line shows a model’s architecture, Hub task and name; clicking the name expands its cached files and sizes. Load downloads a model into the cache and releases it right away. Hosted model files and ZIPs under /drive/models are not listed.

async refresh(action=None)

Read the browser cache and update the list.

Call await manager.refresh() once after displaying manager.view. Load and Delete call it themselves, with the action to run first. A failure is shown in the widget’s status line, not raised.

Parameters:

action – An optional coroutine function that is awaited before the cache is read.