webslm 0.0.0-stage → 0.2.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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/ai-sdk/index.d.ts +81 -0
  4. package/dist/ai-sdk/index.js +90 -0
  5. package/dist/ai-sdk/language-model.d.ts +77 -0
  6. package/dist/ai-sdk/language-model.js +422 -0
  7. package/dist/ai-sdk/loader.d.ts +54 -0
  8. package/dist/ai-sdk/loader.js +170 -0
  9. package/dist/ai-sdk/output.d.ts +43 -0
  10. package/dist/ai-sdk/output.js +152 -0
  11. package/dist/ai-sdk/prompt.d.ts +21 -0
  12. package/dist/ai-sdk/prompt.js +111 -0
  13. package/dist/async-queue.d.ts +22 -0
  14. package/dist/async-queue.js +70 -0
  15. package/dist/cache/cache-api.d.ts +29 -0
  16. package/dist/cache/cache-api.js +115 -0
  17. package/dist/cache/index.d.ts +21 -0
  18. package/dist/cache/index.js +42 -0
  19. package/dist/cache/memory.d.ts +12 -0
  20. package/dist/cache/memory.js +61 -0
  21. package/dist/cache/models.d.ts +67 -0
  22. package/dist/cache/models.js +107 -0
  23. package/dist/cache/node-fs.d.ts +21 -0
  24. package/dist/cache/node-fs.js +147 -0
  25. package/dist/cache/opfs.d.ts +69 -0
  26. package/dist/cache/opfs.js +181 -0
  27. package/dist/cache/store.d.ts +53 -0
  28. package/dist/cache/store.js +64 -0
  29. package/dist/cache-management.d.ts +23 -0
  30. package/dist/cache-management.js +58 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +55 -0
  33. package/dist/client.d.ts +61 -0
  34. package/dist/client.js +256 -0
  35. package/dist/curated.d.ts +22 -0
  36. package/dist/curated.js +53 -0
  37. package/dist/download.d.ts +51 -0
  38. package/dist/download.js +289 -0
  39. package/dist/engine.d.ts +54 -0
  40. package/dist/engine.js +510 -0
  41. package/dist/errors.d.ts +81 -0
  42. package/dist/errors.js +89 -0
  43. package/dist/hub.d.ts +185 -0
  44. package/dist/hub.js +409 -0
  45. package/dist/index.d.ts +37 -0
  46. package/dist/index.js +41 -0
  47. package/dist/models.d.ts +225 -0
  48. package/dist/models.js +730 -0
  49. package/dist/node-pool-worker.d.ts +6 -0
  50. package/dist/node-pool-worker.js +32 -0
  51. package/dist/node-web-worker.d.ts +23 -0
  52. package/dist/node-web-worker.js +84 -0
  53. package/dist/node-worker.d.ts +2 -0
  54. package/dist/node-worker.js +9 -0
  55. package/dist/pool-worker.d.ts +36 -0
  56. package/dist/pool-worker.js +30 -0
  57. package/dist/pool.d.ts +17 -0
  58. package/dist/pool.js +41 -0
  59. package/dist/protocol.d.ts +246 -0
  60. package/dist/protocol.js +19 -0
  61. package/dist/runtime.d.ts +21 -0
  62. package/dist/runtime.js +53 -0
  63. package/dist/safetensors.d.ts +20 -0
  64. package/dist/safetensors.js +2 -0
  65. package/dist/simple.d.ts +310 -0
  66. package/dist/simple.js +553 -0
  67. package/dist/types.d.ts +412 -0
  68. package/dist/types.js +2 -0
  69. package/dist/wasm-flavour.d.ts +85 -0
  70. package/dist/wasm-flavour.js +169 -0
  71. package/dist/wasm.d.ts +34 -0
  72. package/dist/wasm.js +38 -0
  73. package/dist/worker.d.ts +6 -0
  74. package/dist/worker.js +11 -0
  75. package/package.json +92 -3
  76. package/wasm/relaxed/webslm_wasm.d.ts +325 -0
  77. package/wasm/relaxed/webslm_wasm.js +1899 -0
  78. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  79. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
  80. package/wasm/simd/webslm_wasm.d.ts +325 -0
  81. package/wasm/simd/webslm_wasm.js +1899 -0
  82. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  83. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
  84. package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
  85. package/wasm/threads/webslm_wasm.d.ts +357 -0
  86. package/wasm/threads/webslm_wasm.js +2100 -0
  87. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  88. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
package/dist/simple.js ADDED
@@ -0,0 +1,553 @@
1
+ /**
2
+ * The simple API: {@link load}, {@link ask}, {@link stream} and
3
+ * {@link LLM.chat}, built on {@link loadModel}, {@link Model} and
4
+ * {@link Session}.
5
+ */
6
+ import { AsyncQueue } from "./async-queue.js";
7
+ import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
8
+ import { loadModel } from "./models.js";
9
+ /**
10
+ * The model {@link load}, {@link ask} and {@link stream} use when none is
11
+ * given: SmolLM2 360M Instruct, small (about 720 MB to download once),
12
+ * ungated and quick on the CPU.
13
+ */
14
+ export const DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct";
15
+ /** Sampling temperature used when neither the call nor the checkpoint's `generation_config.json` sets one. */
16
+ export const DEFAULT_TEMPERATURE = 0.7;
17
+ /** Largest number of new tokens of an answer, unless `maxTokens` says otherwise. */
18
+ export const DEFAULT_MAX_TOKENS = 512;
19
+ // ---------------------------------------------------------------------------
20
+ // Reasoning blocks
21
+ const OPEN = "<think>";
22
+ const CLOSE = "</think>";
23
+ /** Length of the longest proper prefix of `tag` that ends `text`. */
24
+ function partialTagLength(text, tag) {
25
+ for (let n = Math.min(tag.length - 1, text.length); n > 0; n--) {
26
+ if (text.endsWith(tag.slice(0, n)))
27
+ return n;
28
+ }
29
+ return 0;
30
+ }
31
+ /**
32
+ * Separates a leading `<think>…</think>` block from the answer, on a stream
33
+ * of text pieces. Tags split across pieces are handled; the whitespace
34
+ * around the reasoning and at the start of the answer is dropped.
35
+ */
36
+ export class ReasoningSplitter {
37
+ #sink;
38
+ #mode;
39
+ #buffer = "";
40
+ #reasoningStarted = false;
41
+ /** @param opened The prompt already opened the block (the template ends with `<think>`). */
42
+ constructor(sink, opened) {
43
+ this.#sink = sink;
44
+ this.#mode = opened ? "reasoning" : "start";
45
+ }
46
+ /** Whether the text so far ends inside an unclosed reasoning block. */
47
+ get inReasoning() {
48
+ return this.#mode === "reasoning";
49
+ }
50
+ push(text) {
51
+ this.#buffer += text;
52
+ this.#drain(false);
53
+ }
54
+ /** Flushes what is held back, at the end of the generation. */
55
+ end() {
56
+ this.#drain(true);
57
+ }
58
+ #drain(final) {
59
+ for (;;) {
60
+ switch (this.#mode) {
61
+ case "start": {
62
+ const head = this.#buffer.trimStart();
63
+ if (head.startsWith(OPEN)) {
64
+ this.#buffer = head.slice(OPEN.length);
65
+ this.#mode = "reasoning";
66
+ continue;
67
+ }
68
+ // Whitespace or the beginning of `<think>`: wait for more.
69
+ if (!final && OPEN.startsWith(head))
70
+ return;
71
+ this.#mode = "answer";
72
+ continue;
73
+ }
74
+ case "reasoning": {
75
+ const close = this.#buffer.indexOf(CLOSE);
76
+ if (close !== -1) {
77
+ this.#reasoning(this.#buffer.slice(0, close), true);
78
+ this.#buffer = this.#buffer.slice(close + CLOSE.length);
79
+ this.#mode = "answer-start";
80
+ continue;
81
+ }
82
+ if (final) {
83
+ this.#reasoning(this.#buffer, true);
84
+ this.#buffer = "";
85
+ return;
86
+ }
87
+ // Hold back a possible partial `</think>` and trailing whitespace.
88
+ const safe = this.#buffer
89
+ .slice(0, this.#buffer.length - partialTagLength(this.#buffer, CLOSE))
90
+ .trimEnd();
91
+ this.#reasoning(safe, false);
92
+ this.#buffer = this.#buffer.slice(safe.length);
93
+ return;
94
+ }
95
+ case "answer-start": {
96
+ const head = this.#buffer.trimStart();
97
+ this.#buffer = head;
98
+ if (head === "")
99
+ return;
100
+ this.#mode = "answer";
101
+ continue;
102
+ }
103
+ case "answer":
104
+ if (this.#buffer !== "")
105
+ this.#sink.text(this.#buffer);
106
+ this.#buffer = "";
107
+ return;
108
+ }
109
+ }
110
+ }
111
+ #reasoning(text, closing) {
112
+ let piece = text;
113
+ if (!this.#reasoningStarted) {
114
+ piece = piece.trimStart();
115
+ if (piece === "")
116
+ return;
117
+ this.#reasoningStarted = true;
118
+ }
119
+ if (closing)
120
+ piece = piece.trimEnd();
121
+ if (piece !== "")
122
+ this.#sink.reasoning(piece);
123
+ }
124
+ }
125
+ /**
126
+ * Splits a model's output into its answer and the `<think>…</think>` block
127
+ * that reasoning models (Qwen3, LFM thinking checkpoints...) write first.
128
+ * Text without such a block is all answer. `open` is `true` while the block
129
+ * is not closed yet (a stream still thinking, or an answer cut by `maxTokens`).
130
+ *
131
+ * ```ts
132
+ * splitReasoning("<think>\nThe user greets me.\n</think>\n\nHello!");
133
+ * // { text: "Hello!", reasoning: "The user greets me.", open: false }
134
+ * ```
135
+ */
136
+ export function splitReasoning(output) {
137
+ let text = "";
138
+ let reasoning = "";
139
+ const splitter = new ReasoningSplitter({
140
+ text: (t) => (text += t),
141
+ reasoning: (t) => (reasoning += t),
142
+ }, false);
143
+ splitter.push(output);
144
+ const open = splitter.inReasoning;
145
+ splitter.end();
146
+ return { text, reasoning, open };
147
+ }
148
+ class TextStreamImpl {
149
+ text;
150
+ reasoning;
151
+ #queue = new AsyncQueue();
152
+ #controller = new AbortController();
153
+ #stopped = false;
154
+ constructor(run, options) {
155
+ const { signal, onToken, onReasoning } = options;
156
+ const onAbort = () => this.#controller.abort(signal?.reason);
157
+ if (isAborted(signal))
158
+ onAbort();
159
+ else
160
+ signal?.addEventListener("abort", onAbort, { once: true });
161
+ let text = "";
162
+ let reasoning = "";
163
+ // An error thrown by a callback stops the generation and is rethrown as is.
164
+ let callbackError;
165
+ const call = (callback, piece) => {
166
+ if (callback === undefined || callbackError !== undefined)
167
+ return;
168
+ try {
169
+ callback(piece);
170
+ }
171
+ catch (error) {
172
+ callbackError = { error };
173
+ this.stop();
174
+ }
175
+ };
176
+ const context = {
177
+ signal: this.#controller.signal,
178
+ stopped: () => this.#stopped && !isAborted(signal),
179
+ sink: {
180
+ text: (piece) => {
181
+ text += piece;
182
+ this.#queue.push(piece);
183
+ call(onToken, piece);
184
+ },
185
+ reasoning: (piece) => {
186
+ reasoning += piece;
187
+ call(onReasoning, piece);
188
+ },
189
+ },
190
+ };
191
+ const done = run(context)
192
+ .then(() => {
193
+ if (callbackError !== undefined)
194
+ throw callbackError.error;
195
+ return { text, reasoning };
196
+ }, (error) => {
197
+ throw callbackError !== undefined ? callbackError.error : toWebslmError(error);
198
+ })
199
+ .catch((error) => {
200
+ this.#queue.fail(error);
201
+ throw error;
202
+ })
203
+ .finally(() => {
204
+ signal?.removeEventListener("abort", onAbort);
205
+ this.#queue.end();
206
+ });
207
+ this.text = done.then((r) => r.text);
208
+ this.reasoning = done.then((r) => r.reasoning);
209
+ // Iterating is enough: unread promises must not report unhandled rejections.
210
+ this.text.catch(() => { });
211
+ this.reasoning.catch(() => { });
212
+ }
213
+ stop() {
214
+ if (this.#queue.done || this.#stopped)
215
+ return;
216
+ this.#stopped = true;
217
+ this.#controller.abort();
218
+ }
219
+ [Symbol.asyncIterator]() {
220
+ return this.#queue.iterate(() => this.stop());
221
+ }
222
+ }
223
+ /** @internal Runs async functions one at a time, in call order. */
224
+ export class Lock {
225
+ #tail = Promise.resolve();
226
+ run(fn) {
227
+ const result = this.#tail.then(fn);
228
+ this.#tail = result.catch(() => { });
229
+ return result;
230
+ }
231
+ }
232
+ /** Resolves an `ask`-style call from a stream. */
233
+ async function answerOf(stream, withReasoning) {
234
+ const text = await stream.text;
235
+ return withReasoning === true ? { text, reasoning: await stream.reasoning } : text;
236
+ }
237
+ const NO_TRAITS = { thinkingSwitch: false, opensReasoning: () => false };
238
+ /** @internal The {@link LLM} implementation. */
239
+ class LLMImpl {
240
+ model;
241
+ #lock = new Lock();
242
+ #traits;
243
+ constructor(model) {
244
+ this.model = model;
245
+ }
246
+ get info() {
247
+ return this.model.info();
248
+ }
249
+ ask(prompt, options = {}) {
250
+ return answerOf(this.stream(prompt, options), options.withReasoning);
251
+ }
252
+ stream(prompt, options = {}) {
253
+ return new TextStreamImpl((context) => this.runPrompt(context, prompt, options), options);
254
+ }
255
+ chat(options = {}) {
256
+ return new ChatImpl(this, options);
257
+ }
258
+ async unload() {
259
+ await this.model.unload();
260
+ }
261
+ /** @internal Single-turn generation in the model's default session. */
262
+ async runPrompt(context, prompt, options) {
263
+ checkText(prompt, "prompt");
264
+ const { system } = options;
265
+ await this.run(context, options, {
266
+ target: async () => this.model,
267
+ lock: this.#lock,
268
+ // A bare string lets `generate` complete it as raw text when the
269
+ // checkpoint has no chat template.
270
+ input: () => system === undefined
271
+ ? prompt
272
+ : [
273
+ { role: "system", content: system },
274
+ { role: "user", content: prompt },
275
+ ],
276
+ });
277
+ }
278
+ /** @internal Runs one generation into a stream. */
279
+ async run(context, options, turn) {
280
+ const { signal, stopped, sink } = context;
281
+ await turn.lock.run(async () => {
282
+ if (signal.aborted) {
283
+ if (stopped())
284
+ return;
285
+ throw abortError(signal);
286
+ }
287
+ const target = await turn.target();
288
+ const traits = await this.#templateTraits();
289
+ let text = "";
290
+ let reasoning = "";
291
+ const splitter = new ReasoningSplitter({
292
+ text: (piece) => {
293
+ text += piece;
294
+ sink.text(piece);
295
+ },
296
+ reasoning: (piece) => {
297
+ reasoning += piece;
298
+ sink.reasoning(piece);
299
+ },
300
+ }, traits.opensReasoning(options.think));
301
+ const generation = {
302
+ maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
303
+ temperature: options.temperature ?? this.model.info().generationConfig.temperature ?? DEFAULT_TEMPERATURE,
304
+ ...(options.seed === undefined ? {} : { seed: options.seed }),
305
+ ...(options.stop === undefined ? {} : { stop: options.stop }),
306
+ ...passThrough(options),
307
+ ...templateKwargs(options, traits.thinkingSwitch),
308
+ signal,
309
+ onDelta: (piece) => splitter.push(piece),
310
+ };
311
+ try {
312
+ await target.generate(turn.input(), generation);
313
+ }
314
+ catch (error) {
315
+ // `stop()` ends the stream normally, with the text so far.
316
+ if (!(stopped() && toWebslmError(error).code === "ABORTED"))
317
+ throw error;
318
+ }
319
+ splitter.end();
320
+ turn.onAnswer?.({ text, reasoning });
321
+ });
322
+ }
323
+ /** Renders a probe conversation to see how the template handles reasoning. */
324
+ #templateTraits() {
325
+ this.#traits ??= probeTemplateTraits(this.model);
326
+ return this.#traits;
327
+ }
328
+ }
329
+ /** Generation options the simple API passes through unchanged. */
330
+ function passThrough(options) {
331
+ const keys = [
332
+ "topK",
333
+ "topP",
334
+ "minP",
335
+ "repetitionPenalty",
336
+ "presencePenalty",
337
+ "frequencyPenalty",
338
+ "json",
339
+ "schema",
340
+ "thinkingBudget",
341
+ "loopDetection",
342
+ "contextShift",
343
+ ];
344
+ const out = {};
345
+ for (const key of keys)
346
+ if (options[key] !== undefined)
347
+ out[key] = options[key];
348
+ return out;
349
+ }
350
+ /** `templateKwargs`, with `think` as `enable_thinking` when the template has that switch. */
351
+ function templateKwargs(options, thinkingSwitch) {
352
+ const kwargs = {
353
+ ...options.templateKwargs,
354
+ ...(options.think !== undefined && thinkingSwitch ? { enable_thinking: options.think } : {}),
355
+ };
356
+ return Object.keys(kwargs).length === 0 ? {} : { templateKwargs: kwargs };
357
+ }
358
+ /** @internal Renders a probe conversation to see how a model's template handles reasoning. */
359
+ export async function probeTemplateTraits(model) {
360
+ if (!model.info().hasChatTemplate)
361
+ return NO_TRAITS;
362
+ const messages = [{ role: "user", content: "Hi" }];
363
+ try {
364
+ const [unset, on, off] = await Promise.all([
365
+ model.renderChat(messages),
366
+ model.renderChat(messages, { enable_thinking: true }),
367
+ model.renderChat(messages, { enable_thinking: false }),
368
+ ]);
369
+ const opens = (prompt) => prompt.trimEnd().endsWith(OPEN);
370
+ const thinkingSwitch = on !== off;
371
+ return {
372
+ thinkingSwitch,
373
+ opensReasoning: (think) => !thinkingSwitch || think === undefined ? opens(unset) : think ? opens(on) : opens(off),
374
+ };
375
+ }
376
+ catch {
377
+ return NO_TRAITS;
378
+ }
379
+ }
380
+ function checkText(value, name) {
381
+ if (typeof value !== "string") {
382
+ throw new WebslmError("INVALID_ARGUMENT", `${name} must be a string`);
383
+ }
384
+ }
385
+ /** @internal The {@link Chat} implementation. */
386
+ class ChatImpl {
387
+ system;
388
+ #llm;
389
+ #defaults;
390
+ #lock = new Lock();
391
+ #history;
392
+ #session;
393
+ #epoch = 0;
394
+ #disposed = false;
395
+ constructor(llm, options) {
396
+ if (options.system !== undefined)
397
+ checkText(options.system, "system");
398
+ this.#llm = llm;
399
+ this.system = options.system;
400
+ this.#defaults = options.defaults;
401
+ this.#history = (options.messages ?? []).map((m) => ({ role: m.role, content: m.content }));
402
+ }
403
+ get history() {
404
+ return this.#history.slice();
405
+ }
406
+ send(content, options = {}) {
407
+ return answerOf(this.stream(content, options), options.withReasoning);
408
+ }
409
+ stream(content, options = {}) {
410
+ const merged = { ...this.#defaults, ...options };
411
+ return new TextStreamImpl(async (context) => {
412
+ checkText(content, "content");
413
+ if (this.#disposed)
414
+ throw new WebslmError("DISPOSED", "this chat was disposed");
415
+ const epoch = this.#epoch;
416
+ const user = { role: "user", content };
417
+ await this.#llm.run(context, merged, {
418
+ target: () => this.#openSession(),
419
+ lock: this.#lock,
420
+ // Built when the turn starts, after the turns queued before it.
421
+ input: () => [
422
+ ...(this.system === undefined ? [] : [{ role: "system", content: this.system }]),
423
+ ...this.#history,
424
+ user,
425
+ ],
426
+ onAnswer: (answer) => {
427
+ if (epoch === this.#epoch)
428
+ this.#history.push(user, { role: "assistant", content: answer.text });
429
+ },
430
+ });
431
+ }, merged);
432
+ }
433
+ reset() {
434
+ this.#epoch++;
435
+ this.#history = [];
436
+ }
437
+ async dispose() {
438
+ if (this.#disposed)
439
+ return;
440
+ this.#disposed = true;
441
+ this.#epoch++;
442
+ const session = this.#session;
443
+ this.#session = undefined;
444
+ if (session !== undefined)
445
+ await session.then((s) => s.dispose()).catch(() => { });
446
+ }
447
+ #openSession() {
448
+ if (this.#disposed)
449
+ return Promise.reject(new WebslmError("DISPOSED", "this chat was disposed"));
450
+ if (this.#session === undefined) {
451
+ const pending = this.#llm.model.session();
452
+ pending.catch(() => {
453
+ if (this.#session === pending)
454
+ this.#session = undefined;
455
+ });
456
+ this.#session = pending;
457
+ }
458
+ return this.#session;
459
+ }
460
+ }
461
+ // ---------------------------------------------------------------------------
462
+ // Entry points
463
+ /**
464
+ * Loads a model and returns a handle with simple methods. Every argument is
465
+ * optional: the model defaults to {@link DEFAULT_MODEL}, and the options are
466
+ * those of {@link loadModel} (device `"auto"`, quant `"q8"`, a worker, the
467
+ * offline cache).
468
+ *
469
+ * The first load downloads the checkpoint from the Hugging Face Hub into the
470
+ * cache (OPFS in browsers, `~/.cache/webslm` in Node); later loads read it
471
+ * from there without network.
472
+ *
473
+ * ```ts
474
+ * import { load } from "webslm";
475
+ *
476
+ * const llm = await load("HuggingFaceTB/SmolLM2-360M-Instruct", {
477
+ * onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
478
+ * });
479
+ * console.log(await llm.ask("Write a haiku about the sea"));
480
+ *
481
+ * const chat = llm.chat({ system: "You are concise." });
482
+ * await chat.send("My name is Ana.");
483
+ * console.log(await chat.send("What is my name?"));
484
+ * await llm.unload();
485
+ * ```
486
+ *
487
+ * @param model A Hugging Face repository id, or a {@link ModelSource} (local files, a custom store).
488
+ * @param options Load options; see {@link LoadModelOptions}.
489
+ */
490
+ export async function load(model = DEFAULT_MODEL, options = {}) {
491
+ return new LLMImpl(await loadModel(model, options));
492
+ }
493
+ /** Models loaded by the module-level {@link ask} and {@link stream}, by source. */
494
+ const shared = new Map();
495
+ const objectIds = new WeakMap();
496
+ let nextObjectId = 1;
497
+ /** Identifies a source: repository ids by name, `files` and `fetch` sources by identity. */
498
+ function sharedKey(source) {
499
+ if (typeof source === "string")
500
+ return `hub:${source.trim()}`;
501
+ if (typeof source === "object" && source !== null && "hub" in source) {
502
+ return `hub:${source.hub.trim()}@${source.revision ?? ""}@${source.hubUrl ?? ""}`;
503
+ }
504
+ let id = objectIds.get(source);
505
+ if (id === undefined) {
506
+ id = nextObjectId++;
507
+ objectIds.set(source, id);
508
+ }
509
+ return `object:${id}`;
510
+ }
511
+ /** Loads a model once; concurrent and later calls with the same source share it. */
512
+ function sharedModel(source = DEFAULT_MODEL) {
513
+ const key = sharedKey(source);
514
+ let pending = shared.get(key);
515
+ if (pending === undefined) {
516
+ const loading = loadModel(source).then((model) => new LLMImpl(model));
517
+ // A failed load is retried by the next call.
518
+ loading.catch(() => {
519
+ if (shared.get(key) === loading)
520
+ shared.delete(key);
521
+ });
522
+ shared.set(key, loading);
523
+ pending = loading;
524
+ }
525
+ return pending;
526
+ }
527
+ export function ask(prompt, options = {}) {
528
+ return answerOf(stream(prompt, options), options.withReasoning);
529
+ }
530
+ /**
531
+ * Streams the answer to a prompt with a model loaded on first use and kept
532
+ * for later calls (see {@link unloadAll}). The stream yields pieces of the
533
+ * answer; `text` and `reasoning` resolve once it is complete.
534
+ *
535
+ * ```ts
536
+ * import { stream } from "webslm";
537
+ *
538
+ * for await (const text of stream("Tell me a story")) process.stdout.write(text);
539
+ * ```
540
+ */
541
+ export function stream(prompt, options = {}) {
542
+ const { model, ...rest } = options;
543
+ return new TextStreamImpl(async (context) => {
544
+ const llm = await sharedModel(model);
545
+ await llm.runPrompt(context, prompt, rest);
546
+ }, rest);
547
+ }
548
+ /** Unloads every model loaded by the module-level {@link ask} and {@link stream}. */
549
+ export async function unloadAll() {
550
+ const pending = [...shared.values()];
551
+ shared.clear();
552
+ await Promise.all(pending.map((p) => p.then((llm) => llm.unload(), () => { })));
553
+ }