bitgpu 0.8.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 +81 -11
- package/THIRD_PARTY_LICENSES.md +2 -2
- package/dist/chat.d.ts +194 -9
- package/dist/chat.js +634 -52
- package/dist/chat.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +75 -21
- package/dist/index.js.map +1 -1
- package/dist/{types-CsoJYJlG.d.ts → types-C5f2IKgm.d.ts} +25 -2
- package/package.json +1 -1
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.
|
|
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
|
-
|
|
46
|
-
streaming chat,
|
|
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
|
|
|
@@ -140,18 +144,79 @@ await chat.send(messages, { format: { json: { schema: {
|
|
|
140
144
|
```
|
|
141
145
|
|
|
142
146
|
Enforceable subset: `type` (incl. `integer`), `properties` / `required` /
|
|
143
|
-
`additionalProperties: false`, `items`, `minItems` / `maxItems`, string `enum`,
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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).
|
|
148
212
|
|
|
149
213
|
The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
|
|
150
214
|
see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
|
|
151
215
|
engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
|
|
152
|
-
`bitgpu` never loads any chat code. Rendering and encoding
|
|
153
|
-
transformers.js (`npm run test:chat`), and the
|
|
154
|
-
hardware. Prefer your own tokenizer? Skip
|
|
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.
|
|
155
220
|
|
|
156
221
|
## Bring your own model
|
|
157
222
|
|
|
@@ -215,6 +280,11 @@ WebGPU with compute is required (a clear `WebGPUUnavailableError` is thrown othe
|
|
|
215
280
|
| Firefox | workgroup fallback | WebGPU shipped, but per-dispatch overhead is high; expect low throughput |
|
|
216
281
|
| Android Chrome | device-dependent | works where WebGPU is exposed; VRAM limits apply |
|
|
217
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
|
+
|
|
218
288
|
## CDN usage
|
|
219
289
|
|
|
220
290
|
```html
|
package/THIRD_PARTY_LICENSES.md
CHANGED
|
@@ -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
|
|
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
|
|
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-
|
|
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,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,18 +374,24 @@ 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;
|
|
@@ -224,13 +404,18 @@ interface Chat {
|
|
|
224
404
|
* is the generator's return value: `const it = chat.stream(msgs); for await (const d of it) ...` */
|
|
225
405
|
stream(messages: ChatMessage[], options?: ChatSendOptions): AsyncGenerator<string, ChatResult>;
|
|
226
406
|
/** 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
|
-
|
|
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>;
|
|
229
413
|
/** Token count of the rendered prompt for a message list (chat template applied) - use for
|
|
230
414
|
* window budgeting against `engine.capabilities.maxSeqLen`, e.g. in an onOverflow policy. */
|
|
231
415
|
countTokens(messages: ChatMessage[], opts?: {
|
|
232
416
|
addGenerationPrompt?: boolean;
|
|
233
417
|
think?: boolean;
|
|
418
|
+
tools?: ChatTool[];
|
|
234
419
|
}): number;
|
|
235
420
|
/** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
|
|
236
421
|
* Use this (not engine.resetCache()) so the two stay in sync. */
|
|
@@ -243,5 +428,5 @@ interface Chat {
|
|
|
243
428
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
244
429
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
245
430
|
//#endregion
|
|
246
|
-
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
|
|
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 };
|
|
247
432
|
//# sourceMappingURL=chat.d.ts.map
|