bitgpu 0.7.0 → 0.9.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
@@ -11,6 +11,9 @@ recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU i
11
11
  Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
12
12
  only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
13
13
 
14
+ **[DEMO](https://stfurkan.github.io/bitgpu/examples/chat.html)**: pick a model, let the weights
15
+ stream once from the Hugging Face Hub, and chat with it on your own GPU.
16
+
14
17
  ## Install
15
18
 
16
19
  ```sh
@@ -28,7 +31,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
28
31
  import { createEngine } from 'bitgpu'
29
32
  import { createChat } from 'bitgpu/chat'
30
33
 
31
- const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.7.0/models/bonsai-1.7b'
34
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.9.0/models/bonsai-1.7b'
32
35
  const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
33
36
  const engine = await createEngine({
34
37
  manifestUrl: `${REPO}/manifest.json`,
@@ -42,8 +45,9 @@ const chat = await createChat(engine, {
42
45
  await chat.send([{ role: 'user', content: 'Hi!' }], { onText: (t) => process.stdout.write(t) })
43
46
  ```
44
47
 
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.
48
+ The [demo](https://stfurkan.github.io/bitgpu/examples/chat.html) ([source](examples/chat.html))
49
+ is this quickstart as a single HTML file: model picker, streaming chat, JSON mode with a schema
50
+ editor, and cached downloads.
47
51
 
48
52
  ## Usage
49
53
 
@@ -124,16 +128,95 @@ Constrained decoding: every candidate token is validated against an incremental
124
128
  machine before it can be sampled, so the reply is structurally guaranteed to be one complete,
125
129
  valid JSON value (object or array root) - small 1-bit models free-form JSON unreliably, and this
126
130
  removes that failure class entirely. Generation ends when the root value closes
127
- (`finishReason: 'length'` means `maxTokens` cut it short - raise it). The constraint is
128
- structural, not semantic: prompt for the shape you want. Built on the engine's generic
129
- `candidateFilter` hook (see `GenerateOptions`), which is open for custom grammars.
131
+ (`finishReason: 'length'` means `maxTokens` cut it short - raise it).
132
+
133
+ Pass a **schema** and the shape is enforced token-by-token too - the model cannot open an object
134
+ where an array is required, stop at 1 item when 5 are demanded, invent keys, drift a type, or
135
+ answer outside an enum:
136
+
137
+ ```ts
138
+ await chat.send(messages, { format: { json: { schema: {
139
+ type: 'array', minItems: 5, maxItems: 5,
140
+ items: { type: 'object', required: ['name', 'population'], additionalProperties: false,
141
+ properties: { name: { type: 'string' }, population: { type: 'number' } } },
142
+ } } } })
143
+ // or guaranteed classification: { properties: { mood: { enum: ['positive', 'negative', 'neutral'] } } }
144
+ ```
145
+
146
+ Enforceable subset: `type` (incl. `integer`), `properties` / `required` /
147
+ `additionalProperties: false`, `items`, `minItems` / `maxItems`, string `enum`,
148
+ `minLength` / `maxLength` (code points), integer `minimum` / `maximum` (with prefix
149
+ feasibility, so the model can never be trapped mid-number), and `oneOf` as a **discriminated
150
+ union** - object branches sharing one required property whose single-value `enum` differs per
151
+ branch, e.g. a slide that is either `{type: 'bullets', ...}` or `{type: 'quote', ...}`; the
152
+ machine tracks the live branches until the discriminator commits. All nested to any depth.
153
+ Anything else (`pattern`, float ranges, general `oneOf`, `$ref`, ...) **throws up front** -
154
+ never silently ignored. The guarantee is structural, not semantic: a schema makes the output
155
+ parse into the right shape, not be true. Built on the engine's generic `candidateFilter` hook
156
+ (see `GenerateOptions`), which is open for custom grammars.
157
+
158
+ ### Confidence (`logprobs`)
159
+
160
+ Pass `logprobs: N` (engine or chat options) and every emitted token comes back with its TRUE
161
+ logprob plus the top-N alternatives - log-softmax over the full vocabulary, computed exactly via
162
+ a GPU log-sum-exp (one extra f32 readback per step, not a top-K approximation):
163
+
164
+ ```ts
165
+ const r = await chat.send(messages, { logprobs: 5 })
166
+ const confidence = Math.exp(r.logprobs[0].logprob) // p of the first token; low = the model is guessing
167
+ ```
168
+
169
+ Use it to flag low-confidence answers, build "are you sure?" UX, or detect when a
170
+ schema/tool filter had to force a token the model ranked poorly. Greedy output is bit-identical
171
+ with or without it; `promptLookup` is disabled for the turn.
172
+
173
+ ### Tool calling (`tools`)
174
+
175
+ The model's own protocol (Qwen3-family templates render a `tools` list and emit
176
+ `<tool_call>` blocks), with the same enforcement guarantee as schema mode: a bitgpu tool call
177
+ **cannot be malformed** - once the model opens a call, the name is forced to one of your
178
+ declared tools and the arguments are forced through that tool's `parameters` schema,
179
+ token-by-token.
180
+
181
+ ```ts
182
+ const tools = [{
183
+ type: 'function',
184
+ function: {
185
+ name: 'get_weather',
186
+ description: 'Get the current weather for a city.',
187
+ parameters: { type: 'object', required: ['city'], additionalProperties: false,
188
+ properties: { city: { type: 'string' }, unit: { enum: ['celsius', 'fahrenheit'] } } },
189
+ },
190
+ }]
191
+
192
+ const r = await chat.send(messages, { tools })
193
+ if (r.finishReason === 'tool_calls') {
194
+ const call = r.toolCalls[0] // { name, arguments } - always valid
195
+ const result = await runMyTool(call) // executing is YOUR code, on YOUR terms
196
+ const r2 = await chat.send([
197
+ ...messages,
198
+ { role: 'assistant', content: r.text, tool_calls: r.toolCalls },
199
+ { role: 'tool', content: JSON.stringify(result) },
200
+ ], { tools }) // extends the KV cache - no re-prefill
201
+ }
202
+ ```
203
+
204
+ `toolChoice: { name: 'get_weather' }` **forces** a call to that tool as the entire reply - fully
205
+ enforced end to end, and the reliable way to use tools with small models. `'auto'` (the default)
206
+ lets the model decide, which is where model judgment comes in: a 1-bit model can call when it
207
+ should answer, or answer when it should call. Enforcement guarantees the call's *shape*, never
208
+ its *judgment* - keep tool sets small (2-3 tools), prefer forced calls when the UI knows one is
209
+ needed, and validate argument *values* in your executor. The engine never executes anything,
210
+ never loops, never retries: it returns a validated call and the app stays in charge (there is
211
+ deliberately no agent framework in here).
130
212
 
131
213
  The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
132
214
  see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
133
215
  engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
134
- `bitgpu` never loads any chat code. Rendering and encoding are verified byte-exact against
135
- transformers.js (`npm run test:chat`), and the GPU gate proves the reuse path bit-exact on real
136
- hardware. Prefer your own tokenizer? Skip `bitgpu/chat` entirely - the engine API is unchanged.
216
+ `bitgpu` never loads any chat code. Rendering and encoding (including tool declarations, calls,
217
+ and responses) are verified byte-exact against transformers.js (`npm run test:chat`), and the
218
+ GPU gate proves the reuse paths bit-exact on real hardware. Prefer your own tokenizer? Skip
219
+ `bitgpu/chat` entirely - the engine API is unchanged.
137
220
 
138
221
  ## Bring your own model
139
222
 
@@ -197,6 +280,11 @@ WebGPU with compute is required (a clear `WebGPUUnavailableError` is thrown othe
197
280
  | Firefox | workgroup fallback | WebGPU shipped, but per-dispatch overhead is high; expect low throughput |
198
281
  | Android Chrome | device-dependent | works where WebGPU is exposed; VRAM limits apply |
199
282
 
283
+ The engine has no DOM dependencies and WebGPU is available in workers, so the whole stack runs
284
+ off the main thread: [examples/worker.html](examples/worker.html) is a complete copy-paste
285
+ pattern (module worker + a four-message protocol) whose page stays at full frame rate through
286
+ load, prefill, and decode.
287
+
200
288
  ## CDN usage
201
289
 
202
290
  ```html
@@ -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 { l as TokenLogprobs, n as Engine, o as GenerateOptions } from "./types-C5f2IKgm.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,18 +36,221 @@ 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
  }
43
54
  //#endregion
55
+ //#region src/chat/json.d.ts
56
+ /** The enforceable JSON Schema subset (see validateJsonSchema). */
57
+ interface JsonSchema {
58
+ type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
59
+ properties?: Record<string, JsonSchema>;
60
+ required?: string[];
61
+ additionalProperties?: boolean;
62
+ items?: JsonSchema;
63
+ minItems?: number;
64
+ maxItems?: number;
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;
79
+ }
80
+ /** Validate a schema against the enforceable subset; throws listing anything unsupported. */
81
+ declare function validateJsonSchema(schema: JsonSchema, path?: string, isRoot?: boolean): void;
82
+ declare class JsonMachine {
83
+ private readonly root;
84
+ private stack;
85
+ private phase;
86
+ private uLeft;
87
+ private utf8Left;
88
+ private numSub;
89
+ private numInt;
90
+ private litWord;
91
+ private litPos;
92
+ private strKind;
93
+ private strBuf;
94
+ private strTracking;
95
+ private enumCands;
96
+ private strLenOn;
97
+ private strCount;
98
+ private strMin;
99
+ private strMax;
100
+ private numMin;
101
+ private numMax;
102
+ private numBuf;
103
+ private pending;
104
+ private wsRun;
105
+ constructor(root?: JsonSchema | null);
106
+ clone(): JsonMachine;
107
+ get complete(): boolean;
108
+ /** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
109
+ feed(bytes: Uint8Array): boolean;
110
+ private top;
111
+ /** Byte-space form of a string literal (what strBuf accumulates). */
112
+ private static bytesOf;
113
+ private openValue;
114
+ /** A value just finished; land per the enclosing container and count array items. */
115
+ private closeValue;
116
+ private closeContainer;
117
+ /** Candidate property names for the key being typed (null = unconstrained). */
118
+ private keyCands;
119
+ private startKey;
120
+ /** Structural whitespace is never REQUIRED by JSON, so capping a run cannot make the grammar
121
+ * unsatisfiable - but without a cap, a model denied prose can loop on whitespace forever (the
122
+ * grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
123
+ * allows generous pretty-printing indentation while forcing real progress. */
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;
137
+ private byte;
138
+ /** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
139
+ private enumOk;
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;
253
+ //#endregion
44
254
  //#region src/chat/think.d.ts
45
255
  interface SplitChunk {
46
256
  /** Visible reply text (outside any tag pair). */
@@ -71,26 +281,6 @@ declare class StopScanner {
71
281
  flush(): string;
72
282
  }
73
283
  //#endregion
74
- //#region src/chat/json.d.ts
75
- declare class JsonMachine {
76
- private stack;
77
- private phase;
78
- private isKey;
79
- private uLeft;
80
- private utf8Left;
81
- private numSub;
82
- private litWord;
83
- private litPos;
84
- clone(): JsonMachine;
85
- get complete(): boolean;
86
- /** Feed bytes; false = the text stopped being a valid JSON prefix (state is then undefined). */
87
- feed(bytes: Uint8Array): boolean;
88
- private openValue;
89
- private closeValue;
90
- private closeContainer;
91
- private byte;
92
- }
93
- //#endregion
94
284
  //#region src/chat/index.d.ts
95
285
  /** Options for {@link createChat}. Point it at the model directory (which already hosts
96
286
  * tokenizer.json + tokenizer_config.json next to the manifest), at explicit URLs, or at
@@ -121,6 +311,10 @@ interface ChatSendOptions {
121
311
  noRepeatNgramSize?: number;
122
312
  seed?: number;
123
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;
124
318
  /** Extra stop token ids, in addition to the model's eos. */
125
319
  stopTokens?: number[];
126
320
  /** Stop STRINGS: generation ends when the visible reply contains one (matched across token
@@ -148,27 +342,56 @@ interface ChatSendOptions {
148
342
  /** Reuse the KV cache when this turn is a clean append to the previous one (the committed
149
343
  * conversation plus one new user turn). Default true; set false to force a full prefill. */
150
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;
151
360
  /** Constrained decoding. `'json'` guarantees the reply is one complete, valid JSON value with
152
361
  * an object or array root: every generated token is validated against an incremental JSON
153
362
  * machine (invalid candidates are never sampled), and generation ends when the root value
154
- * closes. Check `finishReason === 'stop'` - `'length'` means maxTokens cut the value short.
155
- * Forces `think: false` and disables `promptLookup`. Constraint is structural, not semantic:
156
- * prompt for the shape you want; this makes the output PARSE, not make sense. */
157
- format?: 'json';
363
+ * closes. `{ json: { schema } }` additionally enforces a JSON Schema SUBSET token-by-token -
364
+ * value types, `properties`/`required`/`additionalProperties: false`, `items`,
365
+ * `minItems`/`maxItems`, string `enum`, `integer` - so the reply cannot even be shaped wrong
366
+ * (an array that must hold 5 items cannot close at 1). Unsupported schema keywords throw
367
+ * loudly up front. Check `finishReason === 'stop'` - `'length'` means maxTokens cut the value
368
+ * short. Forces `think: false` and disables `promptLookup`. The guarantee is structural, not
369
+ * semantic: a schema makes the output parse into the right shape, not be true. */
370
+ format?: 'json' | {
371
+ json: {
372
+ schema?: JsonSchema;
373
+ };
374
+ };
158
375
  }
159
376
  interface ChatResult {
160
- /** The visible reply (think blocks removed). */
377
+ /** The visible reply (think blocks and tool_call blocks removed). */
161
378
  text: string;
162
379
  /** Content of <think> blocks, when the model emitted any. */
163
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[];
164
385
  /** Generated token ids (as returned by the engine; excludes the prompt). */
165
386
  tokens: number[];
166
387
  /** The exact token ids fed to the engine this turn (the full prompt, or the reuse delta). */
167
388
  inputTokenIds: number[];
168
- /** Why generation ended. */
169
- finishReason: 'stop' | 'length' | 'abort';
389
+ /** Why generation ended ('tool_calls' = ended at eos after making tool calls). */
390
+ finishReason: 'stop' | 'length' | 'abort' | 'tool_calls';
170
391
  /** True when this turn extended the KV cache instead of a full prefill. */
171
392
  reusedCache: boolean;
393
+ /** Per-token logprob records aligned with `tokens` (present when options.logprobs was set). */
394
+ logprobs?: TokenLogprobs[];
172
395
  prefillMs: number;
173
396
  decodeMs: number;
174
397
  tokensPerSecond: number;
@@ -181,13 +404,18 @@ interface Chat {
181
404
  * is the generator's return value: `const it = chat.stream(msgs); for await (const d of it) ...` */
182
405
  stream(messages: ChatMessage[], options?: ChatSendOptions): AsyncGenerator<string, ChatResult>;
183
406
  /** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
184
- * so the first real turn is a cheap cache-append instead of a cold full prefill. */
185
- prewarm(messages: ChatMessage[]): Promise<void>;
407
+ * so the first real turn is a cheap cache-append instead of a cold full prefill. Pass the same
408
+ * `tools` the turns will use - the template renders them into the system block, so a prewarm
409
+ * without them warms a different prompt. */
410
+ prewarm(messages: ChatMessage[], opts?: {
411
+ tools?: ChatTool[];
412
+ }): Promise<void>;
186
413
  /** Token count of the rendered prompt for a message list (chat template applied) - use for
187
414
  * window budgeting against `engine.capabilities.maxSeqLen`, e.g. in an onOverflow policy. */
188
415
  countTokens(messages: ChatMessage[], opts?: {
189
416
  addGenerationPrompt?: boolean;
190
417
  think?: boolean;
418
+ tools?: ChatTool[];
191
419
  }): number;
192
420
  /** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
193
421
  * Use this (not engine.resetCache()) so the two stay in sync. */
@@ -200,5 +428,5 @@ interface Chat {
200
428
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
201
429
  declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
202
430
  //#endregion
203
- export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, StopScanner, ThinkSplitter, createChat };
431
+ export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
204
432
  //# sourceMappingURL=chat.d.ts.map