@ax-llm/ax 11.0.52 → 11.0.53

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
@@ -66,6 +66,7 @@ __export(index_exports, {
66
66
  AxAIOpenAIResponsesImpl: () => AxAIOpenAIResponsesImpl,
67
67
  AxAIReka: () => AxAIReka,
68
68
  AxAIRekaModel: () => AxAIRekaModel,
69
+ AxAIServiceAbortedError: () => AxAIServiceAbortedError,
69
70
  AxAIServiceAuthenticationError: () => AxAIServiceAuthenticationError,
70
71
  AxAIServiceError: () => AxAIServiceError,
71
72
  AxAIServiceNetworkError: () => AxAIServiceNetworkError,
@@ -74,6 +75,7 @@ __export(index_exports, {
74
75
  AxAIServiceStreamTerminatedError: () => AxAIServiceStreamTerminatedError,
75
76
  AxAIServiceTimeoutError: () => AxAIServiceTimeoutError,
76
77
  AxAITogether: () => AxAITogether,
78
+ AxAbortableAI: () => AxAbortableAI,
77
79
  AxAgent: () => AxAgent,
78
80
  AxApacheTika: () => AxApacheTika,
79
81
  AxAssertionError: () => AxAssertionError,
@@ -459,10 +461,25 @@ var AxAIServiceStreamTerminatedError = class extends AxAIServiceError {
459
461
  };
460
462
  var AxAIServiceTimeoutError = class extends AxAIServiceError {
461
463
  constructor(url, timeoutMs, requestBody, context3) {
462
- super(`Request timeout after ${timeoutMs}ms`, url, requestBody, void 0, {
463
- timeoutMs,
464
- ...context3
465
- });
464
+ super(
465
+ `Request timed out after ${timeoutMs}ms`,
466
+ url,
467
+ requestBody,
468
+ void 0,
469
+ { timeoutMs, ...context3 }
470
+ );
471
+ this.name = this.constructor.name;
472
+ }
473
+ };
474
+ var AxAIServiceAbortedError = class extends AxAIServiceError {
475
+ constructor(url, reason, requestBody, context3) {
476
+ super(
477
+ `Request aborted${reason ? `: ${reason}` : ""}`,
478
+ url,
479
+ requestBody,
480
+ void 0,
481
+ { abortReason: reason, ...context3 }
482
+ );
466
483
  this.name = this.constructor.name;
467
484
  }
468
485
  };
@@ -522,9 +539,34 @@ var apiCall = async (api, json) => {
522
539
  });
523
540
  let attempt = 0;
524
541
  while (true) {
525
- const controller = new AbortController();
542
+ const combinedAbortController = new AbortController();
543
+ if (api.abortSignal) {
544
+ if (api.abortSignal.aborted) {
545
+ throw new AxAIServiceAbortedError(
546
+ apiUrl.href,
547
+ api.abortSignal.reason,
548
+ json,
549
+ { metrics }
550
+ );
551
+ }
552
+ const userAbortHandler = () => {
553
+ combinedAbortController.abort(
554
+ api.abortSignal.reason || "User aborted request"
555
+ );
556
+ };
557
+ api.abortSignal.addEventListener("abort", userAbortHandler, {
558
+ once: true
559
+ });
560
+ const originalAbort = combinedAbortController.abort.bind(
561
+ combinedAbortController
562
+ );
563
+ combinedAbortController.abort = (reason) => {
564
+ api.abortSignal.removeEventListener("abort", userAbortHandler);
565
+ originalAbort(reason);
566
+ };
567
+ }
526
568
  timeoutId = setTimeout(() => {
527
- controller.abort("Request timeout");
569
+ combinedAbortController.abort("Request timeout");
528
570
  }, timeoutMs);
529
571
  try {
530
572
  const res = await (api.fetch ?? fetch)(apiUrl, {
@@ -536,7 +578,7 @@ var apiCall = async (api, json) => {
536
578
  ...api.headers
537
579
  },
538
580
  body: JSON.stringify(json),
539
- signal: controller.signal
581
+ signal: combinedAbortController.signal
540
582
  });
541
583
  clearTimeout(timeoutId);
542
584
  if (res.status === 401 || res.status === 403) {
@@ -599,12 +641,12 @@ var apiCall = async (api, json) => {
599
641
  let lastChunk;
600
642
  let chunkCount = 0;
601
643
  const trackingStream = new import_web3.TransformStream({
602
- transform(chunk, controller2) {
644
+ transform(chunk, controller) {
603
645
  lastChunk = chunk;
604
646
  chunkCount++;
605
647
  metrics.streamChunks = chunkCount;
606
648
  metrics.lastChunkTime = Date.now();
607
- controller2.enqueue(chunk);
649
+ controller.enqueue(chunk);
608
650
  api.span?.addEvent("stream.chunk", {
609
651
  "stream.chunks": chunkCount,
610
652
  "stream.duration": Date.now() - metrics.startTime,
@@ -614,7 +656,7 @@ var apiCall = async (api, json) => {
614
656
  });
615
657
  let closed = false;
616
658
  return new import_web3.ReadableStream({
617
- start(controller2) {
659
+ start(controller) {
618
660
  const reader = res.body.pipeThrough(new textDecoderStream()).pipeThrough(new SSEParser()).pipeThrough(trackingStream).getReader();
619
661
  async function read() {
620
662
  try {
@@ -623,12 +665,12 @@ var apiCall = async (api, json) => {
623
665
  if (done) {
624
666
  if (!closed) {
625
667
  closed = true;
626
- controller2.close();
668
+ controller.close();
627
669
  }
628
670
  break;
629
671
  }
630
672
  if (closed) break;
631
- controller2.enqueue(value);
673
+ controller.enqueue(value);
632
674
  }
633
675
  } catch (e) {
634
676
  const error = e;
@@ -637,7 +679,7 @@ var apiCall = async (api, json) => {
637
679
  streamDuration: Date.now() - metrics.startTime
638
680
  };
639
681
  if (error.name === "AbortError" || error.message?.includes("aborted")) {
640
- controller2.error(
682
+ controller.error(
641
683
  new AxAIServiceStreamTerminatedError(
642
684
  apiUrl.href,
643
685
  json,
@@ -646,7 +688,7 @@ var apiCall = async (api, json) => {
646
688
  )
647
689
  );
648
690
  } else if (error instanceof TypeError && error.message.includes("cancelled")) {
649
- controller2.error(
691
+ controller.error(
650
692
  new AxAIServiceStreamTerminatedError(
651
693
  apiUrl.href,
652
694
  json,
@@ -658,7 +700,7 @@ var apiCall = async (api, json) => {
658
700
  )
659
701
  );
660
702
  } else {
661
- controller2.error(
703
+ controller.error(
662
704
  new AxAIServiceNetworkError(
663
705
  error,
664
706
  apiUrl.href,
@@ -685,9 +727,18 @@ var apiCall = async (api, json) => {
685
727
  });
686
728
  } catch (error) {
687
729
  if (error instanceof Error && error.name === "AbortError") {
688
- throw new AxAIServiceTimeoutError(apiUrl.href, timeoutMs, json, {
689
- metrics
690
- });
730
+ if (api.abortSignal?.aborted) {
731
+ throw new AxAIServiceAbortedError(
732
+ apiUrl.href,
733
+ api.abortSignal.reason,
734
+ json,
735
+ { metrics }
736
+ );
737
+ } else {
738
+ throw new AxAIServiceTimeoutError(apiUrl.href, timeoutMs, json, {
739
+ metrics
740
+ });
741
+ }
691
742
  }
692
743
  if (api.span?.isRecording()) {
693
744
  api.span.recordException(error);
@@ -932,6 +983,7 @@ var AxBaseAI = class {
932
983
  timeout;
933
984
  excludeContentFromTrace;
934
985
  models;
986
+ abortSignal;
935
987
  modelInfo;
936
988
  modelUsage;
937
989
  embedModelUsage;
@@ -992,6 +1044,7 @@ var AxBaseAI = class {
992
1044
  this.timeout = options.timeout;
993
1045
  this.tracer = options.tracer;
994
1046
  this.excludeContentFromTrace = options.excludeContentFromTrace;
1047
+ this.abortSignal = options.abortSignal;
995
1048
  }
996
1049
  getOptions() {
997
1050
  return {
@@ -1000,7 +1053,8 @@ var AxBaseAI = class {
1000
1053
  fetch: this.fetch,
1001
1054
  tracer: this.tracer,
1002
1055
  timeout: this.timeout,
1003
- excludeContentFromTrace: this.excludeContentFromTrace
1056
+ excludeContentFromTrace: this.excludeContentFromTrace,
1057
+ abortSignal: this.abortSignal
1004
1058
  };
1005
1059
  }
1006
1060
  getModelList() {
@@ -1182,7 +1236,8 @@ var AxBaseAI = class {
1182
1236
  timeout: this.timeout,
1183
1237
  debug,
1184
1238
  fetch: this.fetch,
1185
- span
1239
+ span,
1240
+ abortSignal: options?.abortSignal ?? this.abortSignal
1186
1241
  },
1187
1242
  reqValue
1188
1243
  );
@@ -1339,7 +1394,8 @@ var AxBaseAI = class {
1339
1394
  debug,
1340
1395
  fetch: this.fetch,
1341
1396
  timeout: this.timeout,
1342
- span
1397
+ span,
1398
+ abortSignal: options?.abortSignal ?? this.abortSignal
1343
1399
  },
1344
1400
  reqValue
1345
1401
  );
@@ -5631,6 +5687,8 @@ var validateValue = (field, value) => {
5631
5687
  const ft = field.type ?? { name: "string", isArray: false };
5632
5688
  const validateSingleValue = (expectedType, val) => {
5633
5689
  switch (expectedType) {
5690
+ case "class":
5691
+ return typeof val === "string";
5634
5692
  case "code":
5635
5693
  return typeof val === "string";
5636
5694
  case "string":
@@ -5669,7 +5727,7 @@ var validateValue = (field, value) => {
5669
5727
  }
5670
5728
  if (msg) {
5671
5729
  throw new Error(
5672
- `Validation failed: Expected '${field.name}' to be a ${msg} instead got '${value}'`
5730
+ `Validation failed: Expected '${field.name}' to be type '${msg}' instead got '${value}'`
5673
5731
  );
5674
5732
  }
5675
5733
  return;
@@ -5694,7 +5752,7 @@ var validateValue = (field, value) => {
5694
5752
  }
5695
5753
  if (msg) {
5696
5754
  throw new Error(
5697
- `Validation failed: Expected '${field.name}' to be a ${msg} instead got '${value}'`
5755
+ `Validation failed: Expected '${field.name}' to be type '${msg}' instead got '${value}'`
5698
5756
  );
5699
5757
  }
5700
5758
  return;
@@ -5715,8 +5773,9 @@ var validateValue = (field, value) => {
5715
5773
  isValid = validateSingleValue(ft.name, value);
5716
5774
  }
5717
5775
  if (!isValid) {
5776
+ const gotType = Array.isArray(value) ? "array" : typeof value;
5718
5777
  throw new Error(
5719
- `Validation failed: Expected '${field.name}' to be a ${field.type?.isArray ? "an array of " : ""}${ft.name} instead got '${typeof value}' (${value})`
5778
+ `Validation failed: Expected '${field.name}' to be a ${field.type?.isArray ? "an array of " : ""}${ft.name} instead got '${gotType}' (${JSON.stringify(value)})`
5720
5779
  );
5721
5780
  }
5722
5781
  };
@@ -5921,11 +5980,15 @@ var AxPromptTemplate = class {
5921
5980
  task;
5922
5981
  thoughtFieldName;
5923
5982
  functions;
5983
+ strictExamples;
5984
+ optionalOutputFields;
5924
5985
  constructor(sig, options, fieldTemplates) {
5925
5986
  this.sig = sig;
5926
5987
  this.fieldTemplates = fieldTemplates;
5927
5988
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
5928
5989
  this.functions = options?.functions;
5990
+ this.strictExamples = options?.strictExamples ?? false;
5991
+ this.optionalOutputFields = options?.optionalOutputFields ?? [];
5929
5992
  const task = [];
5930
5993
  const inArgs = renderDescFields(this.sig.getInputFields());
5931
5994
  const outArgs = renderDescFields(this.sig.getOutputFields());
@@ -6095,13 +6158,32 @@ ${outputFields}`);
6095
6158
  };
6096
6159
  renderExamples = (data) => {
6097
6160
  const list = [];
6161
+ const inputExampleContext = {
6162
+ isExample: true,
6163
+ strictExamples: this.strictExamples,
6164
+ optionalOutputFields: this.optionalOutputFields,
6165
+ isInputField: true
6166
+ };
6167
+ const outputExampleContext = {
6168
+ isExample: true,
6169
+ strictExamples: this.strictExamples,
6170
+ optionalOutputFields: this.optionalOutputFields,
6171
+ isInputField: false
6172
+ };
6098
6173
  for (const [index, item] of data.entries()) {
6099
- const renderedInputItem = this.sig.getInputFields().map((field) => this.renderInField(field, item)).filter((v) => v !== void 0).flat();
6100
- const renderedOutputItem = this.sig.getOutputFields().map((field) => this.renderInField(field, item)).filter((v) => v !== void 0).flat();
6174
+ const renderedInputItem = this.sig.getInputFields().map((field) => this.renderInField(field, item, inputExampleContext)).filter((v) => v !== void 0).flat();
6175
+ const outputFields = this.sig.getOutputFields();
6176
+ const renderedOutputItem = outputFields.map((field) => this.renderInField(field, item, outputExampleContext)).filter((v) => v !== void 0).flat();
6101
6177
  if (renderedOutputItem.length === 0) {
6102
- throw new Error(
6103
- `Output fields are required in examples: index: ${index}, data: ${JSON.stringify(item)}`
6178
+ const missingFields = outputFields.filter((field) => !item[field.name]);
6179
+ const allMissingFieldsAreOptional = missingFields.every(
6180
+ (field) => this.optionalOutputFields.includes(field.name)
6104
6181
  );
6182
+ if (!allMissingFieldsAreOptional) {
6183
+ throw new Error(
6184
+ `Output fields are required in examples: index: ${index}, data: ${JSON.stringify(item)}`
6185
+ );
6186
+ }
6105
6187
  }
6106
6188
  const renderedItem = [...renderedInputItem, ...renderedOutputItem];
6107
6189
  if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
@@ -6121,9 +6203,26 @@ ${outputFields}`);
6121
6203
  };
6122
6204
  renderDemos = (data) => {
6123
6205
  const list = [];
6124
- const fields = [...this.sig.getInputFields(), ...this.sig.getOutputFields()];
6206
+ const inputFields = this.sig.getInputFields();
6207
+ const outputFields = this.sig.getOutputFields();
6125
6208
  for (const item of data) {
6126
- const renderedItem = fields.map((field) => this.renderInField(field, item)).filter((v) => v !== void 0).flat();
6209
+ const inputRenderedItems = inputFields.map(
6210
+ (field) => this.renderInField(field, item, {
6211
+ isExample: true,
6212
+ strictExamples: this.strictExamples,
6213
+ optionalOutputFields: this.optionalOutputFields,
6214
+ isInputField: true
6215
+ })
6216
+ ).filter((v) => v !== void 0).flat();
6217
+ const outputRenderedItems = outputFields.map(
6218
+ (field) => this.renderInField(field, item, {
6219
+ isExample: true,
6220
+ strictExamples: this.strictExamples,
6221
+ optionalOutputFields: this.optionalOutputFields,
6222
+ isInputField: false
6223
+ })
6224
+ ).filter((v) => v !== void 0).flat();
6225
+ const renderedItem = [...inputRenderedItems, ...outputRenderedItems];
6127
6226
  renderedItem.slice(0, -1).forEach((v) => {
6128
6227
  if ("text" in v) {
6129
6228
  v.text = v.text + "\n";
@@ -6137,15 +6236,15 @@ ${outputFields}`);
6137
6236
  return list;
6138
6237
  };
6139
6238
  renderInputFields = (values) => {
6140
- const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values)).filter((v) => v !== void 0).flat();
6239
+ const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values, void 0)).filter((v) => v !== void 0).flat();
6141
6240
  renderedItems.filter((v) => v.type === "text").forEach((v) => {
6142
6241
  v.text = v.text + "\n";
6143
6242
  });
6144
6243
  return renderedItems;
6145
6244
  };
6146
- renderInField = (field, values) => {
6245
+ renderInField = (field, values, context3) => {
6147
6246
  const value = values[field.name];
6148
- if (isEmptyValue(field, value)) {
6247
+ if (isEmptyValue(field, value, context3)) {
6149
6248
  return;
6150
6249
  }
6151
6250
  if (field.type) {
@@ -6329,15 +6428,34 @@ function combineConsecutiveStrings(separator) {
6329
6428
  return acc;
6330
6429
  };
6331
6430
  }
6332
- var isEmptyValue = (field, value) => {
6431
+ var isEmptyValue = (field, value, context3) => {
6333
6432
  if (typeof value === "boolean") {
6334
6433
  return false;
6335
6434
  }
6336
6435
  if (!value || (Array.isArray(value) || typeof value === "string") && value.length === 0) {
6337
- if (field.isOptional || field.isInternal) {
6436
+ if (context3?.isExample) {
6437
+ const isInputField = context3?.isInputField ?? true;
6438
+ if (isInputField) {
6439
+ if (!context3?.strictExamples) {
6440
+ return true;
6441
+ } else {
6442
+ if (field.isOptional || field.isInternal) {
6443
+ return true;
6444
+ }
6445
+ throw new Error(`Value for input field '${field.name}' is required.`);
6446
+ }
6447
+ } else {
6448
+ if (field.isOptional || field.isInternal || context3?.optionalOutputFields?.includes(field.name)) {
6449
+ return true;
6450
+ }
6451
+ throw new Error(`Value for output field '${field.name}' is required.`);
6452
+ }
6453
+ }
6454
+ if (field.isOptional || field.isInternal || context3?.optionalOutputFields?.includes(field.name)) {
6338
6455
  return true;
6339
6456
  }
6340
- throw new Error(`Value for input field '${field.name}' is required.`);
6457
+ const fieldType = context3?.isInputField !== false ? "input" : "output";
6458
+ throw new Error(`Value for ${fieldType} field '${field.name}' is required.`);
6341
6459
  }
6342
6460
  return false;
6343
6461
  };
@@ -7597,6 +7715,7 @@ var AxProgramWithSignature = class {
7597
7715
  signature;
7598
7716
  sigHash;
7599
7717
  examples;
7718
+ examplesOptions;
7600
7719
  demos;
7601
7720
  trace;
7602
7721
  usage = [];
@@ -7638,16 +7757,16 @@ var AxProgramWithSignature = class {
7638
7757
  this.key.id = [parentId, this.key.id].join("/");
7639
7758
  }
7640
7759
  }
7641
- setExamples(examples) {
7642
- this._setExamples(examples);
7760
+ setExamples(examples, options) {
7761
+ this._setExamples(examples, options);
7643
7762
  if (!("programId" in examples)) {
7644
7763
  return;
7645
7764
  }
7646
7765
  for (const child of this.children) {
7647
- child.setExamples(examples);
7766
+ child.setExamples(examples, options);
7648
7767
  }
7649
7768
  }
7650
- _setExamples(examples) {
7769
+ _setExamples(examples, options) {
7651
7770
  let traces = [];
7652
7771
  if ("programId" in examples && examples.programId === this.key.id) {
7653
7772
  traces = examples.traces;
@@ -7656,6 +7775,7 @@ var AxProgramWithSignature = class {
7656
7775
  traces = examples;
7657
7776
  }
7658
7777
  if (traces) {
7778
+ this.examplesOptions = options;
7659
7779
  const sig = this.signature;
7660
7780
  const fields = [...sig.getInputFields(), ...sig.getOutputFields()];
7661
7781
  this.examples = traces.map((e) => {
@@ -7736,12 +7856,12 @@ var AxProgram = class {
7736
7856
  this.key.id = [parentId, this.key.id].join("/");
7737
7857
  }
7738
7858
  }
7739
- setExamples(examples) {
7859
+ setExamples(examples, options) {
7740
7860
  if (!("programId" in examples)) {
7741
7861
  return;
7742
7862
  }
7743
7863
  for (const child of this.children) {
7744
- child.setExamples(examples);
7864
+ child.setExamples(examples, options);
7745
7865
  }
7746
7866
  }
7747
7867
  getTraces() {
@@ -7795,7 +7915,9 @@ var AxGen = class extends AxProgramWithSignature {
7795
7915
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
7796
7916
  const promptTemplateOptions = {
7797
7917
  functions: options?.functions,
7798
- thoughtFieldName: this.thoughtFieldName
7918
+ thoughtFieldName: this.thoughtFieldName,
7919
+ strictExamples: options?.strictExamples,
7920
+ optionalOutputFields: options?.optionalOutputFields
7799
7921
  };
7800
7922
  this.promptTemplate = new (options?.promptTemplate ?? AxPromptTemplate)(
7801
7923
  this.signature,
@@ -7881,7 +8003,8 @@ var AxGen = class extends AxProgramWithSignature {
7881
8003
  stream,
7882
8004
  debug: false,
7883
8005
  thinkingTokenBudget,
7884
- traceContext
8006
+ traceContext,
8007
+ abortSignal: options?.abortSignal
7885
8008
  }
7886
8009
  );
7887
8010
  return res;
@@ -8158,7 +8281,9 @@ Content: ${result.content}`
8158
8281
  const promptTemplateClass = this.options?.promptTemplate ?? AxPromptTemplate;
8159
8282
  const currentPromptTemplateOptions = {
8160
8283
  functions: options.functions,
8161
- thoughtFieldName: this.thoughtFieldName
8284
+ thoughtFieldName: this.thoughtFieldName,
8285
+ strictExamples: this.options?.strictExamples,
8286
+ optionalOutputFields: this.options?.optionalOutputFields
8162
8287
  };
8163
8288
  this.promptTemplate = new promptTemplateClass(
8164
8289
  this.signature,
@@ -8344,6 +8469,22 @@ Content: ${result.content}`
8344
8469
  stream: true
8345
8470
  });
8346
8471
  }
8472
+ setExamples(examples, options) {
8473
+ super.setExamples(examples, options);
8474
+ if (options?.optionalOutputFields) {
8475
+ const promptTemplateClass = this.options?.promptTemplate ?? AxPromptTemplate;
8476
+ const currentPromptTemplateOptions = {
8477
+ functions: this.functions,
8478
+ thoughtFieldName: this.thoughtFieldName,
8479
+ strictExamples: this.options?.strictExamples,
8480
+ optionalOutputFields: options.optionalOutputFields
8481
+ };
8482
+ this.promptTemplate = new promptTemplateClass(
8483
+ this.signature,
8484
+ currentPromptTemplateOptions
8485
+ );
8486
+ }
8487
+ }
8347
8488
  };
8348
8489
  var AxGenerateError = class extends Error {
8349
8490
  details;
@@ -8474,8 +8615,8 @@ var AxAgent = class {
8474
8615
  this.func.parameters = addModelParameter(this.func.parameters, mm);
8475
8616
  }
8476
8617
  }
8477
- setExamples(examples) {
8478
- this.program.setExamples(examples);
8618
+ setExamples(examples, options) {
8619
+ this.program.setExamples(examples, options);
8479
8620
  }
8480
8621
  setId(id) {
8481
8622
  this.program.setId(id);
@@ -9769,7 +9910,12 @@ var AxDBManager = class {
9769
9910
  const bs = options?.batchSize ?? 10;
9770
9911
  for (let i = 0; i < chunks.length; i += bs) {
9771
9912
  const batch = chunks.slice(i, i + bs);
9772
- const ret = await this.ai.embed({ texts: batch });
9913
+ const ret = await this.ai.embed(
9914
+ { texts: batch },
9915
+ {
9916
+ abortSignal: options?.abortSignal
9917
+ }
9918
+ );
9773
9919
  const embeddings = ret.embeddings.map((embedding, index) => ({
9774
9920
  id: `chunk_${Date.now() + index}`,
9775
9921
  // Unique ID for each chunk, adjusted by index
@@ -9785,7 +9931,10 @@ var AxDBManager = class {
9785
9931
  throw new Error(`Error processing text: ${error}`);
9786
9932
  }
9787
9933
  };
9788
- query = async (query, { topPercent } = {}) => {
9934
+ query = async (query, {
9935
+ topPercent,
9936
+ abortSignal
9937
+ } = {}) => {
9789
9938
  const texts = Array.isArray(query) ? query : [query];
9790
9939
  if (typeof texts[0] === "string" && this.rewriter) {
9791
9940
  for (const [i, text] of texts.entries()) {
@@ -9797,7 +9946,12 @@ var AxDBManager = class {
9797
9946
  }
9798
9947
  let queries;
9799
9948
  if (typeof texts[0] === "string") {
9800
- const embedResults = await this.ai.embed({ texts });
9949
+ const embedResults = await this.ai.embed(
9950
+ { texts },
9951
+ {
9952
+ abortSignal
9953
+ }
9954
+ );
9801
9955
  queries = embedResults.embeddings.map(
9802
9956
  (values) => this.db.query({ table, values })
9803
9957
  );
@@ -11392,9 +11546,14 @@ var AxSimpleClassifier = class {
11392
11546
  setState(state) {
11393
11547
  this.db.setDB(state);
11394
11548
  }
11395
- setClasses = async (classes) => {
11549
+ setClasses = async (classes, options) => {
11396
11550
  for (const c of classes) {
11397
- const ret = await this.ai.embed({ texts: c.getContext() });
11551
+ const ret = await this.ai.embed(
11552
+ { texts: c.getContext() },
11553
+ {
11554
+ abortSignal: options?.abortSignal
11555
+ }
11556
+ );
11398
11557
  await this.db.upsert({
11399
11558
  id: c.getName(),
11400
11559
  table: "classes",
@@ -11403,7 +11562,12 @@ var AxSimpleClassifier = class {
11403
11562
  }
11404
11563
  };
11405
11564
  async forward(text, options) {
11406
- const { embeddings } = await this.ai.embed({ texts: [text] });
11565
+ const { embeddings } = await this.ai.embed(
11566
+ { texts: [text] },
11567
+ {
11568
+ abortSignal: options?.abortSignal
11569
+ }
11570
+ );
11407
11571
  const matches = await this.db.query({
11408
11572
  table: "classes",
11409
11573
  values: embeddings[0]
@@ -11478,6 +11642,79 @@ var AxTestPrompt = class {
11478
11642
  }
11479
11643
  };
11480
11644
 
11645
+ // ai/abortable.ts
11646
+ var AxAbortableAI = class {
11647
+ abortController;
11648
+ ai;
11649
+ constructor(ai) {
11650
+ this.ai = ai;
11651
+ this.abortController = new AbortController();
11652
+ }
11653
+ /**
11654
+ * Get the current abort signal
11655
+ */
11656
+ get signal() {
11657
+ return this.abortController.signal;
11658
+ }
11659
+ /**
11660
+ * Check if the request has been aborted
11661
+ */
11662
+ get aborted() {
11663
+ return this.abortController.signal.aborted;
11664
+ }
11665
+ /**
11666
+ * Abort the ongoing request
11667
+ * @param reason Optional reason for the abort
11668
+ */
11669
+ abort(reason) {
11670
+ this.abortController.abort(reason);
11671
+ }
11672
+ /**
11673
+ * Reset the abort controller to allow new requests
11674
+ * This creates a new AbortController, allowing fresh requests
11675
+ */
11676
+ reset() {
11677
+ this.abortController = new AbortController();
11678
+ }
11679
+ /**
11680
+ * Send a chat request with abort support
11681
+ */
11682
+ async chat(req, options) {
11683
+ return this.ai.chat(req, {
11684
+ ...options,
11685
+ abortSignal: this.abortController.signal
11686
+ });
11687
+ }
11688
+ /**
11689
+ * Send an embed request with abort support
11690
+ */
11691
+ async embed(req, options) {
11692
+ return this.ai.embed(req, {
11693
+ ...options,
11694
+ abortSignal: this.abortController.signal
11695
+ });
11696
+ }
11697
+ /**
11698
+ * Create a timeout-based abort after specified milliseconds
11699
+ * @param timeoutMs Timeout in milliseconds
11700
+ * @param reason Optional reason for the timeout abort
11701
+ * @returns Timeout ID that can be cleared
11702
+ */
11703
+ abortAfter(timeoutMs, reason = "Request timeout") {
11704
+ return setTimeout(() => {
11705
+ this.abort(reason);
11706
+ }, timeoutMs);
11707
+ }
11708
+ /**
11709
+ * Add an event listener for abort events
11710
+ */
11711
+ onAbort(callback) {
11712
+ this.abortController.signal.addEventListener("abort", () => {
11713
+ callback(this.abortController.signal.reason);
11714
+ });
11715
+ }
11716
+ };
11717
+
11481
11718
  // prompts/cot.ts
11482
11719
  var AxChainOfThought = class extends AxGen {
11483
11720
  constructor(signature, options) {
@@ -11604,7 +11841,10 @@ var AxEmbeddingAdapter = class {
11604
11841
  async embedAdapter(text, extra) {
11605
11842
  const embedRes = await this.aiService.embed(
11606
11843
  { texts: [text] },
11607
- { sessionId: extra?.sessionId }
11844
+ {
11845
+ sessionId: extra?.sessionId,
11846
+ abortSignal: extra?.abortSignal
11847
+ }
11608
11848
  );
11609
11849
  const embeds = embedRes.embeddings.at(0);
11610
11850
  if (!embeds) {
@@ -13368,6 +13608,7 @@ var AxRAG = class extends AxChainOfThought {
13368
13608
  AxAIOpenAIResponsesImpl,
13369
13609
  AxAIReka,
13370
13610
  AxAIRekaModel,
13611
+ AxAIServiceAbortedError,
13371
13612
  AxAIServiceAuthenticationError,
13372
13613
  AxAIServiceError,
13373
13614
  AxAIServiceNetworkError,
@@ -13376,6 +13617,7 @@ var AxRAG = class extends AxChainOfThought {
13376
13617
  AxAIServiceStreamTerminatedError,
13377
13618
  AxAIServiceTimeoutError,
13378
13619
  AxAITogether,
13620
+ AxAbortableAI,
13379
13621
  AxAgent,
13380
13622
  AxApacheTika,
13381
13623
  AxAssertionError,