bitgpu 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,11 +6,16 @@ Today it runs **1-bit (binary-weight)** models.
6
6
  Reference targets are Bonsai **1.7B, 4B and 8B** (Qwen3 architecture, sign-packed binary linear
7
7
  weights + 2/4-bit embeddings, tied or untied lm_head) - every size is gated bit-exact against the
8
8
  reference forward on real hardware. GPU-resident decode (greedy or sampled), streaming, EOS stop,
9
- `AbortSignal`, and cross-turn KV-cache reuse. Runs the fast subgroup path on Apple / NVIDIA /
9
+ `AbortSignal`, cross-turn KV-cache reuse, optional f16/q8 KV-cache compression for long
10
+ contexts in less VRAM, and conversation snapshots (save/restore across page reloads). Runs the
11
+ fast subgroup path on Apple / NVIDIA /
10
12
  recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
11
13
  Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
12
14
  only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
13
15
 
16
+ **[DEMO](https://stfurkan.github.io/bitgpu/examples/chat.html)**: pick a model, let the weights
17
+ stream once from the Hugging Face Hub, and chat with it on your own GPU.
18
+
14
19
  ## Install
15
20
 
16
21
  ```sh
@@ -28,7 +33,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
28
33
  import { createEngine } from 'bitgpu'
29
34
  import { createChat } from 'bitgpu/chat'
30
35
 
31
- const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.8.0/models/bonsai-1.7b'
36
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.10.0/models/bonsai-1.7b'
32
37
  const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
33
38
  const engine = await createEngine({
34
39
  manifestUrl: `${REPO}/manifest.json`,
@@ -42,8 +47,9 @@ const chat = await createChat(engine, {
42
47
  await chat.send([{ role: 'user', content: 'Hi!' }], { onText: (t) => process.stdout.write(t) })
43
48
  ```
44
49
 
45
- Or just open the single-file demo: [`examples/chat.html`](examples/chat.html) - model picker,
46
- streaming chat, and guaranteed-valid JSON mode, entirely on-device.
50
+ The [demo](https://stfurkan.github.io/bitgpu/examples/chat.html) ([source](examples/chat.html))
51
+ is this quickstart as a single HTML file: model picker, streaming chat, JSON mode with a schema
52
+ editor, and cached downloads.
47
53
 
48
54
  ## Usage
49
55
 
@@ -80,6 +86,35 @@ await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSi
80
86
  engine.dispose()
81
87
  ```
82
88
 
89
+ ### KV cache modes (`kvCache`)
90
+
91
+ The KV cache is what grows with conversation length (~224 KB per position at f32 on
92
+ Bonsai-1.7B; `maxSeqLen` caps it). `kvCache` selects its **storage** precision - attention
93
+ arithmetic always stays f32, values are compressed once at cache-write:
94
+
95
+ | Mode | Bytes/value | KV memory | Requires |
96
+ | --- | --- | --- | --- |
97
+ | `'f32'` (default) | 4 | 1x | - |
98
+ | `'f16'` | 2 | 1/2 | `shader-f16` (silently falls back to f32 without it) |
99
+ | `'q8'` | ~1.125 | ~1/4 | nothing - works on every WebGPU adapter |
100
+
101
+ ```ts
102
+ const engine = await createEngine({ modelUrl, kvCache: 'q8', maxSeqLen: 4096 })
103
+ ```
104
+
105
+ `'q8'` stores 8-bit values with one f32 scale per 32-element block (llama.cpp q8_0-style, the
106
+ tier the wider ecosystem treats as near-lossless). Within any mode decoding stays exact and
107
+ deterministic (same seed -> same tokens, cache reuse == full prefill), but f16/q8 outputs are
108
+ **not guaranteed bit-identical to f32** - they are measured instead: the GPU gate compares
109
+ greedy continuations against f32 on every Bonsai size and both kernel paths, and q8 currently
110
+ agrees 96/96 tokens on short prompts, 24/24 after a 400-token prompt and 48/48 after a
111
+ 1500-token prompt (logits cosine >= 0.99997). Long contexts also get *faster* under q8 - decode
112
+ at 1500 tokens of depth measured 37-58% quicker than f32 (attention there is memory-bound and
113
+ reads a quarter of the bytes) - while shallow-context decode measures a few percent slower.
114
+ Reach for `'q8'` to run a 4x longer window in the same VRAM (or the same window on smaller
115
+ GPUs); keep the default `'f32'` when bit-exact reproducibility is the point.
116
+ `engine.capabilities.kvCache` reports what is actually active.
117
+
83
118
  ## Chat (`bitgpu/chat`)
84
119
 
85
120
  The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
@@ -140,18 +175,101 @@ await chat.send(messages, { format: { json: { schema: {
140
175
  ```
141
176
 
142
177
  Enforceable subset: `type` (incl. `integer`), `properties` / `required` /
143
- `additionalProperties: false`, `items`, `minItems` / `maxItems`, string `enum`, nested to any
144
- depth. Anything else (`pattern`, `minimum`, `oneOf`, `$ref`, ...) **throws up front** - never
145
- silently ignored. The guarantee is structural, not semantic: a schema makes the output parse
146
- into the right shape, not be true. Built on the engine's generic `candidateFilter` hook (see
147
- `GenerateOptions`), which is open for custom grammars.
178
+ `additionalProperties: false`, `items`, `minItems` / `maxItems`, string `enum`,
179
+ `minLength` / `maxLength` (code points), integer `minimum` / `maximum` (with prefix
180
+ feasibility, so the model can never be trapped mid-number), and `oneOf` as a **discriminated
181
+ union** - object branches sharing one required property whose single-value `enum` differs per
182
+ branch, e.g. a slide that is either `{type: 'bullets', ...}` or `{type: 'quote', ...}`; the
183
+ machine tracks the live branches until the discriminator commits. All nested to any depth.
184
+ Anything else (`pattern`, float ranges, general `oneOf`, `$ref`, ...) **throws up front** -
185
+ never silently ignored. The guarantee is structural, not semantic: a schema makes the output
186
+ parse into the right shape, not be true. Built on the engine's generic `candidateFilter` hook
187
+ (see `GenerateOptions`), which is open for custom grammars.
188
+
189
+ ### Confidence (`logprobs`)
190
+
191
+ Pass `logprobs: N` (engine or chat options) and every emitted token comes back with its TRUE
192
+ logprob plus the top-N alternatives - log-softmax over the full vocabulary, computed exactly via
193
+ a GPU log-sum-exp (one extra f32 readback per step, not a top-K approximation):
194
+
195
+ ```ts
196
+ const r = await chat.send(messages, { logprobs: 5 })
197
+ const confidence = Math.exp(r.logprobs[0].logprob) // p of the first token; low = the model is guessing
198
+ ```
199
+
200
+ Use it to flag low-confidence answers, build "are you sure?" UX, or detect when a
201
+ schema/tool filter had to force a token the model ranked poorly. Greedy output is bit-identical
202
+ with or without it; `promptLookup` is disabled for the turn.
203
+
204
+ ### Tool calling (`tools`)
205
+
206
+ The model's own protocol (Qwen3-family templates render a `tools` list and emit
207
+ `<tool_call>` blocks), with the same enforcement guarantee as schema mode: a bitgpu tool call
208
+ **cannot be malformed** - once the model opens a call, the name is forced to one of your
209
+ declared tools and the arguments are forced through that tool's `parameters` schema,
210
+ token-by-token.
211
+
212
+ ```ts
213
+ const tools = [{
214
+ type: 'function',
215
+ function: {
216
+ name: 'get_weather',
217
+ description: 'Get the current weather for a city.',
218
+ parameters: { type: 'object', required: ['city'], additionalProperties: false,
219
+ properties: { city: { type: 'string' }, unit: { enum: ['celsius', 'fahrenheit'] } } },
220
+ },
221
+ }]
222
+
223
+ const r = await chat.send(messages, { tools })
224
+ if (r.finishReason === 'tool_calls') {
225
+ const call = r.toolCalls[0] // { name, arguments } - always valid
226
+ const result = await runMyTool(call) // executing is YOUR code, on YOUR terms
227
+ const r2 = await chat.send([
228
+ ...messages,
229
+ { role: 'assistant', content: r.text, tool_calls: r.toolCalls },
230
+ { role: 'tool', content: JSON.stringify(result) },
231
+ ], { tools }) // extends the KV cache - no re-prefill
232
+ }
233
+ ```
234
+
235
+ `toolChoice: { name: 'get_weather' }` **forces** a call to that tool as the entire reply - fully
236
+ enforced end to end, and the reliable way to use tools with small models. `'auto'` (the default)
237
+ lets the model decide, which is where model judgment comes in: a 1-bit model can call when it
238
+ should answer, or answer when it should call. Enforcement guarantees the call's *shape*, never
239
+ its *judgment* - keep tool sets small (2-3 tools), prefer forced calls when the UI knows one is
240
+ needed, and validate argument *values* in your executor. The engine never executes anything,
241
+ never loops, never retries: it returns a validated call and the app stays in charge (there is
242
+ deliberately no agent framework in here).
243
+
244
+ ### Conversation snapshots (`save` / `restore`)
245
+
246
+ `chat.save()` captures the whole conversation - the engine's KV cache plus the chat's exact
247
+ token bookkeeping - as one structured-cloneable object; `chat.restore(snapshot)` brings it back,
248
+ so the next turn extends the cache as if the session never ended (no re-prefill of the history):
249
+
250
+ ```ts
251
+ const snapshot = await chat.save() // structured-cloneable: IndexedDB / OPFS / postMessage
252
+ // (NOT JSON.stringify - the KV buffer would be lost)
253
+ // ...page reload: new engine + chat on the same model and kvCache mode...
254
+ await chat.restore(snapshot)
255
+ await chat.send([...savedMessages, { role: 'user', content: 'as I was saying...' }]) // cache reuse
256
+ ```
257
+
258
+ Use it for instant conversation switching (save several, restore the active one) and for
259
+ resuming after a reload without re-prefilling a long history. Restore validates the model
260
+ architecture and `kvCache` mode and throws on mismatch; restoring is bit-identical to having
261
+ kept the conversation alive (gated on real hardware). Snapshot size scales with the KV mode
262
+ (~224 / 112 / 63 KB per cached token on Bonsai-1.7B at f32 / f16 / q8), which makes
263
+ `kvCache: 'q8'` the natural companion. The engine-level `engine.saveCache()` /
264
+ `engine.restoreCache()` are the same thing for ids-in/ids-out callers.
148
265
 
149
266
  The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
150
267
  see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
151
268
  engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
152
- `bitgpu` never loads any chat code. Rendering and encoding are verified byte-exact against
153
- transformers.js (`npm run test:chat`), and the GPU gate proves the reuse path bit-exact on real
154
- hardware. Prefer your own tokenizer? Skip `bitgpu/chat` entirely - the engine API is unchanged.
269
+ `bitgpu` never loads any chat code. Rendering and encoding (including tool declarations, calls,
270
+ and responses) are verified byte-exact against transformers.js (`npm run test:chat`), and the
271
+ GPU gate proves the reuse paths bit-exact on real hardware. Prefer your own tokenizer? Skip
272
+ `bitgpu/chat` entirely - the engine API is unchanged.
155
273
 
156
274
  ## Bring your own model
157
275
 
@@ -196,6 +314,10 @@ regenerating the verification fixtures for a new model: [tools/README.md](tools/
196
314
  later `generate(delta, { reuseCache: true })` starts from a warm cache (e.g. a static system prompt).
197
315
  - `engine.forward(tokenIds)` - single forward pass (hidden states + logits) for correctness checks.
198
316
  - `engine.resetCache()` - clear the cross-turn KV cache (start a fresh conversation).
317
+ - `engine.saveCache()` / `engine.restoreCache(snapshot)` - snapshot the conversation (KV cache
318
+ contents + token history) as one structured-cloneable object and bring it back later,
319
+ bit-identically - into this engine or a fresh one on the same model and `kvCache` mode. See
320
+ the chat-layer `save()`/`restore()` below for the batteries-included version.
199
321
  - `engine.capabilities` - detected GPU path (`useSubgroups`, `subgroupSize`, adapter info, limits).
200
322
  - `engine.lost` - promise that resolves if the GPU device is lost (also via `onDeviceLost` option);
201
323
  create a new engine to recover.
@@ -215,6 +337,11 @@ WebGPU with compute is required (a clear `WebGPUUnavailableError` is thrown othe
215
337
  | Firefox | workgroup fallback | WebGPU shipped, but per-dispatch overhead is high; expect low throughput |
216
338
  | Android Chrome | device-dependent | works where WebGPU is exposed; VRAM limits apply |
217
339
 
340
+ The engine has no DOM dependencies and WebGPU is available in workers, so the whole stack runs
341
+ off the main thread: [examples/worker.html](examples/worker.html) is a complete copy-paste
342
+ pattern (module worker + a four-message protocol) whose page stays at full frame rate through
343
+ load, prefill, and decode.
344
+
218
345
  ## CDN usage
219
346
 
220
347
  ```html
@@ -240,7 +367,9 @@ npm run check:publish # publint + are-the-types-wrong
240
367
 
241
368
  `examples/verify.html` re-runs the full bit-exactness + throughput suite (forward cosines vs the
242
369
  committed reference fixtures in `test-fixtures/forward/`, known-good greedy ids, sampler kernel
243
- parity, determinism, KV reuse/growth, prompt-lookup identity) against the **built package** and
370
+ parity, determinism, KV reuse/growth, prompt-lookup identity, KV snapshot save/restore round
371
+ trips - including into a fresh engine - and the f16/q8 KV-mode sections: within-mode exactness
372
+ plus greedy agreement vs f32 out to a 1500-token prompt) against the **built package** and
244
373
  prints `PACKAGE OK` or `REGRESSION`.
245
374
 
246
375
  It needs model weights, which are not committed. Point `examples/model` at a directory holding the
@@ -7,13 +7,13 @@ time so the published package has zero runtime dependencies. The core `bitgpu` e
7
7
  ## @huggingface/tokenizers
8
8
 
9
9
  - Copyright (c) Hugging Face
10
- - License: Apache License 2.0 — <https://github.com/huggingface/tokenizers-js/blob/main/LICENSE>
10
+ - License: Apache License 2.0 - <https://github.com/huggingface/tokenizers-js/blob/main/LICENSE>
11
11
  - Source: <https://www.npmjs.com/package/@huggingface/tokenizers>
12
12
 
13
13
  ## @huggingface/jinja
14
14
 
15
15
  - Copyright (c) Hugging Face
16
- - License: Apache License 2.0 — <https://github.com/huggingface/huggingface.js/blob/main/LICENSE>
16
+ - License: Apache License 2.0 - <https://github.com/huggingface/huggingface.js/blob/main/LICENSE>
17
17
  - Source: <https://www.npmjs.com/package/@huggingface/jinja>
18
18
 
19
19
  The full Apache License 2.0 text: <https://www.apache.org/licenses/LICENSE-2.0>
package/dist/chat.d.ts CHANGED
@@ -1,9 +1,16 @@
1
- import { n as Engine, o as GenerateOptions } from "./types-CsoJYJlG.js";
1
+ import { c as KvSnapshot, n as Engine, o as GenerateOptions, u as TokenLogprobs } from "./types-CcgsXirU.js";
2
2
 
3
3
  //#region src/chat/tokenizer.d.ts
4
4
  interface ChatMessage {
5
- role: 'system' | 'user' | 'assistant' | (string & {});
5
+ role: 'system' | 'user' | 'assistant' | 'tool' | (string & {});
6
6
  content: string;
7
+ /** Tool calls made on a past assistant turn (the template renders them back as <tool_call>
8
+ * blocks). Feed a turn's calls back verbatim from {@link ChatResult.toolCalls} when
9
+ * continuing a tool round trip; a `tool` role message then carries each result. */
10
+ tool_calls?: {
11
+ name: string;
12
+ arguments: Record<string, unknown> | string;
13
+ }[];
7
14
  }
8
15
  /** Incremental decoder for streaming generation: feed token ids as they arrive, get the newly
9
16
  * stable visible text each step. Re-decodes the running sequence and emits the delta, holding
@@ -29,14 +36,18 @@ declare class ChatTokenizer {
29
36
  decode(ids: number[], skipSpecialTokens?: boolean): string;
30
37
  /** The raw vocab string for a token id (byte-alias space for byte-level BPE). */
31
38
  idToToken(id: number): string | undefined;
39
+ /** The id of an exact vocab token (e.g. the <tool_call> marker); undefined when absent. */
40
+ tokenToId(token: string): number | undefined;
32
41
  /** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
33
42
  addedTokenIds(): Set<number>;
34
43
  get hasChatTemplate(): boolean;
35
44
  /** Render a message list to a prompt string via the model's own Jinja chat template
36
- * (matches transformers.js apply_chat_template byte-exactly). */
45
+ * (matches transformers.js apply_chat_template byte-exactly). `tools` is passed to the
46
+ * template verbatim (Qwen-family templates serialize each entry into the system block). */
37
47
  applyChatTemplate(messages: ChatMessage[], opts?: {
38
48
  addGenerationPrompt?: boolean;
39
49
  enableThinking?: boolean;
50
+ tools?: readonly unknown[];
40
51
  }): string;
41
52
  createDecoderStream(skipSpecialTokens?: boolean): DecoderStream;
42
53
  }
@@ -52,6 +63,19 @@ interface JsonSchema {
52
63
  minItems?: number;
53
64
  maxItems?: number;
54
65
  enum?: string[];
66
+ /** DISCRIMINATED union only: every branch an object with additionalProperties: false, sharing
67
+ * one required property whose single-value enum differs per branch (the discriminator), with
68
+ * any other shared property schema identical across branches. General oneOf throws. */
69
+ oneOf?: JsonSchema[];
70
+ /** Integer range (type 'integer' only - float ranges are not incrementally enforceable).
71
+ * Enforced with prefix feasibility: a digit is only permitted while SOME completion can still
72
+ * land in range, so the machine can never get stuck mid-number. */
73
+ minimum?: number;
74
+ maximum?: number;
75
+ /** String length in code points (a \uXXXX escape counts as one); type 'string' only, and not
76
+ * combinable with enum (the literals already fix the length). */
77
+ minLength?: number;
78
+ maxLength?: number;
55
79
  }
56
80
  /** Validate a schema against the enforceable subset; throws listing anything unsupported. */
57
81
  declare function validateJsonSchema(schema: JsonSchema, path?: string, isRoot?: boolean): void;
@@ -69,6 +93,13 @@ declare class JsonMachine {
69
93
  private strBuf;
70
94
  private strTracking;
71
95
  private enumCands;
96
+ private strLenOn;
97
+ private strCount;
98
+ private strMin;
99
+ private strMax;
100
+ private numMin;
101
+ private numMax;
102
+ private numBuf;
72
103
  private pending;
73
104
  private wsRun;
74
105
  constructor(root?: JsonSchema | null);
@@ -91,10 +122,134 @@ declare class JsonMachine {
91
122
  * grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
92
123
  * allows generous pretty-printing indentation while forcing real progress. */
93
124
  private ws;
125
+ /** Integer bounds: can SOME digit-extension of the current number prefix (including "stop
126
+ * here") land inside [min, max]? The attainable values from digit string D are
127
+ * union over k >= 0 of sign * [D*10^k, (D+1)*10^k - 1]; leading-zero rules make 0 / -0
128
+ * terminal-only. Rejecting infeasible digits up front means the machine can never trap the
129
+ * model in an unfinishable number. */
130
+ private intFeasible;
131
+ /** May the current number END here (bounds permitting)? */
132
+ private intInRange;
133
+ /** Accept a digit into the current number, bounds permitting. */
134
+ private numAppend;
135
+ /** Count one code point of the current string, maxLength permitting. */
136
+ private strChar;
94
137
  private byte;
95
138
  /** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
96
139
  private enumOk;
97
140
  }
141
+ interface TokenBytesSource {
142
+ idToToken(id: number): string | undefined;
143
+ addedTokenIds(): Set<number>;
144
+ }
145
+ /** Precomputed id -> raw bytes lookup (lazy per id; added/special tokens map to null). */
146
+ declare class TokenByteTable {
147
+ private readonly tk;
148
+ private readonly cache;
149
+ private readonly inv;
150
+ private readonly added;
151
+ constructor(tk: TokenBytesSource);
152
+ bytes(id: number): Uint8Array | null;
153
+ }
154
+ //#endregion
155
+ //#region src/chat/tools.d.ts
156
+ /** A tool declaration, in the shape Qwen-family models were trained on (and the shape the
157
+ * OpenAI/HF ecosystems use); the template serializes it verbatim into the system block. */
158
+ interface ChatTool {
159
+ type: 'function';
160
+ function: {
161
+ name: string;
162
+ description?: string;
163
+ /** JSON Schema for the arguments object - the same enforceable SUBSET as
164
+ * format: { json: { schema } }, and the root must be an object. When omitted, the
165
+ * arguments are only forced to be a valid JSON object. */
166
+ parameters?: JsonSchema;
167
+ };
168
+ }
169
+ /** One parsed tool call from the reply. With tools enabled the arguments are grammar-enforced,
170
+ * so `JSON.parse` can never have failed; `raw` keeps the exact block text for forensics (and is
171
+ * the only place to look if a block was cut short by maxTokens - then `name` is ''). */
172
+ interface ToolCall {
173
+ name: string;
174
+ arguments: Record<string, unknown>;
175
+ /** The exact text between <tool_call> and </tool_call>. */
176
+ raw: string;
177
+ }
178
+ /** Which tool the model must (or may) call. 'auto' (the default when tools are present) lets the
179
+ * model decide; { name } FORCES a call to that tool as the entire reply - the forced path is
180
+ * fully enforced end to end and is the reliable way to use small models. 'none' ignores the
181
+ * tools for this turn. */
182
+ type ToolChoice = 'auto' | 'none' | {
183
+ name: string;
184
+ };
185
+ /** Validate a tools list + choice; throws on anything the enforcer cannot guarantee. */
186
+ declare function validateTools(tools: readonly ChatTool[], choice: ToolChoice): void;
187
+ declare class ToolBodyMachine {
188
+ private readonly cands;
189
+ private readonly schemas;
190
+ private phase;
191
+ private lit;
192
+ private nameBuf;
193
+ private args;
194
+ private wsRun;
195
+ /** true once the closing '}' has landed (only trailing ws may follow). */
196
+ complete: boolean;
197
+ /** the committed tool name (set when its closing quote lands). */
198
+ name: string;
199
+ /** byte-space tool names, and each name's arguments schema */
200
+ constructor(cands: readonly string[], schemas: ReadonlyMap<string, JsonSchema>);
201
+ clone(): ToolBodyMachine;
202
+ static bytesOf(s: string): string;
203
+ feed(bytes: Uint8Array): boolean;
204
+ private byte;
205
+ }
206
+ interface ToolMarkerIds {
207
+ open: number;
208
+ close: number;
209
+ eos: number;
210
+ thinkOpen?: number;
211
+ thinkClose?: number;
212
+ }
213
+ interface PreparedTools {
214
+ tools: readonly ChatTool[];
215
+ ids: ToolMarkerIds;
216
+ /** null = 'auto'; a name = forced single call */
217
+ forced: string | null;
218
+ }
219
+ /** Per-step candidate filter for tool turns. Auto mode: free text (everything permitted) until
220
+ * the model opens <tool_call>, then the body grammar takes over until </tool_call>, then free
221
+ * text again (another call, prose, or eos). Forced mode: the FIRST token must be <tool_call>,
222
+ * the body is constrained to the named tool, and after </tool_call> only eos is permitted.
223
+ * Call advance() with each emitted token to move the real machine. */
224
+ declare function makeToolFilter(table: TokenByteTable, prep: PreparedTools): {
225
+ filter: (ids: Uint32Array | number[]) => number[];
226
+ advance: (id: number) => void;
227
+ };
228
+ /** Stream-safe <tool_call> block extraction (the tool sibling of ThinkSplitter): visible text on
229
+ * one channel, each COMPLETED block's content as its own string, tags never surfacing anywhere.
230
+ * Tags can straddle token boundaries, so chunk edges hold back possible partial tags. */
231
+ declare class ToolCallSplitter {
232
+ private readonly open;
233
+ private readonly close;
234
+ private inside;
235
+ private hold;
236
+ private buf;
237
+ constructor(open?: string, close?: string);
238
+ push(chunk: string): {
239
+ text: string;
240
+ blocks: string[];
241
+ };
242
+ /** Emit whatever is held back. A block cut short by maxTokens surfaces as `partial` (its
243
+ * content never reaches the visible text). */
244
+ flush(): {
245
+ text: string;
246
+ blocks: string[];
247
+ partial: string | null;
248
+ };
249
+ }
250
+ /** Parse one block's content into a ToolCall. With enforcement on this cannot fail for a
251
+ * completed block; a failure (unenforced or truncated content) yields name '' and the raw text. */
252
+ declare function parseToolCall(raw: string): ToolCall;
98
253
  //#endregion
99
254
  //#region src/chat/think.d.ts
100
255
  interface SplitChunk {
@@ -156,6 +311,10 @@ interface ChatSendOptions {
156
311
  noRepeatNgramSize?: number;
157
312
  seed?: number;
158
313
  promptLookup?: GenerateOptions['promptLookup'];
314
+ /** Per-token TRUE logprobs, N top alternatives per step (see GenerateOptions.logprobs) -
315
+ * surface model confidence: a low top-1 logprob or a flat top-N is the model guessing.
316
+ * Disables promptLookup for the turn. */
317
+ logprobs?: number;
159
318
  /** Extra stop token ids, in addition to the model's eos. */
160
319
  stopTokens?: number[];
161
320
  /** Stop STRINGS: generation ends when the visible reply contains one (matched across token
@@ -183,6 +342,21 @@ interface ChatSendOptions {
183
342
  /** Reuse the KV cache when this turn is a clean append to the previous one (the committed
184
343
  * conversation plus one new user turn). Default true; set false to force a full prefill. */
185
344
  reuseCache?: boolean;
345
+ /** Tools the model may call this turn, in the trained (OpenAI-shaped) declaration format. The
346
+ * model's own chat template renders them into the system block; any <tool_call> blocks in the
347
+ * reply are extracted (never shown as text), grammar-ENFORCED against the declared names and
348
+ * each tool's `parameters` schema, and returned parsed in {@link ChatResult.toolCalls}. The
349
+ * app executes a call and feeds the result back as a `tool` role message (plus the assistant
350
+ * turn with its `tool_calls`); the engine never executes anything. Enforcement guarantees the
351
+ * call's SHAPE, not its judgment - whether and what to call is model quality. Cannot combine
352
+ * with `format`; disables `promptLookup` for the turn. */
353
+ tools?: ChatTool[];
354
+ /** 'auto' (default): the model decides. { name }: FORCE a call to that tool as the whole reply
355
+ * (fully enforced end to end - the reliable mode for small models; implies think: false).
356
+ * 'none': ignore `tools` this turn. */
357
+ toolChoice?: ToolChoice;
358
+ /** Fired as each completed tool call is parsed during streaming. */
359
+ onToolCall?: (call: ToolCall) => void;
186
360
  /** Constrained decoding. `'json'` guarantees the reply is one complete, valid JSON value with
187
361
  * an object or array root: every generated token is validated against an incremental JSON
188
362
  * machine (invalid candidates are never sampled), and generation ends when the root value
@@ -200,22 +374,44 @@ interface ChatSendOptions {
200
374
  };
201
375
  }
202
376
  interface ChatResult {
203
- /** The visible reply (think blocks removed). */
377
+ /** The visible reply (think blocks and tool_call blocks removed). */
204
378
  text: string;
205
379
  /** Content of <think> blocks, when the model emitted any. */
206
380
  thinkText: string;
381
+ /** Parsed tool calls, in emission order (empty when the model answered in prose or no tools
382
+ * were given). Grammar enforcement makes every COMPLETED call well-formed; a call cut short
383
+ * by maxTokens has name '' and its partial text in `raw` (finishReason is then 'length'). */
384
+ toolCalls: ToolCall[];
207
385
  /** Generated token ids (as returned by the engine; excludes the prompt). */
208
386
  tokens: number[];
209
387
  /** The exact token ids fed to the engine this turn (the full prompt, or the reuse delta). */
210
388
  inputTokenIds: number[];
211
- /** Why generation ended. */
212
- finishReason: 'stop' | 'length' | 'abort';
389
+ /** Why generation ended ('tool_calls' = ended at eos after making tool calls). */
390
+ finishReason: 'stop' | 'length' | 'abort' | 'tool_calls';
213
391
  /** True when this turn extended the KV cache instead of a full prefill. */
214
392
  reusedCache: boolean;
393
+ /** Per-token logprob records aligned with `tokens` (present when options.logprobs was set). */
394
+ logprobs?: TokenLogprobs[];
215
395
  prefillMs: number;
216
396
  decodeMs: number;
217
397
  tokensPerSecond: number;
218
398
  }
399
+ /** A saved conversation from {@link Chat.save}: the engine's {@link KvSnapshot} plus the
400
+ * chat-layer bookkeeping that makes cache reuse safe. Structured-cloneable (store in
401
+ * IndexedDB / OPFS or postMessage as-is; NOT `JSON.stringify`-able - the KV buffer would be
402
+ * lost). Treat the fields as opaque. */
403
+ interface ChatSnapshot {
404
+ /** Snapshot format version (currently `1`). */
405
+ version: 1;
406
+ /** The engine-level KV cache + token history snapshot. */
407
+ engine: KvSnapshot;
408
+ /** The committed transcript the cache holds, as messages. */
409
+ committed: ChatMessage[];
410
+ /** Whether the cached token sequence already ends with the eos token. */
411
+ cacheEndsAtEos: boolean;
412
+ /** Canonical JSON of the tools list the conversation was rendered with (null = no tools). */
413
+ toolsKey: string | null;
414
+ }
219
415
  interface Chat {
220
416
  /** Generate a reply for the message list. Resolves with the full result; stream text via
221
417
  * `onText`. Turns are serialized: overlapping calls queue instead of interleaving. */
@@ -224,17 +420,32 @@ interface Chat {
224
420
  * is the generator's return value: `const it = chat.stream(msgs); for await (const d of it) ...` */
225
421
  stream(messages: ChatMessage[], options?: ChatSendOptions): AsyncGenerator<string, ChatResult>;
226
422
  /** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
227
- * so the first real turn is a cheap cache-append instead of a cold full prefill. */
228
- prewarm(messages: ChatMessage[]): Promise<void>;
423
+ * so the first real turn is a cheap cache-append instead of a cold full prefill. Pass the same
424
+ * `tools` the turns will use - the template renders them into the system block, so a prewarm
425
+ * without them warms a different prompt. */
426
+ prewarm(messages: ChatMessage[], opts?: {
427
+ tools?: ChatTool[];
428
+ }): Promise<void>;
229
429
  /** Token count of the rendered prompt for a message list (chat template applied) - use for
230
430
  * window budgeting against `engine.capabilities.maxSeqLen`, e.g. in an onOverflow policy. */
231
431
  countTokens(messages: ChatMessage[], opts?: {
232
432
  addGenerationPrompt?: boolean;
233
433
  think?: boolean;
434
+ tools?: ChatTool[];
234
435
  }): number;
235
436
  /** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
236
437
  * Use this (not engine.resetCache()) so the two stay in sync. */
237
438
  reset(): void;
439
+ /** Snapshot the conversation - the engine's KV cache plus the chat's committed-transcript
440
+ * bookkeeping - as one structured-cloneable object. Persist it (IndexedDB / OPFS) or ship it
441
+ * to another worker; restoring it into a chat on the same model and `kvCache` mode makes the
442
+ * next clean-append turn extend the cache exactly as if the conversation never stopped (no
443
+ * re-prefill). Returns null when no conversation is committed. Queues behind in-flight turns
444
+ * like send/stream. */
445
+ save(): Promise<ChatSnapshot | null>;
446
+ /** Replace the current conversation with a saved snapshot (see {@link Chat.save}). Throws when
447
+ * the snapshot does not match this engine's model or `kvCache` mode. */
448
+ restore(snapshot: ChatSnapshot): Promise<void>;
238
449
  /** The model's end-of-sequence token id. */
239
450
  readonly eosTokenId: number;
240
451
  /** Escape hatch: encode/decode/applyChatTemplate for callers that need the text boundary. */
@@ -243,5 +454,5 @@ interface Chat {
243
454
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
244
455
  declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
245
456
  //#endregion
246
- export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
457
+ export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatSnapshot, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
247
458
  //# sourceMappingURL=chat.d.ts.map