@ax-llm/ax 12.0.4 → 12.0.5

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
@@ -8196,7 +8196,7 @@ var AxSignature = class _AxSignature {
8196
8196
  });
8197
8197
  this.inputFields = parsedFields;
8198
8198
  this.invalidateValidationCache();
8199
- this.updateHash();
8199
+ this.updateHashLight();
8200
8200
  } catch (error) {
8201
8201
  if (error instanceof AxSignatureValidationError) {
8202
8202
  throw error;
@@ -8222,7 +8222,7 @@ var AxSignature = class _AxSignature {
8222
8222
  });
8223
8223
  this.outputFields = parsedFields;
8224
8224
  this.invalidateValidationCache();
8225
- this.updateHash();
8225
+ this.updateHashLight();
8226
8226
  } catch (error) {
8227
8227
  if (error instanceof AxSignatureValidationError) {
8228
8228
  throw error;
@@ -9990,219 +9990,6 @@ function validateModels2(services) {
9990
9990
  }
9991
9991
  }
9992
9992
 
9993
- // dsp/optimize.ts
9994
- var AxBootstrapFewShot = class {
9995
- ai;
9996
- teacherAI;
9997
- program;
9998
- examples;
9999
- maxRounds;
10000
- maxDemos;
10001
- maxExamples;
10002
- batchSize;
10003
- earlyStoppingPatience;
10004
- costMonitoring;
10005
- maxTokensPerGeneration;
10006
- verboseMode;
10007
- debugMode;
10008
- traces = [];
10009
- stats = {
10010
- totalCalls: 0,
10011
- successfulDemos: 0,
10012
- estimatedTokenUsage: 0,
10013
- earlyStopped: false
10014
- };
10015
- constructor({
10016
- ai,
10017
- program,
10018
- examples = [],
10019
- options
10020
- }) {
10021
- if (examples.length === 0) {
10022
- throw new Error("No examples found");
10023
- }
10024
- this.maxRounds = options?.maxRounds ?? 3;
10025
- this.maxDemos = options?.maxDemos ?? 4;
10026
- this.maxExamples = options?.maxExamples ?? 16;
10027
- this.batchSize = options?.batchSize ?? 1;
10028
- this.earlyStoppingPatience = options?.earlyStoppingPatience ?? 0;
10029
- this.costMonitoring = options?.costMonitoring ?? false;
10030
- this.maxTokensPerGeneration = options?.maxTokensPerGeneration ?? 0;
10031
- this.verboseMode = options?.verboseMode ?? true;
10032
- this.debugMode = options?.debugMode ?? false;
10033
- this.ai = ai;
10034
- this.teacherAI = options?.teacherAI;
10035
- this.program = program;
10036
- this.examples = examples;
10037
- }
10038
- async compileRound(roundIndex, metricFn, options) {
10039
- const st = (/* @__PURE__ */ new Date()).getTime();
10040
- const maxDemos = options?.maxDemos ?? this.maxDemos;
10041
- const aiOpt = {
10042
- modelConfig: {
10043
- temperature: 0.7
10044
- }
10045
- };
10046
- if (this.maxTokensPerGeneration > 0) {
10047
- aiOpt.modelConfig.max_tokens = this.maxTokensPerGeneration;
10048
- }
10049
- const examples = randomSample(this.examples, this.maxExamples);
10050
- const previousSuccessCount = this.traces.length;
10051
- for (let i = 0; i < examples.length; i += this.batchSize) {
10052
- if (i > 0) {
10053
- aiOpt.modelConfig.temperature = 0.7 + 1e-3 * i;
10054
- }
10055
- const batch = examples.slice(i, i + this.batchSize);
10056
- for (const ex of batch) {
10057
- if (!ex) {
10058
- continue;
10059
- }
10060
- const exList = examples.filter((e) => e !== ex);
10061
- this.program.setExamples(exList);
10062
- const aiService = this.teacherAI || this.ai;
10063
- this.stats.totalCalls++;
10064
- let res;
10065
- let error;
10066
- try {
10067
- res = await this.program.forward(aiService, ex, aiOpt);
10068
- if (this.costMonitoring) {
10069
- this.stats.estimatedTokenUsage += JSON.stringify(ex).length / 4 + JSON.stringify(res).length / 4;
10070
- }
10071
- const score = metricFn({ prediction: res, example: ex });
10072
- const success = score >= 0.5;
10073
- if (success) {
10074
- this.traces = [...this.traces, ...this.program.getTraces()];
10075
- this.stats.successfulDemos++;
10076
- }
10077
- } catch (err) {
10078
- error = err;
10079
- res = {};
10080
- }
10081
- const current = i + examples.length * roundIndex + (batch.indexOf(ex) + 1);
10082
- const total = examples.length * this.maxRounds;
10083
- const et = (/* @__PURE__ */ new Date()).getTime() - st;
10084
- if (this.verboseMode || this.debugMode) {
10085
- const configInfo = {
10086
- maxRounds: this.maxRounds,
10087
- batchSize: this.batchSize,
10088
- earlyStoppingPatience: this.earlyStoppingPatience,
10089
- costMonitoring: this.costMonitoring,
10090
- verboseMode: this.verboseMode,
10091
- debugMode: this.debugMode
10092
- };
10093
- updateDetailedProgress(
10094
- roundIndex,
10095
- current,
10096
- total,
10097
- et,
10098
- ex,
10099
- this.stats,
10100
- configInfo,
10101
- res,
10102
- error
10103
- );
10104
- } else {
10105
- updateProgressBar(
10106
- current,
10107
- total,
10108
- this.traces.length,
10109
- et,
10110
- "Tuning Prompt",
10111
- 30
10112
- );
10113
- }
10114
- if (this.traces.length >= maxDemos) {
10115
- return;
10116
- }
10117
- }
10118
- }
10119
- if (this.earlyStoppingPatience > 0) {
10120
- const newSuccessCount = this.traces.length;
10121
- const improvement = newSuccessCount - previousSuccessCount;
10122
- if (!this.stats.earlyStopping) {
10123
- this.stats.earlyStopping = {
10124
- bestScoreRound: improvement > 0 ? roundIndex : 0,
10125
- patienceExhausted: false
10126
- };
10127
- } else if (improvement > 0) {
10128
- this.stats.earlyStopping.bestScoreRound = roundIndex;
10129
- } else if (roundIndex - this.stats.earlyStopping.bestScoreRound >= this.earlyStoppingPatience) {
10130
- this.stats.earlyStopping.patienceExhausted = true;
10131
- this.stats.earlyStopped = true;
10132
- if (this.verboseMode || this.debugMode) {
10133
- console.log(
10134
- `
10135
- Early stopping triggered after ${roundIndex + 1} rounds. No improvement for ${this.earlyStoppingPatience} rounds.`
10136
- );
10137
- }
10138
- return;
10139
- }
10140
- }
10141
- }
10142
- async compile(metricFn, options) {
10143
- const maxRounds = options?.maxRounds ?? this.maxRounds;
10144
- this.traces = [];
10145
- this.stats = {
10146
- totalCalls: 0,
10147
- successfulDemos: 0,
10148
- estimatedTokenUsage: 0,
10149
- earlyStopped: false
10150
- };
10151
- for (let i = 0; i < maxRounds; i++) {
10152
- await this.compileRound(i, metricFn, options);
10153
- if (this.stats.earlyStopped) {
10154
- break;
10155
- }
10156
- }
10157
- if (this.traces.length === 0) {
10158
- throw new Error(
10159
- "No demonstrations found. Either provider more examples or improve the existing ones."
10160
- );
10161
- }
10162
- const demos = groupTracesByKeys(this.traces);
10163
- return {
10164
- demos,
10165
- stats: this.stats
10166
- };
10167
- }
10168
- // Get optimization statistics
10169
- getStats() {
10170
- return this.stats;
10171
- }
10172
- };
10173
- function groupTracesByKeys(programTraces) {
10174
- const groupedTraces = /* @__PURE__ */ new Map();
10175
- for (const programTrace of programTraces) {
10176
- if (groupedTraces.has(programTrace.programId)) {
10177
- const traces = groupedTraces.get(programTrace.programId);
10178
- if (traces) {
10179
- traces.push(programTrace.trace);
10180
- }
10181
- } else {
10182
- groupedTraces.set(programTrace.programId, [programTrace.trace]);
10183
- }
10184
- }
10185
- const programDemosArray = [];
10186
- for (const [programId, traces] of groupedTraces.entries()) {
10187
- programDemosArray.push({ traces, programId });
10188
- }
10189
- return programDemosArray;
10190
- }
10191
- var randomSample = (array, n) => {
10192
- const clonedArray = [...array];
10193
- for (let i = clonedArray.length - 1; i > 0; i--) {
10194
- const j = Math.floor(Math.random() * (i + 1));
10195
- const caI = clonedArray[i];
10196
- const caJ = clonedArray[j];
10197
- if (!caI || !caJ) {
10198
- throw new Error("Invalid array elements");
10199
- }
10200
- ;
10201
- [clonedArray[i], clonedArray[j]] = [caJ, caI];
10202
- }
10203
- return clonedArray.slice(0, n);
10204
- };
10205
-
10206
9993
  // db/base.ts
10207
9994
  import { SpanKind as SpanKind3 } from "@opentelemetry/api";
10208
9995
  var AxDBBase = class {
@@ -11661,7 +11448,222 @@ var AxMCPStreambleHTTPTransport = class {
11661
11448
  }
11662
11449
  };
11663
11450
 
11664
- // dsp/mipro.ts
11451
+ // dsp/optimizers/bootstrapFewshot.ts
11452
+ var AxBootstrapFewShot = class {
11453
+ ai;
11454
+ teacherAI;
11455
+ program;
11456
+ examples;
11457
+ maxRounds;
11458
+ maxDemos;
11459
+ maxExamples;
11460
+ batchSize;
11461
+ earlyStoppingPatience;
11462
+ costMonitoring;
11463
+ maxTokensPerGeneration;
11464
+ verboseMode;
11465
+ debugMode;
11466
+ traces = [];
11467
+ stats = {
11468
+ totalCalls: 0,
11469
+ successfulDemos: 0,
11470
+ estimatedTokenUsage: 0,
11471
+ earlyStopped: false
11472
+ };
11473
+ constructor({
11474
+ ai,
11475
+ program,
11476
+ examples = [],
11477
+ options
11478
+ }) {
11479
+ if (examples.length === 0) {
11480
+ throw new Error("No examples found");
11481
+ }
11482
+ const bootstrapOptions = options;
11483
+ this.maxRounds = bootstrapOptions?.maxRounds ?? 3;
11484
+ this.maxDemos = bootstrapOptions?.maxDemos ?? 4;
11485
+ this.maxExamples = bootstrapOptions?.maxExamples ?? 16;
11486
+ this.batchSize = bootstrapOptions?.batchSize ?? 1;
11487
+ this.earlyStoppingPatience = bootstrapOptions?.earlyStoppingPatience ?? 0;
11488
+ this.costMonitoring = bootstrapOptions?.costMonitoring ?? false;
11489
+ this.maxTokensPerGeneration = bootstrapOptions?.maxTokensPerGeneration ?? 0;
11490
+ this.verboseMode = bootstrapOptions?.verboseMode ?? true;
11491
+ this.debugMode = bootstrapOptions?.debugMode ?? false;
11492
+ this.ai = ai;
11493
+ this.teacherAI = bootstrapOptions?.teacherAI;
11494
+ this.program = program;
11495
+ this.examples = examples;
11496
+ }
11497
+ async compileRound(roundIndex, metricFn, options) {
11498
+ const st = (/* @__PURE__ */ new Date()).getTime();
11499
+ const maxDemos = options?.maxDemos ?? this.maxDemos;
11500
+ const aiOpt = {
11501
+ modelConfig: {
11502
+ temperature: 0.7
11503
+ }
11504
+ };
11505
+ if (this.maxTokensPerGeneration > 0) {
11506
+ aiOpt.modelConfig.max_tokens = this.maxTokensPerGeneration;
11507
+ }
11508
+ const examples = randomSample(this.examples, this.maxExamples);
11509
+ const previousSuccessCount = this.traces.length;
11510
+ for (let i = 0; i < examples.length; i += this.batchSize) {
11511
+ if (i > 0) {
11512
+ aiOpt.modelConfig.temperature = 0.7 + 1e-3 * i;
11513
+ }
11514
+ const batch = examples.slice(i, i + this.batchSize);
11515
+ for (const ex of batch) {
11516
+ if (!ex) {
11517
+ continue;
11518
+ }
11519
+ const exList = examples.filter((e) => e !== ex);
11520
+ this.program.setExamples(exList);
11521
+ const aiService = this.teacherAI || this.ai;
11522
+ this.stats.totalCalls++;
11523
+ let res;
11524
+ let error;
11525
+ try {
11526
+ res = await this.program.forward(aiService, ex, aiOpt);
11527
+ if (this.costMonitoring) {
11528
+ this.stats.estimatedTokenUsage += JSON.stringify(ex).length / 4 + JSON.stringify(res).length / 4;
11529
+ }
11530
+ const score = metricFn({ prediction: res, example: ex });
11531
+ const success = score >= 0.5;
11532
+ if (success) {
11533
+ this.traces = [...this.traces, ...this.program.getTraces()];
11534
+ this.stats.successfulDemos++;
11535
+ }
11536
+ } catch (err) {
11537
+ error = err;
11538
+ res = {};
11539
+ }
11540
+ const current = i + examples.length * roundIndex + (batch.indexOf(ex) + 1);
11541
+ const total = examples.length * this.maxRounds;
11542
+ const et = (/* @__PURE__ */ new Date()).getTime() - st;
11543
+ if (this.verboseMode || this.debugMode) {
11544
+ const configInfo = {
11545
+ maxRounds: this.maxRounds,
11546
+ batchSize: this.batchSize,
11547
+ earlyStoppingPatience: this.earlyStoppingPatience,
11548
+ costMonitoring: this.costMonitoring,
11549
+ verboseMode: this.verboseMode,
11550
+ debugMode: this.debugMode
11551
+ };
11552
+ updateDetailedProgress(
11553
+ roundIndex,
11554
+ current,
11555
+ total,
11556
+ et,
11557
+ ex,
11558
+ this.stats,
11559
+ configInfo,
11560
+ res,
11561
+ error
11562
+ );
11563
+ } else {
11564
+ updateProgressBar(
11565
+ current,
11566
+ total,
11567
+ this.traces.length,
11568
+ et,
11569
+ "Tuning Prompt",
11570
+ 30
11571
+ );
11572
+ }
11573
+ if (this.traces.length >= maxDemos) {
11574
+ return;
11575
+ }
11576
+ }
11577
+ }
11578
+ if (this.earlyStoppingPatience > 0) {
11579
+ const newSuccessCount = this.traces.length;
11580
+ const improvement = newSuccessCount - previousSuccessCount;
11581
+ if (!this.stats.earlyStopping) {
11582
+ this.stats.earlyStopping = {
11583
+ bestScoreRound: improvement > 0 ? roundIndex : 0,
11584
+ patienceExhausted: false
11585
+ };
11586
+ } else if (improvement > 0) {
11587
+ this.stats.earlyStopping.bestScoreRound = roundIndex;
11588
+ } else if (roundIndex - this.stats.earlyStopping.bestScoreRound >= this.earlyStoppingPatience) {
11589
+ this.stats.earlyStopping.patienceExhausted = true;
11590
+ this.stats.earlyStopped = true;
11591
+ if (this.verboseMode || this.debugMode) {
11592
+ console.log(
11593
+ `
11594
+ Early stopping triggered after ${roundIndex + 1} rounds. No improvement for ${this.earlyStoppingPatience} rounds.`
11595
+ );
11596
+ }
11597
+ return;
11598
+ }
11599
+ }
11600
+ }
11601
+ async compile(metricFn, options) {
11602
+ const compileOptions = options;
11603
+ const maxRounds = compileOptions?.maxRounds ?? this.maxRounds;
11604
+ this.traces = [];
11605
+ this.stats = {
11606
+ totalCalls: 0,
11607
+ successfulDemos: 0,
11608
+ estimatedTokenUsage: 0,
11609
+ earlyStopped: false
11610
+ };
11611
+ for (let i = 0; i < maxRounds; i++) {
11612
+ await this.compileRound(i, metricFn, compileOptions);
11613
+ if (this.stats.earlyStopped) {
11614
+ break;
11615
+ }
11616
+ }
11617
+ if (this.traces.length === 0) {
11618
+ throw new Error(
11619
+ "No demonstrations found. Either provider more examples or improve the existing ones."
11620
+ );
11621
+ }
11622
+ const demos = groupTracesByKeys(this.traces);
11623
+ return {
11624
+ demos,
11625
+ stats: this.stats
11626
+ };
11627
+ }
11628
+ // Get optimization statistics
11629
+ getStats() {
11630
+ return this.stats;
11631
+ }
11632
+ };
11633
+ function groupTracesByKeys(programTraces) {
11634
+ const groupedTraces = /* @__PURE__ */ new Map();
11635
+ for (const programTrace of programTraces) {
11636
+ if (groupedTraces.has(programTrace.programId)) {
11637
+ const traces = groupedTraces.get(programTrace.programId);
11638
+ if (traces) {
11639
+ traces.push(programTrace.trace);
11640
+ }
11641
+ } else {
11642
+ groupedTraces.set(programTrace.programId, [programTrace.trace]);
11643
+ }
11644
+ }
11645
+ const programDemosArray = [];
11646
+ for (const [programId, traces] of groupedTraces.entries()) {
11647
+ programDemosArray.push({ traces, programId });
11648
+ }
11649
+ return programDemosArray;
11650
+ }
11651
+ var randomSample = (array, n) => {
11652
+ const clonedArray = [...array];
11653
+ for (let i = clonedArray.length - 1; i > 0; i--) {
11654
+ const j = Math.floor(Math.random() * (i + 1));
11655
+ const caI = clonedArray[i];
11656
+ const caJ = clonedArray[j];
11657
+ if (!caI || !caJ) {
11658
+ throw new Error("Invalid array elements");
11659
+ }
11660
+ ;
11661
+ [clonedArray[i], clonedArray[j]] = [caJ, caI];
11662
+ }
11663
+ return clonedArray.slice(0, n);
11664
+ };
11665
+
11666
+ // dsp/optimizers/miproV2.ts
11665
11667
  var AxMiPRO = class {
11666
11668
  ai;
11667
11669
  program;
@@ -11887,7 +11889,7 @@ ${dataContext}
11887
11889
  const result = await this.bootstrapper.compile(metricFn, {
11888
11890
  maxDemos: this.maxBootstrappedDemos
11889
11891
  });
11890
- return result.demos;
11892
+ return result.demos || [];
11891
11893
  }
11892
11894
  /**
11893
11895
  * Selects labeled examples directly from the training set
@@ -12221,21 +12223,22 @@ ${dataContext}
12221
12223
  * The main compile method to run MIPROv2 optimization
12222
12224
  * @param metricFn Evaluation metric function
12223
12225
  * @param options Optional configuration options
12224
- * @returns The optimized program
12226
+ * @returns The optimization result
12225
12227
  */
12226
12228
  async compile(metricFn, options) {
12227
- if (options?.auto) {
12228
- this.configureAuto(options.auto);
12229
+ const miproOptions = options;
12230
+ if (miproOptions?.auto) {
12231
+ this.configureAuto(miproOptions.auto);
12229
12232
  }
12230
12233
  const trainset = this.examples;
12231
- const valset = options?.valset || this.examples.slice(0, Math.floor(this.examples.length * 0.8));
12234
+ const valset = miproOptions?.valset || this.examples.slice(0, Math.floor(this.examples.length * 0.8));
12232
12235
  if (this.verbose) {
12233
12236
  console.log(`Starting MIPROv2 optimization with ${this.numTrials} trials`);
12234
12237
  console.log(
12235
12238
  `Using ${trainset.length} examples for training and ${valset.length} for validation`
12236
12239
  );
12237
12240
  }
12238
- if (options?.teacher) {
12241
+ if (miproOptions?.teacher) {
12239
12242
  if (this.verbose) {
12240
12243
  console.log("Using provided teacher to assist with bootstrapping");
12241
12244
  }
@@ -12292,7 +12295,17 @@ ${dataContext}
12292
12295
  bootstrappedDemos,
12293
12296
  labeledExamples
12294
12297
  );
12295
- return this.program;
12298
+ return {
12299
+ program: this.program,
12300
+ demos: bootstrappedDemos
12301
+ };
12302
+ }
12303
+ /**
12304
+ * Get optimization statistics from the internal bootstrapper
12305
+ * @returns Optimization statistics or undefined if not available
12306
+ */
12307
+ getStats() {
12308
+ return this.bootstrapper.getStats();
12296
12309
  }
12297
12310
  };
12298
12311