webslm 0.4.1 → 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.
Files changed (43) hide show
  1. package/README.md +35 -5
  2. package/dist/ai-sdk/language-model.d.ts +4 -1
  3. package/dist/ai-sdk/language-model.js +6 -3
  4. package/dist/ai-sdk/prompt.d.ts +5 -3
  5. package/dist/ai-sdk/prompt.js +57 -5
  6. package/dist/cache/models.d.ts +4 -3
  7. package/dist/cache/models.js +25 -12
  8. package/dist/client.d.ts +1 -2
  9. package/dist/curated.js +9 -0
  10. package/dist/download.d.ts +5 -0
  11. package/dist/download.js +11 -6
  12. package/dist/engine.js +50 -14
  13. package/dist/fit.d.ts +1 -1
  14. package/dist/fit.js +2 -1
  15. package/dist/hub.d.ts +22 -2
  16. package/dist/hub.js +60 -5
  17. package/dist/index.d.ts +1 -1
  18. package/dist/media.d.ts +72 -0
  19. package/dist/media.js +358 -0
  20. package/dist/memory.d.ts +5 -0
  21. package/dist/memory.js +47 -6
  22. package/dist/models.d.ts +13 -4
  23. package/dist/models.js +112 -20
  24. package/dist/native.d.ts +3 -0
  25. package/dist/protocol.d.ts +32 -1
  26. package/dist/recommended-sampling.js +6 -1
  27. package/dist/simple.d.ts +11 -2
  28. package/dist/simple.js +17 -8
  29. package/dist/types.d.ts +109 -2
  30. package/native-manifest.json +29 -29
  31. package/package.json +1 -1
  32. package/wasm/relaxed/webslm_wasm.d.ts +29 -4
  33. package/wasm/relaxed/webslm_wasm.js +75 -16
  34. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  35. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
  36. package/wasm/simd/webslm_wasm.d.ts +29 -4
  37. package/wasm/simd/webslm_wasm.js +75 -16
  38. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  39. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
  40. package/wasm/threads/webslm_wasm.d.ts +30 -5
  41. package/wasm/threads/webslm_wasm.js +80 -21
  42. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  43. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +6 -4
package/dist/models.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
2
  import { EngineClient } from "./client.js";
3
3
  import { type CheckpointTraits } from "./curated.js";
4
- import type { AdapterSource, Backend, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
4
+ import type { AdapterSource, Backend, ApplyAdapterOptions, ChatInputMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
5
5
  /**
6
6
  * An engine (a worker, or the calling thread) that several models can share
7
7
  * (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
@@ -48,15 +48,20 @@ export type NormalizedSource = {
48
48
  readonly repo: string;
49
49
  readonly revision?: string;
50
50
  readonly hubUrl?: string;
51
+ readonly file?: string;
51
52
  } | {
52
53
  readonly kind: "files";
53
54
  readonly files: NonNullable<Extract<ModelSource, {
54
55
  files: unknown;
55
56
  }>["files"]>;
57
+ readonly file?: string;
56
58
  } | {
57
59
  readonly kind: "fetch";
58
60
  readonly fetch: FetchFile;
61
+ readonly file?: string;
59
62
  };
63
+ /** Whether a normalized source loads a GGUF file (named, or the only weights of `files`). */
64
+ export declare function isGgufSource(source: NormalizedSource): boolean;
60
65
  /** Checks a source and turns a repository id string into a hub source. */
61
66
  export declare function normalizeSource(source: string | ModelSource, revision?: string): NormalizedSource;
62
67
  /**
@@ -107,6 +112,8 @@ declare abstract class Conversation {
107
112
  protected abstract readonly hasChatTemplate: boolean;
108
113
  /** What picks the model's recommended sampling. */
109
114
  protected abstract readonly checkpoint: CheckpointTraits;
115
+ /** The images and videos the model takes (`undefined`: text only). */
116
+ protected abstract readonly vision: ModelInfo["vision"];
110
117
  protected abstract onLength(length: number): void;
111
118
  constructor(client: EngineClient, modelId: number);
112
119
  /**
@@ -114,14 +121,14 @@ declare abstract class Conversation {
114
121
  * the session's cache are not recomputed. Stopping (`stop()`, `break`, or
115
122
  * the signal) ends the stream normally with `finishReason: "aborted"`.
116
123
  */
117
- chat(messages: readonly ChatMessage[], options?: GenerateOptions): ChatStream;
124
+ chat(messages: readonly ChatInputMessage[], options?: GenerateOptions): ChatStream;
118
125
  /**
119
126
  * Generates a whole answer. A string prompt is sent as a user message when
120
127
  * the checkpoint has a chat template (pass `raw: true` to complete it as
121
128
  * plain text); an array is a conversation. Rejects with `ABORTED` when the
122
129
  * signal fires.
123
130
  */
124
- generate(prompt: string | readonly ChatMessage[], options?: CompletionOptions): Promise<string>;
131
+ generate(prompt: string | readonly ChatInputMessage[], options?: CompletionOptions): Promise<string>;
125
132
  /** Encodes text into token ids. */
126
133
  tokenize(text: string, options?: {
127
134
  addSpecialTokens?: boolean;
@@ -135,7 +142,7 @@ declare abstract class Conversation {
135
142
  * a new assistant turn. `templateKwargs` are passed to the template (e.g.
136
143
  * `{ enable_thinking: false }`).
137
144
  */
138
- renderChat(messages: readonly ChatMessage[], templateKwargs?: Readonly<Record<string, unknown>>): Promise<string>;
145
+ renderChat(messages: readonly ChatInputMessage[], templateKwargs?: Readonly<Record<string, unknown>>): Promise<string>;
139
146
  }
140
147
  /** A loaded model. Its own `chat`/`generate` use a default session. */
141
148
  export declare class Model extends Conversation {
@@ -152,6 +159,7 @@ export declare class Model extends Conversation {
152
159
  }, ownsEngine?: boolean);
153
160
  protected get hasChatTemplate(): boolean;
154
161
  protected get checkpoint(): CheckpointTraits;
162
+ protected get vision(): ModelInfo["vision"];
155
163
  protected onLength(): void;
156
164
  /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
157
165
  info(): ModelInfo;
@@ -205,6 +213,7 @@ export declare class Session extends Conversation {
205
213
  constructor(client: EngineClient, modelId: number, sessionId: number, info: ModelInfo, onDispose: () => void);
206
214
  protected get hasChatTemplate(): boolean;
207
215
  protected get checkpoint(): CheckpointTraits;
216
+ protected get vision(): ModelInfo["vision"];
208
217
  protected onLength(length: number): void;
209
218
  /** Positions in the cache (as of the last completed call). */
210
219
  get length(): number;
package/dist/models.js CHANGED
@@ -4,7 +4,8 @@ import { EngineClient } from "./client.js";
4
4
  import { recommendedSampling } from "./curated.js";
5
5
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
6
6
  import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
7
- import { checkModel } from "./hub.js";
7
+ import { checkModel, isGgufFile } from "./hub.js";
8
+ import { messageParts, prepareMessages, wireMessage } from "./media.js";
8
9
  import { isNode } from "./runtime.js";
9
10
  const QUANTS = ["q8", "q4", "f32"];
10
11
  const ADAPTER_MODES = ["unmerged", "merged"];
@@ -77,6 +78,24 @@ export function resolveBackend(backend, env = globalThis.process?.env) {
77
78
  }
78
79
  return value;
79
80
  }
81
+ /** Checks the `file` of a source: a GGUF file name. */
82
+ function checkGgufName(file) {
83
+ if (file === undefined)
84
+ return undefined;
85
+ if (typeof file !== "string" || !isGgufFile(file.trim())) {
86
+ throw new WebslmError("INVALID_ARGUMENT", "`file` must name a .gguf file");
87
+ }
88
+ return file.trim();
89
+ }
90
+ /** Whether a normalized source loads a GGUF file (named, or the only weights of `files`). */
91
+ export function isGgufSource(source) {
92
+ if (source.file !== undefined)
93
+ return true;
94
+ if (source.kind !== "files")
95
+ return false;
96
+ const names = Object.keys(source.files);
97
+ return names.some(isGgufFile) && !names.some((n) => n.endsWith(".safetensors"));
98
+ }
80
99
  /** Checks a source and turns a repository id string into a hub source. */
81
100
  export function normalizeSource(source, revision) {
82
101
  if (typeof source === "string") {
@@ -92,6 +111,8 @@ export function normalizeSource(source, revision) {
92
111
  if (keys.length !== 1) {
93
112
  throw new WebslmError("INVALID_ARGUMENT", "a model source must have exactly one of `hub`, `files` or `fetch`");
94
113
  }
114
+ const file = checkGgufName(source.file);
115
+ const withFile = file === undefined ? {} : { file };
95
116
  if ("hub" in source) {
96
117
  if (typeof source.hub !== "string" || source.hub.trim() === "") {
97
118
  throw new WebslmError("INVALID_ARGUMENT", "`hub` must be a repository id");
@@ -102,6 +123,7 @@ export function normalizeSource(source, revision) {
102
123
  repo: source.hub.trim(),
103
124
  ...(rev === undefined ? {} : { revision: rev }),
104
125
  ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
126
+ ...withFile,
105
127
  };
106
128
  }
107
129
  if ("files" in source) {
@@ -114,15 +136,19 @@ export function normalizeSource(source, revision) {
114
136
  throw new WebslmError("INVALID_ARGUMENT", `file "${name}" must be a Blob, an ArrayBuffer or a Uint8Array`);
115
137
  }
116
138
  }
117
- if (!("config.json" in files)) {
118
- throw new WebslmError("INVALID_ARGUMENT", "`files` must include config.json");
139
+ if (file !== undefined && !(file in files)) {
140
+ throw new WebslmError("INVALID_ARGUMENT", `\`files\` has no "${file}"`);
119
141
  }
120
- return { kind: "files", files };
142
+ // A GGUF file carries its configuration.
143
+ if (!("config.json" in files) && !Object.keys(files).some(isGgufFile)) {
144
+ throw new WebslmError("INVALID_ARGUMENT", "`files` must include config.json or a .gguf file");
145
+ }
146
+ return { kind: "files", files, ...withFile };
121
147
  }
122
148
  if (typeof source.fetch !== "function") {
123
149
  throw new WebslmError("INVALID_ARGUMENT", "`fetch` must be a function");
124
150
  }
125
- return { kind: "fetch", fetch: source.fetch };
151
+ return { kind: "fetch", fetch: source.fetch, ...withFile };
126
152
  }
127
153
  /**
128
154
  * Checks a LoRA adapter source: like {@link normalizeSource}, but `files`
@@ -154,11 +180,12 @@ function toWire(normalized, token) {
154
180
  ...(normalized.revision === undefined ? {} : { revision: normalized.revision }),
155
181
  ...(normalized.hubUrl === undefined ? {} : { hubUrl: normalized.hubUrl }),
156
182
  ...(token === undefined ? {} : { token }),
183
+ ...(normalized.file === undefined ? {} : { file: normalized.file }),
157
184
  };
158
185
  case "files":
159
- return { kind: "files", files: normalized.files };
186
+ return { kind: "files", files: normalized.files, ...(normalized.file === undefined ? {} : { file: normalized.file }) };
160
187
  case "fetch":
161
- return { kind: "fetch" };
188
+ return { kind: "fetch", ...(normalized.file === undefined ? {} : { file: normalized.file }) };
162
189
  }
163
190
  }
164
191
  function checkScale(scale) {
@@ -193,11 +220,13 @@ function requestPersistentStorage() {
193
220
  export async function loadModel(source, options = {}) {
194
221
  const device = resolveDevice(options.device);
195
222
  const backend = resolveBackend(options.backend);
196
- const requested = options.quant ?? "q8";
223
+ const normalized = normalizeSource(source, options.revision);
224
+ // A GGUF file loads in its own format unless told otherwise.
225
+ const gguf = isGgufSource(normalized);
226
+ const requested = options.quant ?? (gguf ? "auto" : "q8");
197
227
  if (requested !== "auto" && !QUANTS.includes(requested)) {
198
228
  throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
199
229
  }
200
- const normalized = normalizeSource(source, options.revision);
201
230
  const adapter = options.adapter === undefined ? undefined : normalizeAdapterSource(options.adapter);
202
231
  checkScale(options.adapterScale);
203
232
  if (options.adapterMode !== undefined && !ADAPTER_MODES.includes(options.adapterMode)) {
@@ -207,7 +236,12 @@ export async function loadModel(source, options = {}) {
207
236
  throw abortError(options.signal);
208
237
  if (normalized.kind === "hub" && !isNode())
209
238
  requestPersistentStorage();
210
- const { quant, note: quantNote } = requested === "auto" ? await resolveAutoQuant(normalized, options) : { quant: requested, note: undefined };
239
+ // `auto` on a GGUF file: the engine keeps the file's own format.
240
+ const { quant, note: quantNote } = requested !== "auto"
241
+ ? { quant: requested, note: undefined }
242
+ : gguf
243
+ ? { quant: "auto", note: undefined }
244
+ : await resolveAutoQuant(normalized, options);
211
245
  const shared = options.engine;
212
246
  if (shared !== undefined && !(shared instanceof EngineHandle)) {
213
247
  throw new WebslmError("INVALID_ARGUMENT", "`engine` must come from createEngine()");
@@ -230,6 +264,7 @@ export async function loadModel(source, options = {}) {
230
264
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
231
265
  ...(options.weightCache === false ? { weightCache: false } : {}),
232
266
  ...(options.deterministic === true ? { deterministic: true } : {}),
267
+ ...(options.vision === false ? { vision: false } : {}),
233
268
  ...(options.activations === undefined ? {} : { activations: options.activations }),
234
269
  ...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
235
270
  ...(options.threads === undefined ? {} : { threads: options.threads }),
@@ -281,7 +316,7 @@ export async function resolveAutoQuant(source, options) {
281
316
  else {
282
317
  shapes = await readCheckpointShapes(checkpointReader(source));
283
318
  }
284
- return autoQuant(shapes, resources, options.contextLength);
319
+ return autoQuant(shapes, resources, options.contextLength, options.vision);
285
320
  }
286
321
  catch (error) {
287
322
  if (isAborted(options.signal))
@@ -354,6 +389,15 @@ function wireOptions(options) {
354
389
  out.loopDetection = options.loopDetection;
355
390
  if (options.contextShift !== undefined)
356
391
  out.contextShift = options.contextShift;
392
+ if (options.media !== undefined) {
393
+ const { maxFrames, fps, longestEdge, processor } = options.media;
394
+ out.media = {
395
+ ...(maxFrames === undefined ? {} : { maxFrames }),
396
+ ...(fps === undefined ? {} : { fps }),
397
+ ...(longestEdge === undefined ? {} : { longestEdge }),
398
+ ...(processor === undefined ? {} : { processor }),
399
+ };
400
+ }
357
401
  return out;
358
402
  }
359
403
  /**
@@ -379,6 +423,16 @@ export function withRecommendedSampling(options, checkpoint) {
379
423
  return out;
380
424
  }
381
425
  /** What picks a loaded model's recommended sampling. */
426
+ /** Refuses images and videos a model does not take, before they are read. */
427
+ function checkMediaSupport(messages, vision) {
428
+ const parts = messages.flatMap(messageParts);
429
+ if (vision?.images !== true && parts.some((p) => p.type === "image")) {
430
+ throw new WebslmError("INVALID_ARGUMENT", "this model does not take images (see `info().vision`)");
431
+ }
432
+ if (vision?.videos !== true && parts.some((p) => p.type === "video")) {
433
+ throw new WebslmError("INVALID_ARGUMENT", "this model does not take videos (see `info().vision`)");
434
+ }
435
+ }
382
436
  function checkpointTraits(info) {
383
437
  return { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
384
438
  }
@@ -399,12 +453,21 @@ function checkMessages(messages) {
399
453
  throw new WebslmError("INVALID_ARGUMENT", "messages must be a non-empty array");
400
454
  }
401
455
  return messages.map((m) => {
402
- if (typeof m?.role !== "string" || typeof m.content !== "string") {
403
- throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role` and `content`");
456
+ if (typeof m?.role !== "string" || (typeof m.content !== "string" && !Array.isArray(m.content))) {
457
+ throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role` and a string or array `content`");
404
458
  }
405
- return { role: m.role, content: m.content };
459
+ // Checks the parts (the images and videos are read when sent).
460
+ wireMessage(m, []);
461
+ if (typeof m.content !== "string")
462
+ return { role: m.role, content: m.content };
463
+ const media = "media" in m ? m.media : undefined;
464
+ return media === undefined ? { role: m.role, content: m.content } : { role: m.role, content: m.content, media };
406
465
  });
407
466
  }
467
+ /** The messages as the engine reads them, images and videos left out. */
468
+ function wireMessages(messages) {
469
+ return messages.map((m) => wireMessage(m, []));
470
+ }
408
471
  /** Shared implementation of a streamed generation. */
409
472
  class GenerationStream {
410
473
  result;
@@ -484,6 +547,7 @@ class Conversation {
484
547
  */
485
548
  chat(messages, options = {}) {
486
549
  const checked = checkMessages(messages);
550
+ checkMediaSupport(checked, this.vision);
487
551
  return this.#stream({ type: "chat", messages: checked }, options);
488
552
  }
489
553
  /**
@@ -521,9 +585,23 @@ class Conversation {
521
585
  // normally, with `finishReason: "aborted"`.
522
586
  const controller = new AbortController();
523
587
  return new GenerationStream(async (onDelta) => {
524
- const result = await this.client.request({ ...body, model: this.modelId, ...session, options }, {
588
+ // Images and videos are read here, where the caller's objects live,
589
+ // and their pixels transferred to the engine.
590
+ let request;
591
+ let transfer = [];
592
+ if (body.type === "chat") {
593
+ const { messages, media } = await prepareMessages(body.messages, generateOptions.media);
594
+ request = { type: "chat", messages, ...(media === undefined ? {} : { media }), model: this.modelId, ...session, options };
595
+ if (media !== undefined)
596
+ transfer = [media.data.buffer];
597
+ }
598
+ else {
599
+ request = { ...body, model: this.modelId, ...session, options };
600
+ }
601
+ const result = await this.client.request(request, {
525
602
  onDelta,
526
603
  signal: controller.signal,
604
+ transfer,
527
605
  ...(onPrefill === undefined ? {} : { onPrefill: (done, total) => onPrefill({ done, total }) }),
528
606
  });
529
607
  this.onLength(result.length);
@@ -557,7 +635,7 @@ class Conversation {
557
635
  return this.client.request({
558
636
  type: "renderChat",
559
637
  model: this.modelId,
560
- messages: checkMessages(messages),
638
+ messages: wireMessages(checkMessages(messages)),
561
639
  templateKwargs,
562
640
  });
563
641
  }
@@ -587,6 +665,9 @@ export class Model extends Conversation {
587
665
  get checkpoint() {
588
666
  return checkpointTraits(this.#info);
589
667
  }
668
+ get vision() {
669
+ return this.#info.vision;
670
+ }
590
671
  onLength() { }
591
672
  /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
592
673
  info() {
@@ -698,6 +779,9 @@ export class Session extends Conversation {
698
779
  get checkpoint() {
699
780
  return checkpointTraits(this.#info);
700
781
  }
782
+ get vision() {
783
+ return this.#info.vision;
784
+ }
701
785
  onLength(length) {
702
786
  this.#length = length;
703
787
  }
@@ -831,7 +915,8 @@ export const MODEL_FAMILIES = [
831
915
  {
832
916
  name: "Qwen3.5",
833
917
  modelType: "qwen3_5",
834
- modality: "text",
918
+ // Images and videos too: its checkpoints hold the vision tower.
919
+ modality: "vision-language",
835
920
  exampleRepo: "Qwen/Qwen3.5-0.8B",
836
921
  status: "supported",
837
922
  },
@@ -843,10 +928,17 @@ export const MODEL_FAMILIES = [
843
928
  status: "supported",
844
929
  },
845
930
  {
846
- name: "SmolVLM",
931
+ name: "SmolVLM / SmolVLM2",
847
932
  modelType: "idefics3",
848
933
  modality: "vision-language",
849
- exampleRepo: "HuggingFaceTB/SmolVLM-256M-Instruct",
850
- status: "planned",
934
+ exampleRepo: "HuggingFaceTB/SmolVLM2-256M-Video-Instruct",
935
+ status: "supported",
936
+ },
937
+ {
938
+ name: "LFM2-VL / LFM2.5-VL",
939
+ modelType: "lfm2_vl",
940
+ modality: "vision-language",
941
+ exampleRepo: "LiquidAI/LFM2.5-VL-450M",
942
+ status: "supported",
851
943
  },
852
944
  ];
package/dist/native.d.ts CHANGED
@@ -35,6 +35,8 @@ export type NativePrefillCallback = (done: number, total: number) => void;
35
35
  /** A session of a native model; every call resolves on the model's thread. */
36
36
  export interface NativeSession {
37
37
  chat(messagesJson: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
38
+ /** `chat` with the images and videos of the messages' parts (see `media.ts`). */
39
+ chatWithMedia(messagesJson: string, optionsJson: string, mediaJson: string, mediaData: Uint8Array, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
38
40
  generate(prompt: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
39
41
  fork(): Promise<NativeSession>;
40
42
  scoreContinuations(prefix: Uint32Array, continuationsJson: string): Promise<Float32Array[]>;
@@ -60,6 +62,7 @@ export interface NativeModel {
60
62
  removeAdapter(): Promise<unknown>;
61
63
  createSession(): Promise<NativeSession>;
62
64
  chat: NativeSession["chat"];
65
+ chatWithMedia: NativeSession["chatWithMedia"];
63
66
  generate: NativeSession["generate"];
64
67
  reset(): Promise<void>;
65
68
  tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
@@ -15,13 +15,17 @@ export type WireSource = {
15
15
  readonly revision?: string;
16
16
  readonly hubUrl?: string;
17
17
  readonly token?: string;
18
+ /** A GGUF file of the repository. */
19
+ readonly file?: string;
18
20
  } | {
19
21
  readonly kind: "files";
20
22
  readonly files: Readonly<Record<string, FileData>>;
23
+ readonly file?: string;
21
24
  }
22
25
  /** Reads are forwarded to the page with `read` messages. */
23
26
  | {
24
27
  readonly kind: "fetch";
28
+ readonly file?: string;
25
29
  };
26
30
  export interface WireLoadOptions {
27
31
  readonly quant: string;
@@ -43,6 +47,7 @@ export interface WireLoadOptions {
43
47
  /** `false` turns the converted-weight cache off. */
44
48
  readonly weightCache?: boolean;
45
49
  readonly deterministic?: boolean;
50
+ readonly vision?: boolean;
46
51
  readonly activations?: Activations;
47
52
  readonly wasmFlavour?: WasmFlavour;
48
53
  readonly threads?: number;
@@ -72,10 +77,35 @@ export interface WireGenerateOptions {
72
77
  readonly contextShift?: boolean | {
73
78
  readonly keep?: number;
74
79
  };
80
+ readonly media?: {
81
+ readonly maxFrames?: number;
82
+ readonly fps?: number;
83
+ readonly longestEdge?: number;
84
+ readonly processor?: Readonly<Record<string, unknown>>;
85
+ };
75
86
  }
76
87
  export interface WireMessage {
77
88
  readonly role: string;
78
- readonly content: string;
89
+ /** Text, or parts whose images and videos travel in {@link WireMedia}. */
90
+ readonly content: string | readonly WirePart[];
91
+ }
92
+ /** A content part as the engine reads it. */
93
+ export type WirePart = {
94
+ readonly type: "text";
95
+ readonly text: string;
96
+ } | {
97
+ readonly type: "image";
98
+ } | {
99
+ readonly type: "video";
100
+ };
101
+ /**
102
+ * The images and videos of a `chat` request, one per image or video part
103
+ * in order: `meta` is a JSON array describing each (see `media.ts`),
104
+ * `data` their pixels or image files back to back.
105
+ */
106
+ export interface WireMedia {
107
+ readonly meta: string;
108
+ readonly data: Uint8Array;
79
109
  }
80
110
  type WithId<T> = T & {
81
111
  readonly id: number;
@@ -102,6 +132,7 @@ export type Request = WithId<{
102
132
  readonly model: number;
103
133
  readonly session?: number;
104
134
  readonly messages: readonly WireMessage[];
135
+ readonly media?: WireMedia;
105
136
  readonly options: WireGenerateOptions;
106
137
  } | {
107
138
  readonly type: "generate";
@@ -8,7 +8,7 @@
8
8
  // Each model card: SmolLM2 (its usage example), LFM2.5 and LFM3
9
9
  // ("generation parameters", LFM3's "general" set), Qwen3 (best practices,
10
10
  // thinking and non-thinking), Qwen3.5 (the settings its benchmarks used in
11
- // each mode).
11
+ // each mode), LFM2.5-VL (its text generation parameters).
12
12
  export const RECOMMENDED_SAMPLING = {
13
13
  sets: {
14
14
  smollm2: {
@@ -30,6 +30,9 @@ export const RECOMMENDED_SAMPLING = {
30
30
  answer: { temperature: 0.7, topK: 20, topP: 0.8, minP: 0, presencePenalty: 1.5 },
31
31
  thinking: { temperature: 0.6, topK: 20, topP: 0.95, minP: 0, presencePenalty: 1.5 },
32
32
  },
33
+ lfm2_vl: {
34
+ answer: { temperature: 0.1, minP: 0.15, repetitionPenalty: 1.05 },
35
+ },
33
36
  },
34
37
  repos: {
35
38
  "HuggingFaceTB/SmolLM2-135M-Instruct": "smollm2",
@@ -38,6 +41,7 @@ export const RECOMMENDED_SAMPLING = {
38
41
  "Qwen/Qwen3-0.6B": "qwen3",
39
42
  "Qwen/Qwen3.5-0.8B": "qwen3_5",
40
43
  "LiquidAI/LFM3-1.7B": "lfm3",
44
+ "LiquidAI/LFM2.5-VL-450M": "lfm2_vl",
41
45
  },
42
46
  modelTypes: {
43
47
  lfm2: "lfm2",
@@ -45,6 +49,7 @@ export const RECOMMENDED_SAMPLING = {
45
49
  qwen3: "qwen3",
46
50
  qwen3_5: "qwen3_5",
47
51
  qwen3_5_text: "qwen3_5",
52
+ lfm2_vl: "lfm2_vl",
48
53
  },
49
54
  };
50
55
  /**
package/dist/simple.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * {@link Session}.
5
5
  */
6
6
  import { type Model } from "./models.js";
7
- import type { ChatMessage, LoadModelOptions, ModelInfo, ModelSource } from "./types.js";
7
+ import type { ChatMessage, ImageInput, LoadModelOptions, MediaOptions, ModelInfo, ModelSource, VideoInput } from "./types.js";
8
8
  /**
9
9
  * The model {@link load}, {@link ask} and {@link stream} use when none is
10
10
  * given: LFM2.5 350M, small (about 710 MB to download once), ungated, quick
@@ -80,6 +80,15 @@ export interface PromptOptions {
80
80
  readonly onToken?: (text: string) => void;
81
81
  /** Called with each piece of the reasoning, for models that think before answering. */
82
82
  readonly onReasoning?: (text: string) => void;
83
+ /**
84
+ * Images sent with the prompt, before its text (vision-language models,
85
+ * see `ModelInfo.vision`).
86
+ */
87
+ readonly images?: readonly ImageInput[];
88
+ /** A video sent with the prompt, before its text (models with `vision.videos`). */
89
+ readonly video?: VideoInput;
90
+ /** How images and videos are read: video sampling, processor settings. */
91
+ readonly media?: MediaOptions;
83
92
  }
84
93
  /** Options of {@link LLM.ask} and {@link Chat.send}. */
85
94
  export interface AskOptions extends PromptOptions {
@@ -124,7 +133,7 @@ export interface ChatOptions {
124
133
  /** Turns to start from (user and assistant messages). */
125
134
  readonly messages?: readonly ChatMessage[];
126
135
  /** Default options of every turn; those given to `send` or `stream` take precedence. */
127
- readonly defaults?: Omit<AskOptions, "system" | "signal" | "onToken" | "onReasoning" | "withReasoning">;
136
+ readonly defaults?: Omit<AskOptions, "system" | "signal" | "onToken" | "onReasoning" | "withReasoning" | "images" | "video">;
128
137
  }
129
138
  /** Options of {@link Chat.send} and {@link Chat.stream}: the conversation sets the system prompt. */
130
139
  export type ChatTurnOptions = Omit<AskOptions, "system">;
package/dist/simple.js CHANGED
@@ -282,12 +282,12 @@ class LLMImpl {
282
282
  lock: this.#lock,
283
283
  // A bare string lets `generate` complete it as raw text when the
284
284
  // checkpoint has no chat template.
285
- input: () => system === undefined
286
- ? prompt
287
- : [
288
- { role: "system", content: system },
289
- { role: "user", content: prompt },
290
- ],
285
+ input: () => {
286
+ const user = userMessage(prompt, options);
287
+ if (system === undefined && user.media === undefined)
288
+ return prompt;
289
+ return [...(system === undefined ? [] : [{ role: "system", content: system }]), user];
290
+ },
291
291
  });
292
292
  }
293
293
  /** @internal Runs one generation into a stream. */
@@ -366,6 +366,7 @@ function passThrough(options) {
366
366
  "thinkingBudget",
367
367
  "loopDetection",
368
368
  "contextShift",
369
+ "media",
369
370
  ];
370
371
  const out = {};
371
372
  for (const key of keys)
@@ -373,6 +374,14 @@ function passThrough(options) {
373
374
  out[key] = options[key];
374
375
  return out;
375
376
  }
377
+ /** A user message: `text`, with the images and video of `options`. */
378
+ function userMessage(text, options) {
379
+ const media = [
380
+ ...(options.images ?? []).map((image) => ({ type: "image", image })),
381
+ ...(options.video === undefined ? [] : [{ type: "video", video: options.video }]),
382
+ ];
383
+ return media.length === 0 ? { role: "user", content: text } : { role: "user", content: text, media };
384
+ }
376
385
  /** `templateKwargs`, with `think` as `enable_thinking` when the template has that switch. */
377
386
  function templateKwargs(options, thinkingSwitch) {
378
387
  const kwargs = {
@@ -424,7 +433,7 @@ class ChatImpl {
424
433
  this.#llm = llm;
425
434
  this.system = options.system;
426
435
  this.#defaults = options.defaults;
427
- this.#history = (options.messages ?? []).map((m) => ({ role: m.role, content: m.content }));
436
+ this.#history = (options.messages ?? []).map((m) => m.media === undefined ? { role: m.role, content: m.content } : { role: m.role, content: m.content, media: m.media });
428
437
  }
429
438
  get history() {
430
439
  return this.#history.slice();
@@ -439,7 +448,7 @@ class ChatImpl {
439
448
  if (this.#disposed)
440
449
  throw new WebslmError("DISPOSED", "this chat was disposed");
441
450
  const epoch = this.#epoch;
442
- const user = { role: "user", content };
451
+ const user = userMessage(content, options);
443
452
  await this.#llm.run(context, merged, {
444
453
  target: () => this.#openSession(),
445
454
  lock: this.#lock,