webslm 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -103,6 +103,34 @@ await llm.unload();
103
103
 
104
104
  Each chat keeps its own cache in the engine, so a turn only processes the new message; `chat.dispose()` frees it. Calls on one model, and turns of one chat, run one after the other. `llm.model` is the underlying `Model`, for the advanced API.
105
105
 
106
+ ## Images and video
107
+
108
+ Vision-language models (SmolVLM and SmolVLM2, LFM2-VL and LFM2.5-VL, Qwen3.5) answer about images; SmolVLM2 and Qwen3.5 also about videos. `info().vision` is `{ images, videos }` for them, `undefined` for text-only models.
109
+
110
+ ```ts
111
+ const llm = await load("HuggingFaceTB/SmolVLM2-256M-Video-Instruct");
112
+ await llm.ask("What is in this picture?", { images: [imageElement] });
113
+ await llm.ask("What happens here?", { video: videoElement, media: { fps: 1, maxFrames: 16 } });
114
+
115
+ const chat = llm.chat();
116
+ await chat.send("Describe this chart.", { images: [file] });
117
+ await chat.send("Which bar is the tallest?"); // the image stays in the history
118
+ chat.history[0]; // { role: "user", content: "Describe this chart.", media: [{ type: "image", image: file }] }
119
+
120
+ // Messages carry images and videos in `media`, before their text:
121
+ model.chat([{ role: "user", content: "What is this?", media: [{ type: "image", image: "https://example.com/cat.jpg" }] }]);
122
+ // or interleave them with text in `content` (a `MultimodalMessage`, taken by `chat`, `generate` and `renderChat`):
123
+ model.chat([{ role: "user", content: [{ type: "text", text: "Compare" }, { type: "image", image: a }, { type: "text", text: "and" }, { type: "image", image: b }] }]);
124
+ ```
125
+
126
+ A `ChatMessage`'s `content` is always a string, so code that renders `message.content` (from `chat.history` or `useChat`) keeps working; its images and videos are in the optional `media` (`MediaPart[]`).
127
+
128
+ - **Images** (`ImageInput`): a URL (`data:`, `blob:`, `http(s):`), bytes (`Uint8Array`, `ArrayBuffer`) or a `Blob` of a PNG, JPEG, WebP or GIF file, an `ImageBitmap`, `ImageData`, an `<img>`, `<canvas>` or `<video>` element (its current frame), an `OffscreenCanvas`, or raw pixels `{ data, width, height, channels? }` (`channels` 1, 3 or 4, default 4). Files are decoded with `createImageBitmap` where it exists (browsers, workers); in Node the native engine decodes them, and on WebAssembly without `createImageBitmap` pass pixels. Transparent pixels are composited on white, as `transformers` does.
129
+ - **Videos** (`VideoInput`): a `<video>` element, a URL or a `Blob`, sampled by seeking a `<video>` element (browsers), or frames you sampled yourself, `{ frames, fps }` or `{ frames, timestamps, duration }`, anywhere.
130
+ - **`media`** (`MediaOptions`, in the generation options): `fps` (frames sampled per second of video, default 2; each model's processor then keeps what it keeps), `maxFrames` (default 32), `longestEdge` (SmolVLM's image size: smaller gives fewer tiles and tokens) and `processor` (keys of the checkpoint's `preprocessor_config.json`, e.g. `{ max_image_tokens: 64 }` for LFM2-VL).
131
+
132
+ Images and videos sent to a text-only model are an `INVALID_ARGUMENT` error. The load option `vision: false` loads a vision-language checkpoint as a text-only model, without the memory of its vision encoder (100M parameters for Qwen3.5-0.8B). Memory estimates (`fitModel`, `quant: "auto"`) count the encoder unless `vision: false`. The prefix cache tells images apart by their pixels, so a follow-up about the same image only runs the new tokens.
133
+
106
134
  ## React
107
135
 
108
136
  ```tsx
@@ -160,7 +188,7 @@ await model.unload(); // or webslm.unloadAll()
160
188
  | `tools` with `toolChoice` forcing one function tool (`{ type: "tool" }`, or `"required"` with a single tool) | the tool's input, constrained to its schema, comes back as a tool call (`finishReason: "tool-calls"`), so `generateText` runs the tool |
161
189
  | other `tools` (`"auto"`, several tools, a schema the engine cannot enforce) | an `unsupported` warning, the model answers with text; `toolChoice: "none"` ignores them |
162
190
 
163
- Prompts are text: user and assistant text parts, and text documents (`file` parts whose data is text). Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
191
+ Prompts are user and assistant text parts, text documents (`file` parts whose data is text), and images and videos for [vision-language models](#images-and-video): `file` parts of type `image/*` or `video/*` whose data is bytes, base64 or a URL. Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
164
192
 
165
193
  `CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, with the sampling their model cards recommend, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
166
194
 
@@ -430,7 +458,7 @@ export default defineConfig({
430
458
  });
431
459
  ```
432
460
 
433
- Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.5.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
461
+ Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.6.0/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
434
462
 
435
463
  ## Errors
436
464
 
@@ -55,7 +55,10 @@ export declare class WebslmLanguageModel implements LanguageModelV4 {
55
55
  readonly specificationVersion = "v4";
56
56
  readonly provider = "webslm";
57
57
  readonly modelId: string;
58
- /** Text-only models: no URL is read by the model itself. */
58
+ /**
59
+ * No URL is read by the model itself: the AI SDK downloads image and
60
+ * video URLs and passes their bytes (vision-language models).
61
+ */
59
62
  readonly supportedUrls: Record<string, RegExp[]>;
60
63
  /** @internal Created by a provider: `webslm(modelId)` or `createWebslm(...)(modelId)`. */
61
64
  constructor(modelId: string, slot: ModelSlot, settings: WebslmModelSettings);
@@ -3,7 +3,7 @@ import { toWebslmError } from "../errors.js";
3
3
  import { DEFAULT_TEMPERATURE, ReasoningSplitter } from "../simple.js";
4
4
  import { abortReason, raceAbort } from "./loader.js";
5
5
  import { prepareOutput, thinkingBudgetOf, toolCallId } from "./output.js";
6
- import { convertPrompt, promptText } from "./prompt.js";
6
+ import { contentText, convertPrompt, promptText } from "./prompt.js";
7
7
  const PROVIDER = "webslm";
8
8
  /** The fields of {@link WebslmCallSettings}: the settings that are not load options. */
9
9
  export const CALL_SETTING_KEYS = [
@@ -61,7 +61,7 @@ function thinkOf(options, settings) {
61
61
  function withSystem(messages, instruction) {
62
62
  const first = messages[0];
63
63
  if (first?.role === "system") {
64
- return [{ role: "system", content: `${first.content}\n\n${instruction}` }, ...messages.slice(1)];
64
+ return [{ role: "system", content: `${contentText(first.content)}\n\n${instruction}` }, ...messages.slice(1)];
65
65
  }
66
66
  return [{ role: "system", content: instruction }, ...messages];
67
67
  }
@@ -185,7 +185,10 @@ export class WebslmLanguageModel {
185
185
  specificationVersion = "v4";
186
186
  provider = PROVIDER;
187
187
  modelId;
188
- /** Text-only models: no URL is read by the model itself. */
188
+ /**
189
+ * No URL is read by the model itself: the AI SDK downloads image and
190
+ * video URLs and passes their bytes (vision-language models).
191
+ */
189
192
  supportedUrls = {};
190
193
  #slot;
191
194
  #settings;
@@ -1,11 +1,13 @@
1
1
  /** Turns an AI SDK prompt into the chat messages a chat template renders. */
2
2
  import type { LanguageModelV4Prompt, SharedV4Warning } from "@ai-sdk/provider";
3
- import type { ChatMessage } from "../types.js";
3
+ import type { ChatInputMessage } from "../types.js";
4
4
  /** The chat messages of a prompt, and what could only be approximated. */
5
5
  export interface ConvertedPrompt {
6
- readonly messages: ChatMessage[];
6
+ readonly messages: ChatInputMessage[];
7
7
  readonly warnings: SharedV4Warning[];
8
8
  }
9
+ /** The text of message content (image and video parts left out). */
10
+ export declare function contentText(content: ChatInputMessage["content"]): string;
9
11
  /**
10
12
  * Converts the prompt. Consecutive messages of one role are merged (some
11
13
  * templates require alternating turns). Reasoning of earlier answers is
@@ -18,4 +20,4 @@ export declare function convertPrompt(prompt: LanguageModelV4Prompt): ConvertedP
18
20
  * A prompt as plain text, for checkpoints without a chat template (base
19
21
  * models complete text): the contents one after the other.
20
22
  */
21
- export declare function promptText(messages: readonly ChatMessage[]): string;
23
+ export declare function promptText(messages: readonly ChatInputMessage[]): string;
@@ -4,7 +4,46 @@ import { WebslmError } from "../errors.js";
4
4
  function fileText(part) {
5
5
  if (part.data.type === "text")
6
6
  return part.data.text;
7
- throw new WebslmError("INVALID_ARGUMENT", `webslm runs text-only models: file parts (${part.mediaType}) are not supported`);
7
+ throw new WebslmError("INVALID_ARGUMENT", `file parts of type ${part.mediaType} are not supported (text documents are, and images and videos for vision-language models)`);
8
+ }
9
+ function base64Bytes(data) {
10
+ const binary = atob(data);
11
+ const bytes = new Uint8Array(binary.length);
12
+ for (let i = 0; i < binary.length; i += 1)
13
+ bytes[i] = binary.charCodeAt(i);
14
+ return bytes;
15
+ }
16
+ /**
17
+ * A file part as message content: an image or a video for vision-language
18
+ * models (`image/*`, `video/*`), else its inline text.
19
+ */
20
+ function filePart(part) {
21
+ const kind = part.mediaType.split("/")[0];
22
+ if ((kind === "image" || kind === "video") && part.data.type !== "text") {
23
+ let source;
24
+ switch (part.data.type) {
25
+ case "data":
26
+ source = typeof part.data.data === "string" ? base64Bytes(part.data.data) : part.data.data;
27
+ break;
28
+ case "url":
29
+ source = part.data.url;
30
+ break;
31
+ default:
32
+ throw new WebslmError("INVALID_ARGUMENT", "provider file references are not supported");
33
+ }
34
+ if (kind === "image")
35
+ return { type: "image", image: source };
36
+ // Videos are sampled from a URL or a Blob (in browsers).
37
+ const video = source instanceof URL ? source : new Blob([source], { type: part.mediaType });
38
+ return { type: "video", video };
39
+ }
40
+ return { type: "text", text: fileText(part) };
41
+ }
42
+ /** The text of message content (image and video parts left out). */
43
+ export function contentText(content) {
44
+ if (typeof content === "string")
45
+ return content;
46
+ return content.map((p) => (p.type === "text" ? p.text : "")).join("");
8
47
  }
9
48
  function toolOutputText(output) {
10
49
  switch (output.type) {
@@ -40,10 +79,13 @@ export function convertPrompt(prompt) {
40
79
  const push = (role, content) => {
41
80
  const last = messages.at(-1);
42
81
  if (last !== undefined && last.role === role && role !== "system") {
43
- messages[messages.length - 1] = { role, content: `${last.content}\n\n${content}` };
82
+ const merged = typeof last.content === "string" && typeof content === "string"
83
+ ? `${last.content}\n\n${content}`
84
+ : [...asParts(last.content), { type: "text", text: "\n\n" }, ...asParts(content)];
85
+ messages[messages.length - 1] = message(role, merged);
44
86
  }
45
87
  else {
46
- messages.push({ role, content });
88
+ messages.push(message(role, content));
47
89
  }
48
90
  };
49
91
  for (const message of prompt) {
@@ -52,7 +94,11 @@ export function convertPrompt(prompt) {
52
94
  push("system", message.content);
53
95
  break;
54
96
  case "user":
55
- push("user", message.content.map((part) => (part.type === "text" ? part.text : fileText(part))).join(""));
97
+ {
98
+ const parts = message.content.map((part) => (part.type === "text" ? { type: "text", text: part.text } : filePart(part)));
99
+ // Text-only content stays a string.
100
+ push("user", parts.every((p) => p.type === "text") ? parts.map((p) => p.text).join("") : parts);
101
+ }
56
102
  break;
57
103
  case "assistant": {
58
104
  let text = "";
@@ -107,5 +153,11 @@ export function convertPrompt(prompt) {
107
153
  * models complete text): the contents one after the other.
108
154
  */
109
155
  export function promptText(messages) {
110
- return messages.map((m) => m.content).join("\n\n");
156
+ return messages.map((m) => contentText(m.content)).join("\n\n");
157
+ }
158
+ function message(role, content) {
159
+ return typeof content === "string" ? { role, content } : { role, content };
160
+ }
161
+ function asParts(content) {
162
+ return typeof content === "string" ? [{ type: "text", text: content }] : content;
111
163
  }
package/dist/client.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { WebslmError } from "./errors.js";
6
6
  import type { Request, Response } from "./protocol.js";
7
7
  import type { FetchFile, LoadProgress } from "./types.js";
8
- type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
8
+ export type RequestBody = Request extends infer R ? (R extends Request ? Omit<R, "id"> : never) : never;
9
9
  /** A bidirectional message channel to an engine. */
10
10
  export interface Channel {
11
11
  post(message: Request, transfer?: Transferable[]): void;
@@ -58,4 +58,3 @@ export declare class EngineClient {
58
58
  export declare function browserWorkerChannel(): (handlers: ChannelHandlers) => Channel;
59
59
  /** @internal Appended to errors of a Node worker that fails to start. */
60
60
  export declare const NODE_WORKER_HINT: string;
61
- export {};
package/dist/curated.js CHANGED
@@ -7,6 +7,7 @@ const LFM2 = SETS["lfm2"];
7
7
  const LFM3 = SETS["lfm3"];
8
8
  const QWEN3 = SETS["qwen3"];
9
9
  const QWEN3_5 = SETS["qwen3_5"];
10
+ const LFM2_VL = SETS["lfm2_vl"];
10
11
  /**
11
12
  * Checkpoints validated against `transformers`, smallest first: the first
12
13
  * ones are quick on a laptop CPU, the largest (LFM3 1.7B) wants WebGPU. Any supported repository works too: see
@@ -40,6 +41,14 @@ export const CURATED_MODELS = [
40
41
  note: "Best small model here; follows a conversation well.",
41
42
  sampling: LFM2,
42
43
  },
44
+ {
45
+ repo: "LiquidAI/LFM2.5-VL-450M",
46
+ name: "LFM2.5-VL 450M",
47
+ params: "450M",
48
+ sizeBytes: 897_484_568,
49
+ note: "Sees images: attach a picture and ask about it.",
50
+ sampling: LFM2_VL,
51
+ },
43
52
  {
44
53
  repo: "Qwen/Qwen3-0.6B",
45
54
  name: "Qwen3 0.6B",
package/dist/engine.js CHANGED
@@ -277,7 +277,9 @@ export class Engine {
277
277
  };
278
278
  const options = JSON.stringify(request.options);
279
279
  const summary = (await (request.type === "chat"
280
- ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
280
+ ? request.media === undefined
281
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill)
282
+ : target.chatWithMedia(JSON.stringify(request.messages), options, request.media.meta, request.media.data, onDelta, onPrefill)
281
283
  : target.generate(request.prompt, options, onDelta, onPrefill)));
282
284
  return withTimings(summary, started, first, last);
283
285
  }
@@ -326,7 +328,9 @@ export class Engine {
326
328
  const options = JSON.stringify(request.options);
327
329
  try {
328
330
  const summary = (await (request.type === "chat"
329
- ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill, cancel)
331
+ ? request.media === undefined
332
+ ? target.chat(JSON.stringify(request.messages), options, onDelta, onPrefill, cancel)
333
+ : target.chatWithMedia(JSON.stringify(request.messages), options, request.media.meta, request.media.data, onDelta, onPrefill, cancel)
330
334
  : target.generate(request.prompt, options, onDelta, onPrefill, cancel)));
331
335
  expected = summary.tokens.length;
332
336
  if (received < expected)
@@ -547,6 +551,7 @@ export class Engine {
547
551
  device: options.device ?? "auto",
548
552
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
549
553
  ...(options.deterministic === true ? { deterministic: true } : {}),
554
+ ...(options.vision === false ? { vision: false } : {}),
550
555
  ...(options.activations === undefined ? {} : { activations: options.activations }),
551
556
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
552
557
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
@@ -659,6 +664,7 @@ export class Engine {
659
664
  device: options.device ?? "auto",
660
665
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
661
666
  ...(options.deterministic === true ? { deterministic: true } : {}),
667
+ ...(options.vision === false ? { vision: false } : {}),
662
668
  ...(options.activations === undefined ? {} : { activations: options.activations }),
663
669
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
664
670
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
package/dist/fit.d.ts CHANGED
@@ -166,7 +166,7 @@ export interface CheckpointShapes {
166
166
  /** Reads `config.json` and the safetensors headers (no weights) through `read`. */
167
167
  export declare function readCheckpointShapes(read: CheckpointReader): Promise<CheckpointShapes>;
168
168
  /** What `quant: "auto"` picks for a checkpoint, and why when it is not Q8_0. */
169
- export declare function autoQuant(shapes: CheckpointShapes, resources: BrowserResources, contextLength?: number): {
169
+ export declare function autoQuant(shapes: CheckpointShapes, resources: BrowserResources, contextLength?: number, vision?: boolean): {
170
170
  readonly quant: Quant;
171
171
  readonly note?: string;
172
172
  };
package/dist/fit.js CHANGED
@@ -271,10 +271,11 @@ export async function readCheckpointShapes(read) {
271
271
  return { config, tensors, params };
272
272
  }
273
273
  /** What `quant: "auto"` picks for a checkpoint, and why when it is not Q8_0. */
274
- export function autoQuant(shapes, resources, contextLength) {
274
+ export function autoQuant(shapes, resources, contextLength, vision) {
275
275
  const estimates = AUTO_QUANTS.map((quant) => estimateModelMemory(shapes.config, shapes.tensors, {
276
276
  quant,
277
277
  ...(contextLength === undefined ? {} : { contextLength }),
278
+ ...(vision === undefined ? {} : { vision }),
278
279
  }));
279
280
  const all = deviceLimits(resources);
280
281
  const devices = shapes.params > AUTO_GPU_MIN_PARAMS ? all : all.filter((d) => d.device === "cpu");
package/dist/hub.js CHANGED
@@ -20,6 +20,9 @@ export const SUPPORTED_MODEL_TYPES = [
20
20
  "lfm3",
21
21
  "qwen3_5",
22
22
  "qwen3_5_text",
23
+ "idefics3",
24
+ "smolvlm",
25
+ "lfm2_vl",
23
26
  ];
24
27
  /** Files read besides the weights, when the repository has them. */
25
28
  export const CHECKPOINT_SIDE_FILES = [
@@ -30,6 +33,10 @@ export const CHECKPOINT_SIDE_FILES = [
30
33
  "special_tokens_map.json",
31
34
  "chat_template.jinja",
32
35
  "chat_template.json",
36
+ // Vision-language models: the image and video processors' settings.
37
+ "preprocessor_config.json",
38
+ "processor_config.json",
39
+ "video_preprocessor_config.json",
33
40
  ];
34
41
  export const SAFETENSORS_INDEX = "model.safetensors.index.json";
35
42
  export const SAFETENSORS_SINGLE = "model.safetensors";
package/dist/index.d.ts CHANGED
@@ -18,7 +18,7 @@ import type { SafetensorsHeader } from "./safetensors.js";
18
18
  export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, type Answer, type AskOptions, type Chat, type ChatOptions, type ChatTurnOptions, type LLM, type PromptOptions, type SharedAskOptions, type SharedStreamOptions, type TextStream, } from "./simple.js";
19
19
  export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
20
20
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
21
- export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
21
+ export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatInputMessage, ChatMessage, ChatStream, ContentPart, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, ImageInput, MediaOptions, MediaPart, MultimodalMessage, RawImage, VideoFrames, VideoInput, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
22
22
  export { WebslmError, type WebslmErrorCode } from "./errors.js";
23
23
  export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
24
24
  export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Images and videos of a conversation, turned into what the engine reads:
3
+ * the messages with their image and video parts reduced to placeholders
4
+ * (`{ type: "image" }`, `{ type: "video" }`), a JSON description of each
5
+ * image or video, and one buffer holding their pixels (or image files)
6
+ * back to back (see `webslm_bindings::media` in Rust).
7
+ *
8
+ * This runs where the caller's objects live (the page's main thread for an
9
+ * `HTMLVideoElement`): images are decoded with `createImageBitmap` and a
10
+ * canvas when the environment has them, and videos sampled by seeking a
11
+ * `<video>` element. In Node, image files go to the native engine as they
12
+ * are, which decodes PNG, JPEG, WebP and GIF; pass pixels
13
+ * (`{ data, width, height }`) to the WebAssembly engine.
14
+ */
15
+ import type { WireMedia, WireMessage } from "./protocol.js";
16
+ import type { ChatInputMessage, ContentPart, MediaOptions, MediaPart } from "./types.js";
17
+ /** One image or video, described for the engine. */
18
+ export type WireMediaEntry = {
19
+ readonly kind: "image";
20
+ readonly encoding: "rgba";
21
+ readonly width: number;
22
+ readonly height: number;
23
+ readonly byteLength: number;
24
+ } | {
25
+ readonly kind: "image";
26
+ readonly encoding: "file";
27
+ readonly byteLength: number;
28
+ } | {
29
+ readonly kind: "video";
30
+ readonly encoding: "rgba";
31
+ readonly width: number;
32
+ readonly height: number;
33
+ readonly timestamps: readonly number[];
34
+ readonly duration?: number;
35
+ readonly byteLength: number;
36
+ } | {
37
+ readonly kind: "video";
38
+ readonly encoding: "file";
39
+ readonly frameByteLengths: readonly number[];
40
+ readonly timestamps: readonly number[];
41
+ readonly duration?: number;
42
+ readonly byteLength: number;
43
+ };
44
+ /** Video frames sampled per second when the caller sets no `media.fps`. */
45
+ export declare const DEFAULT_VIDEO_FPS = 2;
46
+ /** Most frames sampled from a video when the caller sets no `media.maxFrames`. */
47
+ export declare const DEFAULT_VIDEO_MAX_FRAMES = 32;
48
+ /**
49
+ * Longest side of the frames captured from a video: the processors scale
50
+ * frames down further (SmolVLM to 512 pixels), and full-size frames would
51
+ * take hundreds of megabytes.
52
+ */
53
+ export declare const VIDEO_CAPTURE_EDGE = 768;
54
+ /** The parts of a message: its media then its text, or its content parts. */
55
+ export declare function messageParts(message: ChatInputMessage): readonly ContentPart[];
56
+ /** Whether a message holds images or videos. */
57
+ export declare function hasMedia(messages: readonly ChatInputMessage[]): boolean;
58
+ /**
59
+ * Checks a message and returns its wire form, with the images and videos
60
+ * of its parts appended to `media` in order.
61
+ */
62
+ export declare function wireMessage(message: ChatInputMessage, media: MediaPart[]): WireMessage;
63
+ /**
64
+ * The wire form of a conversation and its images and videos (`media` is
65
+ * `undefined` without any).
66
+ */
67
+ export declare function prepareMessages(messages: readonly ChatInputMessage[], options?: MediaOptions): Promise<{
68
+ messages: WireMessage[];
69
+ media?: WireMedia;
70
+ }>;
71
+ /** Sampling times of a `duration`-second video: `fps` per second, at most `maxFrames`, evenly spread. */
72
+ export declare function sampleTimes(duration: number, fps: number, maxFrames: number): number[];