@ax-llm/ax 11.0.17 → 11.0.19

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/index.cjs CHANGED
@@ -4087,7 +4087,10 @@ var SignatureParser = class {
4087
4087
  this.skipWhitespace();
4088
4088
  const optionalDesc = this.parseParsedString();
4089
4089
  this.skipWhitespace();
4090
- const inputs = this.parseFieldList(this.parseField.bind(this), "input");
4090
+ const inputs = this.parseFieldList(
4091
+ this.parseInputField.bind(this),
4092
+ "input"
4093
+ );
4091
4094
  this.skipWhitespace();
4092
4095
  if (this.position >= this.input.length) {
4093
4096
  throw new Error(
@@ -4101,7 +4104,10 @@ var SignatureParser = class {
4101
4104
  'Incomplete signature: No output fields specified after "->"'
4102
4105
  );
4103
4106
  }
4104
- const outputs = this.parseFieldList(this.parseField.bind(this), "output");
4107
+ const outputs = this.parseFieldList(
4108
+ this.parseOutputField.bind(this),
4109
+ "output"
4110
+ );
4105
4111
  return {
4106
4112
  desc: optionalDesc?.trim(),
4107
4113
  inputs,
@@ -4163,11 +4169,75 @@ ${pointer}`;
4163
4169
  }
4164
4170
  return fields;
4165
4171
  }
4166
- parseField() {
4172
+ // -------------------------------
4173
+ // Parse input fields (no "class" type and no internal flag)
4174
+ // -------------------------------
4175
+ parseInputField() {
4167
4176
  this.skipWhitespace();
4168
4177
  const name = this.parseParsedIdentifier();
4169
4178
  this.currentFieldName = name;
4170
- const isOptional = this.match("?");
4179
+ let isOptional = void 0;
4180
+ while (true) {
4181
+ if (this.match("?")) {
4182
+ isOptional = true;
4183
+ continue;
4184
+ }
4185
+ if (this.match("!")) {
4186
+ throw new Error(
4187
+ `Input field "${name}" does not support the internal marker "!"`
4188
+ );
4189
+ }
4190
+ break;
4191
+ }
4192
+ let type;
4193
+ this.skipWhitespace();
4194
+ if (this.match(":")) {
4195
+ this.skipWhitespace();
4196
+ if (/^class\b/.test(this.input.slice(this.position))) {
4197
+ throw new Error(
4198
+ `Input field "${name}" does not support the "class" type`
4199
+ );
4200
+ } else {
4201
+ try {
4202
+ const typeName = this.parseTypeNotClass();
4203
+ const isArray = this.match("[]");
4204
+ type = { name: typeName, isArray };
4205
+ } catch (error) {
4206
+ throw new Error(
4207
+ `Input field "${name}": ${error instanceof Error ? error.message : "Unknown error"}`
4208
+ );
4209
+ }
4210
+ }
4211
+ }
4212
+ this.skipWhitespace();
4213
+ const desc = this.parseParsedString();
4214
+ return {
4215
+ name,
4216
+ desc: desc?.trim(),
4217
+ type,
4218
+ isOptional
4219
+ };
4220
+ }
4221
+ // -------------------------------
4222
+ // Parse output fields (supports both "class" type and the internal marker)
4223
+ // -------------------------------
4224
+ parseOutputField() {
4225
+ this.skipWhitespace();
4226
+ const name = this.parseParsedIdentifier();
4227
+ this.currentFieldName = name;
4228
+ let isOptional = false;
4229
+ let isInternal = false;
4230
+ while (true) {
4231
+ if (this.match("?")) {
4232
+ isOptional = true;
4233
+ continue;
4234
+ }
4235
+ if (this.match("!")) {
4236
+ isInternal = true;
4237
+ continue;
4238
+ }
4239
+ break;
4240
+ }
4171
4241
  let type;
4172
4242
  this.skipWhitespace();
4173
4243
  if (this.match(":")) {
@@ -4175,16 +4245,16 @@ ${pointer}`;
4175
4245
  if (this.match("class")) {
4176
4246
  const isArray = this.match("[]");
4177
4247
  this.skipWhitespace();
4178
- const desc2 = this.parseParsedString();
4179
- if (!desc2) {
4248
+ const classNamesString = this.parseParsedString();
4249
+ if (!classNamesString) {
4180
4250
  throw new Error(
4181
- `Field "${name}": Expected class names in quotes after "class" type. Example: class "MyClass1, MyClass2"`
4251
+ `Output field "${name}": Expected class names in quotes after "class" type. Example: class "MyClass1, MyClass2"`
4182
4252
  );
4183
4253
  }
4184
- const classes = desc2.split(/[,\s]+/).map((s) => s.trim()).filter((s) => s.length > 0);
4254
+ const classes = classNamesString.split(/[,\s]+/).map((s) => s.trim()).filter((s) => s.length > 0);
4185
4255
  if (classes.length === 0) {
4186
4256
  throw new Error(
4187
- `Field "${name}": Empty class list provided. At least one class name is required`
4257
+ `Output field "${name}": Empty class list provided. At least one class name is required`
4188
4258
  );
4189
4259
  }
4190
4260
  type = { name: "class", isArray, classes };
@@ -4195,28 +4265,20 @@ ${pointer}`;
4195
4265
  type = { name: typeName, isArray };
4196
4266
  } catch (error) {
4197
4267
  throw new Error(
4198
- `Field "${name}": ${error instanceof Error ? error.message : "Unknown error"}`
4268
+ `Output field "${name}": ${error instanceof Error ? error.message : "Unknown error"}`
4199
4269
  );
4200
4270
  }
4201
4271
  }
4202
4272
  }
4203
4273
  this.skipWhitespace();
4204
4274
  const desc = this.parseParsedString();
4205
- if (type?.name === "class") {
4206
- return {
4207
- name,
4208
- desc: desc?.trim(),
4209
- type,
4210
- isOptional
4211
- };
4212
- } else {
4213
- return {
4214
- name,
4215
- desc: desc?.trim(),
4216
- type,
4217
- isOptional
4218
- };
4219
- }
4275
+ return {
4276
+ name,
4277
+ desc: desc?.trim(),
4278
+ type,
4279
+ isOptional,
4280
+ isInternal
4281
+ };
4220
4282
  }
4221
4283
  parseTypeNotClass() {
4222
4284
  const types = [
@@ -4370,8 +4432,9 @@ var AxSignature = class _AxSignature {
4370
4432
  name: field.name,
4371
4433
  title,
4372
4434
  description: "desc" in field ? field.desc : void 0,
4373
- isOptional: field.isOptional,
4374
- type: field.type ?? { name: "string", isArray: false }
4435
+ type: field.type ?? { name: "string", isArray: false },
4436
+ ..."isInternal" in field ? { isInternal: field.isInternal } : {},
4437
+ ..."isOptional" in field ? { isOptional: field.isOptional } : {}
4375
4438
  };
4376
4439
  };
4377
4440
  parseField = (field) => {
@@ -4405,7 +4468,7 @@ var AxSignature = class _AxSignature {
4405
4468
  getOutputFields = () => this.outputFields;
4406
4469
  getDescription = () => this.description;
4407
4470
  toTitle = (name) => {
4408
- let result = name.replaceAll("_", " ");
4471
+ let result = name.replace(/_/g, " ");
4409
4472
  result = result.replace(/([A-Z]|[0-9]+)/g, " $1").trim();
4410
4473
  return result.charAt(0).toUpperCase() + result.slice(1);
4411
4474
  };
@@ -4537,8 +4600,6 @@ var validateValue = (field, value) => {
4537
4600
  switch (expectedType) {
4538
4601
  case "code":
4539
4602
  return typeof val === "string";
4540
- case "json":
4541
- return typeof val === "object";
4542
4603
  case "string":
4543
4604
  return typeof val === "string";
4544
4605
  case "number":
@@ -4672,7 +4733,9 @@ function mergeDeltas(base, delta) {
4672
4733
  for (const key of Object.keys(delta)) {
4673
4734
  const baseValue = base[key];
4674
4735
  const deltaValue = delta[key];
4675
- if ((baseValue === void 0 || Array.isArray(baseValue)) && Array.isArray(deltaValue)) {
4736
+ if (baseValue === void 0 && Array.isArray(deltaValue)) {
4737
+ base[key] = [...deltaValue];
4738
+ } else if (Array.isArray(baseValue) && Array.isArray(deltaValue)) {
4676
4739
  base[key] = [...baseValue ?? [], ...deltaValue];
4677
4740
  } else if ((baseValue === void 0 || typeof baseValue === "string") && typeof deltaValue === "string") {
4678
4741
  base[key] = (baseValue ?? "") + deltaValue;
@@ -5407,7 +5470,7 @@ var formatDateWithTimezone = (date) => {
5407
5470
 
5408
5471
  // dsp/extract.ts
5409
5472
  var extractValues = (sig, values, content) => {
5410
- const xstate = { extractedFields: [], s: -1 };
5473
+ const xstate = { extractedFields: [], streamedIndex: {}, s: -1 };
5411
5474
  streamingExtractValues(sig, values, xstate, content);
5412
5475
  streamingExtractFinalValue(sig, values, xstate, content);
5413
5476
  };
@@ -5461,7 +5524,7 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5461
5524
  if (parsedValue !== void 0) {
5462
5525
  values[xstate.currField.name] = parsedValue;
5463
5526
  }
5464
- xstate.lastDelta = val;
5527
+ xstate.prevField = { field: xstate.currField, s: xstate.s, e };
5465
5528
  }
5466
5529
  checkMissingRequiredFields(xstate, values, index);
5467
5530
  xstate.s = e + prefixLen;
@@ -5470,6 +5533,9 @@ var streamingExtractValues = (sig, values, xstate, content, streamingValidation
5470
5533
  if (!xstate.extractedFields.includes(field)) {
5471
5534
  xstate.extractedFields.push(field);
5472
5535
  }
5536
+ if (xstate.streamedIndex[field.name] === void 0) {
5537
+ xstate.streamedIndex[field.name] = 0;
5538
+ }
5473
5539
  }
5474
5540
  };
5475
5541
  var streamingExtractFinalValue = (sig, values, xstate, content) => {
@@ -5525,31 +5591,18 @@ var convertValueToType = (field, val) => {
5525
5591
  return val;
5526
5592
  }
5527
5593
  };
5528
- function processStreamingDelta(content, xstate) {
5529
- if (!xstate.currField) {
5530
- return null;
5531
- }
5532
- const { name: fieldName, type: fieldType } = xstate.currField ?? {};
5533
- const { isArray: fieldIsArray, name: fieldTypeName } = fieldType ?? {};
5534
- if (!xstate.streamedIndex) {
5535
- xstate.streamedIndex = {};
5536
- }
5537
- if (fieldIsArray) {
5538
- if (xstate.streamedIndex[fieldName] === void 0) {
5539
- xstate.streamedIndex[fieldName] = 0;
5540
- }
5541
- return null;
5542
- }
5543
- if (fieldTypeName !== "string" && fieldTypeName !== "code") {
5544
- if (xstate.streamedIndex[fieldName] === void 0) {
5545
- xstate.streamedIndex[fieldName] = 0;
5546
- }
5547
- return null;
5594
+ function* yieldDelta(content, field, s, e, xstate) {
5595
+ const { name: fieldName, isInternal } = field;
5596
+ const { isArray: fieldIsArray, name: fieldTypeName } = field.type ?? {};
5597
+ if (isInternal || fieldIsArray || fieldTypeName && fieldTypeName !== "string" && fieldTypeName !== "code") {
5598
+ return;
5548
5599
  }
5549
5600
  const pos = xstate.streamedIndex[fieldName] ?? 0;
5550
- const s = xstate.s + pos;
5551
5601
  const isFirstChunk = pos === 0;
5552
- const d1 = content.substring(s);
5602
+ const d1 = content.substring(s + pos, e);
5603
+ if (d1.length === 0) {
5604
+ return;
5605
+ }
5553
5606
  let d2 = d1.replace(/\s+$/, "");
5554
5607
  if (xstate.currField?.type?.name === "code") {
5555
5608
  d2 = d2.replace(/\s*```\s*$/, "");
@@ -5559,40 +5612,45 @@ function processStreamingDelta(content, xstate) {
5559
5612
  d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
5560
5613
  }
5561
5614
  if (d3.length > 0) {
5615
+ yield { [fieldName]: d3 };
5562
5616
  xstate.streamedIndex[fieldName] = pos + d2.length;
5563
5617
  }
5564
- return d3;
5565
5618
  }
5566
- function getStreamingDelta(content, xstate) {
5567
- if (xstate.lastDelta) {
5568
- processStreamingDelta(xstate.lastDelta, xstate);
5569
- xstate.lastDelta = void 0;
5619
+ function* streamValues(sig, content, values, xstate) {
5620
+ if (xstate.prevField && !xstate.prevField.field.isInternal) {
5621
+ const { field, s, e } = xstate.prevField;
5622
+ yield* yieldDelta(content, field, s, e, xstate);
5623
+ xstate.prevField = void 0;
5570
5624
  }
5571
- return processStreamingDelta(content, xstate);
5572
- }
5573
- function* streamValues(sig, values, xstate, delta) {
5574
- if (!xstate.currField) {
5575
- return;
5576
- }
5577
- const fieldName = xstate.currField.name;
5578
- if (delta && delta.length > 0) {
5579
- yield { [fieldName]: delta };
5625
+ if (!xstate.currField || xstate.currField.isInternal) {
5580
5626
  return;
5581
5627
  }
5628
+ yield* yieldDelta(
5629
+ content,
5630
+ xstate.currField,
5631
+ xstate.s,
5632
+ content.length,
5633
+ xstate
5634
+ );
5635
+ const outputFields = sig.getOutputFields();
5582
5636
  for (const key of Object.keys(values)) {
5637
+ const field = outputFields.find((f) => f.name === key);
5638
+ if (!field || field.isInternal) {
5639
+ continue;
5640
+ }
5583
5641
  const value = values[key];
5584
5642
  if (Array.isArray(value)) {
5585
- if (xstate.streamedIndex?.[key] === void 0) {
5586
- throw new Error("Streamed index is not set for array field " + key);
5587
- }
5588
- const s = xstate.streamedIndex[key];
5643
+ const s = xstate.streamedIndex?.[key] ?? 0;
5589
5644
  const v = value.slice(s);
5590
5645
  if (v && v.length > 0) {
5591
5646
  yield { [key]: v };
5592
5647
  xstate.streamedIndex[key] = s + 1;
5593
5648
  }
5594
- } else {
5649
+ continue;
5650
+ }
5651
+ if (!xstate.streamedIndex[key]) {
5595
5652
  yield { [key]: value };
5653
+ xstate.streamedIndex[key] = 1;
5596
5654
  }
5597
5655
  }
5598
5656
  }
@@ -6084,6 +6142,7 @@ var AxGen = class extends AxProgramWithSignature {
6084
6142
  const values = {};
6085
6143
  const xstate = {
6086
6144
  extractedFields: [],
6145
+ streamedIndex: {},
6087
6146
  s: -1
6088
6147
  };
6089
6148
  let content = "";
@@ -6119,11 +6178,7 @@ var AxGen = class extends AxProgramWithSignature {
6119
6178
  content,
6120
6179
  streamingValidation
6121
6180
  );
6122
- if (skip) {
6123
- continue;
6124
- }
6125
6181
  assertStreamingAssertions(this.streamingAsserts, xstate, content);
6126
- assertAssertions(this.asserts, values);
6127
6182
  if (this.streamingFieldProcessors.length !== 0) {
6128
6183
  await processStreamingFieldProcessors(
6129
6184
  this.streamingFieldProcessors,
@@ -6134,8 +6189,11 @@ var AxGen = class extends AxProgramWithSignature {
6134
6189
  sessionId
6135
6190
  );
6136
6191
  }
6137
- const delta = getStreamingDelta(content, xstate);
6138
- yield* streamValues(this.signature, values, xstate, delta);
6192
+ yield* streamValues(this.signature, content, values, xstate);
6193
+ if (skip) {
6194
+ continue;
6195
+ }
6196
+ assertAssertions(this.asserts, values);
6139
6197
  }
6140
6198
  if (result.finishReason === "length") {
6141
6199
  throw new Error("Max tokens reached before completion");
@@ -6178,8 +6236,7 @@ var AxGen = class extends AxProgramWithSignature {
6178
6236
  true
6179
6237
  );
6180
6238
  }
6181
- const delta = getStreamingDelta(content, xstate);
6182
- yield* streamValues(this.signature, values, xstate, delta);
6239
+ yield* streamValues(this.signature, content, values, xstate);
6183
6240
  }
6184
6241
  }
6185
6242
  async processResponse({
@@ -6233,6 +6290,12 @@ var AxGen = class extends AxProgramWithSignature {
6233
6290
  throw new Error("Max tokens reached before completion");
6234
6291
  }
6235
6292
  }
6293
+ const publicValues = { ...values };
6294
+ for (const field of this.signature.getOutputFields()) {
6295
+ if (field.isInternal) {
6296
+ delete publicValues[field.name];
6297
+ }
6298
+ }
6236
6299
  return { ...values };
6237
6300
  }
6238
6301
  async *_forward2(ai, values, options, span) {
@@ -8117,6 +8180,125 @@ var AxJSInterpreter = class {
8117
8180
  }
8118
8181
  };
8119
8182
 
8183
+ // ai/mock/api.ts
8184
+ var AxMockAIService = class {
8185
+ constructor(config = {}) {
8186
+ this.config = config;
8187
+ this.config.id = this.config.id ?? crypto.randomUUID();
8188
+ }
8189
+ metrics = {
8190
+ latency: {
8191
+ chat: { mean: 0, p95: 0, p99: 0, samples: [] },
8192
+ embed: { mean: 0, p95: 0, p99: 0, samples: [] }
8193
+ },
8194
+ errors: {
8195
+ chat: { count: 0, rate: 0, total: 0 },
8196
+ embed: { count: 0, rate: 0, total: 0 }
8197
+ }
8198
+ };
8199
+ getName() {
8200
+ return this.config.name ?? "mock-ai-service";
8201
+ }
8202
+ getId() {
8203
+ return this.config.id ?? "mock-ai-service-id";
8204
+ }
8205
+ getModelInfo() {
8206
+ return {
8207
+ name: "mock-model",
8208
+ provider: "mock-provider",
8209
+ promptTokenCostPer1M: 100,
8210
+ completionTokenCostPer1M: 100,
8211
+ ...this.config.modelInfo
8212
+ };
8213
+ }
8214
+ getEmbedModelInfo() {
8215
+ return this.config.embedModelInfo;
8216
+ }
8217
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
8218
+ getFeatures(_model) {
8219
+ return {
8220
+ functions: this.config.features?.functions ?? false,
8221
+ streaming: this.config.features?.streaming ?? false
8222
+ };
8223
+ }
8224
+ getModelList() {
8225
+ return this.config.models;
8226
+ }
8227
+ getMetrics() {
8228
+ return this.metrics;
8229
+ }
8230
+ async chat(req, options) {
8231
+ if (this.config.latencyMs) {
8232
+ await new Promise((resolve) => setTimeout(resolve, this.config.latencyMs));
8233
+ }
8234
+ if (this.config.shouldError) {
8235
+ throw new Error(this.config.errorMessage ?? "Mock chat error");
8236
+ }
8237
+ this.updateMetrics("chat");
8238
+ if (typeof this.config.chatResponse === "function") {
8239
+ return await this.config.chatResponse(req);
8240
+ }
8241
+ return this.config.chatResponse ?? {
8242
+ results: [
8243
+ {
8244
+ content: "Mock response",
8245
+ finishReason: "stop"
8246
+ }
8247
+ ],
8248
+ modelUsage: {
8249
+ promptTokens: 10,
8250
+ completionTokens: 5,
8251
+ totalTokens: 15
8252
+ }
8253
+ };
8254
+ }
8255
+ async embed(req, _options) {
8256
+ if (this.config.latencyMs) {
8257
+ await new Promise((resolve) => setTimeout(resolve, this.config.latencyMs));
8258
+ }
8259
+ if (this.config.shouldError) {
8260
+ throw new Error(this.config.errorMessage ?? "Mock embed error");
8261
+ }
8262
+ this.updateMetrics("embed");
8263
+ if (typeof this.config.embedResponse === "function") {
8264
+ return this.config.embedResponse(req);
8265
+ }
8266
+ return this.config.embedResponse ?? {
8267
+ embeddings: [[0.1, 0.2, 0.3]],
8268
+ modelUsage: {
8269
+ promptTokens: 5,
8270
+ completionTokens: 0,
8271
+ totalTokens: 5
8272
+ }
8273
+ };
8274
+ }
8275
+ setOptions(options) {
8276
+ this.config.options = options;
8277
+ }
8278
+ getOptions() {
8279
+ return this.config.options ?? {};
8280
+ }
8281
+ updateMetrics(type) {
8282
+ const latency = this.config.latencyMs ?? 0;
8283
+ this.metrics.latency[type].samples.push(latency);
8284
+ const samples = this.metrics.latency[type].samples;
8285
+ this.metrics.latency[type].mean = samples.reduce((a, b) => a + b, 0) / samples.length;
8286
+ if (samples.length > 0) {
8287
+ const sortedSamples = [...samples].sort((a, b) => a - b);
8288
+ const p95Index = Math.max(0, Math.floor(sortedSamples.length * 0.95) - 1);
8289
+ this.metrics.latency[type].p95 = sortedSamples[p95Index] ?? latency;
8290
+ const p99Index = Math.max(0, Math.floor(sortedSamples.length * 0.99) - 1);
8291
+ this.metrics.latency[type].p99 = sortedSamples[p99Index] ?? latency;
8292
+ }
8293
+ if (this.config.shouldError) {
8294
+ this.metrics.errors[type].count++;
8295
+ this.metrics.errors[type].total++;
8296
+ const totalRequests = this.metrics.latency[type].samples.length;
8297
+ this.metrics.errors[type].rate = totalRequests > 0 ? this.metrics.errors[type].count / totalRequests : 0;
8298
+ }
8299
+ }
8300
+ };
8301
+
8120
8302
  // dsp/router.ts
8121
8303
  var colorLog6 = new ColorLog();
8122
8304
  var AxRoute = class {
@@ -8386,126 +8568,6 @@ var AxEmbeddingAdapter = class {
8386
8568
  }
8387
8569
  };
8388
8570
 
8389
- // ai/mock/api.ts
8390
- var AxMockAIService = class {
8391
- constructor(config = {}) {
8392
- this.config = config;
8393
- this.config.id = this.config.id ?? crypto.randomUUID();
8394
- }
8395
- options = {};
8396
- metrics = {
8397
- latency: {
8398
- chat: { mean: 0, p95: 0, p99: 0, samples: [] },
8399
- embed: { mean: 0, p95: 0, p99: 0, samples: [] }
8400
- },
8401
- errors: {
8402
- chat: { count: 0, rate: 0, total: 0 },
8403
- embed: { count: 0, rate: 0, total: 0 }
8404
- }
8405
- };
8406
- getName() {
8407
- return this.config.name ?? "mock-ai-service";
8408
- }
8409
- getId() {
8410
- return this.config.id ?? "mock-ai-service-id";
8411
- }
8412
- getModelInfo() {
8413
- return {
8414
- name: "mock-model",
8415
- provider: "mock-provider",
8416
- promptTokenCostPer1M: 100,
8417
- completionTokenCostPer1M: 100,
8418
- ...this.config.modelInfo
8419
- };
8420
- }
8421
- getEmbedModelInfo() {
8422
- return this.config.embedModelInfo;
8423
- }
8424
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
8425
- getFeatures(_model) {
8426
- return {
8427
- functions: this.config.features?.functions ?? false,
8428
- streaming: this.config.features?.streaming ?? false
8429
- };
8430
- }
8431
- getModelList() {
8432
- return this.config.models;
8433
- }
8434
- getMetrics() {
8435
- return this.metrics;
8436
- }
8437
- async chat(req, _options) {
8438
- if (this.config.latencyMs) {
8439
- await new Promise((resolve) => setTimeout(resolve, this.config.latencyMs));
8440
- }
8441
- if (this.config.shouldError) {
8442
- throw new Error(this.config.errorMessage ?? "Mock chat error");
8443
- }
8444
- this.updateMetrics("chat");
8445
- if (typeof this.config.chatResponse === "function") {
8446
- return this.config.chatResponse(req);
8447
- }
8448
- return this.config.chatResponse ?? {
8449
- results: [
8450
- {
8451
- content: "Mock response",
8452
- finishReason: "stop"
8453
- }
8454
- ],
8455
- modelUsage: {
8456
- promptTokens: 10,
8457
- completionTokens: 5,
8458
- totalTokens: 15
8459
- }
8460
- };
8461
- }
8462
- async embed(req, _options) {
8463
- if (this.config.latencyMs) {
8464
- await new Promise((resolve) => setTimeout(resolve, this.config.latencyMs));
8465
- }
8466
- if (this.config.shouldError) {
8467
- throw new Error(this.config.errorMessage ?? "Mock embed error");
8468
- }
8469
- this.updateMetrics("embed");
8470
- if (typeof this.config.embedResponse === "function") {
8471
- return this.config.embedResponse(req);
8472
- }
8473
- return this.config.embedResponse ?? {
8474
- embeddings: [[0.1, 0.2, 0.3]],
8475
- modelUsage: {
8476
- promptTokens: 5,
8477
- completionTokens: 0,
8478
- totalTokens: 5
8479
- }
8480
- };
8481
- }
8482
- setOptions(options) {
8483
- this.options = options;
8484
- }
8485
- getOptions() {
8486
- return this.options;
8487
- }
8488
- updateMetrics(type) {
8489
- const latency = this.config.latencyMs ?? 0;
8490
- this.metrics.latency[type].samples.push(latency);
8491
- const samples = this.metrics.latency[type].samples;
8492
- this.metrics.latency[type].mean = samples.reduce((a, b) => a + b, 0) / samples.length;
8493
- if (samples.length > 0) {
8494
- const sortedSamples = [...samples].sort((a, b) => a - b);
8495
- const p95Index = Math.max(0, Math.floor(sortedSamples.length * 0.95) - 1);
8496
- this.metrics.latency[type].p95 = sortedSamples[p95Index] ?? latency;
8497
- const p99Index = Math.max(0, Math.floor(sortedSamples.length * 0.99) - 1);
8498
- this.metrics.latency[type].p99 = sortedSamples[p99Index] ?? latency;
8499
- }
8500
- if (this.config.shouldError) {
8501
- this.metrics.errors[type].count++;
8502
- this.metrics.errors[type].total++;
8503
- const totalRequests = this.metrics.latency[type].samples.length;
8504
- this.metrics.errors[type].rate = totalRequests > 0 ? this.metrics.errors[type].count / totalRequests : 0;
8505
- }
8506
- }
8507
- };
8508
-
8509
8571
  // prompts/rag.ts
8510
8572
  var AxRAG = class extends AxChainOfThought {
8511
8573
  genQuery;