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/dist/chat.js CHANGED
@@ -4249,6 +4249,10 @@ var ChatTokenizer = class {
4249
4249
  idToToken(id) {
4250
4250
  return this.tok.id_to_token(id);
4251
4251
  }
4252
+ /** The id of an exact vocab token (e.g. the <tool_call> marker); undefined when absent. */
4253
+ tokenToId(token) {
4254
+ return this.tok.token_to_id(token);
4255
+ }
4252
4256
  /** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
4253
4257
  addedTokenIds() {
4254
4258
  return new Set(this.tok.get_added_tokens_decoder().keys());
@@ -4257,12 +4261,14 @@ var ChatTokenizer = class {
4257
4261
  return this.template !== null;
4258
4262
  }
4259
4263
  /** Render a message list to a prompt string via the model's own Jinja chat template
4260
- * (matches transformers.js apply_chat_template byte-exactly). */
4264
+ * (matches transformers.js apply_chat_template byte-exactly). `tools` is passed to the
4265
+ * template verbatim (Qwen-family templates serialize each entry into the system block). */
4261
4266
  applyChatTemplate(messages, opts = {}) {
4262
4267
  if (!this.template) throw new Error("bitgpu/chat: the model has no chat_template in tokenizer_config.json");
4263
4268
  return this.template.render({
4264
4269
  ...this.templateContext,
4265
4270
  messages,
4271
+ tools: opts.tools ?? null,
4266
4272
  add_generation_prompt: opts.addGenerationPrompt ?? true,
4267
4273
  enable_thinking: opts.enableThinking ?? false
4268
4274
  });
@@ -4294,7 +4300,7 @@ var ChatTokenizer = class {
4294
4300
  //#endregion
4295
4301
  //#region src/chat/think.ts
4296
4302
  /** Longest suffix of `s` that is a proper prefix of `tag` (what must be held back). */
4297
- function holdback(s, tag) {
4303
+ function holdback$1(s, tag) {
4298
4304
  const max = Math.min(s.length, tag.length - 1);
4299
4305
  for (let k = max; k > 0; k--) if (tag.startsWith(s.slice(s.length - k))) return s.length - k;
4300
4306
  return s.length;
@@ -4316,7 +4322,7 @@ var ThinkSplitter = class {
4316
4322
  for (;;) if (!this.inside) {
4317
4323
  const i = s.indexOf(this.open);
4318
4324
  if (i === -1) {
4319
- const safe = holdback(s, this.open);
4325
+ const safe = holdback$1(s, this.open);
4320
4326
  text += s.slice(0, safe);
4321
4327
  this.hold = s.slice(safe);
4322
4328
  return {
@@ -4330,7 +4336,7 @@ var ThinkSplitter = class {
4330
4336
  } else {
4331
4337
  const i = s.indexOf(this.close);
4332
4338
  if (i === -1) {
4333
- const safe = holdback(s, this.close);
4339
+ const safe = holdback$1(s, this.close);
4334
4340
  think += s.slice(0, safe);
4335
4341
  this.hold = s.slice(safe);
4336
4342
  return {
@@ -4382,7 +4388,7 @@ var StopScanner = class {
4382
4388
  return s.slice(0, mi);
4383
4389
  }
4384
4390
  let safe = s.length;
4385
- for (const st of this.stops) safe = Math.min(safe, holdback(s, st));
4391
+ for (const st of this.stops) safe = Math.min(safe, holdback$1(s, st));
4386
4392
  this.hold = s.slice(safe);
4387
4393
  return s.slice(0, safe);
4388
4394
  }
@@ -4394,7 +4400,94 @@ var StopScanner = class {
4394
4400
  };
4395
4401
  //#endregion
4396
4402
  //#region src/chat/json.ts
4397
- const WS = /* @__PURE__ */ new Set([
4403
+ const SUPPORTED = /* @__PURE__ */ new Set([
4404
+ "type",
4405
+ "properties",
4406
+ "required",
4407
+ "additionalProperties",
4408
+ "items",
4409
+ "minItems",
4410
+ "maxItems",
4411
+ "enum",
4412
+ "oneOf",
4413
+ "minimum",
4414
+ "maximum",
4415
+ "minLength",
4416
+ "maxLength"
4417
+ ]);
4418
+ const TYPES = /* @__PURE__ */ new Set([
4419
+ "object",
4420
+ "array",
4421
+ "string",
4422
+ "number",
4423
+ "integer",
4424
+ "boolean",
4425
+ "null"
4426
+ ]);
4427
+ /** The discriminator of a branch list: a property required by every branch, with a single-value
4428
+ * string enum in every branch, all values distinct. null when the union is not discriminated. */
4429
+ function findDiscriminator(branches) {
4430
+ for (const k of Object.keys(branches[0]?.properties ?? {})) if (branches.every((b) => b.required?.includes(k) && b.properties?.[k]?.enum?.length === 1)) {
4431
+ const vals = branches.map((b) => b.properties[k].enum?.[0]);
4432
+ if (new Set(vals).size === branches.length) return k;
4433
+ }
4434
+ return null;
4435
+ }
4436
+ /** Validate a schema against the enforceable subset; throws listing anything unsupported. */
4437
+ function validateJsonSchema(schema, path = "schema", isRoot = true) {
4438
+ const unknown = Object.keys(schema).filter((k) => !SUPPORTED.has(k));
4439
+ if (unknown.length) throw new Error(`bitgpu/chat: unsupported JSON Schema keyword(s) at ${path}: ${unknown.join(", ")} (enforceable subset: ${[...SUPPORTED].join(", ")})`);
4440
+ if (schema.oneOf !== void 0) {
4441
+ const extra = Object.keys(schema).filter((k) => k !== "oneOf");
4442
+ if (extra.length) throw new Error(`bitgpu/chat: oneOf at ${path} cannot combine with other keywords (got ${extra.join(", ")})`);
4443
+ if (!Array.isArray(schema.oneOf) || schema.oneOf.length < 2) throw new Error(`bitgpu/chat: oneOf at ${path} needs at least 2 branches`);
4444
+ schema.oneOf.forEach((b, i) => {
4445
+ validateJsonSchema(b, `${path}.oneOf[${i}]`, false);
4446
+ if (b.type !== "object" || b.additionalProperties !== false || b.properties === void 0) throw new Error(`bitgpu/chat: every oneOf branch must be { type: 'object', additionalProperties: false, properties: ... } (${path}.oneOf[${i}])`);
4447
+ });
4448
+ const disc = findDiscriminator(schema.oneOf);
4449
+ if (disc === null) throw new Error(`bitgpu/chat: oneOf at ${path} must be a DISCRIMINATED union - a property required by every branch whose single-value enum differs per branch`);
4450
+ const shared = /* @__PURE__ */ new Map();
4451
+ for (const b of schema.oneOf) for (const [k, v] of Object.entries(b.properties ?? {})) {
4452
+ if (k === disc) continue;
4453
+ const s = JSON.stringify(v);
4454
+ const prev = shared.get(k);
4455
+ if (prev !== void 0 && prev !== s) throw new Error(`bitgpu/chat: property '${k}' differs between oneOf branches at ${path} (non-discriminator properties shared by branches must be identical)`);
4456
+ shared.set(k, s);
4457
+ }
4458
+ return;
4459
+ }
4460
+ if (schema.type !== void 0 && !TYPES.has(schema.type)) throw new Error(`bitgpu/chat: unsupported type '${schema.type}' at ${path}`);
4461
+ if (schema.minimum !== void 0 || schema.maximum !== void 0) {
4462
+ if (schema.type !== "integer") throw new Error(`bitgpu/chat: minimum/maximum at ${path} require type 'integer' (float ranges are not incrementally enforceable)`);
4463
+ if (schema.minimum !== void 0 && !Number.isSafeInteger(schema.minimum)) throw new Error(`bitgpu/chat: minimum at ${path} must be a safe integer`);
4464
+ if (schema.maximum !== void 0 && !Number.isSafeInteger(schema.maximum)) throw new Error(`bitgpu/chat: maximum at ${path} must be a safe integer`);
4465
+ if (schema.minimum !== void 0 && schema.maximum !== void 0 && schema.minimum > schema.maximum) throw new Error(`bitgpu/chat: minimum > maximum at ${path}`);
4466
+ }
4467
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0) {
4468
+ if (schema.type !== "string") throw new Error(`bitgpu/chat: minLength/maxLength at ${path} require type 'string'`);
4469
+ if (schema.enum !== void 0) throw new Error(`bitgpu/chat: minLength/maxLength at ${path} cannot combine with enum`);
4470
+ for (const [k, v] of [["minLength", schema.minLength], ["maxLength", schema.maxLength]]) if (v !== void 0 && (!Number.isSafeInteger(v) || v < 0)) throw new Error(`bitgpu/chat: ${k} at ${path} must be a non-negative integer`);
4471
+ if (schema.minLength !== void 0 && schema.maxLength !== void 0 && schema.minLength > schema.maxLength) throw new Error(`bitgpu/chat: minLength > maxLength at ${path}`);
4472
+ }
4473
+ 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`);
4474
+ if (schema.enum !== void 0) {
4475
+ 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`);
4476
+ 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)`);
4477
+ if (schema.type !== void 0 && schema.type !== "string") throw new Error(`bitgpu/chat: enum at ${path} requires type 'string'`);
4478
+ }
4479
+ if (schema.required !== void 0 && schema.properties !== void 0) {
4480
+ 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`);
4481
+ }
4482
+ if (schema.additionalProperties === false && schema.properties === void 0) throw new Error(`bitgpu/chat: additionalProperties: false at ${path} needs a properties map`);
4483
+ if (schema.properties !== void 0) for (const [k, v] of Object.entries(schema.properties)) {
4484
+ if (/["\\\u0000-\u001f]/.test(k)) throw new Error(`bitgpu/chat: property name ${JSON.stringify(k)} at ${path} contains characters that require JSON escaping (unsupported)`);
4485
+ validateJsonSchema(v, `${path}.properties.${k}`, false);
4486
+ }
4487
+ if (schema.items !== void 0) validateJsonSchema(schema.items, `${path}.items`, false);
4488
+ if (schema.minItems !== void 0 && schema.maxItems !== void 0 && schema.minItems > schema.maxItems) throw new Error(`bitgpu/chat: minItems > maxItems at ${path}`);
4489
+ }
4490
+ const WS$1 = /* @__PURE__ */ new Set([
4398
4491
  32,
4399
4492
  9,
4400
4493
  10,
@@ -4403,137 +4496,385 @@ const WS = /* @__PURE__ */ new Set([
4403
4496
  const isDigit = (b) => b >= 48 && b <= 57;
4404
4497
  const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
4405
4498
  const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
4499
+ const utf8$1 = new TextEncoder();
4406
4500
  var JsonMachine = class JsonMachine {
4501
+ root;
4407
4502
  stack = [];
4408
4503
  phase = 0;
4409
- isKey = false;
4410
4504
  uLeft = 0;
4411
4505
  utf8Left = 0;
4412
4506
  numSub = 2;
4507
+ numInt = false;
4413
4508
  litWord = "";
4414
4509
  litPos = 0;
4510
+ strKind = "value";
4511
+ strBuf = "";
4512
+ strTracking = false;
4513
+ enumCands = null;
4514
+ strLenOn = false;
4515
+ strCount = 0;
4516
+ strMin = 0;
4517
+ strMax = Infinity;
4518
+ numMin = null;
4519
+ numMax = null;
4520
+ numBuf = "";
4521
+ pending = null;
4522
+ wsRun = 0;
4523
+ constructor(root = null) {
4524
+ this.root = root;
4525
+ this.pending = root;
4526
+ }
4415
4527
  clone() {
4416
- const m = new JsonMachine();
4417
- m.stack = this.stack.slice();
4528
+ const m = new JsonMachine(this.root);
4529
+ m.stack = this.stack.map((c) => ({
4530
+ kind: c.kind,
4531
+ node: c.node,
4532
+ seen: c.seen.slice(),
4533
+ count: c.count,
4534
+ branches: c.branches ? c.branches.slice() : null,
4535
+ discRaw: c.discRaw,
4536
+ discKey: c.discKey,
4537
+ discPending: c.discPending
4538
+ }));
4418
4539
  m.phase = this.phase;
4419
- m.isKey = this.isKey;
4420
4540
  m.uLeft = this.uLeft;
4421
4541
  m.utf8Left = this.utf8Left;
4422
4542
  m.numSub = this.numSub;
4543
+ m.numInt = this.numInt;
4423
4544
  m.litWord = this.litWord;
4424
4545
  m.litPos = this.litPos;
4546
+ m.strKind = this.strKind;
4547
+ m.strBuf = this.strBuf;
4548
+ m.strTracking = this.strTracking;
4549
+ m.enumCands = this.enumCands;
4550
+ m.strLenOn = this.strLenOn;
4551
+ m.strCount = this.strCount;
4552
+ m.strMin = this.strMin;
4553
+ m.strMax = this.strMax;
4554
+ m.numMin = this.numMin;
4555
+ m.numMax = this.numMax;
4556
+ m.numBuf = this.numBuf;
4557
+ m.pending = this.pending;
4558
+ m.wsRun = this.wsRun;
4425
4559
  return m;
4426
4560
  }
4427
4561
  get complete() {
4428
4562
  return this.phase === 12;
4429
4563
  }
4430
- /** Feed bytes; false = the text stopped being a valid JSON prefix (state is then undefined). */
4564
+ /** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
4431
4565
  feed(bytes) {
4432
4566
  for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
4433
4567
  return true;
4434
4568
  }
4569
+ top() {
4570
+ return this.stack[this.stack.length - 1];
4571
+ }
4572
+ /** Byte-space form of a string literal (what strBuf accumulates). */
4573
+ static bytesOf(s) {
4574
+ return String.fromCharCode(...utf8$1.encode(s));
4575
+ }
4435
4576
  openValue(b) {
4577
+ const sc = this.pending;
4578
+ const t = sc?.type;
4579
+ if (sc?.enum !== void 0 && b !== 34) return false;
4580
+ if (sc?.oneOf !== void 0) {
4581
+ if (b !== 123) return false;
4582
+ const discRaw = findDiscriminator(sc.oneOf);
4583
+ this.stack.push({
4584
+ kind: "{",
4585
+ node: null,
4586
+ seen: [],
4587
+ count: 0,
4588
+ branches: sc.oneOf.slice(),
4589
+ discRaw,
4590
+ discKey: JsonMachine.bytesOf(discRaw),
4591
+ discPending: false
4592
+ });
4593
+ this.phase = 3;
4594
+ this.pending = null;
4595
+ return true;
4596
+ }
4436
4597
  if (b === 123) {
4437
- this.stack.push("{");
4598
+ if (t !== void 0 && t !== "object") return false;
4599
+ this.stack.push({
4600
+ kind: "{",
4601
+ node: sc ?? null,
4602
+ seen: [],
4603
+ count: 0,
4604
+ branches: null,
4605
+ discRaw: null,
4606
+ discKey: null,
4607
+ discPending: false
4608
+ });
4438
4609
  this.phase = 3;
4439
4610
  } else if (b === 91) {
4440
- this.stack.push("[");
4611
+ if (t !== void 0 && t !== "array") return false;
4612
+ this.stack.push({
4613
+ kind: "[",
4614
+ node: sc ?? null,
4615
+ seen: [],
4616
+ count: 0,
4617
+ branches: null,
4618
+ discRaw: null,
4619
+ discKey: null,
4620
+ discPending: false
4621
+ });
4441
4622
  this.phase = 2;
4442
4623
  } else if (b === 34) {
4443
- this.isKey = false;
4624
+ if (t !== void 0 && t !== "string") return false;
4625
+ this.strKind = sc?.enum ? "enum" : "value";
4626
+ this.enumCands = sc?.enum ? sc.enum.map(JsonMachine.bytesOf) : null;
4627
+ this.strBuf = "";
4628
+ this.strTracking = this.strKind === "enum";
4629
+ this.strLenOn = sc?.minLength !== void 0 || sc?.maxLength !== void 0;
4630
+ this.strCount = 0;
4631
+ this.strMin = sc?.minLength ?? 0;
4632
+ this.strMax = sc?.maxLength ?? Infinity;
4444
4633
  this.phase = 7;
4445
4634
  } else if (b === 45 || isDigit(b)) {
4635
+ if (t !== void 0 && t !== "number" && t !== "integer") return false;
4636
+ this.numInt = t === "integer";
4637
+ this.numMin = this.numInt ? sc?.minimum ?? null : null;
4638
+ this.numMax = this.numInt ? sc?.maximum ?? null : null;
4639
+ this.numBuf = String.fromCharCode(b);
4640
+ if (!this.intFeasible()) return false;
4446
4641
  this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
4447
4642
  this.phase = 10;
4448
4643
  } else if (b === 116 || b === 102 || b === 110) {
4449
- this.litWord = b === 116 ? "true" : b === 102 ? "false" : "null";
4644
+ const word = b === 116 ? "true" : b === 102 ? "false" : "null";
4645
+ if (t !== void 0 && !(word === "null" && t === "null" || word !== "null" && t === "boolean")) return false;
4646
+ this.litWord = word;
4450
4647
  this.litPos = 1;
4451
4648
  this.phase = 11;
4452
4649
  } else return false;
4650
+ this.pending = null;
4453
4651
  return true;
4454
4652
  }
4653
+ /** A value just finished; land per the enclosing container and count array items. */
4455
4654
  closeValue() {
4456
- this.phase = this.stack.length === 0 ? 12 : 6;
4655
+ const c = this.top();
4656
+ if (c === void 0) {
4657
+ this.phase = 12;
4658
+ return;
4659
+ }
4660
+ if (c.kind === "[") c.count++;
4661
+ this.phase = 6;
4457
4662
  }
4458
4663
  closeContainer(b) {
4459
- const want = b === 125 ? "{" : "[";
4460
- if (this.stack.pop() !== want) return false;
4664
+ const c = this.top();
4665
+ if (!c || c.kind !== (b === 125 ? "{" : "[")) return false;
4666
+ if (c.kind === "{") {
4667
+ if (c.branches) {
4668
+ if (!c.branches.some((br) => (br.required ?? []).every((k) => c.seen.includes(JsonMachine.bytesOf(k))))) return false;
4669
+ } else if (c.node?.required) {
4670
+ for (const k of c.node.required) if (!c.seen.includes(JsonMachine.bytesOf(k))) return false;
4671
+ }
4672
+ }
4673
+ if (c.kind === "[" && c.node?.minItems !== void 0 && c.count < c.node.minItems) return false;
4674
+ this.stack.pop();
4461
4675
  this.closeValue();
4462
4676
  return true;
4463
4677
  }
4678
+ /** Candidate property names for the key being typed (null = unconstrained). */
4679
+ keyCands(c) {
4680
+ if (c.branches) {
4681
+ const out = /* @__PURE__ */ new Set();
4682
+ for (const b of c.branches) for (const k of Object.keys(b.properties ?? {})) {
4683
+ const kb = JsonMachine.bytesOf(k);
4684
+ if (!c.seen.includes(kb)) out.add(kb);
4685
+ }
4686
+ return [...out];
4687
+ }
4688
+ if (!c.node || c.node.additionalProperties !== false) return null;
4689
+ return Object.keys(c.node.properties ?? {}).map(JsonMachine.bytesOf).filter((k) => !c.seen.includes(k));
4690
+ }
4691
+ startKey(c) {
4692
+ this.strKind = "key";
4693
+ this.enumCands = this.keyCands(c);
4694
+ this.strBuf = "";
4695
+ this.strTracking = true;
4696
+ this.phase = 7;
4697
+ }
4698
+ /** Structural whitespace is never REQUIRED by JSON, so capping a run cannot make the grammar
4699
+ * unsatisfiable - but without a cap, a model denied prose can loop on whitespace forever (the
4700
+ * grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
4701
+ * allows generous pretty-printing indentation while forcing real progress. */
4702
+ ws() {
4703
+ return ++this.wsRun <= 16;
4704
+ }
4705
+ /** Integer bounds: can SOME digit-extension of the current number prefix (including "stop
4706
+ * here") land inside [min, max]? The attainable values from digit string D are
4707
+ * union over k >= 0 of sign * [D*10^k, (D+1)*10^k - 1]; leading-zero rules make 0 / -0
4708
+ * terminal-only. Rejecting infeasible digits up front means the machine can never trap the
4709
+ * model in an unfinishable number. */
4710
+ intFeasible() {
4711
+ if (this.numMin === null && this.numMax === null) return true;
4712
+ const lo = this.numMin ?? -Infinity;
4713
+ const hi = this.numMax ?? Infinity;
4714
+ const neg = this.numBuf[0] === "-";
4715
+ const ds = neg ? this.numBuf.slice(1) : this.numBuf;
4716
+ if (ds === "") return lo <= 0;
4717
+ if (ds === "0") return lo <= 0 && 0 <= hi;
4718
+ const D = Number(ds);
4719
+ for (let pow = 1;; pow *= 10) {
4720
+ const a = D * pow;
4721
+ const b = (D + 1) * pow - 1;
4722
+ const va = neg ? -b : a;
4723
+ const vb = neg ? -a : b;
4724
+ if (va <= hi && vb >= lo) return true;
4725
+ if (neg ? vb < lo : va > hi) return false;
4726
+ if (!Number.isSafeInteger((D + 1) * pow * 10)) return false;
4727
+ }
4728
+ }
4729
+ /** May the current number END here (bounds permitting)? */
4730
+ intInRange() {
4731
+ if (this.numMin === null && this.numMax === null) return true;
4732
+ const v = Number(this.numBuf);
4733
+ return (this.numMin === null || v >= this.numMin) && (this.numMax === null || v <= this.numMax);
4734
+ }
4735
+ /** Accept a digit into the current number, bounds permitting. */
4736
+ numAppend(b) {
4737
+ if (this.numMin === null && this.numMax === null) return true;
4738
+ this.numBuf += String.fromCharCode(b);
4739
+ return this.intFeasible();
4740
+ }
4741
+ /** Count one code point of the current string, maxLength permitting. */
4742
+ strChar() {
4743
+ return !this.strLenOn || ++this.strCount <= this.strMax;
4744
+ }
4464
4745
  byte(b) {
4746
+ if (!WS$1.has(b)) this.wsRun = 0;
4465
4747
  switch (this.phase) {
4466
4748
  case 0:
4467
- if (WS.has(b)) return true;
4749
+ if (WS$1.has(b)) return this.ws();
4468
4750
  if (b === 123 || b === 91) return this.openValue(b);
4469
4751
  return false;
4470
4752
  case 1:
4471
- if (WS.has(b)) return true;
4753
+ if (WS$1.has(b)) return this.ws();
4472
4754
  return this.openValue(b);
4473
- case 2:
4474
- if (WS.has(b)) return true;
4755
+ case 2: {
4756
+ if (WS$1.has(b)) return this.ws();
4475
4757
  if (b === 93) return this.closeContainer(b);
4758
+ const c = this.top();
4759
+ if (c.node?.maxItems === 0) return false;
4760
+ this.pending = c.node?.items ?? null;
4476
4761
  return this.openValue(b);
4762
+ }
4477
4763
  case 3:
4478
- if (WS.has(b)) return true;
4764
+ if (WS$1.has(b)) return this.ws();
4479
4765
  if (b === 125) return this.closeContainer(b);
4480
4766
  if (b === 34) {
4481
- this.isKey = true;
4482
- this.phase = 7;
4767
+ const c = this.top();
4768
+ if (this.keyCands(c)?.length === 0) return false;
4769
+ this.startKey(c);
4483
4770
  return true;
4484
4771
  }
4485
4772
  return false;
4486
4773
  case 4:
4487
- if (WS.has(b)) return true;
4774
+ if (WS$1.has(b)) return this.ws();
4488
4775
  if (b === 34) {
4489
- this.isKey = true;
4490
- this.phase = 7;
4776
+ this.startKey(this.top());
4491
4777
  return true;
4492
4778
  }
4493
4779
  return false;
4494
4780
  case 5:
4495
- if (WS.has(b)) return true;
4781
+ if (WS$1.has(b)) return this.ws();
4496
4782
  if (b === 58) {
4783
+ const c = this.top();
4784
+ const key = c.seen[c.seen.length - 1];
4785
+ if (c.branches) if (key === c.discKey) {
4786
+ this.pending = { enum: c.branches.map((br) => br.properties[c.discRaw].enum?.[0]) };
4787
+ c.discPending = true;
4788
+ } else {
4789
+ let prop = null;
4790
+ for (const br of c.branches) {
4791
+ const hit = Object.entries(br.properties ?? {}).find(([k]) => JsonMachine.bytesOf(k) === key);
4792
+ if (hit) {
4793
+ prop = hit[1];
4794
+ break;
4795
+ }
4796
+ }
4797
+ this.pending = prop;
4798
+ }
4799
+ else {
4800
+ const prop = c.node?.properties ? Object.entries(c.node.properties).find(([k]) => JsonMachine.bytesOf(k) === key) : void 0;
4801
+ this.pending = prop ? prop[1] : null;
4802
+ }
4497
4803
  this.phase = 1;
4498
4804
  return true;
4499
4805
  }
4500
4806
  return false;
4501
4807
  case 6: {
4502
- if (WS.has(b)) return true;
4503
- const top = this.stack[this.stack.length - 1];
4504
- if (b === 44) {
4505
- this.phase = top === "{" ? 4 : 1;
4808
+ if (WS$1.has(b)) return this.ws();
4809
+ const c = this.top();
4810
+ if (b === 44 && c) {
4811
+ if (c.kind === "{") {
4812
+ if (this.keyCands(c)?.length === 0) return false;
4813
+ this.phase = 4;
4814
+ } else {
4815
+ if (c.node?.maxItems !== void 0 && c.count >= c.node.maxItems) return false;
4816
+ this.pending = c.node?.items ?? null;
4817
+ this.phase = 1;
4818
+ }
4506
4819
  return true;
4507
4820
  }
4508
- if (b === 125 && top === "{" || b === 93 && top === "[") return this.closeContainer(b);
4821
+ if ((b === 125 || b === 93) && c) return this.closeContainer(b);
4509
4822
  return false;
4510
4823
  }
4511
4824
  case 7:
4512
4825
  if (this.utf8Left > 0) {
4513
4826
  if (b >= 128 && b <= 191) {
4514
4827
  this.utf8Left--;
4515
- return true;
4828
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4829
+ return this.enumOk();
4516
4830
  }
4517
4831
  return false;
4518
4832
  }
4519
4833
  if (b === 34) {
4520
- if (this.isKey) {
4521
- this.isKey = false;
4834
+ if (this.strKind === "key") {
4835
+ const c = this.top();
4836
+ if (this.enumCands !== null && !this.enumCands.includes(this.strBuf)) return false;
4837
+ if ((c.node?.properties || c.branches) && c.seen.includes(this.strBuf)) return false;
4838
+ c.seen.push(this.strBuf);
4839
+ if (c.branches) {
4840
+ c.branches = c.branches.filter((br) => Object.keys(br.properties ?? {}).some((k) => JsonMachine.bytesOf(k) === this.strBuf));
4841
+ if (c.branches.length === 0) return false;
4842
+ }
4522
4843
  this.phase = 5;
4523
- } else this.closeValue();
4844
+ } else {
4845
+ if (this.strKind === "enum" && !this.enumCands.includes(this.strBuf)) return false;
4846
+ if (this.strLenOn && this.strCount < this.strMin) return false;
4847
+ const c = this.top();
4848
+ if (c?.discPending) {
4849
+ c.branches = c.branches.filter((br) => JsonMachine.bytesOf(br.properties[c.discRaw].enum?.[0]) === this.strBuf);
4850
+ c.discPending = false;
4851
+ if (c.branches.length === 0) return false;
4852
+ }
4853
+ this.closeValue();
4854
+ }
4855
+ this.strTracking = false;
4856
+ this.strLenOn = false;
4524
4857
  return true;
4525
4858
  }
4526
4859
  if (b === 92) {
4860
+ if (this.strKind === "enum" || this.strKind === "key" && this.enumCands !== null) return false;
4861
+ if (!this.strChar()) return false;
4527
4862
  this.phase = 8;
4528
4863
  return true;
4529
4864
  }
4530
4865
  if (b < 32) return false;
4531
- if (b < 128) return true;
4866
+ if (b < 128) {
4867
+ if (!this.strChar()) return false;
4868
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4869
+ return this.enumOk();
4870
+ }
4532
4871
  if (b >= 194 && b <= 223) this.utf8Left = 1;
4533
4872
  else if (b >= 224 && b <= 239) this.utf8Left = 2;
4534
4873
  else if (b >= 240 && b <= 244) this.utf8Left = 3;
4535
4874
  else return false;
4536
- return true;
4875
+ if (!this.strChar()) return false;
4876
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4877
+ return this.enumOk();
4537
4878
  case 8:
4538
4879
  if (b === 117) {
4539
4880
  this.uLeft = 4;
@@ -4550,12 +4891,14 @@ var JsonMachine = class JsonMachine {
4550
4891
  114,
4551
4892
  116
4552
4893
  ].includes(b)) {
4894
+ if (this.strTracking) this.strBuf += "\\" + String.fromCharCode(b);
4553
4895
  this.phase = 7;
4554
4896
  return true;
4555
4897
  }
4556
4898
  return false;
4557
4899
  case 9:
4558
4900
  if (!isHex(b)) return false;
4901
+ if (this.strTracking) this.strBuf += String.fromCharCode(b);
4559
4902
  if (--this.uLeft === 0) this.phase = 7;
4560
4903
  return true;
4561
4904
  case 10:
@@ -4563,12 +4906,12 @@ var JsonMachine = class JsonMachine {
4563
4906
  case 0:
4564
4907
  if (!isDigit(b)) return false;
4565
4908
  this.numSub = b === 48 ? 1 : 2;
4566
- return true;
4909
+ return this.numAppend(b);
4567
4910
  case 1:
4568
4911
  case 2:
4569
4912
  if (isDigit(b)) {
4570
4913
  if (this.numSub === 1) return false;
4571
- return true;
4914
+ return this.numAppend(b);
4572
4915
  }
4573
4916
  break;
4574
4917
  case 3:
@@ -4594,15 +4937,16 @@ var JsonMachine = class JsonMachine {
4594
4937
  if (isDigit(b)) return true;
4595
4938
  break;
4596
4939
  }
4597
- if (b === 46 && (this.numSub === 1 || this.numSub === 2)) {
4940
+ if (b === 46 && !this.numInt && (this.numSub === 1 || this.numSub === 2)) {
4598
4941
  this.numSub = 3;
4599
4942
  return true;
4600
4943
  }
4601
- if ((b === 101 || b === 69) && numberDone(this.numSub) && this.numSub !== 7) {
4944
+ if ((b === 101 || b === 69) && !this.numInt && numberDone(this.numSub) && this.numSub !== 7) {
4602
4945
  this.numSub = 5;
4603
4946
  return true;
4604
4947
  }
4605
4948
  if (numberDone(this.numSub)) {
4949
+ if (!this.intInRange()) return false;
4606
4950
  this.closeValue();
4607
4951
  return this.byte(b);
4608
4952
  }
@@ -4611,9 +4955,16 @@ var JsonMachine = class JsonMachine {
4611
4955
  if (b !== this.litWord.charCodeAt(this.litPos)) return false;
4612
4956
  if (++this.litPos === this.litWord.length) this.closeValue();
4613
4957
  return true;
4614
- case 12: return WS.has(b);
4958
+ case 12: return WS$1.has(b);
4615
4959
  }
4616
4960
  }
4961
+ /** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
4962
+ enumOk() {
4963
+ if (!this.strTracking || this.enumCands === null) return true;
4964
+ const buf = this.strBuf;
4965
+ for (const c of this.enumCands) if (c.startsWith(buf)) return true;
4966
+ return false;
4967
+ }
4617
4968
  };
4618
4969
  function aliasToByte() {
4619
4970
  const bs = [];
@@ -4664,10 +5015,10 @@ var TokenByteTable = class {
4664
5015
  }
4665
5016
  };
4666
5017
  /** 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 generation ends
4668
- * naturally. Call advance() with each chosen token to move the real machine forward. */
4669
- function makeJsonFilter(table, eosTokenId) {
4670
- const machine = new JsonMachine();
5018
+ * a valid, schema-conforming JSON prefix; once the root value is complete, permit ONLY eos so
5019
+ * generation ends naturally. Call advance() with each chosen token to move the real machine. */
5020
+ function makeJsonFilter(table, eosTokenId, schema = null) {
5021
+ const machine = new JsonMachine(schema);
4671
5022
  return {
4672
5023
  machine,
4673
5024
  filter: (ids) => {
@@ -4691,6 +5042,299 @@ function makeJsonFilter(table, eosTokenId) {
4691
5042
  };
4692
5043
  }
4693
5044
  //#endregion
5045
+ //#region src/chat/tools.ts
5046
+ const BAD_NAME = /["\\\u0000-\u001f]/;
5047
+ /** Validate a tools list + choice; throws on anything the enforcer cannot guarantee. */
5048
+ function validateTools(tools, choice) {
5049
+ if (tools.length === 0) throw new Error("bitgpu/chat: tools is empty");
5050
+ const seen = /* @__PURE__ */ new Set();
5051
+ for (let i = 0; i < tools.length; i++) {
5052
+ const t = tools[i];
5053
+ if (t?.type !== "function" || typeof t.function?.name !== "string" || t.function.name.length === 0) throw new Error(`bitgpu/chat: tools[${i}] must be { type: 'function', function: { name, ... } }`);
5054
+ const name = t.function.name;
5055
+ if (BAD_NAME.test(name)) throw new Error(`bitgpu/chat: tool name ${JSON.stringify(name)} contains characters that require JSON escaping (unsupported)`);
5056
+ if (seen.has(name)) throw new Error(`bitgpu/chat: duplicate tool name '${name}'`);
5057
+ seen.add(name);
5058
+ const p = t.function.parameters;
5059
+ if (p !== void 0) {
5060
+ if (p.type !== void 0 && p.type !== "object") throw new Error(`bitgpu/chat: tools[${i}].function.parameters must describe an object (got type '${p.type}')`);
5061
+ validateJsonSchema(p.type === void 0 ? {
5062
+ ...p,
5063
+ type: "object"
5064
+ } : p, `tools[${i}].function.parameters`, true);
5065
+ }
5066
+ }
5067
+ if (typeof choice === "object" && !seen.has(choice.name)) throw new Error(`bitgpu/chat: toolChoice names unknown tool '${choice.name}'`);
5068
+ }
5069
+ /** The arguments schema the enforcer uses for a tool (parameters, defaulted to "any object"). */
5070
+ function argsSchemaOf(t) {
5071
+ const p = t.function.parameters;
5072
+ if (p === void 0) return { type: "object" };
5073
+ return p.type === void 0 ? {
5074
+ ...p,
5075
+ type: "object"
5076
+ } : p;
5077
+ }
5078
+ const utf8 = new TextEncoder();
5079
+ const LIT1 = utf8.encode("{\"name\": \"");
5080
+ const LIT2 = utf8.encode("\", \"arguments\": ");
5081
+ const WS = /* @__PURE__ */ new Set([
5082
+ 32,
5083
+ 9,
5084
+ 10,
5085
+ 13
5086
+ ]);
5087
+ const WS_CAP = 4;
5088
+ var ToolBodyMachine = class ToolBodyMachine {
5089
+ cands;
5090
+ schemas;
5091
+ phase = 0;
5092
+ lit = 0;
5093
+ nameBuf = "";
5094
+ args = null;
5095
+ wsRun = 0;
5096
+ /** true once the closing '}' has landed (only trailing ws may follow). */
5097
+ complete = false;
5098
+ /** the committed tool name (set when its closing quote lands). */
5099
+ name = "";
5100
+ /** byte-space tool names, and each name's arguments schema */
5101
+ constructor(cands, schemas) {
5102
+ this.cands = cands;
5103
+ this.schemas = schemas;
5104
+ }
5105
+ clone() {
5106
+ const m = new ToolBodyMachine(this.cands, this.schemas);
5107
+ m.phase = this.phase;
5108
+ m.lit = this.lit;
5109
+ m.nameBuf = this.nameBuf;
5110
+ m.args = this.args ? this.args.clone() : null;
5111
+ m.wsRun = this.wsRun;
5112
+ m.complete = this.complete;
5113
+ m.name = this.name;
5114
+ return m;
5115
+ }
5116
+ static bytesOf(s) {
5117
+ return String.fromCharCode(...utf8.encode(s));
5118
+ }
5119
+ feed(bytes) {
5120
+ for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
5121
+ return true;
5122
+ }
5123
+ byte(b) {
5124
+ switch (this.phase) {
5125
+ case 0:
5126
+ if (WS.has(b)) return ++this.wsRun <= WS_CAP;
5127
+ if (b !== LIT1[0]) return false;
5128
+ this.phase = 1;
5129
+ this.lit = 1;
5130
+ return true;
5131
+ case 1:
5132
+ if (b !== LIT1[this.lit]) return false;
5133
+ if (++this.lit === LIT1.length) {
5134
+ this.phase = 2;
5135
+ this.nameBuf = "";
5136
+ }
5137
+ return true;
5138
+ case 2:
5139
+ if (b === 34) {
5140
+ if (!this.cands.includes(this.nameBuf)) return false;
5141
+ this.name = this.nameBuf;
5142
+ this.phase = 3;
5143
+ this.lit = 1;
5144
+ return true;
5145
+ }
5146
+ this.nameBuf += String.fromCharCode(b);
5147
+ for (const c of this.cands) if (c.startsWith(this.nameBuf)) return true;
5148
+ return false;
5149
+ case 3:
5150
+ if (b !== LIT2[this.lit]) return false;
5151
+ if (++this.lit === LIT2.length) {
5152
+ this.phase = 4;
5153
+ this.args = new JsonMachine(this.schemas.get(this.name) ?? { type: "object" });
5154
+ }
5155
+ return true;
5156
+ case 4: {
5157
+ const a = this.args;
5158
+ if (a.complete) {
5159
+ if (WS.has(b)) return ++this.wsRun <= WS_CAP;
5160
+ if (b !== 125) return false;
5161
+ this.wsRun = 0;
5162
+ this.phase = 5;
5163
+ this.complete = true;
5164
+ return true;
5165
+ }
5166
+ return a.feed(Uint8Array.of(b));
5167
+ }
5168
+ case 5: return WS.has(b) && ++this.wsRun <= WS_CAP;
5169
+ }
5170
+ }
5171
+ };
5172
+ /** Per-step candidate filter for tool turns. Auto mode: free text (everything permitted) until
5173
+ * the model opens <tool_call>, then the body grammar takes over until </tool_call>, then free
5174
+ * text again (another call, prose, or eos). Forced mode: the FIRST token must be <tool_call>,
5175
+ * the body is constrained to the named tool, and after </tool_call> only eos is permitted.
5176
+ * Call advance() with each emitted token to move the real machine. */
5177
+ function makeToolFilter(table, prep) {
5178
+ const { ids, forced } = prep;
5179
+ const cands = (forced ? prep.tools.filter((t) => t.function.name === forced) : prep.tools).map((t) => t.function.name).map(ToolBodyMachine.bytesOf);
5180
+ const schemas = new Map(prep.tools.map((t) => [ToolBodyMachine.bytesOf(t.function.name), argsSchemaOf(t)]));
5181
+ let state = forced ? 1 : 0;
5182
+ let body = null;
5183
+ let inThink = false;
5184
+ return {
5185
+ filter: (candidates) => {
5186
+ if (state === 0 || inThink) return Array.from(candidates, Number);
5187
+ const out = [];
5188
+ for (const id of candidates) {
5189
+ const n = Number(id);
5190
+ if (state === 1) {
5191
+ if (n === ids.open) out.push(n);
5192
+ continue;
5193
+ }
5194
+ if (state === 3) {
5195
+ if (n === ids.eos) out.push(n);
5196
+ continue;
5197
+ }
5198
+ const m = body;
5199
+ if (n === ids.close) {
5200
+ if (m.complete) out.push(n);
5201
+ continue;
5202
+ }
5203
+ const bytes = table.bytes(n);
5204
+ if (!bytes || bytes.length === 0) continue;
5205
+ if (m.clone().feed(bytes)) out.push(n);
5206
+ }
5207
+ return out;
5208
+ },
5209
+ advance: (id) => {
5210
+ if (id === ids.thinkOpen) {
5211
+ inThink = true;
5212
+ return;
5213
+ }
5214
+ if (id === ids.thinkClose) {
5215
+ inThink = false;
5216
+ return;
5217
+ }
5218
+ if (inThink) return;
5219
+ switch (state) {
5220
+ case 0:
5221
+ case 1:
5222
+ if (id === ids.open) {
5223
+ state = 2;
5224
+ body = new ToolBodyMachine(cands, schemas);
5225
+ }
5226
+ return;
5227
+ case 2:
5228
+ if (id === ids.close) {
5229
+ state = forced ? 3 : 0;
5230
+ body = null;
5231
+ return;
5232
+ }
5233
+ {
5234
+ const bytes = table.bytes(id);
5235
+ if (bytes) body.feed(bytes);
5236
+ }
5237
+ return;
5238
+ case 3: return;
5239
+ }
5240
+ }
5241
+ };
5242
+ }
5243
+ /** Longest suffix of `s` that is a proper prefix of `tag` (what must be held back). */
5244
+ function holdback(s, tag) {
5245
+ const max = Math.min(s.length, tag.length - 1);
5246
+ for (let k = max; k > 0; k--) if (tag.startsWith(s.slice(s.length - k))) return s.length - k;
5247
+ return s.length;
5248
+ }
5249
+ /** Stream-safe <tool_call> block extraction (the tool sibling of ThinkSplitter): visible text on
5250
+ * one channel, each COMPLETED block's content as its own string, tags never surfacing anywhere.
5251
+ * Tags can straddle token boundaries, so chunk edges hold back possible partial tags. */
5252
+ var ToolCallSplitter = class {
5253
+ open;
5254
+ close;
5255
+ inside = false;
5256
+ hold = "";
5257
+ buf = "";
5258
+ constructor(open = "<tool_call>", close = "</tool_call>") {
5259
+ this.open = open;
5260
+ this.close = close;
5261
+ }
5262
+ push(chunk) {
5263
+ let s = this.hold + chunk;
5264
+ this.hold = "";
5265
+ let text = "";
5266
+ const blocks = [];
5267
+ for (;;) if (!this.inside) {
5268
+ const i = s.indexOf(this.open);
5269
+ if (i === -1) {
5270
+ const safe = holdback(s, this.open);
5271
+ text += s.slice(0, safe);
5272
+ this.hold = s.slice(safe);
5273
+ return {
5274
+ text,
5275
+ blocks
5276
+ };
5277
+ }
5278
+ text += s.slice(0, i);
5279
+ s = s.slice(i + this.open.length);
5280
+ this.inside = true;
5281
+ this.buf = "";
5282
+ } else {
5283
+ const i = s.indexOf(this.close);
5284
+ if (i === -1) {
5285
+ const safe = holdback(s, this.close);
5286
+ this.buf += s.slice(0, safe);
5287
+ this.hold = s.slice(safe);
5288
+ return {
5289
+ text,
5290
+ blocks
5291
+ };
5292
+ }
5293
+ blocks.push(this.buf + s.slice(0, i));
5294
+ this.buf = "";
5295
+ s = s.slice(i + this.close.length);
5296
+ this.inside = false;
5297
+ }
5298
+ }
5299
+ /** Emit whatever is held back. A block cut short by maxTokens surfaces as `partial` (its
5300
+ * content never reaches the visible text). */
5301
+ flush() {
5302
+ const r = this.inside ? {
5303
+ text: "",
5304
+ blocks: [],
5305
+ partial: this.buf + this.hold
5306
+ } : {
5307
+ text: this.hold,
5308
+ blocks: [],
5309
+ partial: null
5310
+ };
5311
+ this.hold = "";
5312
+ this.buf = "";
5313
+ this.inside = false;
5314
+ return r;
5315
+ }
5316
+ };
5317
+ /** Parse one block's content into a ToolCall. With enforcement on this cannot fail for a
5318
+ * completed block; a failure (unenforced or truncated content) yields name '' and the raw text. */
5319
+ function parseToolCall(raw) {
5320
+ try {
5321
+ const v = JSON.parse(raw.trim());
5322
+ const name = typeof v?.name === "string" ? v.name : "";
5323
+ let args = v?.arguments;
5324
+ if (typeof args === "string") args = JSON.parse(args);
5325
+ if (name && args !== null && typeof args === "object" && !Array.isArray(args)) return {
5326
+ name,
5327
+ arguments: args,
5328
+ raw
5329
+ };
5330
+ } catch {}
5331
+ return {
5332
+ name: "",
5333
+ arguments: {},
5334
+ raw
5335
+ };
5336
+ }
5337
+ //#endregion
4694
5338
  //#region src/chat/index.ts
4695
5339
  function deriveChatWrap(tk) {
4696
5340
  if (!tk.hasChatTemplate) return null;
@@ -4723,6 +5367,10 @@ function deriveChatWrap(tk) {
4723
5367
  return null;
4724
5368
  }
4725
5369
  }
5370
+ const tcKey = (tcs) => JSON.stringify(tcs?.map((t) => [t.name, t.arguments]) ?? null);
5371
+ function msgEq(a, b) {
5372
+ return a.role === b.role && a.content === b.content && tcKey(a.tool_calls) === tcKey(b.tool_calls);
5373
+ }
4726
5374
  /** True iff `next` is exactly `committed` plus one new trailing user turn - a clean append, so the
4727
5375
  * engine can extend its KV cache with just that turn. Compared as MESSAGES, not token ids: chat
4728
5376
  * templates render past assistant turns differently from live ones (e.g. Qwen3's empty <think>
@@ -4730,7 +5378,18 @@ function deriveChatWrap(tk) {
4730
5378
  function isCleanAppend(committed, next) {
4731
5379
  if (!committed || next.length !== committed.length + 1) return false;
4732
5380
  if (next[next.length - 1].role !== "user") return false;
4733
- for (let i = 0; i < committed.length; i++) if (next[i].role !== committed[i].role || next[i].content !== committed[i].content) return false;
5381
+ for (let i = 0; i < committed.length; i++) if (!msgEq(next[i], committed[i])) return false;
5382
+ return true;
5383
+ }
5384
+ /** True iff `next` is `committed` (whose last turn is an assistant turn WITH tool calls) plus
5385
+ * only trailing `tool` result messages - the continuation leg of a tool round trip, appendable
5386
+ * to the KV cache the same way a user turn is. */
5387
+ function isToolAppend(committed, next) {
5388
+ if (!committed || committed.length === 0 || next.length <= committed.length) return false;
5389
+ const last = committed[committed.length - 1];
5390
+ if (last.role !== "assistant" || !last.tool_calls?.length) return false;
5391
+ for (let i = 0; i < committed.length; i++) if (!msgEq(next[i], committed[i])) return false;
5392
+ for (let i = committed.length; i < next.length; i++) if (next[i].role !== "tool") return false;
4734
5393
  return true;
4735
5394
  }
4736
5395
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
@@ -4753,11 +5412,47 @@ async function createChat(engine, options) {
4753
5412
  const wrap = deriveChatWrap(tk);
4754
5413
  let committed = null;
4755
5414
  let cacheEndsAtEos = false;
5415
+ let committedToolsKey = null;
4756
5416
  let resetEpoch = 0;
4757
5417
  const dropCache = () => {
4758
5418
  committed = null;
5419
+ committedToolsKey = null;
4759
5420
  engine.resetCache();
4760
5421
  };
5422
+ let templateToolsOk = null;
5423
+ function prepareTools(tools, choice) {
5424
+ validateTools(tools, choice);
5425
+ if (templateToolsOk === null) try {
5426
+ const probe = tk.applyChatTemplate([{
5427
+ role: "user",
5428
+ content: "x"
5429
+ }], {
5430
+ addGenerationPrompt: false,
5431
+ tools: [{
5432
+ type: "function",
5433
+ function: { name: "bitgpu_probe_tool" }
5434
+ }]
5435
+ });
5436
+ templateToolsOk = probe.includes("bitgpu_probe_tool") && probe.includes("<tool_call>");
5437
+ } catch {
5438
+ templateToolsOk = false;
5439
+ }
5440
+ if (!templateToolsOk) throw new Error("bitgpu/chat: this model's chat template does not support tools");
5441
+ const open = tk.tokenToId("<tool_call>");
5442
+ const close = tk.tokenToId("</tool_call>");
5443
+ if (open === void 0 || close === void 0) throw new Error("bitgpu/chat: the vocabulary has no <tool_call> marker tokens, so tool calls cannot be enforced");
5444
+ return {
5445
+ tools,
5446
+ forced: typeof choice === "object" ? choice.name : null,
5447
+ ids: {
5448
+ open,
5449
+ close,
5450
+ eos: tk.eosTokenId,
5451
+ thinkOpen: tk.tokenToId("<think>"),
5452
+ thinkClose: tk.tokenToId("</think>")
5453
+ }
5454
+ };
5455
+ }
4761
5456
  let chain = Promise.resolve();
4762
5457
  const serialize = (fn) => {
4763
5458
  return (...args) => {
@@ -4769,20 +5464,37 @@ async function createChat(engine, options) {
4769
5464
  let byteTable = null;
4770
5465
  async function sendImpl(messages, o = {}) {
4771
5466
  if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
4772
- const json = o.format === "json";
4773
- const think = !json && (o.think ?? false);
4774
- const canReuse = (o.reuseCache ?? true) && !think && wrap !== null && isCleanAppend(committed, messages);
5467
+ const json = o.format !== void 0;
5468
+ const schema = typeof o.format === "object" ? o.format.json.schema ?? null : null;
5469
+ if (schema) validateJsonSchema(schema);
5470
+ const toolsGiven = o.tools !== void 0 && o.tools.length > 0 && o.toolChoice !== "none";
5471
+ if (toolsGiven && json) throw new Error("bitgpu/chat: tools cannot be combined with format (a constrained-JSON reply has no room for tool calls)");
5472
+ const prep = toolsGiven ? prepareTools(o.tools, o.toolChoice ?? "auto") : null;
5473
+ const toolsKey = prep ? JSON.stringify(prep.tools) : null;
5474
+ const think = !json && prep?.forced == null && (o.think ?? false);
5475
+ const wantReuse = (o.reuseCache ?? true) && !think && wrap !== null && toolsKey === committedToolsKey;
5476
+ const userAppend = wantReuse && isCleanAppend(committed, messages);
5477
+ const toolAppend = wantReuse && !userAppend && isToolAppend(committed, messages);
5478
+ const canReuse = userAppend || toolAppend;
4775
5479
  let inputTokenIds;
4776
- if (canReuse) {
5480
+ if (userAppend) {
4777
5481
  const w = wrap;
4778
5482
  const userText = messages[messages.length - 1].content;
4779
5483
  const deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}\n${w.userPrefix}${userText}${w.userSuffix}${w.genPrompt}`;
4780
5484
  inputTokenIds = tk.encode(deltaStr, false);
5485
+ } else if (toolAppend) {
5486
+ const toolMsgs = messages.slice(committed.length);
5487
+ const deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}\n` + tk.applyChatTemplate(toolMsgs, {
5488
+ addGenerationPrompt: true,
5489
+ enableThinking: false
5490
+ });
5491
+ inputTokenIds = tk.encode(deltaStr, false);
4781
5492
  } else {
4782
5493
  dropCache();
4783
5494
  inputTokenIds = tk.encode(tk.applyChatTemplate(messages, {
4784
5495
  addGenerationPrompt: true,
4785
- enableThinking: think
5496
+ enableThinking: think,
5497
+ tools: prep?.tools
4786
5498
  }), false);
4787
5499
  }
4788
5500
  const decoder = tk.createDecoderStream(true);
@@ -4792,15 +5504,28 @@ async function createChat(engine, options) {
4792
5504
  const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
4793
5505
  let text = "";
4794
5506
  let thinkText = "";
4795
- const emit = (chunk) => {
4796
- if (chunk.text) {
4797
- const visible = stops ? stops.push(chunk.text) : chunk.text;
4798
- if (visible) {
4799
- text += visible;
4800
- o.onText?.(visible);
4801
- }
4802
- if (stops?.matched) stopCtl?.abort();
5507
+ const toolSplit = prep ? new ToolCallSplitter() : null;
5508
+ const toolCalls = [];
5509
+ const pushBlock = (block) => {
5510
+ const call = parseToolCall(block);
5511
+ toolCalls.push(call);
5512
+ if (call.name) o.onToolCall?.(call);
5513
+ };
5514
+ const emitVisible = (vis) => {
5515
+ if (!vis) return;
5516
+ const visible = stops ? stops.push(vis) : vis;
5517
+ if (visible) {
5518
+ text += visible;
5519
+ o.onText?.(visible);
4803
5520
  }
5521
+ if (stops?.matched) stopCtl?.abort();
5522
+ };
5523
+ const emit = (chunk) => {
5524
+ if (chunk.text) if (toolSplit) {
5525
+ const r = toolSplit.push(chunk.text);
5526
+ for (const b of r.blocks) pushBlock(b);
5527
+ emitVisible(r.text);
5528
+ } else emitVisible(chunk.text);
4804
5529
  if (chunk.think) {
4805
5530
  thinkText += chunk.think;
4806
5531
  o.onThink?.(chunk.think);
@@ -4808,7 +5533,8 @@ async function createChat(engine, options) {
4808
5533
  };
4809
5534
  const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
4810
5535
  const epoch0 = resetEpoch;
4811
- const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId) : null;
5536
+ const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
5537
+ const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep) : null;
4812
5538
  let result;
4813
5539
  try {
4814
5540
  result = await engine.generate(inputTokenIds, {
@@ -4819,13 +5545,15 @@ async function createChat(engine, options) {
4819
5545
  repetitionPenalty: o.repetitionPenalty,
4820
5546
  noRepeatNgramSize: o.noRepeatNgramSize,
4821
5547
  seed: o.seed,
4822
- promptLookup: json ? false : o.promptLookup,
5548
+ logprobs: o.logprobs,
5549
+ promptLookup: json || prep ? false : o.promptLookup,
4823
5550
  stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
4824
5551
  reuseCache: canReuse,
4825
5552
  signal,
4826
- candidateFilter: jf ? (ids) => jf.filter(ids) : void 0,
5553
+ candidateFilter: jf ? (ids) => jf.filter(ids) : tf ? (ids) => tf.filter(ids) : void 0,
4827
5554
  onToken: (id) => {
4828
5555
  jf?.advance(id);
5556
+ tf?.advance(id);
4829
5557
  emit(splitter.push(decoder.push(id)));
4830
5558
  }
4831
5559
  });
@@ -4850,39 +5578,57 @@ async function createChat(engine, options) {
4850
5578
  }
4851
5579
  emit(splitter.push(decoder.flush()));
4852
5580
  emit(splitter.flush());
5581
+ if (toolSplit) {
5582
+ const fr = toolSplit.flush();
5583
+ for (const b of fr.blocks) pushBlock(b);
5584
+ if (fr.partial !== null) pushBlock(fr.partial);
5585
+ emitVisible(fr.text);
5586
+ }
4853
5587
  const aborted = o.signal?.aborted ?? false;
5588
+ const callsClean = toolCalls.every((c) => c.name !== "");
4854
5589
  if (aborted || stops?.matched) dropCache();
4855
5590
  else if (think) dropCache();
4856
- else if (wrap !== null && text.trim() && resetEpoch === epoch0) {
4857
- committed = [...messages, {
5591
+ else if (wrap !== null && (text.trim() || toolCalls.length > 0) && callsClean && resetEpoch === epoch0) {
5592
+ const assistant = {
4858
5593
  role: "assistant",
4859
5594
  content: text
4860
- }];
5595
+ };
5596
+ if (toolCalls.length) assistant.tool_calls = toolCalls.map((c) => ({
5597
+ name: c.name,
5598
+ arguments: c.arguments
5599
+ }));
5600
+ committed = [...messages, assistant];
5601
+ committedToolsKey = toolsKey;
4861
5602
  cacheEndsAtEos = false;
4862
5603
  } else dropCache();
4863
5604
  return {
4864
5605
  text,
4865
5606
  thinkText,
5607
+ toolCalls,
4866
5608
  tokens: result.tokens,
4867
5609
  inputTokenIds,
4868
- finishReason: aborted ? "abort" : stops?.matched ? "stop" : result.tokens.length >= maxTokens ? "length" : "stop",
5610
+ finishReason: aborted ? "abort" : stops?.matched ? "stop" : result.tokens.length >= maxTokens ? "length" : toolCalls.length > 0 ? "tool_calls" : "stop",
4869
5611
  reusedCache: canReuse,
5612
+ ...result.logprobs ? { logprobs: result.logprobs } : {},
4870
5613
  prefillMs: result.prefillMs,
4871
5614
  decodeMs: result.decodeMs,
4872
5615
  tokensPerSecond: result.tokensPerSecond
4873
5616
  };
4874
5617
  }
4875
5618
  const send = serialize(sendImpl);
4876
- async function prewarmImpl(messages) {
5619
+ async function prewarmImpl(messages, opts = {}) {
4877
5620
  if (wrap === null) return;
5621
+ const prep = opts.tools?.length ? prepareTools(opts.tools, "auto") : null;
4878
5622
  const str = tk.applyChatTemplate(messages, {
4879
5623
  addGenerationPrompt: false,
4880
- enableThinking: false
5624
+ enableThinking: false,
5625
+ tools: prep?.tools
4881
5626
  }).replace(/\n$/, "");
4882
5627
  const epoch0 = resetEpoch;
4883
5628
  await engine.prefill(tk.encode(str, false));
4884
5629
  if (resetEpoch !== epoch0) return;
4885
5630
  committed = [...messages];
5631
+ committedToolsKey = prep ? JSON.stringify(prep.tools) : null;
4886
5632
  cacheEndsAtEos = true;
4887
5633
  }
4888
5634
  return {
@@ -4930,7 +5676,8 @@ async function createChat(engine, options) {
4930
5676
  prewarm: serialize(prewarmImpl),
4931
5677
  countTokens: (messages, opts) => tk.encode(tk.applyChatTemplate(messages, {
4932
5678
  addGenerationPrompt: opts?.addGenerationPrompt ?? true,
4933
- enableThinking: opts?.think ?? false
5679
+ enableThinking: opts?.think ?? false,
5680
+ tools: opts?.tools
4934
5681
  }), false).length,
4935
5682
  reset: () => {
4936
5683
  resetEpoch++;
@@ -4941,6 +5688,6 @@ async function createChat(engine, options) {
4941
5688
  };
4942
5689
  }
4943
5690
  //#endregion
4944
- export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat };
5691
+ export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
4945
5692
 
4946
5693
  //# sourceMappingURL=chat.js.map