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
@@ -0,0 +1,422 @@
1
+ /** The AI SDK language model (specification v4) over a webslm model. */
2
+ import { toWebslmError } from "../errors.js";
3
+ import { DEFAULT_TEMPERATURE, ReasoningSplitter } from "../simple.js";
4
+ import { abortReason, raceAbort } from "./loader.js";
5
+ import { prepareOutput, thinkingBudgetOf, toolCallId } from "./output.js";
6
+ import { convertPrompt, promptText } from "./prompt.js";
7
+ const PROVIDER = "webslm";
8
+ /** The fields of {@link WebslmCallSettings}: the settings that are not load options. */
9
+ export const CALL_SETTING_KEYS = [
10
+ "think",
11
+ "maxTokens",
12
+ "temperature",
13
+ "topK",
14
+ "topP",
15
+ "minP",
16
+ "repetitionPenalty",
17
+ "thinkingBudget",
18
+ "templateKwargs",
19
+ ];
20
+ /** `providerOptions.webslm` of a call, read leniently (unknown keys and wrong types are ignored). */
21
+ function callProviderOptions(options) {
22
+ const raw = options.providerOptions?.[PROVIDER];
23
+ if (raw === undefined)
24
+ return {};
25
+ const out = {};
26
+ if (typeof raw.think === "boolean")
27
+ out.think = raw.think;
28
+ const numbers = [
29
+ "maxTokens",
30
+ "temperature",
31
+ "topK",
32
+ "topP",
33
+ "minP",
34
+ "repetitionPenalty",
35
+ "thinkingBudget",
36
+ ];
37
+ for (const key of numbers) {
38
+ const value = raw[key];
39
+ if (typeof value === "number")
40
+ out[key] = value;
41
+ }
42
+ const kwargs = raw.templateKwargs;
43
+ if (typeof kwargs === "object" && kwargs !== null && !Array.isArray(kwargs)) {
44
+ out.templateKwargs = kwargs;
45
+ }
46
+ return out;
47
+ }
48
+ /** Whether a call asks the model to think: the AI SDK's `reasoning`, then the settings. */
49
+ function thinkOf(options, settings) {
50
+ switch (options.reasoning) {
51
+ case undefined:
52
+ case "provider-default":
53
+ return settings.think;
54
+ case "none":
55
+ return false;
56
+ default:
57
+ return true;
58
+ }
59
+ }
60
+ /** Prepends `instruction` to the system message, or adds one. */
61
+ function withSystem(messages, instruction) {
62
+ const first = messages[0];
63
+ if (first?.role === "system") {
64
+ return [{ role: "system", content: `${first.content}\n\n${instruction}` }, ...messages.slice(1)];
65
+ }
66
+ return [{ role: "system", content: instruction }, ...messages];
67
+ }
68
+ function prepare(options, defaults) {
69
+ const converted = convertPrompt(options.prompt);
70
+ let messages = converted.messages;
71
+ const warnings = [...converted.warnings];
72
+ const settings = { ...defaults, ...callProviderOptions(options) };
73
+ const output = prepareOutput(options);
74
+ warnings.push(...output.warnings);
75
+ if (output.instruction !== undefined)
76
+ messages = withSystem(messages, output.instruction);
77
+ return { messages, warnings, settings, think: thinkOf(options, settings), output: output.mode };
78
+ }
79
+ /** Engine generation options of a call. */
80
+ function generationOptions(options, prepared, info, thinkingSwitch) {
81
+ const { settings, think, output } = prepared;
82
+ const maxTokens = options.maxOutputTokens ?? settings.maxTokens;
83
+ const thinkingBudget = think === false ? undefined : (settings.thinkingBudget ?? thinkingBudgetOf(options.reasoning));
84
+ const schema = output.kind === "text" ? undefined : output.schema;
85
+ const topK = options.topK ?? settings.topK;
86
+ const topP = options.topP ?? settings.topP;
87
+ const kwargs = {
88
+ ...settings.templateKwargs,
89
+ ...(think !== undefined && thinkingSwitch ? { enable_thinking: think } : {}),
90
+ };
91
+ return {
92
+ temperature: options.temperature ??
93
+ settings.temperature ??
94
+ info.generationConfig.temperature ??
95
+ DEFAULT_TEMPERATURE,
96
+ ...(maxTokens === undefined ? {} : { maxTokens }),
97
+ ...(topK === undefined ? {} : { topK }),
98
+ ...(topP === undefined ? {} : { topP }),
99
+ ...(settings.minP === undefined ? {} : { minP: settings.minP }),
100
+ ...(settings.repetitionPenalty === undefined
101
+ ? {}
102
+ : { repetitionPenalty: settings.repetitionPenalty }),
103
+ ...(options.presencePenalty === undefined ? {} : { presencePenalty: options.presencePenalty }),
104
+ ...(options.frequencyPenalty === undefined ? {} : { frequencyPenalty: options.frequencyPenalty }),
105
+ ...(thinkingBudget === undefined ? {} : { thinkingBudget }),
106
+ ...(output.kind === "text" ? {} : schema === undefined ? { json: true } : { schema }),
107
+ ...(options.seed === undefined ? {} : { seed: options.seed }),
108
+ ...(options.stopSequences === undefined || options.stopSequences.length === 0
109
+ ? {}
110
+ : { stop: options.stopSequences }),
111
+ ...(Object.keys(kwargs).length === 0 ? {} : { templateKwargs: kwargs }),
112
+ };
113
+ }
114
+ function finishReasonOf(result) {
115
+ if (result === undefined)
116
+ return { unified: "other", raw: undefined };
117
+ const raw = result.finishReason;
118
+ switch (raw) {
119
+ case "stop":
120
+ case "stop_string":
121
+ return { unified: "stop", raw };
122
+ case "length":
123
+ case "context_full":
124
+ return { unified: "length", raw };
125
+ default:
126
+ return { unified: "other", raw };
127
+ }
128
+ }
129
+ /** The input of a forced tool call, when the model wrote valid JSON. */
130
+ function toolInputOf(output, text) {
131
+ if (output.kind !== "tool")
132
+ return undefined;
133
+ const input = text.trim();
134
+ try {
135
+ JSON.parse(input);
136
+ return input;
137
+ }
138
+ catch {
139
+ // Cut by `maxTokens`, say: left as text.
140
+ return undefined;
141
+ }
142
+ }
143
+ function usageOf(result, reasoned) {
144
+ if (result === undefined) {
145
+ return {
146
+ inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
147
+ outputTokens: { total: undefined, text: undefined, reasoning: undefined },
148
+ };
149
+ }
150
+ return {
151
+ inputTokens: {
152
+ total: result.promptTokens,
153
+ noCache: result.promptTokens - result.reusedTokens,
154
+ cacheRead: result.reusedTokens,
155
+ cacheWrite: undefined,
156
+ },
157
+ outputTokens: {
158
+ total: result.generatedTokens,
159
+ // The split between reasoning and answer is not counted.
160
+ text: reasoned ? undefined : result.generatedTokens,
161
+ reasoning: reasoned ? undefined : 0,
162
+ },
163
+ raw: {
164
+ promptTokens: result.promptTokens,
165
+ reusedTokens: result.reusedTokens,
166
+ generatedTokens: result.generatedTokens,
167
+ },
168
+ };
169
+ }
170
+ function metadataOf(result, info) {
171
+ const webslm = { backend: info.backend };
172
+ if (result !== undefined) {
173
+ webslm.finishReason = result.finishReason;
174
+ webslm.timeToFirstTokenMs = result.timeToFirstTokenMs;
175
+ webslm.tokensPerSecond = result.tokensPerSecond;
176
+ }
177
+ return { webslm };
178
+ }
179
+ /**
180
+ * A webslm model as an AI SDK `LanguageModelV4`. The checkpoint is
181
+ * downloaded and loaded on the first call (or by {@link load}), then kept
182
+ * for later calls; calls run one after the other.
183
+ */
184
+ export class WebslmLanguageModel {
185
+ specificationVersion = "v4";
186
+ provider = PROVIDER;
187
+ modelId;
188
+ /** Text-only models: no URL is read by the model itself. */
189
+ supportedUrls = {};
190
+ #slot;
191
+ #settings;
192
+ /** @internal Created by a provider: `webslm(modelId)` or `createWebslm(...)(modelId)`. */
193
+ constructor(modelId, slot, settings) {
194
+ this.modelId = modelId;
195
+ this.#slot = slot;
196
+ this.#settings = settings;
197
+ }
198
+ /** Description of the model once loaded (architecture, backend, files...). */
199
+ get info() {
200
+ return this.#slot.loaded?.model.info();
201
+ }
202
+ /**
203
+ * Downloads (once, into the cache) and loads the model now rather than on
204
+ * the first call, reporting progress. Resolves to its description.
205
+ */
206
+ async load(options = {}) {
207
+ const loaded = await this.#acquire(options.signal, options.onProgress);
208
+ return loaded.model.info();
209
+ }
210
+ /**
211
+ * Frees the model (once the generation in progress ends). Every language
212
+ * model of the provider with the same id and load options shares it; the
213
+ * next call loads it again.
214
+ */
215
+ unload() {
216
+ return this.#slot.unload();
217
+ }
218
+ #acquire(signal, onProgress) {
219
+ return this.#slot.acquire(signal, [this.#settings.onProgress, onProgress]);
220
+ }
221
+ /** Runs a generation: loads the model if needed, then waits for its turn. */
222
+ async #run(options, prepared, sink, signal) {
223
+ const loaded = await this.#acquire(signal);
224
+ return raceAbort(loaded.lock.run(async () => {
225
+ if (signal.aborted)
226
+ throw abortReason(signal);
227
+ const { model } = loaded;
228
+ const info = model.info();
229
+ const traits = await loaded.traits;
230
+ const generation = generationOptions(options, prepared, info, traits.thinkingSwitch);
231
+ const splitter = new ReasoningSplitter(sink, traits.opensReasoning(prepared.think));
232
+ let result;
233
+ if (info.hasChatTemplate) {
234
+ const stream = model.chat(prepared.messages, { ...generation, signal });
235
+ for await (const delta of stream)
236
+ splitter.push(delta);
237
+ result = await stream.result;
238
+ }
239
+ else {
240
+ await model.generate(promptText(prepared.messages), {
241
+ ...generation,
242
+ raw: true,
243
+ signal,
244
+ onDelta: (delta) => splitter.push(delta),
245
+ });
246
+ }
247
+ if (signal.aborted)
248
+ throw abortReason(signal);
249
+ splitter.end();
250
+ return { result, info };
251
+ }), signal);
252
+ }
253
+ async doGenerate(options) {
254
+ const prepared = prepare(options, this.#settings);
255
+ const call = callSignal(options.abortSignal);
256
+ const timestamp = new Date();
257
+ let text = "";
258
+ let reasoning = "";
259
+ try {
260
+ const { result, info } = await this.#run(options, prepared, {
261
+ text: (piece) => (text += piece),
262
+ reasoning: (piece) => (reasoning += piece),
263
+ }, call.signal);
264
+ const content = [];
265
+ if (reasoning !== "")
266
+ content.push({ type: "reasoning", text: reasoning });
267
+ const input = toolInputOf(prepared.output, text);
268
+ if (input !== undefined && prepared.output.kind === "tool") {
269
+ const toolName = prepared.output.tool.name;
270
+ content.push({ type: "tool-call", toolCallId: toolCallId(), toolName, input });
271
+ }
272
+ else if (text !== "") {
273
+ content.push({ type: "text", text });
274
+ }
275
+ const finishReason = finishReasonOf(result);
276
+ return {
277
+ content,
278
+ finishReason: input === undefined ? finishReason : { unified: "tool-calls", raw: finishReason.raw },
279
+ usage: usageOf(result, reasoning !== ""),
280
+ providerMetadata: metadataOf(result, info),
281
+ response: { modelId: this.modelId, timestamp },
282
+ warnings: prepared.warnings,
283
+ };
284
+ }
285
+ catch (error) {
286
+ throw publicError(error, options.abortSignal);
287
+ }
288
+ finally {
289
+ call.release();
290
+ }
291
+ }
292
+ async doStream(options) {
293
+ const prepared = prepare(options, this.#settings);
294
+ const call = callSignal(options.abortSignal);
295
+ // Load before answering, so that a failed download rejects the call.
296
+ try {
297
+ await this.#acquire(call.signal);
298
+ }
299
+ catch (error) {
300
+ call.release();
301
+ throw publicError(error, options.abortSignal);
302
+ }
303
+ const modelId = this.modelId;
304
+ const timestamp = new Date();
305
+ // Cancelled by the reader, closed or errored: nothing more is enqueued.
306
+ let ended = false;
307
+ const stream = new ReadableStream({
308
+ start: (out) => {
309
+ const enqueue = (part) => {
310
+ if (!ended)
311
+ out.enqueue(part);
312
+ };
313
+ const end = (error) => {
314
+ if (ended)
315
+ return;
316
+ ended = true;
317
+ if (error === undefined)
318
+ out.close();
319
+ else
320
+ out.error(error);
321
+ };
322
+ enqueue({ type: "stream-start", warnings: prepared.warnings });
323
+ enqueue({ type: "response-metadata", modelId, timestamp });
324
+ let open;
325
+ let reasoned = false;
326
+ let toolText = "";
327
+ const close = () => {
328
+ if (open === "text")
329
+ enqueue({ type: "text-end", id: "text-0" });
330
+ if (open === "reasoning")
331
+ enqueue({ type: "reasoning-end", id: "reasoning-0" });
332
+ open = undefined;
333
+ };
334
+ const sink = {
335
+ reasoning: (delta) => {
336
+ if (open !== "reasoning") {
337
+ close();
338
+ open = "reasoning";
339
+ reasoned = true;
340
+ enqueue({ type: "reasoning-start", id: "reasoning-0" });
341
+ }
342
+ enqueue({ type: "reasoning-delta", id: "reasoning-0", delta });
343
+ },
344
+ text: (delta) => {
345
+ // A tool call is sent whole once its JSON is complete.
346
+ if (prepared.output.kind === "tool") {
347
+ toolText += delta;
348
+ return;
349
+ }
350
+ if (open !== "text") {
351
+ close();
352
+ open = "text";
353
+ enqueue({ type: "text-start", id: "text-0" });
354
+ }
355
+ enqueue({ type: "text-delta", id: "text-0", delta });
356
+ },
357
+ };
358
+ this.#run(options, prepared, sink, call.signal)
359
+ .then(({ result, info }) => {
360
+ close();
361
+ let finishReason = finishReasonOf(result);
362
+ const input = toolInputOf(prepared.output, toolText);
363
+ if (input !== undefined && prepared.output.kind === "tool") {
364
+ const id = toolCallId();
365
+ const toolName = prepared.output.tool.name;
366
+ enqueue({ type: "tool-input-start", id, toolName });
367
+ enqueue({ type: "tool-input-delta", id, delta: input });
368
+ enqueue({ type: "tool-input-end", id });
369
+ enqueue({ type: "tool-call", toolCallId: id, toolName, input });
370
+ finishReason = { unified: "tool-calls", raw: finishReason.raw };
371
+ }
372
+ else if (toolText !== "") {
373
+ enqueue({ type: "text-start", id: "text-0" });
374
+ enqueue({ type: "text-delta", id: "text-0", delta: toolText });
375
+ enqueue({ type: "text-end", id: "text-0" });
376
+ }
377
+ enqueue({
378
+ type: "finish",
379
+ finishReason,
380
+ usage: usageOf(result, reasoned),
381
+ providerMetadata: metadataOf(result, info),
382
+ });
383
+ end();
384
+ }, (error) => {
385
+ if (options.abortSignal?.aborted === true) {
386
+ end(abortReason(options.abortSignal));
387
+ return;
388
+ }
389
+ enqueue({ type: "error", error: toWebslmError(error) });
390
+ end();
391
+ })
392
+ .finally(() => call.release());
393
+ },
394
+ cancel: () => {
395
+ ended = true;
396
+ call.abort();
397
+ },
398
+ });
399
+ return { stream };
400
+ }
401
+ }
402
+ function callSignal(caller) {
403
+ const controller = new AbortController();
404
+ const follow = () => controller.abort(caller?.reason);
405
+ if (caller?.aborted === true)
406
+ follow();
407
+ else
408
+ caller?.addEventListener("abort", follow, { once: true });
409
+ return {
410
+ signal: controller.signal,
411
+ abort: () => controller.abort(),
412
+ release: () => caller?.removeEventListener("abort", follow),
413
+ };
414
+ }
415
+ /** The caller's abort reason when it aborted, else a typed webslm error. */
416
+ function publicError(error, signal) {
417
+ if (signal?.aborted === true)
418
+ return abortReason(signal);
419
+ if (error instanceof DOMException)
420
+ return error;
421
+ return toWebslmError(error);
422
+ }
@@ -0,0 +1,54 @@
1
+ /** Lazy, shared model loads for the AI SDK provider. */
2
+ import type { Model } from "../models.js";
3
+ import { Lock, type TemplateTraits } from "../simple.js";
4
+ import type { LoadModelOptions, LoadProgress } from "../types.js";
5
+ /**
6
+ * What loads models: `webslm` itself by default. Pass the module
7
+ * (`import * as webslm from "webslm"`) or any object with a compatible
8
+ * `loadModel`, for instance to count or cache loads yourself.
9
+ */
10
+ export interface WebslmEngine {
11
+ loadModel(source: string, options: LoadModelOptions): Promise<Model>;
12
+ }
13
+ /** Options of a load that decide which engine instance a model gets (not callbacks). */
14
+ export type WebslmLoadOptions = Omit<LoadModelOptions, "signal" | "onProgress">;
15
+ /** A model ready for generations: calls run one at a time, in order. */
16
+ export interface LoadedModel {
17
+ readonly model: Model;
18
+ readonly lock: Lock;
19
+ readonly traits: Promise<TemplateTraits>;
20
+ }
21
+ type ProgressListener = (progress: LoadProgress) => void;
22
+ /** The reason of an aborted signal, as an `AbortError` when it is not an error already. */
23
+ export declare function abortReason(signal: AbortSignal): Error;
24
+ /** `promise`, or a rejection with the signal's reason as soon as it aborts. */
25
+ export declare function raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T>;
26
+ /**
27
+ * One model of a provider: loaded on first use and shared by every
28
+ * language model with the same id and load options. A load that every
29
+ * waiting caller gave up on (their signals aborted) is cancelled.
30
+ */
31
+ export declare class ModelSlot {
32
+ #private;
33
+ constructor(engine: WebslmEngine, modelId: string, options: WebslmLoadOptions);
34
+ /** The loaded model, if it is loaded. */
35
+ get loaded(): LoadedModel | undefined;
36
+ /** Loads the model, or waits for the load in progress, reporting its progress to `listeners`. */
37
+ acquire(signal: AbortSignal | undefined, listeners?: readonly (ProgressListener | undefined)[]): Promise<LoadedModel>;
38
+ /** Frees the model (after the generation in progress) or cancels its load. */
39
+ unload(): Promise<void>;
40
+ }
41
+ /** Every field of {@link WebslmLoadOptions}. */
42
+ /**
43
+ * The load options among a model's settings: every setting but the call
44
+ * defaults (`omit`) and the callbacks, so that load options added to
45
+ * `loadModel` later pass through too.
46
+ */
47
+ export declare function pickLoadOptions(settings: object, omit: readonly string[]): WebslmLoadOptions;
48
+ /**
49
+ * A key naming a model and the load options that make it a distinct engine
50
+ * instance: plain values by value, objects (a LoRA adapter's files, say) by
51
+ * identity.
52
+ */
53
+ export declare function slotKey(modelId: string, options: WebslmLoadOptions): string;
54
+ export {};
@@ -0,0 +1,170 @@
1
+ /** Lazy, shared model loads for the AI SDK provider. */
2
+ import { Lock, probeTemplateTraits } from "../simple.js";
3
+ /** The reason of an aborted signal, as an `AbortError` when it is not an error already. */
4
+ export function abortReason(signal) {
5
+ const reason = signal.reason;
6
+ if (reason instanceof Error)
7
+ return reason;
8
+ const message = typeof reason === "string" ? reason : "This operation was aborted";
9
+ return new DOMException(message, "AbortError");
10
+ }
11
+ /** `promise`, or a rejection with the signal's reason as soon as it aborts. */
12
+ export function raceAbort(promise, signal) {
13
+ if (signal === undefined)
14
+ return promise;
15
+ if (signal.aborted)
16
+ return Promise.reject(abortReason(signal));
17
+ return new Promise((resolve, reject) => {
18
+ const onAbort = () => reject(abortReason(signal));
19
+ signal.addEventListener("abort", onAbort, { once: true });
20
+ promise.then((value) => {
21
+ signal.removeEventListener("abort", onAbort);
22
+ resolve(value);
23
+ }, (error) => {
24
+ signal.removeEventListener("abort", onAbort);
25
+ reject(error);
26
+ });
27
+ });
28
+ }
29
+ /**
30
+ * One model of a provider: loaded on first use and shared by every
31
+ * language model with the same id and load options. A load that every
32
+ * waiting caller gave up on (their signals aborted) is cancelled.
33
+ */
34
+ export class ModelSlot {
35
+ #engine;
36
+ #modelId;
37
+ #options;
38
+ #listeners = new Set();
39
+ #loaded;
40
+ #pending;
41
+ constructor(engine, modelId, options) {
42
+ this.#engine = engine;
43
+ this.#modelId = modelId;
44
+ this.#options = options;
45
+ }
46
+ /** The loaded model, if it is loaded. */
47
+ get loaded() {
48
+ return this.#loaded;
49
+ }
50
+ /** Loads the model, or waits for the load in progress, reporting its progress to `listeners`. */
51
+ async acquire(signal, listeners = []) {
52
+ if (this.#loaded !== undefined)
53
+ return this.#loaded;
54
+ if (signal?.aborted === true)
55
+ throw abortReason(signal);
56
+ const own = listeners.filter((l) => l !== undefined);
57
+ for (const listener of own)
58
+ this.#listeners.add(listener);
59
+ const pending = (this.#pending ??= this.#start());
60
+ pending.waiters++;
61
+ try {
62
+ return await raceAbort(pending.promise, signal);
63
+ }
64
+ finally {
65
+ pending.waiters--;
66
+ for (const listener of own)
67
+ this.#listeners.delete(listener);
68
+ // Nobody waits for this load any more: stop downloading.
69
+ if (pending.waiters === 0 && this.#pending === pending && this.#loaded === undefined) {
70
+ this.#pending = undefined;
71
+ pending.controller.abort();
72
+ }
73
+ }
74
+ }
75
+ #start() {
76
+ const controller = new AbortController();
77
+ let loading;
78
+ try {
79
+ loading = this.#engine.loadModel(this.#modelId, {
80
+ ...this.#options,
81
+ signal: controller.signal,
82
+ onProgress: (progress) => {
83
+ for (const listener of this.#listeners) {
84
+ try {
85
+ listener(progress);
86
+ }
87
+ catch {
88
+ // A failing progress callback must not fail the load others wait for.
89
+ }
90
+ }
91
+ },
92
+ });
93
+ }
94
+ catch (error) {
95
+ loading = Promise.reject(error);
96
+ }
97
+ const entry = {
98
+ controller,
99
+ waiters: 0,
100
+ promise: loading.then((model) => {
101
+ if (this.#pending !== entry) {
102
+ // Cancelled after it finished: nobody holds it.
103
+ void model.unload().catch(() => { });
104
+ throw new DOMException("This operation was aborted", "AbortError");
105
+ }
106
+ this.#pending = undefined;
107
+ const loaded = { model, lock: new Lock(), traits: probeTemplateTraits(model) };
108
+ this.#loaded = loaded;
109
+ return loaded;
110
+ }, (error) => {
111
+ if (this.#pending === entry)
112
+ this.#pending = undefined;
113
+ throw error;
114
+ }),
115
+ };
116
+ // Callers see the error through `acquire`.
117
+ entry.promise.catch(() => { });
118
+ return entry;
119
+ }
120
+ /** Frees the model (after the generation in progress) or cancels its load. */
121
+ async unload() {
122
+ const pending = this.#pending;
123
+ if (pending !== undefined) {
124
+ this.#pending = undefined;
125
+ pending.controller.abort();
126
+ }
127
+ const loaded = this.#loaded;
128
+ this.#loaded = undefined;
129
+ if (loaded !== undefined)
130
+ await loaded.lock.run(() => loaded.model.unload());
131
+ }
132
+ }
133
+ /** Every field of {@link WebslmLoadOptions}. */
134
+ /**
135
+ * The load options among a model's settings: every setting but the call
136
+ * defaults (`omit`) and the callbacks, so that load options added to
137
+ * `loadModel` later pass through too.
138
+ */
139
+ export function pickLoadOptions(settings, omit) {
140
+ const out = {};
141
+ for (const [key, value] of Object.entries(settings)) {
142
+ if (value === undefined || omit.includes(key) || key === "signal" || key === "onProgress")
143
+ continue;
144
+ out[key] = value;
145
+ }
146
+ return out;
147
+ }
148
+ const objectIds = new WeakMap();
149
+ let nextObjectId = 1;
150
+ /**
151
+ * A key naming a model and the load options that make it a distinct engine
152
+ * instance: plain values by value, objects (a LoRA adapter's files, say) by
153
+ * identity.
154
+ */
155
+ export function slotKey(modelId, options) {
156
+ const entries = Object.entries(options)
157
+ .filter(([, value]) => value !== undefined)
158
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
159
+ .map(([key, value]) => {
160
+ if (typeof value !== "object" || value === null)
161
+ return [key, value];
162
+ let id = objectIds.get(value);
163
+ if (id === undefined) {
164
+ id = nextObjectId++;
165
+ objectIds.set(value, id);
166
+ }
167
+ return [key, `#${id}`];
168
+ });
169
+ return JSON.stringify([modelId.trim(), entries]);
170
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * What a call asks the model to write: text, JSON (constrained by the
3
+ * engine's JSON grammar when it can enforce the schema), or the input of a
4
+ * single forced tool, which is JSON following the tool's schema.
5
+ */
6
+ import type { LanguageModelV4CallOptions, LanguageModelV4FunctionTool, SharedV4Warning } from "@ai-sdk/provider";
7
+ /** The first keyword of `schema` (or of a schema nested in it) that the engine cannot enforce. */
8
+ export declare function unsupportedKeyword(schema: unknown): string | undefined;
9
+ /** What the model writes. */
10
+ export type OutputMode = {
11
+ readonly kind: "text";
12
+ } | {
13
+ readonly kind: "json";
14
+ /** The schema the engine enforces, when it can; else any JSON object. */
15
+ readonly schema?: Readonly<Record<string, unknown>>;
16
+ } | {
17
+ readonly kind: "tool";
18
+ readonly tool: LanguageModelV4FunctionTool;
19
+ readonly schema: Readonly<Record<string, unknown>>;
20
+ };
21
+ /** The output mode of a call, the system instruction that goes with it, and warnings. */
22
+ export interface PreparedOutput {
23
+ readonly mode: OutputMode;
24
+ readonly instruction?: string;
25
+ readonly warnings: SharedV4Warning[];
26
+ }
27
+ /**
28
+ * Decides what the model writes:
29
+ *
30
+ * - `responseFormat: { type: "json" }`: JSON, with its schema enforced token
31
+ * by token when the engine supports every keyword in it; otherwise any JSON
32
+ * object, the schema given in the system prompt (a `compatibility` warning).
33
+ * - one forced function tool (`toolChoice` naming it, or `"required"` with a
34
+ * single tool): the tool's input, constrained to its schema, returned as a
35
+ * tool call. A schema the engine cannot enforce, several tools or
36
+ * `toolChoice: "auto"` leave tools unsupported (a warning; the model answers
37
+ * with text). `toolChoice: "none"` ignores the tools.
38
+ */
39
+ export declare function prepareOutput(options: LanguageModelV4CallOptions): PreparedOutput;
40
+ /** The thinking budget of a `reasoning` level, when it sets one. */
41
+ export declare function thinkingBudgetOf(reasoning: LanguageModelV4CallOptions["reasoning"]): number | undefined;
42
+ /** A tool call id, unique enough within a conversation. */
43
+ export declare function toolCallId(): string;