bitgpu 0.8.0 → 0.10.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 +142 -13
- package/THIRD_PARTY_LICENSES.md +2 -2
- package/dist/chat.d.ts +220 -9
- package/dist/chat.js +655 -52
- package/dist/chat.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +249 -56
- package/dist/index.js.map +1 -1
- package/dist/{types-CsoJYJlG.d.ts → types-CcgsXirU.d.ts} +77 -12
- package/package.json +1 -1
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
|
}
|
|
@@ -4402,7 +4408,12 @@ const SUPPORTED = /* @__PURE__ */ new Set([
|
|
|
4402
4408
|
"items",
|
|
4403
4409
|
"minItems",
|
|
4404
4410
|
"maxItems",
|
|
4405
|
-
"enum"
|
|
4411
|
+
"enum",
|
|
4412
|
+
"oneOf",
|
|
4413
|
+
"minimum",
|
|
4414
|
+
"maximum",
|
|
4415
|
+
"minLength",
|
|
4416
|
+
"maxLength"
|
|
4406
4417
|
]);
|
|
4407
4418
|
const TYPES = /* @__PURE__ */ new Set([
|
|
4408
4419
|
"object",
|
|
@@ -4413,11 +4424,52 @@ const TYPES = /* @__PURE__ */ new Set([
|
|
|
4413
4424
|
"boolean",
|
|
4414
4425
|
"null"
|
|
4415
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
|
+
}
|
|
4416
4436
|
/** Validate a schema against the enforceable subset; throws listing anything unsupported. */
|
|
4417
4437
|
function validateJsonSchema(schema, path = "schema", isRoot = true) {
|
|
4418
4438
|
const unknown = Object.keys(schema).filter((k) => !SUPPORTED.has(k));
|
|
4419
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
|
+
}
|
|
4420
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
|
+
}
|
|
4421
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`);
|
|
4422
4474
|
if (schema.enum !== void 0) {
|
|
4423
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`);
|
|
@@ -4435,7 +4487,7 @@ function validateJsonSchema(schema, path = "schema", isRoot = true) {
|
|
|
4435
4487
|
if (schema.items !== void 0) validateJsonSchema(schema.items, `${path}.items`, false);
|
|
4436
4488
|
if (schema.minItems !== void 0 && schema.maxItems !== void 0 && schema.minItems > schema.maxItems) throw new Error(`bitgpu/chat: minItems > maxItems at ${path}`);
|
|
4437
4489
|
}
|
|
4438
|
-
const WS = /* @__PURE__ */ new Set([
|
|
4490
|
+
const WS$1 = /* @__PURE__ */ new Set([
|
|
4439
4491
|
32,
|
|
4440
4492
|
9,
|
|
4441
4493
|
10,
|
|
@@ -4444,7 +4496,7 @@ const WS = /* @__PURE__ */ new Set([
|
|
|
4444
4496
|
const isDigit = (b) => b >= 48 && b <= 57;
|
|
4445
4497
|
const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
|
|
4446
4498
|
const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
|
|
4447
|
-
const utf8 = new TextEncoder();
|
|
4499
|
+
const utf8$1 = new TextEncoder();
|
|
4448
4500
|
var JsonMachine = class JsonMachine {
|
|
4449
4501
|
root;
|
|
4450
4502
|
stack = [];
|
|
@@ -4459,6 +4511,13 @@ var JsonMachine = class JsonMachine {
|
|
|
4459
4511
|
strBuf = "";
|
|
4460
4512
|
strTracking = false;
|
|
4461
4513
|
enumCands = null;
|
|
4514
|
+
strLenOn = false;
|
|
4515
|
+
strCount = 0;
|
|
4516
|
+
strMin = 0;
|
|
4517
|
+
strMax = Infinity;
|
|
4518
|
+
numMin = null;
|
|
4519
|
+
numMax = null;
|
|
4520
|
+
numBuf = "";
|
|
4462
4521
|
pending = null;
|
|
4463
4522
|
wsRun = 0;
|
|
4464
4523
|
constructor(root = null) {
|
|
@@ -4471,7 +4530,11 @@ var JsonMachine = class JsonMachine {
|
|
|
4471
4530
|
kind: c.kind,
|
|
4472
4531
|
node: c.node,
|
|
4473
4532
|
seen: c.seen.slice(),
|
|
4474
|
-
count: c.count
|
|
4533
|
+
count: c.count,
|
|
4534
|
+
branches: c.branches ? c.branches.slice() : null,
|
|
4535
|
+
discRaw: c.discRaw,
|
|
4536
|
+
discKey: c.discKey,
|
|
4537
|
+
discPending: c.discPending
|
|
4475
4538
|
}));
|
|
4476
4539
|
m.phase = this.phase;
|
|
4477
4540
|
m.uLeft = this.uLeft;
|
|
@@ -4484,6 +4547,13 @@ var JsonMachine = class JsonMachine {
|
|
|
4484
4547
|
m.strBuf = this.strBuf;
|
|
4485
4548
|
m.strTracking = this.strTracking;
|
|
4486
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;
|
|
4487
4557
|
m.pending = this.pending;
|
|
4488
4558
|
m.wsRun = this.wsRun;
|
|
4489
4559
|
return m;
|
|
@@ -4501,18 +4571,40 @@ var JsonMachine = class JsonMachine {
|
|
|
4501
4571
|
}
|
|
4502
4572
|
/** Byte-space form of a string literal (what strBuf accumulates). */
|
|
4503
4573
|
static bytesOf(s) {
|
|
4504
|
-
return String.fromCharCode(...utf8.encode(s));
|
|
4574
|
+
return String.fromCharCode(...utf8$1.encode(s));
|
|
4505
4575
|
}
|
|
4506
4576
|
openValue(b) {
|
|
4507
4577
|
const sc = this.pending;
|
|
4508
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
|
+
}
|
|
4509
4597
|
if (b === 123) {
|
|
4510
4598
|
if (t !== void 0 && t !== "object") return false;
|
|
4511
4599
|
this.stack.push({
|
|
4512
4600
|
kind: "{",
|
|
4513
4601
|
node: sc ?? null,
|
|
4514
4602
|
seen: [],
|
|
4515
|
-
count: 0
|
|
4603
|
+
count: 0,
|
|
4604
|
+
branches: null,
|
|
4605
|
+
discRaw: null,
|
|
4606
|
+
discKey: null,
|
|
4607
|
+
discPending: false
|
|
4516
4608
|
});
|
|
4517
4609
|
this.phase = 3;
|
|
4518
4610
|
} else if (b === 91) {
|
|
@@ -4521,7 +4613,11 @@ var JsonMachine = class JsonMachine {
|
|
|
4521
4613
|
kind: "[",
|
|
4522
4614
|
node: sc ?? null,
|
|
4523
4615
|
seen: [],
|
|
4524
|
-
count: 0
|
|
4616
|
+
count: 0,
|
|
4617
|
+
branches: null,
|
|
4618
|
+
discRaw: null,
|
|
4619
|
+
discKey: null,
|
|
4620
|
+
discPending: false
|
|
4525
4621
|
});
|
|
4526
4622
|
this.phase = 2;
|
|
4527
4623
|
} else if (b === 34) {
|
|
@@ -4530,10 +4626,18 @@ var JsonMachine = class JsonMachine {
|
|
|
4530
4626
|
this.enumCands = sc?.enum ? sc.enum.map(JsonMachine.bytesOf) : null;
|
|
4531
4627
|
this.strBuf = "";
|
|
4532
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;
|
|
4533
4633
|
this.phase = 7;
|
|
4534
4634
|
} else if (b === 45 || isDigit(b)) {
|
|
4535
4635
|
if (t !== void 0 && t !== "number" && t !== "integer") return false;
|
|
4536
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;
|
|
4537
4641
|
this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
|
|
4538
4642
|
this.phase = 10;
|
|
4539
4643
|
} else if (b === 116 || b === 102 || b === 110) {
|
|
@@ -4559,8 +4663,12 @@ var JsonMachine = class JsonMachine {
|
|
|
4559
4663
|
closeContainer(b) {
|
|
4560
4664
|
const c = this.top();
|
|
4561
4665
|
if (!c || c.kind !== (b === 125 ? "{" : "[")) return false;
|
|
4562
|
-
if (c.kind === "{"
|
|
4563
|
-
|
|
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
|
+
}
|
|
4564
4672
|
}
|
|
4565
4673
|
if (c.kind === "[" && c.node?.minItems !== void 0 && c.count < c.node.minItems) return false;
|
|
4566
4674
|
this.stack.pop();
|
|
@@ -4569,8 +4677,16 @@ var JsonMachine = class JsonMachine {
|
|
|
4569
4677
|
}
|
|
4570
4678
|
/** Candidate property names for the key being typed (null = unconstrained). */
|
|
4571
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
|
+
}
|
|
4572
4688
|
if (!c.node || c.node.additionalProperties !== false) return null;
|
|
4573
|
-
return Object.keys(c.node.properties ?? {}).filter((k) => !c.seen.includes(k))
|
|
4689
|
+
return Object.keys(c.node.properties ?? {}).map(JsonMachine.bytesOf).filter((k) => !c.seen.includes(k));
|
|
4574
4690
|
}
|
|
4575
4691
|
startKey(c) {
|
|
4576
4692
|
this.strKind = "key";
|
|
@@ -4586,18 +4702,58 @@ var JsonMachine = class JsonMachine {
|
|
|
4586
4702
|
ws() {
|
|
4587
4703
|
return ++this.wsRun <= 16;
|
|
4588
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
|
+
}
|
|
4589
4745
|
byte(b) {
|
|
4590
|
-
if (!WS.has(b)) this.wsRun = 0;
|
|
4746
|
+
if (!WS$1.has(b)) this.wsRun = 0;
|
|
4591
4747
|
switch (this.phase) {
|
|
4592
4748
|
case 0:
|
|
4593
|
-
if (WS.has(b)) return this.ws();
|
|
4749
|
+
if (WS$1.has(b)) return this.ws();
|
|
4594
4750
|
if (b === 123 || b === 91) return this.openValue(b);
|
|
4595
4751
|
return false;
|
|
4596
4752
|
case 1:
|
|
4597
|
-
if (WS.has(b)) return this.ws();
|
|
4753
|
+
if (WS$1.has(b)) return this.ws();
|
|
4598
4754
|
return this.openValue(b);
|
|
4599
4755
|
case 2: {
|
|
4600
|
-
if (WS.has(b)) return this.ws();
|
|
4756
|
+
if (WS$1.has(b)) return this.ws();
|
|
4601
4757
|
if (b === 93) return this.closeContainer(b);
|
|
4602
4758
|
const c = this.top();
|
|
4603
4759
|
if (c.node?.maxItems === 0) return false;
|
|
@@ -4605,7 +4761,7 @@ var JsonMachine = class JsonMachine {
|
|
|
4605
4761
|
return this.openValue(b);
|
|
4606
4762
|
}
|
|
4607
4763
|
case 3:
|
|
4608
|
-
if (WS.has(b)) return this.ws();
|
|
4764
|
+
if (WS$1.has(b)) return this.ws();
|
|
4609
4765
|
if (b === 125) return this.closeContainer(b);
|
|
4610
4766
|
if (b === 34) {
|
|
4611
4767
|
const c = this.top();
|
|
@@ -4615,25 +4771,41 @@ var JsonMachine = class JsonMachine {
|
|
|
4615
4771
|
}
|
|
4616
4772
|
return false;
|
|
4617
4773
|
case 4:
|
|
4618
|
-
if (WS.has(b)) return this.ws();
|
|
4774
|
+
if (WS$1.has(b)) return this.ws();
|
|
4619
4775
|
if (b === 34) {
|
|
4620
4776
|
this.startKey(this.top());
|
|
4621
4777
|
return true;
|
|
4622
4778
|
}
|
|
4623
4779
|
return false;
|
|
4624
4780
|
case 5:
|
|
4625
|
-
if (WS.has(b)) return this.ws();
|
|
4781
|
+
if (WS$1.has(b)) return this.ws();
|
|
4626
4782
|
if (b === 58) {
|
|
4627
4783
|
const c = this.top();
|
|
4628
4784
|
const key = c.seen[c.seen.length - 1];
|
|
4629
|
-
|
|
4630
|
-
|
|
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
|
+
}
|
|
4631
4803
|
this.phase = 1;
|
|
4632
4804
|
return true;
|
|
4633
4805
|
}
|
|
4634
4806
|
return false;
|
|
4635
4807
|
case 6: {
|
|
4636
|
-
if (WS.has(b)) return this.ws();
|
|
4808
|
+
if (WS$1.has(b)) return this.ws();
|
|
4637
4809
|
const c = this.top();
|
|
4638
4810
|
if (b === 44 && c) {
|
|
4639
4811
|
if (c.kind === "{") {
|
|
@@ -4662,23 +4834,37 @@ var JsonMachine = class JsonMachine {
|
|
|
4662
4834
|
if (this.strKind === "key") {
|
|
4663
4835
|
const c = this.top();
|
|
4664
4836
|
if (this.enumCands !== null && !this.enumCands.includes(this.strBuf)) return false;
|
|
4665
|
-
if (c.node?.properties && c.seen.includes(this.strBuf)) return false;
|
|
4837
|
+
if ((c.node?.properties || c.branches) && c.seen.includes(this.strBuf)) return false;
|
|
4666
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
|
+
}
|
|
4667
4843
|
this.phase = 5;
|
|
4668
4844
|
} else {
|
|
4669
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
|
+
}
|
|
4670
4853
|
this.closeValue();
|
|
4671
4854
|
}
|
|
4672
4855
|
this.strTracking = false;
|
|
4856
|
+
this.strLenOn = false;
|
|
4673
4857
|
return true;
|
|
4674
4858
|
}
|
|
4675
4859
|
if (b === 92) {
|
|
4676
4860
|
if (this.strKind === "enum" || this.strKind === "key" && this.enumCands !== null) return false;
|
|
4861
|
+
if (!this.strChar()) return false;
|
|
4677
4862
|
this.phase = 8;
|
|
4678
4863
|
return true;
|
|
4679
4864
|
}
|
|
4680
4865
|
if (b < 32) return false;
|
|
4681
4866
|
if (b < 128) {
|
|
4867
|
+
if (!this.strChar()) return false;
|
|
4682
4868
|
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4683
4869
|
return this.enumOk();
|
|
4684
4870
|
}
|
|
@@ -4686,6 +4872,7 @@ var JsonMachine = class JsonMachine {
|
|
|
4686
4872
|
else if (b >= 224 && b <= 239) this.utf8Left = 2;
|
|
4687
4873
|
else if (b >= 240 && b <= 244) this.utf8Left = 3;
|
|
4688
4874
|
else return false;
|
|
4875
|
+
if (!this.strChar()) return false;
|
|
4689
4876
|
if (this.strTracking) this.strBuf += String.fromCharCode(b);
|
|
4690
4877
|
return this.enumOk();
|
|
4691
4878
|
case 8:
|
|
@@ -4719,12 +4906,12 @@ var JsonMachine = class JsonMachine {
|
|
|
4719
4906
|
case 0:
|
|
4720
4907
|
if (!isDigit(b)) return false;
|
|
4721
4908
|
this.numSub = b === 48 ? 1 : 2;
|
|
4722
|
-
return
|
|
4909
|
+
return this.numAppend(b);
|
|
4723
4910
|
case 1:
|
|
4724
4911
|
case 2:
|
|
4725
4912
|
if (isDigit(b)) {
|
|
4726
4913
|
if (this.numSub === 1) return false;
|
|
4727
|
-
return
|
|
4914
|
+
return this.numAppend(b);
|
|
4728
4915
|
}
|
|
4729
4916
|
break;
|
|
4730
4917
|
case 3:
|
|
@@ -4759,6 +4946,7 @@ var JsonMachine = class JsonMachine {
|
|
|
4759
4946
|
return true;
|
|
4760
4947
|
}
|
|
4761
4948
|
if (numberDone(this.numSub)) {
|
|
4949
|
+
if (!this.intInRange()) return false;
|
|
4762
4950
|
this.closeValue();
|
|
4763
4951
|
return this.byte(b);
|
|
4764
4952
|
}
|
|
@@ -4767,7 +4955,7 @@ var JsonMachine = class JsonMachine {
|
|
|
4767
4955
|
if (b !== this.litWord.charCodeAt(this.litPos)) return false;
|
|
4768
4956
|
if (++this.litPos === this.litWord.length) this.closeValue();
|
|
4769
4957
|
return true;
|
|
4770
|
-
case 12: return WS.has(b);
|
|
4958
|
+
case 12: return WS$1.has(b);
|
|
4771
4959
|
}
|
|
4772
4960
|
}
|
|
4773
4961
|
/** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
|
|
@@ -4854,6 +5042,299 @@ function makeJsonFilter(table, eosTokenId, schema = null) {
|
|
|
4854
5042
|
};
|
|
4855
5043
|
}
|
|
4856
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
|
|
4857
5338
|
//#region src/chat/index.ts
|
|
4858
5339
|
function deriveChatWrap(tk) {
|
|
4859
5340
|
if (!tk.hasChatTemplate) return null;
|
|
@@ -4886,6 +5367,10 @@ function deriveChatWrap(tk) {
|
|
|
4886
5367
|
return null;
|
|
4887
5368
|
}
|
|
4888
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
|
+
}
|
|
4889
5374
|
/** True iff `next` is exactly `committed` plus one new trailing user turn - a clean append, so the
|
|
4890
5375
|
* engine can extend its KV cache with just that turn. Compared as MESSAGES, not token ids: chat
|
|
4891
5376
|
* templates render past assistant turns differently from live ones (e.g. Qwen3's empty <think>
|
|
@@ -4893,7 +5378,18 @@ function deriveChatWrap(tk) {
|
|
|
4893
5378
|
function isCleanAppend(committed, next) {
|
|
4894
5379
|
if (!committed || next.length !== committed.length + 1) return false;
|
|
4895
5380
|
if (next[next.length - 1].role !== "user") return false;
|
|
4896
|
-
for (let i = 0; i < committed.length; i++) if (next[i]
|
|
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;
|
|
4897
5393
|
return true;
|
|
4898
5394
|
}
|
|
4899
5395
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
@@ -4916,11 +5412,47 @@ async function createChat(engine, options) {
|
|
|
4916
5412
|
const wrap = deriveChatWrap(tk);
|
|
4917
5413
|
let committed = null;
|
|
4918
5414
|
let cacheEndsAtEos = false;
|
|
5415
|
+
let committedToolsKey = null;
|
|
4919
5416
|
let resetEpoch = 0;
|
|
4920
5417
|
const dropCache = () => {
|
|
4921
5418
|
committed = null;
|
|
5419
|
+
committedToolsKey = null;
|
|
4922
5420
|
engine.resetCache();
|
|
4923
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
|
+
}
|
|
4924
5456
|
let chain = Promise.resolve();
|
|
4925
5457
|
const serialize = (fn) => {
|
|
4926
5458
|
return (...args) => {
|
|
@@ -4935,19 +5467,34 @@ async function createChat(engine, options) {
|
|
|
4935
5467
|
const json = o.format !== void 0;
|
|
4936
5468
|
const schema = typeof o.format === "object" ? o.format.json.schema ?? null : null;
|
|
4937
5469
|
if (schema) validateJsonSchema(schema);
|
|
4938
|
-
const
|
|
4939
|
-
|
|
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;
|
|
4940
5479
|
let inputTokenIds;
|
|
4941
|
-
if (
|
|
5480
|
+
if (userAppend) {
|
|
4942
5481
|
const w = wrap;
|
|
4943
5482
|
const userText = messages[messages.length - 1].content;
|
|
4944
5483
|
const deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}\n${w.userPrefix}${userText}${w.userSuffix}${w.genPrompt}`;
|
|
4945
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);
|
|
4946
5492
|
} else {
|
|
4947
5493
|
dropCache();
|
|
4948
5494
|
inputTokenIds = tk.encode(tk.applyChatTemplate(messages, {
|
|
4949
5495
|
addGenerationPrompt: true,
|
|
4950
|
-
enableThinking: think
|
|
5496
|
+
enableThinking: think,
|
|
5497
|
+
tools: prep?.tools
|
|
4951
5498
|
}), false);
|
|
4952
5499
|
}
|
|
4953
5500
|
const decoder = tk.createDecoderStream(true);
|
|
@@ -4957,15 +5504,28 @@ async function createChat(engine, options) {
|
|
|
4957
5504
|
const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
|
|
4958
5505
|
let text = "";
|
|
4959
5506
|
let thinkText = "";
|
|
4960
|
-
const
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
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);
|
|
4968
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);
|
|
4969
5529
|
if (chunk.think) {
|
|
4970
5530
|
thinkText += chunk.think;
|
|
4971
5531
|
o.onThink?.(chunk.think);
|
|
@@ -4974,6 +5534,7 @@ async function createChat(engine, options) {
|
|
|
4974
5534
|
const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
|
|
4975
5535
|
const epoch0 = resetEpoch;
|
|
4976
5536
|
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
|
|
5537
|
+
const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep) : null;
|
|
4977
5538
|
let result;
|
|
4978
5539
|
try {
|
|
4979
5540
|
result = await engine.generate(inputTokenIds, {
|
|
@@ -4984,13 +5545,15 @@ async function createChat(engine, options) {
|
|
|
4984
5545
|
repetitionPenalty: o.repetitionPenalty,
|
|
4985
5546
|
noRepeatNgramSize: o.noRepeatNgramSize,
|
|
4986
5547
|
seed: o.seed,
|
|
4987
|
-
|
|
5548
|
+
logprobs: o.logprobs,
|
|
5549
|
+
promptLookup: json || prep ? false : o.promptLookup,
|
|
4988
5550
|
stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
|
|
4989
5551
|
reuseCache: canReuse,
|
|
4990
5552
|
signal,
|
|
4991
|
-
candidateFilter: jf ? (ids) => jf.filter(ids) : void 0,
|
|
5553
|
+
candidateFilter: jf ? (ids) => jf.filter(ids) : tf ? (ids) => tf.filter(ids) : void 0,
|
|
4992
5554
|
onToken: (id) => {
|
|
4993
5555
|
jf?.advance(id);
|
|
5556
|
+
tf?.advance(id);
|
|
4994
5557
|
emit(splitter.push(decoder.push(id)));
|
|
4995
5558
|
}
|
|
4996
5559
|
});
|
|
@@ -5015,39 +5578,57 @@ async function createChat(engine, options) {
|
|
|
5015
5578
|
}
|
|
5016
5579
|
emit(splitter.push(decoder.flush()));
|
|
5017
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
|
+
}
|
|
5018
5587
|
const aborted = o.signal?.aborted ?? false;
|
|
5588
|
+
const callsClean = toolCalls.every((c) => c.name !== "");
|
|
5019
5589
|
if (aborted || stops?.matched) dropCache();
|
|
5020
5590
|
else if (think) dropCache();
|
|
5021
|
-
else if (wrap !== null && text.trim() && resetEpoch === epoch0) {
|
|
5022
|
-
|
|
5591
|
+
else if (wrap !== null && (text.trim() || toolCalls.length > 0) && callsClean && resetEpoch === epoch0) {
|
|
5592
|
+
const assistant = {
|
|
5023
5593
|
role: "assistant",
|
|
5024
5594
|
content: text
|
|
5025
|
-
}
|
|
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;
|
|
5026
5602
|
cacheEndsAtEos = false;
|
|
5027
5603
|
} else dropCache();
|
|
5028
5604
|
return {
|
|
5029
5605
|
text,
|
|
5030
5606
|
thinkText,
|
|
5607
|
+
toolCalls,
|
|
5031
5608
|
tokens: result.tokens,
|
|
5032
5609
|
inputTokenIds,
|
|
5033
|
-
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",
|
|
5034
5611
|
reusedCache: canReuse,
|
|
5612
|
+
...result.logprobs ? { logprobs: result.logprobs } : {},
|
|
5035
5613
|
prefillMs: result.prefillMs,
|
|
5036
5614
|
decodeMs: result.decodeMs,
|
|
5037
5615
|
tokensPerSecond: result.tokensPerSecond
|
|
5038
5616
|
};
|
|
5039
5617
|
}
|
|
5040
5618
|
const send = serialize(sendImpl);
|
|
5041
|
-
async function prewarmImpl(messages) {
|
|
5619
|
+
async function prewarmImpl(messages, opts = {}) {
|
|
5042
5620
|
if (wrap === null) return;
|
|
5621
|
+
const prep = opts.tools?.length ? prepareTools(opts.tools, "auto") : null;
|
|
5043
5622
|
const str = tk.applyChatTemplate(messages, {
|
|
5044
5623
|
addGenerationPrompt: false,
|
|
5045
|
-
enableThinking: false
|
|
5624
|
+
enableThinking: false,
|
|
5625
|
+
tools: prep?.tools
|
|
5046
5626
|
}).replace(/\n$/, "");
|
|
5047
5627
|
const epoch0 = resetEpoch;
|
|
5048
5628
|
await engine.prefill(tk.encode(str, false));
|
|
5049
5629
|
if (resetEpoch !== epoch0) return;
|
|
5050
5630
|
committed = [...messages];
|
|
5631
|
+
committedToolsKey = prep ? JSON.stringify(prep.tools) : null;
|
|
5051
5632
|
cacheEndsAtEos = true;
|
|
5052
5633
|
}
|
|
5053
5634
|
return {
|
|
@@ -5095,17 +5676,39 @@ async function createChat(engine, options) {
|
|
|
5095
5676
|
prewarm: serialize(prewarmImpl),
|
|
5096
5677
|
countTokens: (messages, opts) => tk.encode(tk.applyChatTemplate(messages, {
|
|
5097
5678
|
addGenerationPrompt: opts?.addGenerationPrompt ?? true,
|
|
5098
|
-
enableThinking: opts?.think ?? false
|
|
5679
|
+
enableThinking: opts?.think ?? false,
|
|
5680
|
+
tools: opts?.tools
|
|
5099
5681
|
}), false).length,
|
|
5100
5682
|
reset: () => {
|
|
5101
5683
|
resetEpoch++;
|
|
5102
5684
|
dropCache();
|
|
5103
5685
|
},
|
|
5686
|
+
save: serialize(async () => {
|
|
5687
|
+
if (committed === null) return null;
|
|
5688
|
+
const eng = await engine.saveCache();
|
|
5689
|
+
if (!eng) return null;
|
|
5690
|
+
return {
|
|
5691
|
+
version: 1,
|
|
5692
|
+
engine: eng,
|
|
5693
|
+
committed: JSON.parse(JSON.stringify(committed)),
|
|
5694
|
+
cacheEndsAtEos,
|
|
5695
|
+
toolsKey: committedToolsKey
|
|
5696
|
+
};
|
|
5697
|
+
}),
|
|
5698
|
+
restore: serialize(async (snap) => {
|
|
5699
|
+
if (!snap || snap.version !== 1) throw new Error("bitgpu/chat: unsupported chat snapshot version");
|
|
5700
|
+
if (!Array.isArray(snap.committed) || snap.committed.length === 0) throw new Error("bitgpu/chat: chat snapshot holds no committed transcript");
|
|
5701
|
+
await engine.restoreCache(snap.engine);
|
|
5702
|
+
resetEpoch++;
|
|
5703
|
+
committed = JSON.parse(JSON.stringify(snap.committed));
|
|
5704
|
+
committedToolsKey = snap.toolsKey ?? null;
|
|
5705
|
+
cacheEndsAtEos = !!snap.cacheEndsAtEos;
|
|
5706
|
+
}),
|
|
5104
5707
|
eosTokenId: tk.eosTokenId,
|
|
5105
5708
|
tokenizer: tk
|
|
5106
5709
|
};
|
|
5107
5710
|
}
|
|
5108
5711
|
//#endregion
|
|
5109
|
-
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
|
|
5712
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
|
|
5110
5713
|
|
|
5111
5714
|
//# sourceMappingURL=chat.js.map
|