@ax-llm/ax 10.0.35 → 10.0.37

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.js CHANGED
@@ -405,6 +405,14 @@ var AxBaseAI = class {
405
405
  this.tracer = options.tracer;
406
406
  }
407
407
  }
408
+ getOptions() {
409
+ return {
410
+ debug: this.debug,
411
+ rateLimiter: this.rt,
412
+ fetch: this.fetch,
413
+ tracer: this.tracer
414
+ };
415
+ }
408
416
  getModelInfo() {
409
417
  const mi = getModelInfo({
410
418
  model: this.models.model,
@@ -702,11 +710,11 @@ var logChatRequest = (req) => {
702
710
  return `${colorLog.blueBright("System:")}
703
711
  ${colorLog.whiteBright(msg.content)}`;
704
712
  case "function":
705
- return `${colorLog.blueBright("\nFunction Result:")}
713
+ return `${colorLog.blueBright("Function Result:")}
706
714
  ${colorLog.whiteBright(msg.result)}`;
707
715
  case "user": {
708
716
  if (typeof msg.content === "string") {
709
- return `${colorLog.blueBright("\nUser:")}
717
+ return `${colorLog.blueBright("User:")}
710
718
  ${colorLog.whiteBright(msg.content)}`;
711
719
  }
712
720
  const items2 = msg.content.map((v) => {
@@ -719,7 +727,7 @@ ${colorLog.whiteBright(msg.content)}`;
719
727
  throw new Error("Invalid content type");
720
728
  }
721
729
  });
722
- return `${colorLog.blueBright("\nUser:")}
730
+ return `${colorLog.blueBright("User:")}
723
731
  ${items2.join("\n")}`;
724
732
  }
725
733
  case "assistant": {
@@ -739,8 +747,7 @@ ${colorLog.whiteBright(msg.content ?? "<empty>")}`;
739
747
  }
740
748
  });
741
749
  if (items) {
742
- console.log("\n==========");
743
- console.log(items.join("\n"));
750
+ process.stdout.write("\n===\n" + items.join("\n") + "\n\n---\n");
744
751
  }
745
752
  };
746
753
  var logResponse = (resp) => {
@@ -3099,6 +3106,9 @@ var AxAI = class {
3099
3106
  setOptions(options) {
3100
3107
  this.ai.setOptions(options);
3101
3108
  }
3109
+ getOptions() {
3110
+ return this.ai.getOptions();
3111
+ }
3102
3112
  };
3103
3113
 
3104
3114
  // prompts/agent.ts
@@ -3129,76 +3139,145 @@ function mergeFunctionCalls(functionCalls, functionCallDeltas) {
3129
3139
  }
3130
3140
 
3131
3141
  // mem/memory.ts
3132
- var AxMemory = class {
3133
- data = [];
3134
- sdata = /* @__PURE__ */ new Map();
3135
- limit;
3136
- constructor(limit = 50) {
3142
+ var defaultLimit = 1e4;
3143
+ var MemoryImpl = class {
3144
+ constructor(limit = defaultLimit) {
3145
+ this.limit = limit;
3137
3146
  if (limit <= 0) {
3138
3147
  throw Error("argument 'limit' must be greater than 0");
3139
3148
  }
3140
- this.limit = limit;
3141
3149
  }
3142
- add(value, sessionId) {
3143
- const d = this.get(sessionId);
3144
- let n = 0;
3150
+ data = [];
3151
+ add(value) {
3145
3152
  if (Array.isArray(value)) {
3146
- n = d.push(...structuredClone(value));
3153
+ this.data.push(...value.map((chat) => ({ chat: structuredClone(chat) })));
3147
3154
  } else {
3148
- n = d.push({
3149
- ...structuredClone(value)
3155
+ this.data.push({
3156
+ chat: structuredClone(value)
3150
3157
  });
3151
3158
  }
3152
- if (d.length > this.limit) {
3153
- d.splice(0, this.limit + n - this.limit);
3159
+ if (this.data.length > this.limit) {
3160
+ const removeCount = this.data.length - this.limit;
3161
+ this.data.splice(0, removeCount);
3154
3162
  }
3155
3163
  }
3156
- addResult({ content, name, functionCalls }, sessionId) {
3164
+ addResult({
3165
+ content,
3166
+ name,
3167
+ functionCalls
3168
+ }) {
3157
3169
  if (!content && (!functionCalls || functionCalls.length === 0)) {
3158
3170
  return;
3159
3171
  }
3160
- this.add({ content, name, role: "assistant", functionCalls }, sessionId);
3172
+ this.add({ content, name, role: "assistant", functionCalls });
3161
3173
  }
3162
- updateResult({ content, name, functionCalls }, sessionId) {
3163
- const items = this.get(sessionId);
3164
- const lastItem = items.at(-1);
3165
- if (!lastItem || lastItem.role !== "assistant") {
3166
- this.addResult({ content, name, functionCalls }, sessionId);
3174
+ updateResult({
3175
+ content,
3176
+ name,
3177
+ functionCalls
3178
+ }) {
3179
+ const lastItem = this.data.at(-1);
3180
+ if (!lastItem || lastItem.chat.role !== "assistant") {
3181
+ this.addResult({ content, name, functionCalls });
3167
3182
  return;
3168
3183
  }
3169
- if ("content" in lastItem && content) {
3170
- lastItem.content = content;
3184
+ if ("content" in lastItem.chat && content) {
3185
+ lastItem.chat.content = content;
3186
+ }
3187
+ if ("name" in lastItem.chat && name) {
3188
+ lastItem.chat.name = name;
3171
3189
  }
3172
- if ("name" in lastItem && name) {
3173
- lastItem.name = name;
3190
+ if ("functionCalls" in lastItem.chat && functionCalls) {
3191
+ lastItem.chat.functionCalls = functionCalls;
3192
+ }
3193
+ }
3194
+ addTag(name) {
3195
+ const lastItem = this.data.at(-1);
3196
+ if (!lastItem) {
3197
+ return;
3198
+ }
3199
+ if (!lastItem.tags) {
3200
+ lastItem.tags = [];
3201
+ }
3202
+ if (!lastItem.tags.includes(name)) {
3203
+ lastItem.tags.push(name);
3204
+ }
3205
+ }
3206
+ rewindToTag(name) {
3207
+ const tagIndex = this.data.findIndex((item) => item.tags?.includes(name));
3208
+ if (tagIndex === -1) {
3209
+ throw new Error(`Tag "${name}" not found`);
3210
+ }
3211
+ const removedItems = this.data.splice(tagIndex);
3212
+ return removedItems.map((item) => item.chat);
3213
+ }
3214
+ removeByTag(name) {
3215
+ const indices = this.data.reduce((acc, item, index) => {
3216
+ if (item.tags?.includes(name)) {
3217
+ acc.push(index);
3218
+ }
3219
+ return acc;
3220
+ }, []);
3221
+ if (indices.length === 0) {
3222
+ throw new Error(`No items found with tag "${name}"`);
3223
+ }
3224
+ return indices.reverse().map((index) => this.data.splice(index, 1).at(0)?.chat).filter(Boolean).reverse();
3225
+ }
3226
+ history() {
3227
+ return this.data.map((item) => item.chat);
3228
+ }
3229
+ getLast() {
3230
+ const lastItem = this.data.at(-1);
3231
+ return lastItem?.chat;
3232
+ }
3233
+ reset() {
3234
+ this.data = [];
3235
+ }
3236
+ };
3237
+ var AxMemory = class {
3238
+ constructor(limit = defaultLimit) {
3239
+ this.limit = limit;
3240
+ this.defaultMemory = new MemoryImpl(limit);
3241
+ }
3242
+ memories = /* @__PURE__ */ new Map();
3243
+ defaultMemory;
3244
+ getMemory(sessionId) {
3245
+ if (!sessionId) {
3246
+ return this.defaultMemory;
3174
3247
  }
3175
- if ("functionCalls" in lastItem && functionCalls) {
3176
- lastItem.functionCalls = functionCalls;
3248
+ if (!this.memories.has(sessionId)) {
3249
+ this.memories.set(sessionId, new MemoryImpl(this.limit));
3177
3250
  }
3251
+ return this.memories.get(sessionId);
3252
+ }
3253
+ add(value, sessionId) {
3254
+ this.getMemory(sessionId).add(value);
3255
+ }
3256
+ addResult(result, sessionId) {
3257
+ this.getMemory(sessionId).addResult(result);
3258
+ }
3259
+ updateResult(result, sessionId) {
3260
+ this.getMemory(sessionId).updateResult(result);
3261
+ }
3262
+ addTag(name, sessionId) {
3263
+ this.getMemory(sessionId).addTag(name);
3264
+ }
3265
+ rewindToTag(name, sessionId) {
3266
+ return this.getMemory(sessionId).rewindToTag(name);
3178
3267
  }
3179
3268
  history(sessionId) {
3180
- return this.get(sessionId);
3269
+ return this.getMemory(sessionId).history();
3181
3270
  }
3182
3271
  getLast(sessionId) {
3183
- const d = this.get(sessionId);
3184
- return d.at(-1);
3272
+ return this.getMemory(sessionId).getLast();
3185
3273
  }
3186
3274
  reset(sessionId) {
3187
3275
  if (!sessionId) {
3188
- this.data = [];
3276
+ this.defaultMemory.reset();
3189
3277
  } else {
3190
- this.sdata.set(sessionId, []);
3278
+ this.memories.set(sessionId, new MemoryImpl(this.limit));
3191
3279
  }
3192
3280
  }
3193
- get(sessionId) {
3194
- if (!sessionId) {
3195
- return this.data;
3196
- }
3197
- if (!this.sdata.has(sessionId)) {
3198
- this.sdata.set(sessionId, []);
3199
- }
3200
- return this.sdata.get(sessionId) || [];
3201
- }
3202
3281
  };
3203
3282
 
3204
3283
  // dsp/asserts.ts
@@ -3218,12 +3297,11 @@ var AxAssertionError = class extends Error {
3218
3297
  }
3219
3298
  getValue = () => this.values;
3220
3299
  getOptional = () => this.optional;
3221
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
3222
- getFixingInstructions = (_sig) => {
3300
+ getFixingInstructions = () => {
3223
3301
  const extraFields = [];
3224
3302
  extraFields.push({
3225
3303
  name: "error",
3226
- title: "Error",
3304
+ title: "Error In Output",
3227
3305
  description: this.message
3228
3306
  });
3229
3307
  return extraFields;
@@ -3232,17 +3310,12 @@ var AxAssertionError = class extends Error {
3232
3310
  var assertAssertions = (asserts, values) => {
3233
3311
  for (const assert of asserts) {
3234
3312
  const { fn, message, optional } = assert;
3235
- try {
3236
- const res = fn(values);
3237
- if (res === void 0) {
3238
- continue;
3239
- }
3240
- if (!res && message) {
3241
- throw new AxAssertionError({ message, values, optional });
3242
- }
3243
- } catch (e) {
3244
- const message2 = e.message;
3245
- throw new AxAssertionError({ message: message2, values, optional });
3313
+ const res = fn(values);
3314
+ if (res === void 0) {
3315
+ continue;
3316
+ }
3317
+ if (!res && message) {
3318
+ throw new AxAssertionError({ message, values, optional });
3246
3319
  }
3247
3320
  }
3248
3321
  };
@@ -3259,17 +3332,12 @@ var assertStreamingAssertions = (asserts, values, xstate, content, final) => {
3259
3332
  const currValue = content.substring(xstate.s);
3260
3333
  for (const assert of fieldAsserts) {
3261
3334
  const { message, optional, fn } = assert;
3262
- try {
3263
- const res = fn(currValue, final);
3264
- if (res === void 0) {
3265
- continue;
3266
- }
3267
- if (!res && message) {
3268
- throw new AxAssertionError({ message, values, optional });
3269
- }
3270
- } catch (e) {
3271
- const message2 = e.message;
3272
- throw new AxAssertionError({ message: message2, values, optional });
3335
+ const res = fn(currValue, final);
3336
+ if (res === void 0) {
3337
+ continue;
3338
+ }
3339
+ if (!res && message) {
3340
+ throw new AxAssertionError({ message, values, optional });
3273
3341
  }
3274
3342
  }
3275
3343
  };
@@ -4031,7 +4099,7 @@ var AxPromptTemplate = class {
4031
4099
  const inArgs = this.renderDescFields(this.sig.getInputFields());
4032
4100
  const outArgs = this.renderDescFields(this.sig.getOutputFields());
4033
4101
  const task = [
4034
- `You will be provided with the following fields: ${inArgs}. Your task is to generate two new fields: ${outArgs}.`
4102
+ `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
4035
4103
  ];
4036
4104
  const funcs = functions?.map(
4037
4105
  (f) => "toFunction" in f ? f.toFunction() : f
@@ -4363,7 +4431,7 @@ function capitalizeFirstLetter(str) {
4363
4431
  }
4364
4432
 
4365
4433
  // dsp/validate.ts
4366
- var AxValidationError = class extends Error {
4434
+ var ValidationError = class extends Error {
4367
4435
  field;
4368
4436
  value;
4369
4437
  constructor({
@@ -4383,9 +4451,9 @@ var AxValidationError = class extends Error {
4383
4451
  const f = this.field;
4384
4452
  const extraFields = [
4385
4453
  {
4386
- name: `invalidField`,
4387
- title: `Invalid Field`,
4388
- description: `Ensure the field \`${f.title}\` is of type \`${toFieldType(f.type)}\``
4454
+ name: `outputError`,
4455
+ title: `Invalid Output Field`,
4456
+ description: `Invalid format for field \`${f.title}\` of type \`${toFieldType(f.type)}\`, format should match: \`${f.description}\``
4389
4457
  }
4390
4458
  ];
4391
4459
  return extraFields;
@@ -4398,7 +4466,7 @@ function parseLLMFriendlyDate(field, dateStr) {
4398
4466
  return _parseLLMFriendlyDate(dateStr);
4399
4467
  } catch (err) {
4400
4468
  const message = err.message;
4401
- throw new AxValidationError({ field, message, value: dateStr });
4469
+ throw new ValidationError({ field, message, value: dateStr });
4402
4470
  }
4403
4471
  }
4404
4472
  function _parseLLMFriendlyDate(dateStr) {
@@ -4415,7 +4483,7 @@ function parseLLMFriendlyDateTime(field, dateStr) {
4415
4483
  return _parseLLMFriendlyDateTime(dateStr);
4416
4484
  } catch (err) {
4417
4485
  const message = err.message;
4418
- throw new AxValidationError({ field, message, value: dateStr });
4486
+ throw new ValidationError({ field, message, value: dateStr });
4419
4487
  }
4420
4488
  }
4421
4489
  function _parseLLMFriendlyDateTime(dateTimeStr) {
@@ -4532,7 +4600,7 @@ var convertValueToType = (field, val) => {
4532
4600
  var expectedTypeError = (field, err, value = "") => {
4533
4601
  const exp = field.type?.isArray ? `array of ${field.type.name}` : field.type?.name;
4534
4602
  const message = `Error '${err.message}', expected '${exp}' got '${value}'`;
4535
- return new AxValidationError({ message, field, value });
4603
+ return new ValidationError({ message, field, value });
4536
4604
  };
4537
4605
  function validateAndParseFieldValue(field, fieldValue) {
4538
4606
  const fv = fieldValue?.toLocaleLowerCase();
@@ -4748,6 +4816,7 @@ function parseFunctionCalls(ai, functionCalls, values, model) {
4748
4816
  }
4749
4817
 
4750
4818
  // dsp/generate.ts
4819
+ var colorLog4 = new ColorLog();
4751
4820
  var AxGen = class extends AxProgramWithSignature {
4752
4821
  promptTemplate;
4753
4822
  asserts;
@@ -4964,7 +5033,7 @@ var AxGen = class extends AxProgramWithSignature {
4964
5033
  }
4965
5034
  async _forward(ai, values, options, span) {
4966
5035
  const stopFunction = (options?.stopFunction ?? this.options?.stopFunction)?.toLowerCase();
4967
- const maxRetries = options?.maxRetries ?? this.options?.maxRetries ?? 15;
5036
+ const maxRetries = options?.maxRetries ?? this.options?.maxRetries ?? 3;
4968
5037
  const maxSteps = options?.maxSteps ?? this.options?.maxSteps ?? 10;
4969
5038
  const mem = options?.mem ?? this.options?.mem ?? new AxMemory();
4970
5039
  let err;
@@ -4981,7 +5050,7 @@ var AxGen = class extends AxProgramWithSignature {
4981
5050
  });
4982
5051
  mem.add(prompt, options?.sessionId);
4983
5052
  multiStepLoop: for (let n = 0; n < maxSteps; n++) {
4984
- for (let i = 0; i < maxRetries; i++) {
5053
+ for (let errCount = 0; errCount < maxRetries; errCount++) {
4985
5054
  try {
4986
5055
  const output = await this.forwardCore({
4987
5056
  options,
@@ -4989,35 +5058,49 @@ var AxGen = class extends AxProgramWithSignature {
4989
5058
  mem
4990
5059
  });
4991
5060
  const lastMemItem = mem.getLast(options?.sessionId);
4992
- const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
4993
- if (lastMemItem?.role === "function") {
4994
- if (!stopFunction || !stopFunctionExecuted) {
4995
- continue multiStepLoop;
5061
+ if (lastMemItem) {
5062
+ const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
5063
+ if (lastMemItem.role === "function") {
5064
+ if (!stopFunction || !stopFunctionExecuted) {
5065
+ continue multiStepLoop;
5066
+ }
5067
+ }
5068
+ if (!stopFunctionExecuted) {
5069
+ assertRequiredFields(this.signature, output);
4996
5070
  }
4997
- }
4998
- if (!stopFunctionExecuted) {
4999
- assertRequiredFields(this.signature, output);
5000
5071
  }
5001
5072
  this.trace = { ...values, ...output };
5002
5073
  return output;
5003
5074
  } catch (e) {
5004
- let extraFields;
5075
+ let errorFields;
5005
5076
  span?.recordException(e);
5006
- if (e instanceof AxValidationError) {
5007
- extraFields = e.getFixingInstructions();
5077
+ if (e instanceof ValidationError) {
5078
+ errorFields = e.getFixingInstructions();
5008
5079
  err = e;
5009
5080
  } else if (e instanceof AxAssertionError) {
5010
5081
  const e1 = e;
5011
- extraFields = e1.getFixingInstructions(this.signature);
5082
+ errorFields = e1.getFixingInstructions();
5012
5083
  err = e;
5013
5084
  } else {
5014
5085
  throw e;
5015
5086
  }
5016
- if (extraFields) {
5017
- const content = this.promptTemplate.renderExtraFields(extraFields);
5018
- mem.add({ role: "user", content }, options?.sessionId);
5019
- if (options?.debug) {
5020
- console.log("Error Correction:", content);
5087
+ if (errorFields) {
5088
+ mem.add(
5089
+ {
5090
+ role: "user",
5091
+ content: this.promptTemplate.renderExtraFields(errorFields)
5092
+ },
5093
+ options?.sessionId
5094
+ );
5095
+ mem.addTag("error");
5096
+ if (ai.getOptions().debug) {
5097
+ process.stdout.write(
5098
+ colorLog4.red(
5099
+ `Error Correction:
5100
+ ${JSON.stringify(errorFields, null, 2)}
5101
+ `
5102
+ )
5103
+ );
5021
5104
  }
5022
5105
  }
5023
5106
  }
@@ -5302,9 +5385,11 @@ var AxBalancer = class {
5302
5385
  try {
5303
5386
  return await this.currentService.chat(req, options);
5304
5387
  } catch (e) {
5388
+ console.warn(`Service ${this.currentService.getName()} failed`);
5305
5389
  if (!this.getNextService()) {
5306
5390
  throw e;
5307
5391
  }
5392
+ console.warn(`Switching to service ${this.currentService.getName()}`);
5308
5393
  }
5309
5394
  }
5310
5395
  }
@@ -5314,15 +5399,20 @@ var AxBalancer = class {
5314
5399
  try {
5315
5400
  return await this.currentService.embed(req, options);
5316
5401
  } catch (e) {
5402
+ console.warn(`Service ${this.currentService.getName()} failed`);
5317
5403
  if (!this.getNextService()) {
5318
5404
  throw e;
5319
5405
  }
5406
+ console.warn(`Switching to service ${this.currentService.getName()}`);
5320
5407
  }
5321
5408
  }
5322
5409
  }
5323
5410
  setOptions(options) {
5324
5411
  this.currentService.setOptions(options);
5325
5412
  }
5413
+ getOptions() {
5414
+ return this.currentService.getOptions();
5415
+ }
5326
5416
  };
5327
5417
 
5328
5418
  // dsp/optimize.ts
@@ -6528,7 +6618,7 @@ var AxJSInterpreter = class {
6528
6618
  };
6529
6619
 
6530
6620
  // dsp/router.ts
6531
- var colorLog4 = new ColorLog();
6621
+ var colorLog5 = new ColorLog();
6532
6622
  var AxRoute = class {
6533
6623
  name;
6534
6624
  context;
@@ -6580,7 +6670,7 @@ var AxRouter = class {
6580
6670
  }
6581
6671
  if (this.debug) {
6582
6672
  console.log(
6583
- colorLog4.whiteBright(`query: ${text}`) + "\n" + colorLog4.greenBright(
6673
+ colorLog5.whiteBright(`query: ${text}`) + "\n" + colorLog5.greenBright(
6584
6674
  JSON.stringify(m.map((m2) => `${m2.id}, ${m2.score}`))
6585
6675
  )
6586
6676
  );
@@ -6893,7 +6983,6 @@ export {
6893
6983
  AxRouter,
6894
6984
  AxSignature,
6895
6985
  AxSpanKindValues,
6896
- AxTestPrompt,
6897
- AxValidationError
6986
+ AxTestPrompt
6898
6987
  };
6899
6988
  //# sourceMappingURL=index.js.map