@ax-llm/ax 10.0.34 → 10.0.36

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
@@ -93,8 +93,7 @@ __export(index_exports, {
93
93
  AxRouter: () => AxRouter,
94
94
  AxSignature: () => AxSignature,
95
95
  AxSpanKindValues: () => AxSpanKindValues,
96
- AxTestPrompt: () => AxTestPrompt,
97
- AxValidationError: () => AxValidationError
96
+ AxTestPrompt: () => AxTestPrompt
98
97
  });
99
98
  module.exports = __toCommonJS(index_exports);
100
99
 
@@ -499,6 +498,14 @@ var AxBaseAI = class {
499
498
  this.tracer = options.tracer;
500
499
  }
501
500
  }
501
+ getOptions() {
502
+ return {
503
+ debug: this.debug,
504
+ rateLimiter: this.rt,
505
+ fetch: this.fetch,
506
+ tracer: this.tracer
507
+ };
508
+ }
502
509
  getModelInfo() {
503
510
  const mi = getModelInfo({
504
511
  model: this.models.model,
@@ -796,11 +803,11 @@ var logChatRequest = (req) => {
796
803
  return `${colorLog.blueBright("System:")}
797
804
  ${colorLog.whiteBright(msg.content)}`;
798
805
  case "function":
799
- return `${colorLog.blueBright("\nFunction Result:")}
806
+ return `${colorLog.blueBright("Function Result:")}
800
807
  ${colorLog.whiteBright(msg.result)}`;
801
808
  case "user": {
802
809
  if (typeof msg.content === "string") {
803
- return `${colorLog.blueBright("\nUser:")}
810
+ return `${colorLog.blueBright("User:")}
804
811
  ${colorLog.whiteBright(msg.content)}`;
805
812
  }
806
813
  const items2 = msg.content.map((v) => {
@@ -813,7 +820,7 @@ ${colorLog.whiteBright(msg.content)}`;
813
820
  throw new Error("Invalid content type");
814
821
  }
815
822
  });
816
- return `${colorLog.blueBright("\nUser:")}
823
+ return `${colorLog.blueBright("User:")}
817
824
  ${items2.join("\n")}`;
818
825
  }
819
826
  case "assistant": {
@@ -833,8 +840,7 @@ ${colorLog.whiteBright(msg.content ?? "<empty>")}`;
833
840
  }
834
841
  });
835
842
  if (items) {
836
- console.log("\n==========");
837
- console.log(items.join("\n"));
843
+ process.stdout.write("\n===\n" + items.join("\n") + "\n\n---\n");
838
844
  }
839
845
  };
840
846
  var logResponse = (resp) => {
@@ -2204,7 +2210,7 @@ var AxAIGoogleGeminiImpl = class {
2204
2210
  throw new Error("Chat prompt is empty");
2205
2211
  }
2206
2212
  const apiConfig = {
2207
- name: stream ? `/models/${model}:streamGenerateContent?alt=sse` : `/models/${model}:createContent`
2213
+ name: stream ? `/models/${model}:streamGenerateContent?alt=sse` : `/models/${model}:generateContent`
2208
2214
  };
2209
2215
  if (this.isVertex === false) {
2210
2216
  const pf = stream ? "&" : "?";
@@ -3193,6 +3199,9 @@ var AxAI = class {
3193
3199
  setOptions(options) {
3194
3200
  this.ai.setOptions(options);
3195
3201
  }
3202
+ getOptions() {
3203
+ return this.ai.getOptions();
3204
+ }
3196
3205
  };
3197
3206
 
3198
3207
  // prompts/agent.ts
@@ -3223,76 +3232,145 @@ function mergeFunctionCalls(functionCalls, functionCallDeltas) {
3223
3232
  }
3224
3233
 
3225
3234
  // mem/memory.ts
3226
- var AxMemory = class {
3227
- data = [];
3228
- sdata = /* @__PURE__ */ new Map();
3229
- limit;
3230
- constructor(limit = 50) {
3235
+ var defaultLimit = 1e4;
3236
+ var MemoryImpl = class {
3237
+ constructor(limit = defaultLimit) {
3238
+ this.limit = limit;
3231
3239
  if (limit <= 0) {
3232
3240
  throw Error("argument 'limit' must be greater than 0");
3233
3241
  }
3234
- this.limit = limit;
3235
3242
  }
3236
- add(value, sessionId) {
3237
- const d = this.get(sessionId);
3238
- let n = 0;
3243
+ data = [];
3244
+ add(value) {
3239
3245
  if (Array.isArray(value)) {
3240
- n = d.push(...structuredClone(value));
3246
+ this.data.push(...value.map((chat) => ({ chat: structuredClone(chat) })));
3241
3247
  } else {
3242
- n = d.push({
3243
- ...structuredClone(value)
3248
+ this.data.push({
3249
+ chat: structuredClone(value)
3244
3250
  });
3245
3251
  }
3246
- if (d.length > this.limit) {
3247
- d.splice(0, this.limit + n - this.limit);
3252
+ if (this.data.length > this.limit) {
3253
+ const removeCount = this.data.length - this.limit;
3254
+ this.data.splice(0, removeCount);
3248
3255
  }
3249
3256
  }
3250
- addResult({ content, name, functionCalls }, sessionId) {
3257
+ addResult({
3258
+ content,
3259
+ name,
3260
+ functionCalls
3261
+ }) {
3251
3262
  if (!content && (!functionCalls || functionCalls.length === 0)) {
3252
3263
  return;
3253
3264
  }
3254
- this.add({ content, name, role: "assistant", functionCalls }, sessionId);
3265
+ this.add({ content, name, role: "assistant", functionCalls });
3255
3266
  }
3256
- updateResult({ content, name, functionCalls }, sessionId) {
3257
- const items = this.get(sessionId);
3258
- const lastItem = items.at(-1);
3259
- if (!lastItem || lastItem.role !== "assistant") {
3260
- this.addResult({ content, name, functionCalls }, sessionId);
3267
+ updateResult({
3268
+ content,
3269
+ name,
3270
+ functionCalls
3271
+ }) {
3272
+ const lastItem = this.data.at(-1);
3273
+ if (!lastItem || lastItem.chat.role !== "assistant") {
3274
+ this.addResult({ content, name, functionCalls });
3261
3275
  return;
3262
3276
  }
3263
- if ("content" in lastItem && content) {
3264
- lastItem.content = content;
3277
+ if ("content" in lastItem.chat && content) {
3278
+ lastItem.chat.content = content;
3279
+ }
3280
+ if ("name" in lastItem.chat && name) {
3281
+ lastItem.chat.name = name;
3265
3282
  }
3266
- if ("name" in lastItem && name) {
3267
- lastItem.name = name;
3283
+ if ("functionCalls" in lastItem.chat && functionCalls) {
3284
+ lastItem.chat.functionCalls = functionCalls;
3285
+ }
3286
+ }
3287
+ addTag(name) {
3288
+ const lastItem = this.data.at(-1);
3289
+ if (!lastItem) {
3290
+ return;
3291
+ }
3292
+ if (!lastItem.tags) {
3293
+ lastItem.tags = [];
3294
+ }
3295
+ if (!lastItem.tags.includes(name)) {
3296
+ lastItem.tags.push(name);
3297
+ }
3298
+ }
3299
+ rewindToTag(name) {
3300
+ const tagIndex = this.data.findIndex((item) => item.tags?.includes(name));
3301
+ if (tagIndex === -1) {
3302
+ throw new Error(`Tag "${name}" not found`);
3303
+ }
3304
+ const removedItems = this.data.splice(tagIndex);
3305
+ return removedItems.map((item) => item.chat);
3306
+ }
3307
+ removeByTag(name) {
3308
+ const indices = this.data.reduce((acc, item, index) => {
3309
+ if (item.tags?.includes(name)) {
3310
+ acc.push(index);
3311
+ }
3312
+ return acc;
3313
+ }, []);
3314
+ if (indices.length === 0) {
3315
+ throw new Error(`No items found with tag "${name}"`);
3316
+ }
3317
+ return indices.reverse().map((index) => this.data.splice(index, 1).at(0)?.chat).filter(Boolean).reverse();
3318
+ }
3319
+ history() {
3320
+ return this.data.map((item) => item.chat);
3321
+ }
3322
+ getLast() {
3323
+ const lastItem = this.data.at(-1);
3324
+ return lastItem?.chat;
3325
+ }
3326
+ reset() {
3327
+ this.data = [];
3328
+ }
3329
+ };
3330
+ var AxMemory = class {
3331
+ constructor(limit = defaultLimit) {
3332
+ this.limit = limit;
3333
+ this.defaultMemory = new MemoryImpl(limit);
3334
+ }
3335
+ memories = /* @__PURE__ */ new Map();
3336
+ defaultMemory;
3337
+ getMemory(sessionId) {
3338
+ if (!sessionId) {
3339
+ return this.defaultMemory;
3268
3340
  }
3269
- if ("functionCalls" in lastItem && functionCalls) {
3270
- lastItem.functionCalls = functionCalls;
3341
+ if (!this.memories.has(sessionId)) {
3342
+ this.memories.set(sessionId, new MemoryImpl(this.limit));
3271
3343
  }
3344
+ return this.memories.get(sessionId);
3345
+ }
3346
+ add(value, sessionId) {
3347
+ this.getMemory(sessionId).add(value);
3348
+ }
3349
+ addResult(result, sessionId) {
3350
+ this.getMemory(sessionId).addResult(result);
3351
+ }
3352
+ updateResult(result, sessionId) {
3353
+ this.getMemory(sessionId).updateResult(result);
3354
+ }
3355
+ addTag(name, sessionId) {
3356
+ this.getMemory(sessionId).addTag(name);
3357
+ }
3358
+ rewindToTag(name, sessionId) {
3359
+ return this.getMemory(sessionId).rewindToTag(name);
3272
3360
  }
3273
3361
  history(sessionId) {
3274
- return this.get(sessionId);
3362
+ return this.getMemory(sessionId).history();
3275
3363
  }
3276
3364
  getLast(sessionId) {
3277
- const d = this.get(sessionId);
3278
- return d.at(-1);
3365
+ return this.getMemory(sessionId).getLast();
3279
3366
  }
3280
3367
  reset(sessionId) {
3281
3368
  if (!sessionId) {
3282
- this.data = [];
3369
+ this.defaultMemory.reset();
3283
3370
  } else {
3284
- this.sdata.set(sessionId, []);
3371
+ this.memories.set(sessionId, new MemoryImpl(this.limit));
3285
3372
  }
3286
3373
  }
3287
- get(sessionId) {
3288
- if (!sessionId) {
3289
- return this.data;
3290
- }
3291
- if (!this.sdata.has(sessionId)) {
3292
- this.sdata.set(sessionId, []);
3293
- }
3294
- return this.sdata.get(sessionId) || [];
3295
- }
3296
3374
  };
3297
3375
 
3298
3376
  // dsp/asserts.ts
@@ -3312,12 +3390,11 @@ var AxAssertionError = class extends Error {
3312
3390
  }
3313
3391
  getValue = () => this.values;
3314
3392
  getOptional = () => this.optional;
3315
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
3316
- getFixingInstructions = (_sig) => {
3393
+ getFixingInstructions = () => {
3317
3394
  const extraFields = [];
3318
3395
  extraFields.push({
3319
3396
  name: "error",
3320
- title: "Error",
3397
+ title: "Error In Output",
3321
3398
  description: this.message
3322
3399
  });
3323
3400
  return extraFields;
@@ -3326,17 +3403,12 @@ var AxAssertionError = class extends Error {
3326
3403
  var assertAssertions = (asserts, values) => {
3327
3404
  for (const assert of asserts) {
3328
3405
  const { fn, message, optional } = assert;
3329
- try {
3330
- const res = fn(values);
3331
- if (res === void 0) {
3332
- continue;
3333
- }
3334
- if (!res && message) {
3335
- throw new AxAssertionError({ message, values, optional });
3336
- }
3337
- } catch (e) {
3338
- const message2 = e.message;
3339
- throw new AxAssertionError({ message: message2, values, optional });
3406
+ const res = fn(values);
3407
+ if (res === void 0) {
3408
+ continue;
3409
+ }
3410
+ if (!res && message) {
3411
+ throw new AxAssertionError({ message, values, optional });
3340
3412
  }
3341
3413
  }
3342
3414
  };
@@ -3353,17 +3425,12 @@ var assertStreamingAssertions = (asserts, values, xstate, content, final) => {
3353
3425
  const currValue = content.substring(xstate.s);
3354
3426
  for (const assert of fieldAsserts) {
3355
3427
  const { message, optional, fn } = assert;
3356
- try {
3357
- const res = fn(currValue, final);
3358
- if (res === void 0) {
3359
- continue;
3360
- }
3361
- if (!res && message) {
3362
- throw new AxAssertionError({ message, values, optional });
3363
- }
3364
- } catch (e) {
3365
- const message2 = e.message;
3366
- throw new AxAssertionError({ message: message2, values, optional });
3428
+ const res = fn(currValue, final);
3429
+ if (res === void 0) {
3430
+ continue;
3431
+ }
3432
+ if (!res && message) {
3433
+ throw new AxAssertionError({ message, values, optional });
3367
3434
  }
3368
3435
  }
3369
3436
  };
@@ -4125,7 +4192,7 @@ var AxPromptTemplate = class {
4125
4192
  const inArgs = this.renderDescFields(this.sig.getInputFields());
4126
4193
  const outArgs = this.renderDescFields(this.sig.getOutputFields());
4127
4194
  const task = [
4128
- `You will be provided with the following fields: ${inArgs}. Your task is to generate two new fields: ${outArgs}.`
4195
+ `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
4129
4196
  ];
4130
4197
  const funcs = functions?.map(
4131
4198
  (f) => "toFunction" in f ? f.toFunction() : f
@@ -4457,7 +4524,7 @@ function capitalizeFirstLetter(str) {
4457
4524
  }
4458
4525
 
4459
4526
  // dsp/validate.ts
4460
- var AxValidationError = class extends Error {
4527
+ var ValidationError = class extends Error {
4461
4528
  field;
4462
4529
  value;
4463
4530
  constructor({
@@ -4477,9 +4544,9 @@ var AxValidationError = class extends Error {
4477
4544
  const f = this.field;
4478
4545
  const extraFields = [
4479
4546
  {
4480
- name: `invalidField`,
4481
- title: `Invalid Field`,
4482
- description: `Ensure the field \`${f.title}\` is of type \`${toFieldType(f.type)}\``
4547
+ name: `outputError`,
4548
+ title: `Invalid Output Field`,
4549
+ description: `Invalid format for field \`${f.title}\` of type \`${toFieldType(f.type)}\`, format should match: \`${f.description}\``
4483
4550
  }
4484
4551
  ];
4485
4552
  return extraFields;
@@ -4492,7 +4559,7 @@ function parseLLMFriendlyDate(field, dateStr) {
4492
4559
  return _parseLLMFriendlyDate(dateStr);
4493
4560
  } catch (err) {
4494
4561
  const message = err.message;
4495
- throw new AxValidationError({ field, message, value: dateStr });
4562
+ throw new ValidationError({ field, message, value: dateStr });
4496
4563
  }
4497
4564
  }
4498
4565
  function _parseLLMFriendlyDate(dateStr) {
@@ -4509,7 +4576,7 @@ function parseLLMFriendlyDateTime(field, dateStr) {
4509
4576
  return _parseLLMFriendlyDateTime(dateStr);
4510
4577
  } catch (err) {
4511
4578
  const message = err.message;
4512
- throw new AxValidationError({ field, message, value: dateStr });
4579
+ throw new ValidationError({ field, message, value: dateStr });
4513
4580
  }
4514
4581
  }
4515
4582
  function _parseLLMFriendlyDateTime(dateTimeStr) {
@@ -4626,7 +4693,7 @@ var convertValueToType = (field, val) => {
4626
4693
  var expectedTypeError = (field, err, value = "") => {
4627
4694
  const exp = field.type?.isArray ? `array of ${field.type.name}` : field.type?.name;
4628
4695
  const message = `Error '${err.message}', expected '${exp}' got '${value}'`;
4629
- return new AxValidationError({ message, field, value });
4696
+ return new ValidationError({ message, field, value });
4630
4697
  };
4631
4698
  function validateAndParseFieldValue(field, fieldValue) {
4632
4699
  const fv = fieldValue?.toLocaleLowerCase();
@@ -4842,6 +4909,7 @@ function parseFunctionCalls(ai, functionCalls, values, model) {
4842
4909
  }
4843
4910
 
4844
4911
  // dsp/generate.ts
4912
+ var colorLog4 = new ColorLog();
4845
4913
  var AxGen = class extends AxProgramWithSignature {
4846
4914
  promptTemplate;
4847
4915
  asserts;
@@ -5058,7 +5126,7 @@ var AxGen = class extends AxProgramWithSignature {
5058
5126
  }
5059
5127
  async _forward(ai, values, options, span) {
5060
5128
  const stopFunction = (options?.stopFunction ?? this.options?.stopFunction)?.toLowerCase();
5061
- const maxRetries = options?.maxRetries ?? this.options?.maxRetries ?? 15;
5129
+ const maxRetries = options?.maxRetries ?? this.options?.maxRetries ?? 3;
5062
5130
  const maxSteps = options?.maxSteps ?? this.options?.maxSteps ?? 10;
5063
5131
  const mem = options?.mem ?? this.options?.mem ?? new AxMemory();
5064
5132
  let err;
@@ -5075,7 +5143,7 @@ var AxGen = class extends AxProgramWithSignature {
5075
5143
  });
5076
5144
  mem.add(prompt, options?.sessionId);
5077
5145
  multiStepLoop: for (let n = 0; n < maxSteps; n++) {
5078
- for (let i = 0; i < maxRetries; i++) {
5146
+ for (let errCount = 0; errCount < maxRetries; errCount++) {
5079
5147
  try {
5080
5148
  const output = await this.forwardCore({
5081
5149
  options,
@@ -5083,35 +5151,49 @@ var AxGen = class extends AxProgramWithSignature {
5083
5151
  mem
5084
5152
  });
5085
5153
  const lastMemItem = mem.getLast(options?.sessionId);
5086
- const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
5087
- if (lastMemItem?.role === "function") {
5088
- if (!stopFunction || !stopFunctionExecuted) {
5089
- continue multiStepLoop;
5154
+ if (lastMemItem) {
5155
+ const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
5156
+ if (lastMemItem.role === "function") {
5157
+ if (!stopFunction || !stopFunctionExecuted) {
5158
+ continue multiStepLoop;
5159
+ }
5160
+ }
5161
+ if (!stopFunctionExecuted) {
5162
+ assertRequiredFields(this.signature, output);
5090
5163
  }
5091
- }
5092
- if (!stopFunctionExecuted) {
5093
- assertRequiredFields(this.signature, output);
5094
5164
  }
5095
5165
  this.trace = { ...values, ...output };
5096
5166
  return output;
5097
5167
  } catch (e) {
5098
- let extraFields;
5168
+ let errorFields;
5099
5169
  span?.recordException(e);
5100
- if (e instanceof AxValidationError) {
5101
- extraFields = e.getFixingInstructions();
5170
+ if (e instanceof ValidationError) {
5171
+ errorFields = e.getFixingInstructions();
5102
5172
  err = e;
5103
5173
  } else if (e instanceof AxAssertionError) {
5104
5174
  const e1 = e;
5105
- extraFields = e1.getFixingInstructions(this.signature);
5175
+ errorFields = e1.getFixingInstructions();
5106
5176
  err = e;
5107
5177
  } else {
5108
5178
  throw e;
5109
5179
  }
5110
- if (extraFields) {
5111
- const content = this.promptTemplate.renderExtraFields(extraFields);
5112
- mem.add({ role: "user", content }, options?.sessionId);
5113
- if (options?.debug) {
5114
- console.log("Error Correction:", content);
5180
+ if (errorFields) {
5181
+ mem.add(
5182
+ {
5183
+ role: "user",
5184
+ content: this.promptTemplate.renderExtraFields(errorFields)
5185
+ },
5186
+ options?.sessionId
5187
+ );
5188
+ mem.addTag("error");
5189
+ if (ai.getOptions().debug) {
5190
+ process.stdout.write(
5191
+ colorLog4.red(
5192
+ `Error Correction:
5193
+ ${JSON.stringify(errorFields, null, 2)}
5194
+ `
5195
+ )
5196
+ );
5115
5197
  }
5116
5198
  }
5117
5199
  }
@@ -5417,6 +5499,9 @@ var AxBalancer = class {
5417
5499
  setOptions(options) {
5418
5500
  this.currentService.setOptions(options);
5419
5501
  }
5502
+ getOptions() {
5503
+ return this.currentService.getOptions();
5504
+ }
5420
5505
  };
5421
5506
 
5422
5507
  // dsp/optimize.ts
@@ -6622,7 +6707,7 @@ var AxJSInterpreter = class {
6622
6707
  };
6623
6708
 
6624
6709
  // dsp/router.ts
6625
- var colorLog4 = new ColorLog();
6710
+ var colorLog5 = new ColorLog();
6626
6711
  var AxRoute = class {
6627
6712
  name;
6628
6713
  context;
@@ -6674,7 +6759,7 @@ var AxRouter = class {
6674
6759
  }
6675
6760
  if (this.debug) {
6676
6761
  console.log(
6677
- colorLog4.whiteBright(`query: ${text}`) + "\n" + colorLog4.greenBright(
6762
+ colorLog5.whiteBright(`query: ${text}`) + "\n" + colorLog5.greenBright(
6678
6763
  JSON.stringify(m.map((m2) => `${m2.id}, ${m2.score}`))
6679
6764
  )
6680
6765
  );
@@ -6988,7 +7073,6 @@ var AxRAG = class extends AxChainOfThought {
6988
7073
  AxRouter,
6989
7074
  AxSignature,
6990
7075
  AxSpanKindValues,
6991
- AxTestPrompt,
6992
- AxValidationError
7076
+ AxTestPrompt
6993
7077
  });
6994
7078
  //# sourceMappingURL=index.cjs.map