bitgpu 0.6.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/dist/chat.js CHANGED
@@ -4245,6 +4245,14 @@ var ChatTokenizer = class {
4245
4245
  if (ids.length === 0) return "";
4246
4246
  return this.tok.decode(ids, { skip_special_tokens: skipSpecialTokens });
4247
4247
  }
4248
+ /** The raw vocab string for a token id (byte-alias space for byte-level BPE). */
4249
+ idToToken(id) {
4250
+ return this.tok.id_to_token(id);
4251
+ }
4252
+ /** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
4253
+ addedTokenIds() {
4254
+ return new Set(this.tok.get_added_tokens_decoder().keys());
4255
+ }
4248
4256
  get hasChatTemplate() {
4249
4257
  return this.template !== null;
4250
4258
  }
@@ -4350,6 +4358,501 @@ var ThinkSplitter = class {
4350
4358
  return r;
4351
4359
  }
4352
4360
  };
4361
+ /** Stream-safe stop-sequence scanner: emits visible text up to (excluding) the earliest match of
4362
+ * any stop string, holding back chunk-edge suffixes that could begin one (stops can straddle
4363
+ * token boundaries). Once matched, everything further is swallowed. */
4364
+ var StopScanner = class {
4365
+ stops;
4366
+ matched = false;
4367
+ hold = "";
4368
+ constructor(stops) {
4369
+ this.stops = stops;
4370
+ }
4371
+ push(text) {
4372
+ if (this.matched) return "";
4373
+ const s = this.hold + text;
4374
+ let mi = -1;
4375
+ for (const st of this.stops) {
4376
+ const i = s.indexOf(st);
4377
+ if (i !== -1 && (mi === -1 || i < mi)) mi = i;
4378
+ }
4379
+ if (mi !== -1) {
4380
+ this.matched = true;
4381
+ this.hold = "";
4382
+ return s.slice(0, mi);
4383
+ }
4384
+ let safe = s.length;
4385
+ for (const st of this.stops) safe = Math.min(safe, holdback(s, st));
4386
+ this.hold = s.slice(safe);
4387
+ return s.slice(0, safe);
4388
+ }
4389
+ flush() {
4390
+ const r = this.matched ? "" : this.hold;
4391
+ this.hold = "";
4392
+ return r;
4393
+ }
4394
+ };
4395
+ //#endregion
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
+ }
4438
+ const WS = /* @__PURE__ */ new Set([
4439
+ 32,
4440
+ 9,
4441
+ 10,
4442
+ 13
4443
+ ]);
4444
+ const isDigit = (b) => b >= 48 && b <= 57;
4445
+ const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
4446
+ const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
4447
+ const utf8 = new TextEncoder();
4448
+ var JsonMachine = class JsonMachine {
4449
+ root;
4450
+ stack = [];
4451
+ phase = 0;
4452
+ uLeft = 0;
4453
+ utf8Left = 0;
4454
+ numSub = 2;
4455
+ numInt = false;
4456
+ litWord = "";
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
+ }
4468
+ clone() {
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
+ }));
4476
+ m.phase = this.phase;
4477
+ m.uLeft = this.uLeft;
4478
+ m.utf8Left = this.utf8Left;
4479
+ m.numSub = this.numSub;
4480
+ m.numInt = this.numInt;
4481
+ m.litWord = this.litWord;
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;
4489
+ return m;
4490
+ }
4491
+ get complete() {
4492
+ return this.phase === 12;
4493
+ }
4494
+ /** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
4495
+ feed(bytes) {
4496
+ for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
4497
+ return true;
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
+ }
4506
+ openValue(b) {
4507
+ const sc = this.pending;
4508
+ const t = sc?.type;
4509
+ if (b === 123) {
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
+ });
4517
+ this.phase = 3;
4518
+ } else if (b === 91) {
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
+ });
4526
+ this.phase = 2;
4527
+ } else if (b === 34) {
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";
4533
+ this.phase = 7;
4534
+ } else if (b === 45 || isDigit(b)) {
4535
+ if (t !== void 0 && t !== "number" && t !== "integer") return false;
4536
+ this.numInt = t === "integer";
4537
+ this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
4538
+ this.phase = 10;
4539
+ } else if (b === 116 || b === 102 || b === 110) {
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;
4543
+ this.litPos = 1;
4544
+ this.phase = 11;
4545
+ } else return false;
4546
+ this.pending = null;
4547
+ return true;
4548
+ }
4549
+ /** A value just finished; land per the enclosing container and count array items. */
4550
+ closeValue() {
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;
4558
+ }
4559
+ closeContainer(b) {
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();
4567
+ this.closeValue();
4568
+ return true;
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
+ }
4589
+ byte(b) {
4590
+ if (!WS.has(b)) this.wsRun = 0;
4591
+ switch (this.phase) {
4592
+ case 0:
4593
+ if (WS.has(b)) return this.ws();
4594
+ if (b === 123 || b === 91) return this.openValue(b);
4595
+ return false;
4596
+ case 1:
4597
+ if (WS.has(b)) return this.ws();
4598
+ return this.openValue(b);
4599
+ case 2: {
4600
+ if (WS.has(b)) return this.ws();
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;
4605
+ return this.openValue(b);
4606
+ }
4607
+ case 3:
4608
+ if (WS.has(b)) return this.ws();
4609
+ if (b === 125) return this.closeContainer(b);
4610
+ if (b === 34) {
4611
+ const c = this.top();
4612
+ if (this.keyCands(c)?.length === 0) return false;
4613
+ this.startKey(c);
4614
+ return true;
4615
+ }
4616
+ return false;
4617
+ case 4:
4618
+ if (WS.has(b)) return this.ws();
4619
+ if (b === 34) {
4620
+ this.startKey(this.top());
4621
+ return true;
4622
+ }
4623
+ return false;
4624
+ case 5:
4625
+ if (WS.has(b)) return this.ws();
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;
4631
+ this.phase = 1;
4632
+ return true;
4633
+ }
4634
+ return false;
4635
+ case 6: {
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
+ }
4647
+ return true;
4648
+ }
4649
+ if ((b === 125 || b === 93) && c) return this.closeContainer(b);
4650
+ return false;
4651
+ }
4652
+ case 7:
4653
+ if (this.utf8Left > 0) {
4654
+ if (b >= 128 && b <= 191) {
4655
+ this.utf8Left--;
4656
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4657
+ return this.enumOk();
4658
+ }
4659
+ return false;
4660
+ }
4661
+ if (b === 34) {
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);
4667
+ this.phase = 5;
4668
+ } else {
4669
+ if (this.strKind === "enum" && !this.enumCands.includes(this.strBuf)) return false;
4670
+ this.closeValue();
4671
+ }
4672
+ this.strTracking = false;
4673
+ return true;
4674
+ }
4675
+ if (b === 92) {
4676
+ if (this.strKind === "enum" || this.strKind === "key" && this.enumCands !== null) return false;
4677
+ this.phase = 8;
4678
+ return true;
4679
+ }
4680
+ if (b < 32) return false;
4681
+ if (b < 128) {
4682
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4683
+ return this.enumOk();
4684
+ }
4685
+ if (b >= 194 && b <= 223) this.utf8Left = 1;
4686
+ else if (b >= 224 && b <= 239) this.utf8Left = 2;
4687
+ else if (b >= 240 && b <= 244) this.utf8Left = 3;
4688
+ else return false;
4689
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4690
+ return this.enumOk();
4691
+ case 8:
4692
+ if (b === 117) {
4693
+ this.uLeft = 4;
4694
+ this.phase = 9;
4695
+ return true;
4696
+ }
4697
+ if ([
4698
+ 34,
4699
+ 92,
4700
+ 47,
4701
+ 98,
4702
+ 102,
4703
+ 110,
4704
+ 114,
4705
+ 116
4706
+ ].includes(b)) {
4707
+ if (this.strTracking) this.strBuf += "\\" + String.fromCharCode(b);
4708
+ this.phase = 7;
4709
+ return true;
4710
+ }
4711
+ return false;
4712
+ case 9:
4713
+ if (!isHex(b)) return false;
4714
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4715
+ if (--this.uLeft === 0) this.phase = 7;
4716
+ return true;
4717
+ case 10:
4718
+ switch (this.numSub) {
4719
+ case 0:
4720
+ if (!isDigit(b)) return false;
4721
+ this.numSub = b === 48 ? 1 : 2;
4722
+ return true;
4723
+ case 1:
4724
+ case 2:
4725
+ if (isDigit(b)) {
4726
+ if (this.numSub === 1) return false;
4727
+ return true;
4728
+ }
4729
+ break;
4730
+ case 3:
4731
+ if (!isDigit(b)) return false;
4732
+ this.numSub = 4;
4733
+ return true;
4734
+ case 4:
4735
+ if (isDigit(b)) return true;
4736
+ break;
4737
+ case 5:
4738
+ if (b === 43 || b === 45) {
4739
+ this.numSub = 6;
4740
+ return true;
4741
+ }
4742
+ if (!isDigit(b)) return false;
4743
+ this.numSub = 7;
4744
+ return true;
4745
+ case 6:
4746
+ if (!isDigit(b)) return false;
4747
+ this.numSub = 7;
4748
+ return true;
4749
+ case 7:
4750
+ if (isDigit(b)) return true;
4751
+ break;
4752
+ }
4753
+ if (b === 46 && !this.numInt && (this.numSub === 1 || this.numSub === 2)) {
4754
+ this.numSub = 3;
4755
+ return true;
4756
+ }
4757
+ if ((b === 101 || b === 69) && !this.numInt && numberDone(this.numSub) && this.numSub !== 7) {
4758
+ this.numSub = 5;
4759
+ return true;
4760
+ }
4761
+ if (numberDone(this.numSub)) {
4762
+ this.closeValue();
4763
+ return this.byte(b);
4764
+ }
4765
+ return false;
4766
+ case 11:
4767
+ if (b !== this.litWord.charCodeAt(this.litPos)) return false;
4768
+ if (++this.litPos === this.litWord.length) this.closeValue();
4769
+ return true;
4770
+ case 12: return WS.has(b);
4771
+ }
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
+ }
4780
+ };
4781
+ function aliasToByte() {
4782
+ const bs = [];
4783
+ for (let i = 33; i <= 126; i++) bs.push(i);
4784
+ for (let i = 161; i <= 172; i++) bs.push(i);
4785
+ for (let i = 174; i <= 255; i++) bs.push(i);
4786
+ const cs = [...bs];
4787
+ let n = 0;
4788
+ for (let b = 0; b < 256; b++) if (!bs.includes(b)) {
4789
+ bs.push(b);
4790
+ cs.push(256 + n);
4791
+ n++;
4792
+ }
4793
+ return new Map(bs.map((b, i) => [cs[i], b]));
4794
+ }
4795
+ /** Precomputed id -> raw bytes lookup (lazy per id; added/special tokens map to null). */
4796
+ var TokenByteTable = class {
4797
+ tk;
4798
+ cache = /* @__PURE__ */ new Map();
4799
+ inv = aliasToByte();
4800
+ added;
4801
+ constructor(tk) {
4802
+ this.tk = tk;
4803
+ this.added = tk.addedTokenIds();
4804
+ }
4805
+ bytes(id) {
4806
+ const hit = this.cache.get(id);
4807
+ if (hit !== void 0) return hit;
4808
+ let out = null;
4809
+ if (!this.added.has(id)) {
4810
+ const s = this.tk.idToToken(id);
4811
+ if (s !== void 0) {
4812
+ const b = new Uint8Array(s.length);
4813
+ let ok = true;
4814
+ for (let i = 0; i < s.length; i++) {
4815
+ const v = this.inv.get(s.charCodeAt(i));
4816
+ if (v === void 0) {
4817
+ ok = false;
4818
+ break;
4819
+ }
4820
+ b[i] = v;
4821
+ }
4822
+ out = ok ? b : null;
4823
+ }
4824
+ }
4825
+ this.cache.set(id, out);
4826
+ return out;
4827
+ }
4828
+ };
4829
+ /** The per-step candidate filter for format:'json': permit candidates whose bytes keep the text
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);
4834
+ return {
4835
+ machine,
4836
+ filter: (ids) => {
4837
+ const out = [];
4838
+ for (const id of ids) {
4839
+ if (machine.complete) {
4840
+ if (id === eosTokenId) out.push(Number(id));
4841
+ continue;
4842
+ }
4843
+ const bytes = table.bytes(Number(id));
4844
+ if (!bytes || bytes.length === 0) continue;
4845
+ if (machine.clone().feed(bytes)) out.push(Number(id));
4846
+ }
4847
+ return out;
4848
+ },
4849
+ advance: (id) => {
4850
+ if (machine.complete) return;
4851
+ const bytes = table.bytes(id);
4852
+ if (bytes) machine.feed(bytes);
4853
+ }
4854
+ };
4855
+ }
4353
4856
  //#endregion
4354
4857
  //#region src/chat/index.ts
4355
4858
  function deriveChatWrap(tk) {
@@ -4426,9 +4929,13 @@ async function createChat(engine, options) {
4426
4929
  return run;
4427
4930
  };
4428
4931
  };
4932
+ let byteTable = null;
4429
4933
  async function sendImpl(messages, o = {}) {
4430
4934
  if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
4431
- const think = o.think ?? false;
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);
4938
+ const think = !json && (o.think ?? false);
4432
4939
  const canReuse = (o.reuseCache ?? true) && !think && wrap !== null && isCleanAppend(committed, messages);
4433
4940
  let inputTokenIds;
4434
4941
  if (canReuse) {
@@ -4445,12 +4952,19 @@ async function createChat(engine, options) {
4445
4952
  }
4446
4953
  const decoder = tk.createDecoderStream(true);
4447
4954
  const splitter = new ThinkSplitter();
4955
+ const stops = o.stopSequences?.length ? new StopScanner(o.stopSequences) : null;
4956
+ const stopCtl = stops ? new AbortController() : null;
4957
+ const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
4448
4958
  let text = "";
4449
4959
  let thinkText = "";
4450
4960
  const emit = (chunk) => {
4451
4961
  if (chunk.text) {
4452
- text += chunk.text;
4453
- o.onText?.(chunk.text);
4962
+ const visible = stops ? stops.push(chunk.text) : chunk.text;
4963
+ if (visible) {
4964
+ text += visible;
4965
+ o.onText?.(visible);
4966
+ }
4967
+ if (stops?.matched) stopCtl?.abort();
4454
4968
  }
4455
4969
  if (chunk.think) {
4456
4970
  thinkText += chunk.think;
@@ -4459,6 +4973,7 @@ async function createChat(engine, options) {
4459
4973
  };
4460
4974
  const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
4461
4975
  const epoch0 = resetEpoch;
4976
+ const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
4462
4977
  let result;
4463
4978
  try {
4464
4979
  result = await engine.generate(inputTokenIds, {
@@ -4469,20 +4984,39 @@ async function createChat(engine, options) {
4469
4984
  repetitionPenalty: o.repetitionPenalty,
4470
4985
  noRepeatNgramSize: o.noRepeatNgramSize,
4471
4986
  seed: o.seed,
4472
- promptLookup: o.promptLookup,
4987
+ promptLookup: json ? false : o.promptLookup,
4473
4988
  stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
4474
4989
  reuseCache: canReuse,
4475
- signal: o.signal,
4476
- onToken: (id) => emit(splitter.push(decoder.push(id)))
4990
+ signal,
4991
+ candidateFilter: jf ? (ids) => jf.filter(ids) : void 0,
4992
+ onToken: (id) => {
4993
+ jf?.advance(id);
4994
+ emit(splitter.push(decoder.push(id)));
4995
+ }
4477
4996
  });
4478
4997
  } catch (err) {
4479
- if (!/maxSeqLen/.test(err.message)) dropCache();
4998
+ if (/maxSeqLen/.test(err.message)) {
4999
+ if (o.onOverflow) {
5000
+ const trimmed = o.onOverflow({
5001
+ promptTokenCount: inputTokenIds.length,
5002
+ maxSeqLen: engine.capabilities.maxSeqLen
5003
+ });
5004
+ if (trimmed && trimmed.length > 0) {
5005
+ dropCache();
5006
+ return await sendImpl(trimmed, {
5007
+ ...o,
5008
+ onOverflow: void 0,
5009
+ reuseCache: false
5010
+ });
5011
+ }
5012
+ }
5013
+ } else dropCache();
4480
5014
  throw err;
4481
5015
  }
4482
5016
  emit(splitter.push(decoder.flush()));
4483
5017
  emit(splitter.flush());
4484
5018
  const aborted = o.signal?.aborted ?? false;
4485
- if (aborted) dropCache();
5019
+ if (aborted || stops?.matched) dropCache();
4486
5020
  else if (think) dropCache();
4487
5021
  else if (wrap !== null && text.trim() && resetEpoch === epoch0) {
4488
5022
  committed = [...messages, {
@@ -4496,7 +5030,7 @@ async function createChat(engine, options) {
4496
5030
  thinkText,
4497
5031
  tokens: result.tokens,
4498
5032
  inputTokenIds,
4499
- finishReason: aborted ? "abort" : result.tokens.length >= maxTokens ? "length" : "stop",
5033
+ finishReason: aborted ? "abort" : stops?.matched ? "stop" : result.tokens.length >= maxTokens ? "length" : "stop",
4500
5034
  reusedCache: canReuse,
4501
5035
  prefillMs: result.prefillMs,
4502
5036
  decodeMs: result.decodeMs,
@@ -4559,6 +5093,10 @@ async function createChat(engine, options) {
4559
5093
  return gen();
4560
5094
  },
4561
5095
  prewarm: serialize(prewarmImpl),
5096
+ countTokens: (messages, opts) => tk.encode(tk.applyChatTemplate(messages, {
5097
+ addGenerationPrompt: opts?.addGenerationPrompt ?? true,
5098
+ enableThinking: opts?.think ?? false
5099
+ }), false).length,
4562
5100
  reset: () => {
4563
5101
  resetEpoch++;
4564
5102
  dropCache();
@@ -4568,6 +5106,6 @@ async function createChat(engine, options) {
4568
5106
  };
4569
5107
  }
4570
5108
  //#endregion
4571
- export { ChatTokenizer, ThinkSplitter, createChat };
5109
+ export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
4572
5110
 
4573
5111
  //# sourceMappingURL=chat.js.map