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.
- package/LICENSE +21 -0
- package/README.md +373 -2
- package/dist/ai-sdk/index.d.ts +81 -0
- package/dist/ai-sdk/index.js +90 -0
- package/dist/ai-sdk/language-model.d.ts +77 -0
- package/dist/ai-sdk/language-model.js +422 -0
- package/dist/ai-sdk/loader.d.ts +54 -0
- package/dist/ai-sdk/loader.js +170 -0
- package/dist/ai-sdk/output.d.ts +43 -0
- package/dist/ai-sdk/output.js +152 -0
- package/dist/ai-sdk/prompt.d.ts +21 -0
- package/dist/ai-sdk/prompt.js +111 -0
- package/dist/async-queue.d.ts +22 -0
- package/dist/async-queue.js +70 -0
- package/dist/cache/cache-api.d.ts +29 -0
- package/dist/cache/cache-api.js +115 -0
- package/dist/cache/index.d.ts +21 -0
- package/dist/cache/index.js +42 -0
- package/dist/cache/memory.d.ts +12 -0
- package/dist/cache/memory.js +61 -0
- package/dist/cache/models.d.ts +67 -0
- package/dist/cache/models.js +107 -0
- package/dist/cache/node-fs.d.ts +21 -0
- package/dist/cache/node-fs.js +147 -0
- package/dist/cache/opfs.d.ts +69 -0
- package/dist/cache/opfs.js +181 -0
- package/dist/cache/store.d.ts +53 -0
- package/dist/cache/store.js +64 -0
- package/dist/cache-management.d.ts +23 -0
- package/dist/cache-management.js +58 -0
- package/dist/capabilities.d.ts +67 -0
- package/dist/capabilities.js +55 -0
- package/dist/client.d.ts +61 -0
- package/dist/client.js +256 -0
- package/dist/curated.d.ts +22 -0
- package/dist/curated.js +53 -0
- package/dist/download.d.ts +51 -0
- package/dist/download.js +289 -0
- package/dist/engine.d.ts +54 -0
- package/dist/engine.js +510 -0
- package/dist/errors.d.ts +81 -0
- package/dist/errors.js +89 -0
- package/dist/hub.d.ts +185 -0
- package/dist/hub.js +409 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +41 -0
- package/dist/models.d.ts +225 -0
- package/dist/models.js +730 -0
- package/dist/node-pool-worker.d.ts +6 -0
- package/dist/node-pool-worker.js +32 -0
- package/dist/node-web-worker.d.ts +23 -0
- package/dist/node-web-worker.js +84 -0
- package/dist/node-worker.d.ts +2 -0
- package/dist/node-worker.js +9 -0
- package/dist/pool-worker.d.ts +36 -0
- package/dist/pool-worker.js +30 -0
- package/dist/pool.d.ts +17 -0
- package/dist/pool.js +41 -0
- package/dist/protocol.d.ts +246 -0
- package/dist/protocol.js +19 -0
- package/dist/runtime.d.ts +21 -0
- package/dist/runtime.js +53 -0
- package/dist/safetensors.d.ts +20 -0
- package/dist/safetensors.js +2 -0
- package/dist/simple.d.ts +310 -0
- package/dist/simple.js +553 -0
- package/dist/types.d.ts +412 -0
- package/dist/types.js +2 -0
- package/dist/wasm-flavour.d.ts +85 -0
- package/dist/wasm-flavour.js +169 -0
- package/dist/wasm.d.ts +34 -0
- package/dist/wasm.js +38 -0
- package/dist/worker.d.ts +6 -0
- package/dist/worker.js +11 -0
- package/package.json +92 -3
- package/wasm/relaxed/webslm_wasm.d.ts +325 -0
- package/wasm/relaxed/webslm_wasm.js +1899 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
- package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/simd/webslm_wasm.d.ts +325 -0
- package/wasm/simd/webslm_wasm.js +1899 -0
- package/wasm/simd/webslm_wasm_bg.wasm +0 -0
- package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
- package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
- package/wasm/threads/webslm_wasm.d.ts +357 -0
- package/wasm/threads/webslm_wasm.js +2100 -0
- package/wasm/threads/webslm_wasm_bg.wasm +0 -0
- package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Maxime Golfier
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,374 @@
|
|
|
1
|
-
#
|
|
1
|
+
# webslm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run small language models in the browser and in Node, straight from their original Hugging Face checkpoints. A Rust engine compiled to WebAssembly reads `config.json`, `tokenizer.json`, the chat template and the `*.safetensors` weights as published, with no conversion step.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install webslm
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { ask } from "webslm";
|
|
11
|
+
|
|
12
|
+
console.log(await ask("Write a haiku about the sea"));
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The first call downloads the default model ([SmolLM2 360M Instruct](https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct), about 720 MB) into a local cache; later runs load it offline. The same code runs in browsers, Node 20+ and Bun, with no bundler or setup in Node.
|
|
16
|
+
|
|
17
|
+
- Runs in a dedicated module Worker in browsers (`worker_threads` in Node), so the page stays responsive.
|
|
18
|
+
- Downloads a checkpoint once into the Origin Private File System (a directory in Node), resumes interrupted downloads, checks the Hub's SHA-256 and loads offline afterwards.
|
|
19
|
+
- Streams answers, keeps conversations, and exposes a low-level session API (teacher-forced scoring, step-wise decoding, logits and hidden states as `Float32Array`s).
|
|
20
|
+
- Searches the Hub for models it can run.
|
|
21
|
+
|
|
22
|
+
Supported architectures: Llama-style (SmolLM2, Mistral), Qwen2, Qwen3, Qwen3.5 (language model; Gated DeltaNet hybrid), LFM2 / LFM2.5 and LFM3. Models run on WebGPU or on the CPU through WebAssembly (SIMD, and Web Worker threads where the page allows): with `device: "auto"` (the default), WebGPU for models above ~100M parameters when the browser has an adapter, the CPU otherwise; `ModelInfo.backend` says which one runs. ESM only; browsers with WebAssembly SIMD (every current browser). Demo: <https://maxgfr.github.io/webslm/>.
|
|
23
|
+
|
|
24
|
+
## Ask
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { ask } from "webslm";
|
|
28
|
+
|
|
29
|
+
const text = await ask("What is the capital of France?"); // DEFAULT_MODEL
|
|
30
|
+
const fact = await ask("What is 2 + 2?", { model: "Qwen/Qwen3-0.6B", think: false });
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`ask` and `stream` load their model on first use and share it between calls (concurrent calls wait for the same load). `unloadAll()` frees them. A Node script exits on its own when it is done; no cleanup is needed.
|
|
34
|
+
|
|
35
|
+
Options, all optional:
|
|
36
|
+
|
|
37
|
+
| Option | Default | |
|
|
38
|
+
| --- | --- | --- |
|
|
39
|
+
| `model` | `DEFAULT_MODEL` | Hub repository id or a [source](#sources) (module-level calls only) |
|
|
40
|
+
| `maxTokens` | `512` | Largest number of new tokens (reasoning included) |
|
|
41
|
+
| `temperature` | the checkpoint's `generation_config.json`, else `0.7` | `0` is greedy, deterministic decoding |
|
|
42
|
+
| `system` | | System prompt |
|
|
43
|
+
| `think` | the template's default | `enable_thinking` for models that reason first (Qwen3, LFM3, and Qwen3.5 when asked); ignored by the others |
|
|
44
|
+
| `stop` | | Strings that end the answer (never emitted, not even in part) |
|
|
45
|
+
| `seed` | | Seed of the sampler: same seed, same answer |
|
|
46
|
+
| `topK`, `topP`, `minP` | the checkpoint's | Sampling filters |
|
|
47
|
+
| `repetitionPenalty`, `presencePenalty`, `frequencyPenalty` | | Penalties on repeated tokens |
|
|
48
|
+
| `json` | `false` | Answer with a JSON object (constrained decoding) |
|
|
49
|
+
| `schema` | | Answer with JSON following this JSON schema (see [Generation controls](#generation-controls)) |
|
|
50
|
+
| `thinkingBudget` | | Most reasoning tokens before the model must answer |
|
|
51
|
+
| `loopDetection` | `false` | Stop when the answer starts repeating itself |
|
|
52
|
+
| `contextShift` | `false` | When the context is full, drop the oldest turns (the system prompt stays) |
|
|
53
|
+
| `templateKwargs` | | Extra chat template variables |
|
|
54
|
+
| `signal` | | `AbortSignal`; `ask` then rejects with code `"ABORTED"` |
|
|
55
|
+
| `onToken` | | Called with each piece of the answer |
|
|
56
|
+
| `onReasoning` | | Called with each piece of the reasoning |
|
|
57
|
+
| `withReasoning` | `false` | `ask` resolves to `{ text, reasoning }` |
|
|
58
|
+
|
|
59
|
+
### Reasoning
|
|
60
|
+
|
|
61
|
+
Models such as Qwen3 and LFM3 write their reasoning in a `<think>…</think>` block before the answer. `ask`, `stream` and chats return the answer without it; ask for it explicitly:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const { text, reasoning } = await ask("Is 97 prime?", { model: "Qwen/Qwen3-0.6B", withReasoning: true });
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The split is generic: a `<think>` block at the start of the output (or one the chat template opens in the prompt) is reasoning, whatever the model. `splitReasoning(output)` applies it to text you already have. A reasoning model can spend its `maxTokens` thinking, leaving an empty answer: raise `maxTokens` or pass `think: false`.
|
|
68
|
+
|
|
69
|
+
## Stream
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { stream } from "webslm";
|
|
73
|
+
|
|
74
|
+
const answer = stream("Tell me a story");
|
|
75
|
+
for await (const text of answer) process.stdout.write(text);
|
|
76
|
+
await answer.text; // the whole answer
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`answer.stop()`, or leaving the loop early, stops the generation; the stream then ends normally and `answer.text` holds what was generated. `answer.reasoning` resolves to the reasoning, if any.
|
|
80
|
+
|
|
81
|
+
## Load a model and chat
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { load } from "webslm";
|
|
85
|
+
|
|
86
|
+
const llm = await load("HuggingFaceTB/SmolLM2-360M-Instruct", {
|
|
87
|
+
onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
await llm.ask("Hi!"); // single turn, nothing remembered
|
|
91
|
+
for await (const text of llm.stream("Hi!")) process.stdout.write(text);
|
|
92
|
+
|
|
93
|
+
const chat = llm.chat({ system: "You are concise." });
|
|
94
|
+
await chat.send("My name is Ana.");
|
|
95
|
+
for await (const text of chat.stream("What is my name?")) process.stdout.write(text);
|
|
96
|
+
chat.history; // [{ role: "user", content: "My name is Ana." }, { role: "assistant", ... }, ...]
|
|
97
|
+
chat.reset();
|
|
98
|
+
|
|
99
|
+
await llm.unload();
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
|
|
103
|
+
|
|
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
|
+
|
|
106
|
+
## React
|
|
107
|
+
|
|
108
|
+
```tsx
|
|
109
|
+
import { useLLM } from "webslm-react";
|
|
110
|
+
|
|
111
|
+
const { ask, stream, chat, status, progress, error } = useLLM(); // or useLLM("Qwen/Qwen3-0.6B")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
See [webslm-react](https://www.npmjs.com/package/webslm-react).
|
|
115
|
+
|
|
116
|
+
## AI SDK
|
|
117
|
+
|
|
118
|
+
`webslm/ai-sdk` is a provider for the [AI SDK](https://ai-sdk.dev) (`ai` v7, language model specification v4): `generateText`, `streamText`, `useChat` and everything else built on it run on a model in the page, with no server.
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
npm install webslm ai
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { webslm } from "webslm/ai-sdk";
|
|
126
|
+
import { generateText, streamText } from "ai";
|
|
127
|
+
|
|
128
|
+
const { text, usage } = await generateText({
|
|
129
|
+
model: webslm("HuggingFaceTB/SmolLM2-360M-Instruct"),
|
|
130
|
+
prompt: "Write a haiku about the sea",
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const result = streamText({ model: webslm("Qwen/Qwen3-0.6B"), prompt: "Is 97 prime?" });
|
|
134
|
+
for await (const part of result.fullStream) {
|
|
135
|
+
if (part.type === "reasoning-delta") console.log("thinking:", part.text);
|
|
136
|
+
if (part.type === "text-delta") document.body.append(part.text);
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The model is downloaded (once, into the cache) and loaded on the first call, then kept: every `webslm(id)` with the same id and load options shares it, and calls run one after the other. Load it earlier to show progress:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const model = webslm("Qwen/Qwen3-0.6B", { quant: "q4", think: false });
|
|
144
|
+
await model.load({ onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes) });
|
|
145
|
+
model.info; // ModelInfo once loaded
|
|
146
|
+
await model.unload(); // or webslm.unloadAll()
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`webslm(modelId, settings)` takes the [load options](#load-a-model-and-chat) of `loadModel` (`device`, `quant`, `revision`, `token`, `contextLength`, `worker`, `cacheDir`, `deterministic`, `onProgress`...) and call defaults: `think`, `maxTokens`, `temperature`, `topK`, `topP`, `minP`, `repetitionPenalty`, `thinkingBudget`, `templateKwargs`. `createWebslm({ loadOptions, engine })` makes a provider with its own defaults and model cache; `engine` is what loads the models (webslm's `loadModel` by default).
|
|
150
|
+
|
|
151
|
+
| AI SDK | webslm |
|
|
152
|
+
| ------ | ------ |
|
|
153
|
+
| `maxOutputTokens`, `temperature`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `seed`, `stopSequences`, `abortSignal` | passed to the engine; unset `temperature` is the checkpoint's, else 0.7 |
|
|
154
|
+
| `reasoning` | `"none"` turns thinking off (`enable_thinking: false`), any other level on, with a `thinkingBudget` of 128 (`minimal`), 512 (`low`) or 2048 (`medium`) tokens; reasoning comes back as reasoning parts |
|
|
155
|
+
| `providerOptions.webslm` | `think`, `maxTokens`, `temperature`, `topK`, `topP`, `minP`, `repetitionPenalty`, `thinkingBudget`, `templateKwargs` for one call |
|
|
156
|
+
| `usage` | prompt tokens (`cacheRead`: tokens served from the KV cache of earlier turns) and generated tokens |
|
|
157
|
+
| `finishReason` | `stop` (end of turn or a stop sequence), `length` (`maxOutputTokens` or a full context), `other` (raw: `rawFinishReason`) |
|
|
158
|
+
| `providerMetadata.webslm` | `backend`, `timeToFirstTokenMs`, `tokensPerSecond` |
|
|
159
|
+
| `responseFormat: { type: "json", schema }` | constrained decoding (`schema`, or `json` without one), the schema also given in the system prompt; a schema with keywords the engine cannot enforce (`anyOf`, `minLength`, `format`...) falls back to any JSON object (a `compatibility` warning) |
|
|
160
|
+
| `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
|
+
| other `tools` (`"auto"`, several tools, a schema the engine cannot enforce) | an `unsupported` warning, the model answers with text; `toolChoice: "none"` ignores them |
|
|
162
|
+
|
|
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.
|
|
164
|
+
|
|
165
|
+
`CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, 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
|
+
|
|
167
|
+
## Advanced API
|
|
168
|
+
|
|
169
|
+
The simple API above is built on `loadModel`, `Model` and `Session`, which expose every option.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { loadModel } from "webslm";
|
|
173
|
+
|
|
174
|
+
const model = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", {
|
|
175
|
+
quant: "q8", // "q8" (default), "q4" (experimental) or "f32"
|
|
176
|
+
onProgress: (p) => console.log(p.phase, p.file, p.overallLoadedBytes, p.overallTotalBytes),
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
const stream = model.chat([{ role: "user", content: "Write a haiku about the sea." }], {
|
|
180
|
+
maxTokens: 256,
|
|
181
|
+
temperature: 0.7,
|
|
182
|
+
topP: 0.9,
|
|
183
|
+
});
|
|
184
|
+
for await (const delta of stream) document.body.append(delta);
|
|
185
|
+
const { tokensPerSecond, timeToFirstTokenMs, finishReason } = await stream.result;
|
|
186
|
+
|
|
187
|
+
const text = await model.generate("What is the capital of France?"); // whole answer
|
|
188
|
+
await model.unload();
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`chat` reuses the session's cache across turns, so a follow-up only processes the new message. Stop a stream with `stream.stop()`, by breaking out of the loop, or with `signal`. Sampling options left unset come from the checkpoint's `generation_config.json` (`model.info().generationConfig`) when it enables sampling, else decoding is greedy; `temperature: 0` is greedy. Chat template variables go through `templateKwargs`, e.g. `{ enable_thinking: false }` for Qwen3. Output is returned as generated, `<think>` blocks included.
|
|
192
|
+
|
|
193
|
+
## Generation controls
|
|
194
|
+
|
|
195
|
+
Every generation (`chat`, `generate`, and the simple API's options) takes these controls:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const city = await model.generate("Describe Paris.", {
|
|
199
|
+
schema: {
|
|
200
|
+
type: "object",
|
|
201
|
+
properties: { name: { type: "string" }, population: { type: "integer" } },
|
|
202
|
+
required: ["name"],
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
JSON.parse(city); // always valid, follows the schema
|
|
206
|
+
|
|
207
|
+
const stream = model.chat(messages, {
|
|
208
|
+
stop: ["\nUser:"], // matched across token boundaries, never emitted in part
|
|
209
|
+
stopTokens: [42], // token ids that end the generation
|
|
210
|
+
temperature: 0.8,
|
|
211
|
+
seed: 7, // same seed and options: same tokens
|
|
212
|
+
presencePenalty: 0.5,
|
|
213
|
+
frequencyPenalty: 0.2,
|
|
214
|
+
logprobs: 5, // log-probability of each token and of the 5 most likely ones
|
|
215
|
+
thinkingBudget: 256, // Qwen3: close <think> after 256 tokens, then answer
|
|
216
|
+
loopDetection: true, // stop with finishReason "loop" on repetition
|
|
217
|
+
contextShift: true, // drop the oldest tokens instead of stopping when the context is full
|
|
218
|
+
onToken: (t) => {
|
|
219
|
+
console.log(t.id, t.text, t.logprob, t.topLogprobs, t.forced);
|
|
220
|
+
return t.text !== "."; // false stops right after this token
|
|
221
|
+
},
|
|
222
|
+
onPrefill: ({ done, total }) => console.log(`prompt ${done}/${total}`),
|
|
223
|
+
signal, // aborts, also in the middle of a long prompt
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
- **JSON**: `json: true` constrains the output to a JSON object; `schema` to a JSON Schema subset: `type` (or a list), `properties`, `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `enum`, `const`. Properties come in any order; an object with `properties` only accepts those unless `additionalProperties` says otherwise. Keywords that cannot be enforced (`pattern`, `format`, `minimum`, `minLength`, `anyOf`, `$ref`...) are rejected with `INVALID_ARGUMENT`. Whitespace runs are capped at 24 characters. Generation ends when the document closes; `maxTokens` can still cut it. A reasoning block before the JSON stays free.
|
|
228
|
+
- **Log-probabilities** are the model's own (before temperature, penalties and constraints). Without them, and without other controls that need every logit (penalties, JSON), greedy and top-k sampling read back only the best candidates (the fast path on WebGPU).
|
|
229
|
+
- **`onToken`** returning `false` stops the generation at that token: the result ends there, even if the worker had computed more.
|
|
230
|
+
|
|
231
|
+
Sessions can reuse one computed prefix for several continuations:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const session = await model.session();
|
|
235
|
+
const prefix = await model.tokenize(await model.renderChat([{ role: "user", content: "Capital of France?" }]));
|
|
236
|
+
const [paris, lyon] = await session.scoreContinuations(prefix, [
|
|
237
|
+
await model.tokenize("Paris."),
|
|
238
|
+
await model.tokenize("Lyon."),
|
|
239
|
+
]); // Float32Array of per-token log-probabilities; the prefix runs once
|
|
240
|
+
const fork = await session.fork(); // a copy of the cache: continue in two directions
|
|
241
|
+
await session.shiftContext(32, 512); // drop 512 positions after the first 32, recompute the rest
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Several models can share one worker (one WebAssembly instance and thread pool):
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
import { createEngine, loadModel } from "webslm";
|
|
248
|
+
|
|
249
|
+
const engine = await createEngine();
|
|
250
|
+
const small = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", { engine });
|
|
251
|
+
const large = await loadModel("Qwen/Qwen3-0.6B", { engine });
|
|
252
|
+
await small.unload(); // frees the model, keeps the engine
|
|
253
|
+
await engine.terminate();
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## Sources
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
type ModelSource =
|
|
260
|
+
| { hub: string; revision?: string; hubUrl?: string } // a plain string is a hub repo id
|
|
261
|
+
| { files: Record<string, Blob | ArrayBuffer | Uint8Array> } // "config.json", "tokenizer.json", "model.safetensors"...
|
|
262
|
+
| { fetch: (path: string, range?: [number, number]) => Promise<ArrayBuffer | Uint8Array | null> };
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
- **Hub**: the revision (default `main`) is resolved to a commit sha, every needed file is downloaded fully into the cache under `webslm/{repo}/{sha}/`, and the engine reads ranges from there. A later load of the same revision makes no request at all; delete the cached model (or pass a newer revision) to pick up new commits. Pass `token` in the options for gated or private repositories; it is only sent to `hubUrl`.
|
|
266
|
+
- **Files**: bytes the page already holds (an upload, IndexedDB, a training job's output).
|
|
267
|
+
- **Fetch**: a custom store. `range` is `[start, end)`. Return `null` for a missing file: optional files such as `generation_config.json` are probed.
|
|
268
|
+
|
|
269
|
+
`model.info()` lists every file read with its SHA-256, so an application can check what it runs.
|
|
270
|
+
|
|
271
|
+
## LoRA adapters
|
|
272
|
+
|
|
273
|
+
PEFT LoRA adapters, as published on the Hub (`adapter_config.json` and `adapter_model.safetensors`), from the same kinds of sources as models (a repo id, `{ hub }`, `{ files }` or `{ fetch }`):
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
// Merged as the model loads (also with the simple API: `load(model, { adapter })`).
|
|
277
|
+
const model = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", {
|
|
278
|
+
adapter: "user/my-lora",
|
|
279
|
+
adapterScale: 1, // default
|
|
280
|
+
});
|
|
281
|
+
model.info().lora; // { modules: ["model.layers.20.self_attn.q_proj", ...], scale, rank, baseModel, repo, revision }
|
|
282
|
+
|
|
283
|
+
// Later: swap to another adapter, then back to the base model.
|
|
284
|
+
await model.applyAdapter({ files: { "adapter_config.json": config, "adapter_model.safetensors": weights } }, { scale: 0.5 });
|
|
285
|
+
await model.removeAdapter();
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
The adapter is merged into the matrices it targets, `W' = W + (lora_alpha / r) · scale · B·A` (`lora_alpha / sqrt(r)` with `use_rslora`), in f32 before quantization, so decoding runs at the base model's speed. `target_modules` (names, a regular expression or `"all-linear"`), `exclude_modules`, `layers_to_transform`, `layers_pattern`, `rank_pattern` and `alpha_pattern` are honoured. `applyAdapter` reads the affected base matrices again from the model's source (the cache for Hub models; a `fetch` source is called again) and replaces the previous adapter; `removeAdapter` restores the base weights exactly (bit-identical logits). An adapter that does not fit the model rejects with `INVALID_ADAPTER` and leaves the model unchanged; DoRA, LoRA biases and `modules_to_save` are refused. Every session starts over at its next call after a change.
|
|
289
|
+
|
|
290
|
+
## Low-level sessions
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
const session = await model.session(); // independent KV cache over the same weights
|
|
294
|
+
const ids = await model.tokenize(await model.renderChat([{ role: "user", content: "Hi" }]));
|
|
295
|
+
const out = await session.score(ids, { logits: "all", hiddenStates: [4] });
|
|
296
|
+
// out.logits: Float32Array [positions × vocabSize]; out.hidden[4]: [positions × hiddenSize]
|
|
297
|
+
const next = await session.step(42, { logits: true });
|
|
298
|
+
session.length; // positions in the cache
|
|
299
|
+
await session.truncate(ids.length);
|
|
300
|
+
await session.reset();
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Hidden state `i` is the residual stream after layer `i` counted from 1 (`0` is the embedding output), before the final norm: the indexing of `transformers`' `output_hidden_states`. Buffers are transferred from the worker without copies.
|
|
304
|
+
|
|
305
|
+
Attention caches rewind for free. Models with recurrent layers (LFM2 and LFM3 short convolutions, Qwen3.5 Gated DeltaNet, LFM3's sliding-window ring buffers) cannot rewind their state, so `truncate(n)` recomputes it from the first `n` tokens (a prefill of `n` tokens); chats that diverge inside the cache do the same.
|
|
306
|
+
|
|
307
|
+
## Hub helpers and cache
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
import { searchModels, checkModel, listCachedModels, deleteCachedModel, cacheUsage } from "webslm";
|
|
311
|
+
|
|
312
|
+
const results = await searchModels("qwen", { maxParams: 2e9, limit: 20 });
|
|
313
|
+
// [{ repo, supported, reason?, gated, params, sizeBytes, modelType, estimatedMemoryBytes }]
|
|
314
|
+
const check = await checkModel("Qwen/Qwen3-0.6B"); // config, tokenizer, template, safetensors headers by Range
|
|
315
|
+
await listCachedModels();
|
|
316
|
+
await deleteCachedModel("Qwen/Qwen3-0.6B");
|
|
317
|
+
await cacheUsage(); // { usedBytes, originUsageBytes, quotaBytes, persisted }
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Node, Bun and Deno
|
|
321
|
+
|
|
322
|
+
The same API works in Node 20+ and Bun, as a plain ESM script with no bundler. The cache lives in `WEBSLM_CACHE_DIR` or `~/.cache/webslm` (`cacheDir` in the options overrides it). `WEBSLM_OFFLINE=1` (or `HF_HUB_OFFLINE=1`) forbids network access: models already in the cache load, anything else rejects with `NETWORK`. `HF_ENDPOINT` replaces `https://huggingface.co` (a mirror, or a local stand-in in tests) unless a source gives its own `hubUrl`. The engine runs in a `worker_threads` worker, which does not keep the process alive between calls; pass `worker: false` to run it on the calling thread. Deno 2 runs Hub models as is; for a `files` source of a few hundred megabytes, pass `worker: false` (Deno's `worker_threads` cannot copy buffers that large).
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { readFile } from "node:fs/promises";
|
|
326
|
+
import { load } from "webslm";
|
|
327
|
+
|
|
328
|
+
const dir = "./SmolLM2-135M-Instruct";
|
|
329
|
+
const files = Object.fromEntries(
|
|
330
|
+
await Promise.all(
|
|
331
|
+
["config.json", "tokenizer.json", "tokenizer_config.json", "model.safetensors"].map(
|
|
332
|
+
async (f) => [f, await readFile(`${dir}/${f}`)] as const,
|
|
333
|
+
),
|
|
334
|
+
),
|
|
335
|
+
);
|
|
336
|
+
const llm = await load({ files });
|
|
337
|
+
console.log(await llm.ask("Hello!"));
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
## CPU builds and deterministic mode
|
|
341
|
+
|
|
342
|
+
The package ships three WebAssembly builds of the engine and each worker picks the fastest one the environment supports (`selectWasmFlavour()`), unless `wasmFlavour` says otherwise:
|
|
343
|
+
|
|
344
|
+
- `"threads"`: relaxed SIMD and a pool of Web Workers sharing the module's memory, one per logical core up to 8 (`threads` overrides it). Needs `SharedArrayBuffer`: a cross-origin isolated page (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`, or [coi-serviceworker](https://github.com/gzuidhof/coi-serviceworker)), or Node.
|
|
345
|
+
- `"relaxed"`: SIMD128 and relaxed SIMD, one thread.
|
|
346
|
+
- `"simd"`: SIMD128, one thread; runs wherever WebAssembly SIMD does.
|
|
347
|
+
|
|
348
|
+
`model.info().cpu` reports `{ flavour, kernels, threads, deterministic }`, and `model.info().backend` a readable summary such as `"CPU (wasm, relaxed SIMD, 8 threads)"`. Each worker instantiates one build: the first model loaded in it decides.
|
|
349
|
+
|
|
350
|
+
`deterministic: true` selects kernels whose results are bit-identical in every build and natively (the `webslm` command-line tool and the Rust crates on x86_64 and aarch64): same weights, prompt and options, same logits, whatever the browser, CPU or thread count. It gives up fused multiply-adds, which costs speed with `f32` weights only; quantized weights run the same kernels either way.
|
|
351
|
+
|
|
352
|
+
## Bundlers
|
|
353
|
+
|
|
354
|
+
The workers (the engine's, and the thread pool's) and the `.wasm` modules are referenced with `new Worker(new URL(..., import.meta.url))` and `new URL(..., import.meta.url)`, which Vite, webpack 5, Turbopack, Rollup and esbuild-based tools understand. With Vite, keep webslm out of dependency pre-bundling and emit ES workers:
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
// vite.config.ts
|
|
358
|
+
export default defineConfig({
|
|
359
|
+
optimizeDeps: { exclude: ["webslm"] },
|
|
360
|
+
worker: { format: "es" },
|
|
361
|
+
});
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
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.2.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>.
|
|
365
|
+
|
|
366
|
+
## Errors
|
|
367
|
+
|
|
368
|
+
Every error is a `WebslmError` with a stable `code`: `ABORTED`, `NOT_FOUND`, `UNAUTHORIZED` (gated repository), `NETWORK`, `UNSUPPORTED_MODEL`, `UNSUPPORTED_DEVICE`, `INVALID_CHECKPOINT`, `INVALID_ADAPTER`, `NO_CHAT_TEMPLATE`, `INVALID_STATE`, `INVALID_ARGUMENT`, `BUSY`, `DISPOSED`, `READ_FAILED`, `INTEGRITY`, `CACHE`, `WORKER`, `GPU_OUT_OF_MEMORY`, `GPU_DEVICE_LOST`, `GPU_ERROR`, `ENGINE`.
|
|
369
|
+
|
|
370
|
+
WebGPU reports failures asynchronously; webslm checks the device's error scopes, its uncaptured errors and its lost callback, so a model that does not fit fails instead of producing zeros. Before uploading anything, the weights and KV cache are estimated against the adapter's `maxBufferSize` and `maxStorageBufferBindingSize`: a model that cannot fit rejects with `GPU_OUT_OF_MEMORY` (on `device: "webgpu"`) or loads on the CPU (on `"auto"`, with `deviceNote`). An allocation the device refuses while loading or running rejects with `GPU_OUT_OF_MEMORY`, a lost device (driver reset, GPU removed) with `GPU_DEVICE_LOST`: load the model again.
|
|
371
|
+
|
|
372
|
+
## License
|
|
373
|
+
|
|
374
|
+
MIT
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webslm as an [AI SDK](https://ai-sdk.dev) provider: small language models
|
|
3
|
+
* running in the page (or in Node), behind `generateText`, `streamText` and
|
|
4
|
+
* everything else built on the AI SDK's language model interface.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
8
|
+
* import { generateText, streamText } from "ai";
|
|
9
|
+
*
|
|
10
|
+
* const { text } = await generateText({
|
|
11
|
+
* model: webslm("HuggingFaceTB/SmolLM2-360M-Instruct"),
|
|
12
|
+
* prompt: "Write a haiku about the sea",
|
|
13
|
+
* });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
17
|
+
* `webslm`: install them to use this entry point.
|
|
18
|
+
*
|
|
19
|
+
* @packageDocumentation
|
|
20
|
+
*/
|
|
21
|
+
import type { ProviderV4 } from "@ai-sdk/provider";
|
|
22
|
+
import { WebslmLanguageModel, type WebslmModelSettings } from "./language-model.js";
|
|
23
|
+
import { type WebslmEngine, type WebslmLoadOptions } from "./loader.js";
|
|
24
|
+
export { CURATED_MODELS, type CuratedModel } from "../curated.js";
|
|
25
|
+
export { searchModels, type HubModel, type SearchModelsOptions } from "../hub.js";
|
|
26
|
+
export { DEFAULT_MODEL } from "../simple.js";
|
|
27
|
+
export type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
|
|
28
|
+
export { WebslmLanguageModel, type WebslmCallSettings, type WebslmModelSettings, type WebslmPreloadOptions, } from "./language-model.js";
|
|
29
|
+
export type { WebslmEngine, WebslmLoadOptions } from "./loader.js";
|
|
30
|
+
/** Options of {@link createWebslm}. */
|
|
31
|
+
export interface WebslmProviderSettings {
|
|
32
|
+
/**
|
|
33
|
+
* Load options of every model of the provider (device, quant, cache
|
|
34
|
+
* directory, worker, Hub token...). A model's own settings take precedence.
|
|
35
|
+
*/
|
|
36
|
+
readonly loadOptions?: WebslmLoadOptions;
|
|
37
|
+
/** What loads the models (defaults to webslm's `loadModel`). */
|
|
38
|
+
readonly engine?: WebslmEngine;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* An AI SDK provider of webslm models. Call it with a Hugging Face
|
|
42
|
+
* repository id; the language models it returns for one id and the same
|
|
43
|
+
* load options share one loaded model.
|
|
44
|
+
*/
|
|
45
|
+
export interface WebslmProvider extends ProviderV4 {
|
|
46
|
+
(modelId: string, settings?: WebslmModelSettings): WebslmLanguageModel;
|
|
47
|
+
languageModel(modelId: string, settings?: WebslmModelSettings): WebslmLanguageModel;
|
|
48
|
+
/** Frees every model this provider loaded (each loads again on its next call). */
|
|
49
|
+
unloadAll(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates a provider with its own load options and model cache.
|
|
53
|
+
*
|
|
54
|
+
* ```ts
|
|
55
|
+
* import { createWebslm } from "webslm/ai-sdk";
|
|
56
|
+
*
|
|
57
|
+
* const local = createWebslm({ loadOptions: { device: "cpu", quant: "q4" } });
|
|
58
|
+
* const model = local("Qwen/Qwen3-0.6B", { think: false });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export declare function createWebslm(options?: WebslmProviderSettings): WebslmProvider;
|
|
62
|
+
/**
|
|
63
|
+
* The default provider: models load with the default options (device
|
|
64
|
+
* `"auto"`, quant `"q8"`, a worker, the offline cache) and are shared by
|
|
65
|
+
* every `webslm(id)` with the same id and options.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
69
|
+
* import { streamText } from "ai";
|
|
70
|
+
*
|
|
71
|
+
* const model = webslm("Qwen/Qwen3-0.6B", {
|
|
72
|
+
* onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
|
|
73
|
+
* });
|
|
74
|
+
* const result = streamText({ model, prompt: "Is 97 prime?" });
|
|
75
|
+
* for await (const part of result.fullStream) {
|
|
76
|
+
* if (part.type === "reasoning-delta") process.stdout.write(part.text);
|
|
77
|
+
* if (part.type === "text-delta") process.stdout.write(part.text);
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare const webslm: WebslmProvider;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webslm as an [AI SDK](https://ai-sdk.dev) provider: small language models
|
|
3
|
+
* running in the page (or in Node), behind `generateText`, `streamText` and
|
|
4
|
+
* everything else built on the AI SDK's language model interface.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
8
|
+
* import { generateText, streamText } from "ai";
|
|
9
|
+
*
|
|
10
|
+
* const { text } = await generateText({
|
|
11
|
+
* model: webslm("HuggingFaceTB/SmolLM2-360M-Instruct"),
|
|
12
|
+
* prompt: "Write a haiku about the sea",
|
|
13
|
+
* });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* `ai` (v7) and `@ai-sdk/provider` (v4) are optional peer dependencies of
|
|
17
|
+
* `webslm`: install them to use this entry point.
|
|
18
|
+
*
|
|
19
|
+
* @packageDocumentation
|
|
20
|
+
*/
|
|
21
|
+
import { WebslmError } from "../errors.js";
|
|
22
|
+
import { loadModel } from "../models.js";
|
|
23
|
+
import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
|
|
24
|
+
import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
|
|
25
|
+
export { CURATED_MODELS } from "../curated.js";
|
|
26
|
+
export { searchModels } from "../hub.js";
|
|
27
|
+
export { DEFAULT_MODEL } from "../simple.js";
|
|
28
|
+
export { WebslmLanguageModel, } from "./language-model.js";
|
|
29
|
+
function unsupportedModel(kind) {
|
|
30
|
+
throw new WebslmError("INVALID_ARGUMENT", `webslm provides language models only, not ${kind} models`);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a provider with its own load options and model cache.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { createWebslm } from "webslm/ai-sdk";
|
|
37
|
+
*
|
|
38
|
+
* const local = createWebslm({ loadOptions: { device: "cpu", quant: "q4" } });
|
|
39
|
+
* const model = local("Qwen/Qwen3-0.6B", { think: false });
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function createWebslm(options = {}) {
|
|
43
|
+
const engine = options.engine ?? { loadModel };
|
|
44
|
+
const slots = new Map();
|
|
45
|
+
const languageModel = (modelId, settings = {}) => {
|
|
46
|
+
if (typeof modelId !== "string" || modelId.trim() === "") {
|
|
47
|
+
throw new WebslmError("INVALID_ARGUMENT", "the model id must be a Hugging Face repository id");
|
|
48
|
+
}
|
|
49
|
+
const id = modelId.trim();
|
|
50
|
+
const loadOptions = { ...options.loadOptions, ...pickLoadOptions(settings, CALL_SETTING_KEYS) };
|
|
51
|
+
const key = slotKey(id, loadOptions);
|
|
52
|
+
let slot = slots.get(key);
|
|
53
|
+
if (slot === undefined) {
|
|
54
|
+
slot = new ModelSlot(engine, id, loadOptions);
|
|
55
|
+
slots.set(key, slot);
|
|
56
|
+
}
|
|
57
|
+
return new WebslmLanguageModel(id, slot, settings);
|
|
58
|
+
};
|
|
59
|
+
const provider = (modelId, settings) => languageModel(modelId, settings);
|
|
60
|
+
return Object.assign(provider, {
|
|
61
|
+
specificationVersion: "v4",
|
|
62
|
+
languageModel,
|
|
63
|
+
embeddingModel: () => unsupportedModel("embedding"),
|
|
64
|
+
imageModel: () => unsupportedModel("image"),
|
|
65
|
+
unloadAll: async () => {
|
|
66
|
+
const all = [...slots.values()];
|
|
67
|
+
await Promise.all(all.map((slot) => slot.unload()));
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The default provider: models load with the default options (device
|
|
73
|
+
* `"auto"`, quant `"q8"`, a worker, the offline cache) and are shared by
|
|
74
|
+
* every `webslm(id)` with the same id and options.
|
|
75
|
+
*
|
|
76
|
+
* ```ts
|
|
77
|
+
* import { webslm } from "webslm/ai-sdk";
|
|
78
|
+
* import { streamText } from "ai";
|
|
79
|
+
*
|
|
80
|
+
* const model = webslm("Qwen/Qwen3-0.6B", {
|
|
81
|
+
* onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
|
|
82
|
+
* });
|
|
83
|
+
* const result = streamText({ model, prompt: "Is 97 prime?" });
|
|
84
|
+
* for await (const part of result.fullStream) {
|
|
85
|
+
* if (part.type === "reasoning-delta") process.stdout.write(part.text);
|
|
86
|
+
* if (part.type === "text-delta") process.stdout.write(part.text);
|
|
87
|
+
* }
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export const webslm = createWebslm();
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** The AI SDK language model (specification v4) over a webslm model. */
|
|
2
|
+
import type { LanguageModelV4, LanguageModelV4CallOptions, LanguageModelV4GenerateResult, LanguageModelV4StreamResult } from "@ai-sdk/provider";
|
|
3
|
+
import type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
|
|
4
|
+
import { type ModelSlot } from "./loader.js";
|
|
5
|
+
/**
|
|
6
|
+
* Defaults of every call of a model. A call's own settings (`temperature`,
|
|
7
|
+
* `maxOutputTokens`...) and its `providerOptions.webslm` take precedence.
|
|
8
|
+
*/
|
|
9
|
+
export interface WebslmCallSettings {
|
|
10
|
+
/**
|
|
11
|
+
* Whether a model that can reason before answering (Qwen3) does so: sets
|
|
12
|
+
* the chat template's `enable_thinking`. The AI SDK's `reasoning` call
|
|
13
|
+
* setting overrides it (`"none"` turns it off, any level on). Unset, the
|
|
14
|
+
* template decides.
|
|
15
|
+
*/
|
|
16
|
+
readonly think?: boolean;
|
|
17
|
+
/** Largest number of new tokens when the call sets no `maxOutputTokens` (engine default 512). */
|
|
18
|
+
readonly maxTokens?: number;
|
|
19
|
+
/** Sampling temperature when the call sets none; else the checkpoint's, else 0.7. */
|
|
20
|
+
readonly temperature?: number;
|
|
21
|
+
readonly topK?: number;
|
|
22
|
+
readonly topP?: number;
|
|
23
|
+
/** Drop tokens less likely than this fraction of the most likely one. */
|
|
24
|
+
readonly minP?: number;
|
|
25
|
+
/** Penalty on tokens already in the context (1 disables). */
|
|
26
|
+
readonly repetitionPenalty?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Most tokens of a reasoning block before the model must answer. Unset,
|
|
29
|
+
* the AI SDK's `reasoning` level sets one (`minimal` 128, `low` 512,
|
|
30
|
+
* `medium` 2048; none above).
|
|
31
|
+
*/
|
|
32
|
+
readonly thinkingBudget?: number;
|
|
33
|
+
/** Extra chat template variables. */
|
|
34
|
+
readonly templateKwargs?: Readonly<Record<string, unknown>>;
|
|
35
|
+
}
|
|
36
|
+
/** Settings of `webslm(modelId, settings)`: how to load the model, and call defaults. */
|
|
37
|
+
export interface WebslmModelSettings extends Omit<LoadModelOptions, "signal">, WebslmCallSettings {
|
|
38
|
+
}
|
|
39
|
+
/** Options of {@link WebslmLanguageModel.load}. */
|
|
40
|
+
export interface WebslmPreloadOptions {
|
|
41
|
+
/** Download and load progress, besides the model's own `onProgress`. */
|
|
42
|
+
readonly onProgress?: (progress: LoadProgress) => void;
|
|
43
|
+
/** Stops waiting; the load itself stops when nobody else waits for it. */
|
|
44
|
+
readonly signal?: AbortSignal;
|
|
45
|
+
}
|
|
46
|
+
/** The fields of {@link WebslmCallSettings}: the settings that are not load options. */
|
|
47
|
+
export declare const CALL_SETTING_KEYS: readonly ["think", "maxTokens", "temperature", "topK", "topP", "minP", "repetitionPenalty", "thinkingBudget", "templateKwargs"];
|
|
48
|
+
/**
|
|
49
|
+
* A webslm model as an AI SDK `LanguageModelV4`. The checkpoint is
|
|
50
|
+
* downloaded and loaded on the first call (or by {@link load}), then kept
|
|
51
|
+
* for later calls; calls run one after the other.
|
|
52
|
+
*/
|
|
53
|
+
export declare class WebslmLanguageModel implements LanguageModelV4 {
|
|
54
|
+
#private;
|
|
55
|
+
readonly specificationVersion = "v4";
|
|
56
|
+
readonly provider = "webslm";
|
|
57
|
+
readonly modelId: string;
|
|
58
|
+
/** Text-only models: no URL is read by the model itself. */
|
|
59
|
+
readonly supportedUrls: Record<string, RegExp[]>;
|
|
60
|
+
/** @internal Created by a provider: `webslm(modelId)` or `createWebslm(...)(modelId)`. */
|
|
61
|
+
constructor(modelId: string, slot: ModelSlot, settings: WebslmModelSettings);
|
|
62
|
+
/** Description of the model once loaded (architecture, backend, files...). */
|
|
63
|
+
get info(): ModelInfo | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* Downloads (once, into the cache) and loads the model now rather than on
|
|
66
|
+
* the first call, reporting progress. Resolves to its description.
|
|
67
|
+
*/
|
|
68
|
+
load(options?: WebslmPreloadOptions): Promise<ModelInfo>;
|
|
69
|
+
/**
|
|
70
|
+
* Frees the model (once the generation in progress ends). Every language
|
|
71
|
+
* model of the provider with the same id and load options shares it; the
|
|
72
|
+
* next call loads it again.
|
|
73
|
+
*/
|
|
74
|
+
unload(): Promise<void>;
|
|
75
|
+
doGenerate(options: LanguageModelV4CallOptions): Promise<LanguageModelV4GenerateResult>;
|
|
76
|
+
doStream(options: LanguageModelV4CallOptions): Promise<LanguageModelV4StreamResult>;
|
|
77
|
+
}
|