bitgpu 0.7.0 → 0.8.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 +22 -4
- package/dist/chat.d.ts +68 -25
- package/dist/chat.js +208 -43
- package/dist/chat.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
|
|
|
28
28
|
import { createEngine } from 'bitgpu'
|
|
29
29
|
import { createChat } from 'bitgpu/chat'
|
|
30
30
|
|
|
31
|
-
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.
|
|
31
|
+
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.8.0/models/bonsai-1.7b'
|
|
32
32
|
const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
|
|
33
33
|
const engine = await createEngine({
|
|
34
34
|
manifestUrl: `${REPO}/manifest.json`,
|
|
@@ -124,9 +124,27 @@ Constrained decoding: every candidate token is validated against an incremental
|
|
|
124
124
|
machine before it can be sampled, so the reply is structurally guaranteed to be one complete,
|
|
125
125
|
valid JSON value (object or array root) - small 1-bit models free-form JSON unreliably, and this
|
|
126
126
|
removes that failure class entirely. Generation ends when the root value closes
|
|
127
|
-
(`finishReason: 'length'` means `maxTokens` cut it short - raise it).
|
|
128
|
-
|
|
129
|
-
|
|
127
|
+
(`finishReason: 'length'` means `maxTokens` cut it short - raise it).
|
|
128
|
+
|
|
129
|
+
Pass a **schema** and the shape is enforced token-by-token too - the model cannot open an object
|
|
130
|
+
where an array is required, stop at 1 item when 5 are demanded, invent keys, drift a type, or
|
|
131
|
+
answer outside an enum:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
await chat.send(messages, { format: { json: { schema: {
|
|
135
|
+
type: 'array', minItems: 5, maxItems: 5,
|
|
136
|
+
items: { type: 'object', required: ['name', 'population'], additionalProperties: false,
|
|
137
|
+
properties: { name: { type: 'string' }, population: { type: 'number' } } },
|
|
138
|
+
} } } })
|
|
139
|
+
// or guaranteed classification: { properties: { mood: { enum: ['positive', 'negative', 'neutral'] } } }
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
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.
|
|
130
148
|
|
|
131
149
|
The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
|
|
132
150
|
see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
|
package/dist/chat.d.ts
CHANGED
|
@@ -41,6 +41,61 @@ declare class ChatTokenizer {
|
|
|
41
41
|
createDecoderStream(skipSpecialTokens?: boolean): DecoderStream;
|
|
42
42
|
}
|
|
43
43
|
//#endregion
|
|
44
|
+
//#region src/chat/json.d.ts
|
|
45
|
+
/** The enforceable JSON Schema subset (see validateJsonSchema). */
|
|
46
|
+
interface JsonSchema {
|
|
47
|
+
type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
|
|
48
|
+
properties?: Record<string, JsonSchema>;
|
|
49
|
+
required?: string[];
|
|
50
|
+
additionalProperties?: boolean;
|
|
51
|
+
items?: JsonSchema;
|
|
52
|
+
minItems?: number;
|
|
53
|
+
maxItems?: number;
|
|
54
|
+
enum?: string[];
|
|
55
|
+
}
|
|
56
|
+
/** Validate a schema against the enforceable subset; throws listing anything unsupported. */
|
|
57
|
+
declare function validateJsonSchema(schema: JsonSchema, path?: string, isRoot?: boolean): void;
|
|
58
|
+
declare class JsonMachine {
|
|
59
|
+
private readonly root;
|
|
60
|
+
private stack;
|
|
61
|
+
private phase;
|
|
62
|
+
private uLeft;
|
|
63
|
+
private utf8Left;
|
|
64
|
+
private numSub;
|
|
65
|
+
private numInt;
|
|
66
|
+
private litWord;
|
|
67
|
+
private litPos;
|
|
68
|
+
private strKind;
|
|
69
|
+
private strBuf;
|
|
70
|
+
private strTracking;
|
|
71
|
+
private enumCands;
|
|
72
|
+
private pending;
|
|
73
|
+
private wsRun;
|
|
74
|
+
constructor(root?: JsonSchema | null);
|
|
75
|
+
clone(): JsonMachine;
|
|
76
|
+
get complete(): boolean;
|
|
77
|
+
/** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
|
|
78
|
+
feed(bytes: Uint8Array): boolean;
|
|
79
|
+
private top;
|
|
80
|
+
/** Byte-space form of a string literal (what strBuf accumulates). */
|
|
81
|
+
private static bytesOf;
|
|
82
|
+
private openValue;
|
|
83
|
+
/** A value just finished; land per the enclosing container and count array items. */
|
|
84
|
+
private closeValue;
|
|
85
|
+
private closeContainer;
|
|
86
|
+
/** Candidate property names for the key being typed (null = unconstrained). */
|
|
87
|
+
private keyCands;
|
|
88
|
+
private startKey;
|
|
89
|
+
/** Structural whitespace is never REQUIRED by JSON, so capping a run cannot make the grammar
|
|
90
|
+
* unsatisfiable - but without a cap, a model denied prose can loop on whitespace forever (the
|
|
91
|
+
* grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
|
|
92
|
+
* allows generous pretty-printing indentation while forcing real progress. */
|
|
93
|
+
private ws;
|
|
94
|
+
private byte;
|
|
95
|
+
/** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
|
|
96
|
+
private enumOk;
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
44
99
|
//#region src/chat/think.d.ts
|
|
45
100
|
interface SplitChunk {
|
|
46
101
|
/** Visible reply text (outside any tag pair). */
|
|
@@ -71,26 +126,6 @@ declare class StopScanner {
|
|
|
71
126
|
flush(): string;
|
|
72
127
|
}
|
|
73
128
|
//#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
129
|
//#region src/chat/index.d.ts
|
|
95
130
|
/** Options for {@link createChat}. Point it at the model directory (which already hosts
|
|
96
131
|
* tokenizer.json + tokenizer_config.json next to the manifest), at explicit URLs, or at
|
|
@@ -151,10 +186,18 @@ interface ChatSendOptions {
|
|
|
151
186
|
/** Constrained decoding. `'json'` guarantees the reply is one complete, valid JSON value with
|
|
152
187
|
* an object or array root: every generated token is validated against an incremental JSON
|
|
153
188
|
* machine (invalid candidates are never sampled), and generation ends when the root value
|
|
154
|
-
* closes.
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
|
|
189
|
+
* closes. `{ json: { schema } }` additionally enforces a JSON Schema SUBSET token-by-token -
|
|
190
|
+
* value types, `properties`/`required`/`additionalProperties: false`, `items`,
|
|
191
|
+
* `minItems`/`maxItems`, string `enum`, `integer` - so the reply cannot even be shaped wrong
|
|
192
|
+
* (an array that must hold 5 items cannot close at 1). Unsupported schema keywords throw
|
|
193
|
+
* loudly up front. Check `finishReason === 'stop'` - `'length'` means maxTokens cut the value
|
|
194
|
+
* short. Forces `think: false` and disables `promptLookup`. The guarantee is structural, not
|
|
195
|
+
* semantic: a schema makes the output parse into the right shape, not be true. */
|
|
196
|
+
format?: 'json' | {
|
|
197
|
+
json: {
|
|
198
|
+
schema?: JsonSchema;
|
|
199
|
+
};
|
|
200
|
+
};
|
|
158
201
|
}
|
|
159
202
|
interface ChatResult {
|
|
160
203
|
/** The visible reply (think blocks removed). */
|
|
@@ -200,5 +243,5 @@ interface Chat {
|
|
|
200
243
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
201
244
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
202
245
|
//#endregion
|
|
203
|
-
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, StopScanner, ThinkSplitter, createChat };
|
|
246
|
+
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
|
|
204
247
|
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
CHANGED
|
@@ -4394,6 +4394,47 @@ var StopScanner = class {
|
|
|
4394
4394
|
};
|
|
4395
4395
|
//#endregion
|
|
4396
4396
|
//#region src/chat/json.ts
|
|
4397
|
+
const SUPPORTED = /* @__PURE__ */ new Set([
|
|
4398
|
+
"type",
|
|
4399
|
+
"properties",
|
|
4400
|
+
"required",
|
|
4401
|
+
"additionalProperties",
|
|
4402
|
+
"items",
|
|
4403
|
+
"minItems",
|
|
4404
|
+
"maxItems",
|
|
4405
|
+
"enum"
|
|
4406
|
+
]);
|
|
4407
|
+
const TYPES = /* @__PURE__ */ new Set([
|
|
4408
|
+
"object",
|
|
4409
|
+
"array",
|
|
4410
|
+
"string",
|
|
4411
|
+
"number",
|
|
4412
|
+
"integer",
|
|
4413
|
+
"boolean",
|
|
4414
|
+
"null"
|
|
4415
|
+
]);
|
|
4416
|
+
/** Validate a schema against the enforceable subset; throws listing anything unsupported. */
|
|
4417
|
+
function validateJsonSchema(schema, path = "schema", isRoot = true) {
|
|
4418
|
+
const unknown = Object.keys(schema).filter((k) => !SUPPORTED.has(k));
|
|
4419
|
+
if (unknown.length) throw new Error(`bitgpu/chat: unsupported JSON Schema keyword(s) at ${path}: ${unknown.join(", ")} (enforceable subset: ${[...SUPPORTED].join(", ")})`);
|
|
4420
|
+
if (schema.type !== void 0 && !TYPES.has(schema.type)) throw new Error(`bitgpu/chat: unsupported type '${schema.type}' at ${path}`);
|
|
4421
|
+
if (isRoot && schema.type !== void 0 && schema.type !== "object" && schema.type !== "array") throw new Error(`bitgpu/chat: the schema root must be an object or array (got '${schema.type}'); JSON mode requires a container root`);
|
|
4422
|
+
if (schema.enum !== void 0) {
|
|
4423
|
+
if (!Array.isArray(schema.enum) || schema.enum.length === 0 || !schema.enum.every((v) => typeof v === "string")) throw new Error(`bitgpu/chat: enum at ${path} must be a non-empty array of strings`);
|
|
4424
|
+
for (const v of schema.enum) if (/["\\\u0000-\u001f]/.test(v)) throw new Error(`bitgpu/chat: enum value ${JSON.stringify(v)} at ${path} contains characters that require JSON escaping (unsupported)`);
|
|
4425
|
+
if (schema.type !== void 0 && schema.type !== "string") throw new Error(`bitgpu/chat: enum at ${path} requires type 'string'`);
|
|
4426
|
+
}
|
|
4427
|
+
if (schema.required !== void 0 && schema.properties !== void 0) {
|
|
4428
|
+
for (const k of schema.required) if (!(k in schema.properties)) throw new Error(`bitgpu/chat: required key '${k}' at ${path} is missing from properties`);
|
|
4429
|
+
}
|
|
4430
|
+
if (schema.additionalProperties === false && schema.properties === void 0) throw new Error(`bitgpu/chat: additionalProperties: false at ${path} needs a properties map`);
|
|
4431
|
+
if (schema.properties !== void 0) for (const [k, v] of Object.entries(schema.properties)) {
|
|
4432
|
+
if (/["\\\u0000-\u001f]/.test(k)) throw new Error(`bitgpu/chat: property name ${JSON.stringify(k)} at ${path} contains characters that require JSON escaping (unsupported)`);
|
|
4433
|
+
validateJsonSchema(v, `${path}.properties.${k}`, false);
|
|
4434
|
+
}
|
|
4435
|
+
if (schema.items !== void 0) validateJsonSchema(schema.items, `${path}.items`, false);
|
|
4436
|
+
if (schema.minItems !== void 0 && schema.maxItems !== void 0 && schema.minItems > schema.maxItems) throw new Error(`bitgpu/chat: minItems > maxItems at ${path}`);
|
|
4437
|
+
}
|
|
4397
4438
|
const WS = /* @__PURE__ */ new Set([
|
|
4398
4439
|
32,
|
|
4399
4440
|
9,
|
|
@@ -4403,137 +4444,250 @@ const WS = /* @__PURE__ */ new Set([
|
|
|
4403
4444
|
const isDigit = (b) => b >= 48 && b <= 57;
|
|
4404
4445
|
const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
|
|
4405
4446
|
const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
|
|
4447
|
+
const utf8 = new TextEncoder();
|
|
4406
4448
|
var JsonMachine = class JsonMachine {
|
|
4449
|
+
root;
|
|
4407
4450
|
stack = [];
|
|
4408
4451
|
phase = 0;
|
|
4409
|
-
isKey = false;
|
|
4410
4452
|
uLeft = 0;
|
|
4411
4453
|
utf8Left = 0;
|
|
4412
4454
|
numSub = 2;
|
|
4455
|
+
numInt = false;
|
|
4413
4456
|
litWord = "";
|
|
4414
4457
|
litPos = 0;
|
|
4458
|
+
strKind = "value";
|
|
4459
|
+
strBuf = "";
|
|
4460
|
+
strTracking = false;
|
|
4461
|
+
enumCands = null;
|
|
4462
|
+
pending = null;
|
|
4463
|
+
wsRun = 0;
|
|
4464
|
+
constructor(root = null) {
|
|
4465
|
+
this.root = root;
|
|
4466
|
+
this.pending = root;
|
|
4467
|
+
}
|
|
4415
4468
|
clone() {
|
|
4416
|
-
const m = new JsonMachine();
|
|
4417
|
-
m.stack = this.stack.
|
|
4469
|
+
const m = new JsonMachine(this.root);
|
|
4470
|
+
m.stack = this.stack.map((c) => ({
|
|
4471
|
+
kind: c.kind,
|
|
4472
|
+
node: c.node,
|
|
4473
|
+
seen: c.seen.slice(),
|
|
4474
|
+
count: c.count
|
|
4475
|
+
}));
|
|
4418
4476
|
m.phase = this.phase;
|
|
4419
|
-
m.isKey = this.isKey;
|
|
4420
4477
|
m.uLeft = this.uLeft;
|
|
4421
4478
|
m.utf8Left = this.utf8Left;
|
|
4422
4479
|
m.numSub = this.numSub;
|
|
4480
|
+
m.numInt = this.numInt;
|
|
4423
4481
|
m.litWord = this.litWord;
|
|
4424
4482
|
m.litPos = this.litPos;
|
|
4483
|
+
m.strKind = this.strKind;
|
|
4484
|
+
m.strBuf = this.strBuf;
|
|
4485
|
+
m.strTracking = this.strTracking;
|
|
4486
|
+
m.enumCands = this.enumCands;
|
|
4487
|
+
m.pending = this.pending;
|
|
4488
|
+
m.wsRun = this.wsRun;
|
|
4425
4489
|
return m;
|
|
4426
4490
|
}
|
|
4427
4491
|
get complete() {
|
|
4428
4492
|
return this.phase === 12;
|
|
4429
4493
|
}
|
|
4430
|
-
/** Feed bytes; false = the text stopped being a valid
|
|
4494
|
+
/** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
|
|
4431
4495
|
feed(bytes) {
|
|
4432
4496
|
for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
|
|
4433
4497
|
return true;
|
|
4434
4498
|
}
|
|
4499
|
+
top() {
|
|
4500
|
+
return this.stack[this.stack.length - 1];
|
|
4501
|
+
}
|
|
4502
|
+
/** Byte-space form of a string literal (what strBuf accumulates). */
|
|
4503
|
+
static bytesOf(s) {
|
|
4504
|
+
return String.fromCharCode(...utf8.encode(s));
|
|
4505
|
+
}
|
|
4435
4506
|
openValue(b) {
|
|
4507
|
+
const sc = this.pending;
|
|
4508
|
+
const t = sc?.type;
|
|
4436
4509
|
if (b === 123) {
|
|
4437
|
-
|
|
4510
|
+
if (t !== void 0 && t !== "object") return false;
|
|
4511
|
+
this.stack.push({
|
|
4512
|
+
kind: "{",
|
|
4513
|
+
node: sc ?? null,
|
|
4514
|
+
seen: [],
|
|
4515
|
+
count: 0
|
|
4516
|
+
});
|
|
4438
4517
|
this.phase = 3;
|
|
4439
4518
|
} else if (b === 91) {
|
|
4440
|
-
|
|
4519
|
+
if (t !== void 0 && t !== "array") return false;
|
|
4520
|
+
this.stack.push({
|
|
4521
|
+
kind: "[",
|
|
4522
|
+
node: sc ?? null,
|
|
4523
|
+
seen: [],
|
|
4524
|
+
count: 0
|
|
4525
|
+
});
|
|
4441
4526
|
this.phase = 2;
|
|
4442
4527
|
} else if (b === 34) {
|
|
4443
|
-
|
|
4528
|
+
if (t !== void 0 && t !== "string") return false;
|
|
4529
|
+
this.strKind = sc?.enum ? "enum" : "value";
|
|
4530
|
+
this.enumCands = sc?.enum ? sc.enum.map(JsonMachine.bytesOf) : null;
|
|
4531
|
+
this.strBuf = "";
|
|
4532
|
+
this.strTracking = this.strKind === "enum";
|
|
4444
4533
|
this.phase = 7;
|
|
4445
4534
|
} else if (b === 45 || isDigit(b)) {
|
|
4535
|
+
if (t !== void 0 && t !== "number" && t !== "integer") return false;
|
|
4536
|
+
this.numInt = t === "integer";
|
|
4446
4537
|
this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
|
|
4447
4538
|
this.phase = 10;
|
|
4448
4539
|
} else if (b === 116 || b === 102 || b === 110) {
|
|
4449
|
-
|
|
4540
|
+
const word = b === 116 ? "true" : b === 102 ? "false" : "null";
|
|
4541
|
+
if (t !== void 0 && !(word === "null" && t === "null" || word !== "null" && t === "boolean")) return false;
|
|
4542
|
+
this.litWord = word;
|
|
4450
4543
|
this.litPos = 1;
|
|
4451
4544
|
this.phase = 11;
|
|
4452
4545
|
} else return false;
|
|
4546
|
+
this.pending = null;
|
|
4453
4547
|
return true;
|
|
4454
4548
|
}
|
|
4549
|
+
/** A value just finished; land per the enclosing container and count array items. */
|
|
4455
4550
|
closeValue() {
|
|
4456
|
-
|
|
4551
|
+
const c = this.top();
|
|
4552
|
+
if (c === void 0) {
|
|
4553
|
+
this.phase = 12;
|
|
4554
|
+
return;
|
|
4555
|
+
}
|
|
4556
|
+
if (c.kind === "[") c.count++;
|
|
4557
|
+
this.phase = 6;
|
|
4457
4558
|
}
|
|
4458
4559
|
closeContainer(b) {
|
|
4459
|
-
const
|
|
4460
|
-
if (
|
|
4560
|
+
const c = this.top();
|
|
4561
|
+
if (!c || c.kind !== (b === 125 ? "{" : "[")) return false;
|
|
4562
|
+
if (c.kind === "{" && c.node?.required) {
|
|
4563
|
+
for (const k of c.node.required) if (!c.seen.includes(k)) return false;
|
|
4564
|
+
}
|
|
4565
|
+
if (c.kind === "[" && c.node?.minItems !== void 0 && c.count < c.node.minItems) return false;
|
|
4566
|
+
this.stack.pop();
|
|
4461
4567
|
this.closeValue();
|
|
4462
4568
|
return true;
|
|
4463
4569
|
}
|
|
4570
|
+
/** Candidate property names for the key being typed (null = unconstrained). */
|
|
4571
|
+
keyCands(c) {
|
|
4572
|
+
if (!c.node || c.node.additionalProperties !== false) return null;
|
|
4573
|
+
return Object.keys(c.node.properties ?? {}).filter((k) => !c.seen.includes(k)).map(JsonMachine.bytesOf);
|
|
4574
|
+
}
|
|
4575
|
+
startKey(c) {
|
|
4576
|
+
this.strKind = "key";
|
|
4577
|
+
this.enumCands = this.keyCands(c);
|
|
4578
|
+
this.strBuf = "";
|
|
4579
|
+
this.strTracking = true;
|
|
4580
|
+
this.phase = 7;
|
|
4581
|
+
}
|
|
4582
|
+
/** Structural whitespace is never REQUIRED by JSON, so capping a run cannot make the grammar
|
|
4583
|
+
* unsatisfiable - but without a cap, a model denied prose can loop on whitespace forever (the
|
|
4584
|
+
* grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
|
|
4585
|
+
* allows generous pretty-printing indentation while forcing real progress. */
|
|
4586
|
+
ws() {
|
|
4587
|
+
return ++this.wsRun <= 16;
|
|
4588
|
+
}
|
|
4464
4589
|
byte(b) {
|
|
4590
|
+
if (!WS.has(b)) this.wsRun = 0;
|
|
4465
4591
|
switch (this.phase) {
|
|
4466
4592
|
case 0:
|
|
4467
|
-
if (WS.has(b)) return
|
|
4593
|
+
if (WS.has(b)) return this.ws();
|
|
4468
4594
|
if (b === 123 || b === 91) return this.openValue(b);
|
|
4469
4595
|
return false;
|
|
4470
4596
|
case 1:
|
|
4471
|
-
if (WS.has(b)) return
|
|
4597
|
+
if (WS.has(b)) return this.ws();
|
|
4472
4598
|
return this.openValue(b);
|
|
4473
|
-
case 2:
|
|
4474
|
-
if (WS.has(b)) return
|
|
4599
|
+
case 2: {
|
|
4600
|
+
if (WS.has(b)) return this.ws();
|
|
4475
4601
|
if (b === 93) return this.closeContainer(b);
|
|
4602
|
+
const c = this.top();
|
|
4603
|
+
if (c.node?.maxItems === 0) return false;
|
|
4604
|
+
this.pending = c.node?.items ?? null;
|
|
4476
4605
|
return this.openValue(b);
|
|
4606
|
+
}
|
|
4477
4607
|
case 3:
|
|
4478
|
-
if (WS.has(b)) return
|
|
4608
|
+
if (WS.has(b)) return this.ws();
|
|
4479
4609
|
if (b === 125) return this.closeContainer(b);
|
|
4480
4610
|
if (b === 34) {
|
|
4481
|
-
|
|
4482
|
-
this.
|
|
4611
|
+
const c = this.top();
|
|
4612
|
+
if (this.keyCands(c)?.length === 0) return false;
|
|
4613
|
+
this.startKey(c);
|
|
4483
4614
|
return true;
|
|
4484
4615
|
}
|
|
4485
4616
|
return false;
|
|
4486
4617
|
case 4:
|
|
4487
|
-
if (WS.has(b)) return
|
|
4618
|
+
if (WS.has(b)) return this.ws();
|
|
4488
4619
|
if (b === 34) {
|
|
4489
|
-
this.
|
|
4490
|
-
this.phase = 7;
|
|
4620
|
+
this.startKey(this.top());
|
|
4491
4621
|
return true;
|
|
4492
4622
|
}
|
|
4493
4623
|
return false;
|
|
4494
4624
|
case 5:
|
|
4495
|
-
if (WS.has(b)) return
|
|
4625
|
+
if (WS.has(b)) return this.ws();
|
|
4496
4626
|
if (b === 58) {
|
|
4627
|
+
const c = this.top();
|
|
4628
|
+
const key = c.seen[c.seen.length - 1];
|
|
4629
|
+
const prop = c.node?.properties ? Object.entries(c.node.properties).find(([k]) => JsonMachine.bytesOf(k) === key) : void 0;
|
|
4630
|
+
this.pending = prop ? prop[1] : null;
|
|
4497
4631
|
this.phase = 1;
|
|
4498
4632
|
return true;
|
|
4499
4633
|
}
|
|
4500
4634
|
return false;
|
|
4501
4635
|
case 6: {
|
|
4502
|
-
if (WS.has(b)) return
|
|
4503
|
-
const
|
|
4504
|
-
if (b === 44) {
|
|
4505
|
-
|
|
4636
|
+
if (WS.has(b)) return this.ws();
|
|
4637
|
+
const c = this.top();
|
|
4638
|
+
if (b === 44 && c) {
|
|
4639
|
+
if (c.kind === "{") {
|
|
4640
|
+
if (this.keyCands(c)?.length === 0) return false;
|
|
4641
|
+
this.phase = 4;
|
|
4642
|
+
} else {
|
|
4643
|
+
if (c.node?.maxItems !== void 0 && c.count >= c.node.maxItems) return false;
|
|
4644
|
+
this.pending = c.node?.items ?? null;
|
|
4645
|
+
this.phase = 1;
|
|
4646
|
+
}
|
|
4506
4647
|
return true;
|
|
4507
4648
|
}
|
|
4508
|
-
if (b === 125
|
|
4649
|
+
if ((b === 125 || b === 93) && c) return this.closeContainer(b);
|
|
4509
4650
|
return false;
|
|
4510
4651
|
}
|
|
4511
4652
|
case 7:
|
|
4512
4653
|
if (this.utf8Left > 0) {
|
|
4513
4654
|
if (b >= 128 && b <= 191) {
|
|
4514
4655
|
this.utf8Left--;
|
|
4515
|
-
|
|
4656
|
+
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4657
|
+
return this.enumOk();
|
|
4516
4658
|
}
|
|
4517
4659
|
return false;
|
|
4518
4660
|
}
|
|
4519
4661
|
if (b === 34) {
|
|
4520
|
-
if (this.
|
|
4521
|
-
|
|
4662
|
+
if (this.strKind === "key") {
|
|
4663
|
+
const c = this.top();
|
|
4664
|
+
if (this.enumCands !== null && !this.enumCands.includes(this.strBuf)) return false;
|
|
4665
|
+
if (c.node?.properties && c.seen.includes(this.strBuf)) return false;
|
|
4666
|
+
c.seen.push(this.strBuf);
|
|
4522
4667
|
this.phase = 5;
|
|
4523
|
-
} else
|
|
4668
|
+
} else {
|
|
4669
|
+
if (this.strKind === "enum" && !this.enumCands.includes(this.strBuf)) return false;
|
|
4670
|
+
this.closeValue();
|
|
4671
|
+
}
|
|
4672
|
+
this.strTracking = false;
|
|
4524
4673
|
return true;
|
|
4525
4674
|
}
|
|
4526
4675
|
if (b === 92) {
|
|
4676
|
+
if (this.strKind === "enum" || this.strKind === "key" && this.enumCands !== null) return false;
|
|
4527
4677
|
this.phase = 8;
|
|
4528
4678
|
return true;
|
|
4529
4679
|
}
|
|
4530
4680
|
if (b < 32) return false;
|
|
4531
|
-
if (b < 128)
|
|
4681
|
+
if (b < 128) {
|
|
4682
|
+
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4683
|
+
return this.enumOk();
|
|
4684
|
+
}
|
|
4532
4685
|
if (b >= 194 && b <= 223) this.utf8Left = 1;
|
|
4533
4686
|
else if (b >= 224 && b <= 239) this.utf8Left = 2;
|
|
4534
4687
|
else if (b >= 240 && b <= 244) this.utf8Left = 3;
|
|
4535
4688
|
else return false;
|
|
4536
|
-
|
|
4689
|
+
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4690
|
+
return this.enumOk();
|
|
4537
4691
|
case 8:
|
|
4538
4692
|
if (b === 117) {
|
|
4539
4693
|
this.uLeft = 4;
|
|
@@ -4550,12 +4704,14 @@ var JsonMachine = class JsonMachine {
|
|
|
4550
4704
|
114,
|
|
4551
4705
|
116
|
|
4552
4706
|
].includes(b)) {
|
|
4707
|
+
if (this.strTracking) this.strBuf += "\\" + String.fromCharCode(b);
|
|
4553
4708
|
this.phase = 7;
|
|
4554
4709
|
return true;
|
|
4555
4710
|
}
|
|
4556
4711
|
return false;
|
|
4557
4712
|
case 9:
|
|
4558
4713
|
if (!isHex(b)) return false;
|
|
4714
|
+
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4559
4715
|
if (--this.uLeft === 0) this.phase = 7;
|
|
4560
4716
|
return true;
|
|
4561
4717
|
case 10:
|
|
@@ -4594,11 +4750,11 @@ var JsonMachine = class JsonMachine {
|
|
|
4594
4750
|
if (isDigit(b)) return true;
|
|
4595
4751
|
break;
|
|
4596
4752
|
}
|
|
4597
|
-
if (b === 46 && (this.numSub === 1 || this.numSub === 2)) {
|
|
4753
|
+
if (b === 46 && !this.numInt && (this.numSub === 1 || this.numSub === 2)) {
|
|
4598
4754
|
this.numSub = 3;
|
|
4599
4755
|
return true;
|
|
4600
4756
|
}
|
|
4601
|
-
if ((b === 101 || b === 69) && numberDone(this.numSub) && this.numSub !== 7) {
|
|
4757
|
+
if ((b === 101 || b === 69) && !this.numInt && numberDone(this.numSub) && this.numSub !== 7) {
|
|
4602
4758
|
this.numSub = 5;
|
|
4603
4759
|
return true;
|
|
4604
4760
|
}
|
|
@@ -4614,6 +4770,13 @@ var JsonMachine = class JsonMachine {
|
|
|
4614
4770
|
case 12: return WS.has(b);
|
|
4615
4771
|
}
|
|
4616
4772
|
}
|
|
4773
|
+
/** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
|
|
4774
|
+
enumOk() {
|
|
4775
|
+
if (!this.strTracking || this.enumCands === null) return true;
|
|
4776
|
+
const buf = this.strBuf;
|
|
4777
|
+
for (const c of this.enumCands) if (c.startsWith(buf)) return true;
|
|
4778
|
+
return false;
|
|
4779
|
+
}
|
|
4617
4780
|
};
|
|
4618
4781
|
function aliasToByte() {
|
|
4619
4782
|
const bs = [];
|
|
@@ -4664,10 +4827,10 @@ var TokenByteTable = class {
|
|
|
4664
4827
|
}
|
|
4665
4828
|
};
|
|
4666
4829
|
/** The per-step candidate filter for format:'json': permit candidates whose bytes keep the text
|
|
4667
|
-
* a valid JSON prefix; once the root value is complete, permit ONLY eos so
|
|
4668
|
-
* naturally. Call advance() with each chosen token to move the real machine
|
|
4669
|
-
function makeJsonFilter(table, eosTokenId) {
|
|
4670
|
-
const machine = new JsonMachine();
|
|
4830
|
+
* a valid, schema-conforming JSON prefix; once the root value is complete, permit ONLY eos so
|
|
4831
|
+
* generation ends naturally. Call advance() with each chosen token to move the real machine. */
|
|
4832
|
+
function makeJsonFilter(table, eosTokenId, schema = null) {
|
|
4833
|
+
const machine = new JsonMachine(schema);
|
|
4671
4834
|
return {
|
|
4672
4835
|
machine,
|
|
4673
4836
|
filter: (ids) => {
|
|
@@ -4769,7 +4932,9 @@ async function createChat(engine, options) {
|
|
|
4769
4932
|
let byteTable = null;
|
|
4770
4933
|
async function sendImpl(messages, o = {}) {
|
|
4771
4934
|
if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
|
|
4772
|
-
const json = o.format
|
|
4935
|
+
const json = o.format !== void 0;
|
|
4936
|
+
const schema = typeof o.format === "object" ? o.format.json.schema ?? null : null;
|
|
4937
|
+
if (schema) validateJsonSchema(schema);
|
|
4773
4938
|
const think = !json && (o.think ?? false);
|
|
4774
4939
|
const canReuse = (o.reuseCache ?? true) && !think && wrap !== null && isCleanAppend(committed, messages);
|
|
4775
4940
|
let inputTokenIds;
|
|
@@ -4808,7 +4973,7 @@ async function createChat(engine, options) {
|
|
|
4808
4973
|
};
|
|
4809
4974
|
const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
|
|
4810
4975
|
const epoch0 = resetEpoch;
|
|
4811
|
-
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId) : null;
|
|
4976
|
+
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
|
|
4812
4977
|
let result;
|
|
4813
4978
|
try {
|
|
4814
4979
|
result = await engine.generate(inputTokenIds, {
|
|
@@ -4941,6 +5106,6 @@ async function createChat(engine, options) {
|
|
|
4941
5106
|
};
|
|
4942
5107
|
}
|
|
4943
5108
|
//#endregion
|
|
4944
|
-
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat };
|
|
5109
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
|
|
4945
5110
|
|
|
4946
5111
|
//# sourceMappingURL=chat.js.map
|