@ax-llm/ax 11.0.26 → 11.0.28

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
@@ -85,6 +85,7 @@ __export(index_exports, {
85
85
  AxDefaultResultReranker: () => AxDefaultResultReranker,
86
86
  AxDockerSession: () => AxDockerSession,
87
87
  AxEmbeddingAdapter: () => AxEmbeddingAdapter,
88
+ AxEvalUtil: () => AxEvalUtil,
88
89
  AxFunctionError: () => AxFunctionError,
89
90
  AxFunctionProcessor: () => AxFunctionProcessor,
90
91
  AxGen: () => AxGen,
@@ -97,6 +98,7 @@ __export(index_exports, {
97
98
  AxMCPHTTPTransport: () => AxMCPHTTPTransport,
98
99
  AxMCPStdioTransport: () => AxMCPStdioTransport,
99
100
  AxMemory: () => AxMemory,
101
+ AxMiPRO: () => AxMiPRO,
100
102
  AxMockAIService: () => AxMockAIService,
101
103
  AxMultiServiceRouter: () => AxMultiServiceRouter,
102
104
  AxProgram: () => AxProgram,
@@ -108,7 +110,48 @@ __export(index_exports, {
108
110
  AxSimpleClassifier: () => AxSimpleClassifier,
109
111
  AxSimpleClassifierClass: () => AxSimpleClassifierClass,
110
112
  AxSpanKindValues: () => AxSpanKindValues,
111
- AxTestPrompt: () => AxTestPrompt
113
+ AxStringUtil: () => AxStringUtil,
114
+ AxTestPrompt: () => AxTestPrompt,
115
+ axAIAnthropicDefaultConfig: () => axAIAnthropicDefaultConfig,
116
+ axAIAzureOpenAIBestConfig: () => axAIAzureOpenAIBestConfig,
117
+ axAIAzureOpenAICreativeConfig: () => axAIAzureOpenAICreativeConfig,
118
+ axAIAzureOpenAIDefaultConfig: () => axAIAzureOpenAIDefaultConfig,
119
+ axAIAzureOpenAIFastConfig: () => axAIAzureOpenAIFastConfig,
120
+ axAICohereCreativeConfig: () => axAICohereCreativeConfig,
121
+ axAICohereDefaultConfig: () => axAICohereDefaultConfig,
122
+ axAIDeepSeekCodeConfig: () => axAIDeepSeekCodeConfig,
123
+ axAIDeepSeekDefaultConfig: () => axAIDeepSeekDefaultConfig,
124
+ axAIGoogleGeminiDefaultConfig: () => axAIGoogleGeminiDefaultConfig,
125
+ axAIGoogleGeminiDefaultCreativeConfig: () => axAIGoogleGeminiDefaultCreativeConfig,
126
+ axAIHuggingFaceCreativeConfig: () => axAIHuggingFaceCreativeConfig,
127
+ axAIHuggingFaceDefaultConfig: () => axAIHuggingFaceDefaultConfig,
128
+ axAIMistralBestConfig: () => axAIMistralBestConfig,
129
+ axAIMistralDefaultConfig: () => axAIMistralDefaultConfig,
130
+ axAIOllamaDefaultConfig: () => axAIOllamaDefaultConfig,
131
+ axAIOllamaDefaultCreativeConfig: () => axAIOllamaDefaultCreativeConfig,
132
+ axAIOpenAIBestConfig: () => axAIOpenAIBestConfig,
133
+ axAIOpenAICreativeConfig: () => axAIOpenAICreativeConfig,
134
+ axAIOpenAIDefaultConfig: () => axAIOpenAIDefaultConfig,
135
+ axAIOpenAIFastConfig: () => axAIOpenAIFastConfig,
136
+ axAIRekaBestConfig: () => axAIRekaBestConfig,
137
+ axAIRekaCreativeConfig: () => axAIRekaCreativeConfig,
138
+ axAIRekaDefaultConfig: () => axAIRekaDefaultConfig,
139
+ axAIRekaFastConfig: () => axAIRekaFastConfig,
140
+ axAITogetherDefaultConfig: () => axAITogetherDefaultConfig,
141
+ axBaseAIDefaultConfig: () => axBaseAIDefaultConfig,
142
+ axBaseAIDefaultCreativeConfig: () => axBaseAIDefaultCreativeConfig,
143
+ axModelInfoAnthropic: () => axModelInfoAnthropic,
144
+ axModelInfoCohere: () => axModelInfoCohere,
145
+ axModelInfoDeepSeek: () => axModelInfoDeepSeek,
146
+ axModelInfoGoogleGemini: () => axModelInfoGoogleGemini,
147
+ axModelInfoGroq: () => axModelInfoGroq,
148
+ axModelInfoHuggingFace: () => axModelInfoHuggingFace,
149
+ axModelInfoMistral: () => axModelInfoMistral,
150
+ axModelInfoOpenAI: () => axModelInfoOpenAI,
151
+ axModelInfoReka: () => axModelInfoReka,
152
+ axModelInfoTogether: () => axModelInfoTogether,
153
+ axSpanAttributes: () => axSpanAttributes,
154
+ axSpanEvents: () => axSpanEvents
112
155
  });
113
156
  module.exports = __toCommonJS(index_exports);
114
157
 
@@ -151,6 +194,9 @@ var axSpanAttributes = {
151
194
  DB_QUERY_RESULT_VECTOR: "db.query.result.vector",
152
195
  DB_QUERY_RESULT_DOCUMENT: "db.query.result.document"
153
196
  };
197
+ var axSpanEvents = {
198
+ LLM_PROMPT: "gen_ai.prompt"
199
+ };
154
200
  var AxLLMRequestTypeValues = /* @__PURE__ */ ((AxLLMRequestTypeValues2) => {
155
201
  AxLLMRequestTypeValues2["COMPLETION"] = "completion";
156
202
  AxLLMRequestTypeValues2["CHAT"] = "chat";
@@ -806,6 +852,12 @@ var axBaseAIDefaultConfig = () => structuredClone({
806
852
  topK: 40,
807
853
  topP: 0.9
808
854
  });
855
+ var axBaseAIDefaultCreativeConfig = () => structuredClone({
856
+ maxTokens: 2e3,
857
+ temperature: 0.4,
858
+ topP: 0.7,
859
+ frequencyPenalty: 0.2
860
+ });
809
861
  var AxBaseAI = class {
810
862
  constructor(aiImpl, {
811
863
  name,
@@ -1847,6 +1899,19 @@ var axAIOpenAIDefaultConfig = () => structuredClone({
1847
1899
  embedModel: "text-embedding-3-small" /* TextEmbedding3Small */,
1848
1900
  ...axBaseAIDefaultConfig()
1849
1901
  });
1902
+ var axAIOpenAIBestConfig = () => structuredClone({
1903
+ ...axAIOpenAIDefaultConfig(),
1904
+ model: "gpt-4o" /* GPT4O */
1905
+ });
1906
+ var axAIOpenAICreativeConfig = () => structuredClone({
1907
+ model: "gpt-4o" /* GPT4O */,
1908
+ embedModel: "text-embedding-3-small" /* TextEmbedding3Small */,
1909
+ ...axBaseAIDefaultCreativeConfig()
1910
+ });
1911
+ var axAIOpenAIFastConfig = () => ({
1912
+ ...axAIOpenAIDefaultConfig(),
1913
+ model: "gpt-4o-mini" /* GPT4OMini */
1914
+ });
1850
1915
  var AxAIOpenAIImpl = class {
1851
1916
  constructor(config, streamingUsage, dimensions) {
1852
1917
  this.config = config;
@@ -2152,6 +2217,9 @@ var AxAIOpenAI = class extends AxAIOpenAIBase {
2152
2217
 
2153
2218
  // ai/azure-openai/api.ts
2154
2219
  var axAIAzureOpenAIDefaultConfig = axAIOpenAIDefaultConfig;
2220
+ var axAIAzureOpenAICreativeConfig = axAIOpenAICreativeConfig;
2221
+ var axAIAzureOpenAIFastConfig = axAIOpenAIFastConfig;
2222
+ var axAIAzureOpenAIBestConfig = axAIOpenAIBestConfig;
2155
2223
  var AxAIAzureOpenAI = class extends AxAIOpenAIBase {
2156
2224
  constructor({
2157
2225
  apiKey,
@@ -2268,6 +2336,11 @@ var axAICohereDefaultConfig = () => structuredClone({
2268
2336
  embedModel: "embed-english-v3.0" /* EmbedEnglishV30 */,
2269
2337
  ...axBaseAIDefaultConfig()
2270
2338
  });
2339
+ var axAICohereCreativeConfig = () => structuredClone({
2340
+ model: "command-r" /* CommandR */,
2341
+ embedModel: "embed-english-v3.0" /* EmbedEnglishV30 */,
2342
+ ...axBaseAIDefaultCreativeConfig()
2343
+ });
2271
2344
  var AxAICohereImpl = class {
2272
2345
  constructor(config) {
2273
2346
  this.config = config;
@@ -2544,6 +2617,10 @@ var axAIDeepSeekDefaultConfig = () => structuredClone({
2544
2617
  model: "deepseek-chat" /* DeepSeekChat */,
2545
2618
  ...axBaseAIDefaultConfig()
2546
2619
  });
2620
+ var axAIDeepSeekCodeConfig = () => structuredClone({
2621
+ model: "deepseek-coder" /* DeepSeekCoder */,
2622
+ ...axBaseAIDefaultCreativeConfig()
2623
+ });
2547
2624
  var AxAIDeepSeek = class extends AxAIOpenAIBase {
2548
2625
  constructor({
2549
2626
  apiKey,
@@ -2691,6 +2768,12 @@ var axAIGoogleGeminiDefaultConfig = () => structuredClone({
2691
2768
  safetySettings,
2692
2769
  ...axBaseAIDefaultConfig()
2693
2770
  });
2771
+ var axAIGoogleGeminiDefaultCreativeConfig = () => structuredClone({
2772
+ model: "gemini-2.0-flash" /* Gemini20Flash */,
2773
+ embedModel: "text-embedding-004" /* TextEmbedding004 */,
2774
+ safetySettings,
2775
+ ...axBaseAIDefaultCreativeConfig()
2776
+ });
2694
2777
  var AxAIGoogleGeminiImpl = class {
2695
2778
  constructor(config, isVertex, endpointId, apiKey, options) {
2696
2779
  this.config = config;
@@ -3202,6 +3285,10 @@ var axAIHuggingFaceDefaultConfig = () => structuredClone({
3202
3285
  model: "meta-llama/Llama-2-70b-chat-hf" /* MetaLlama270BChatHF */,
3203
3286
  ...axBaseAIDefaultConfig()
3204
3287
  });
3288
+ var axAIHuggingFaceCreativeConfig = () => structuredClone({
3289
+ model: "meta-llama/Llama-2-70b-chat-hf" /* MetaLlama270BChatHF */,
3290
+ ...axBaseAIDefaultCreativeConfig()
3291
+ });
3205
3292
  var AxAIHuggingFaceImpl = class {
3206
3293
  constructor(config) {
3207
3294
  this.config = config;
@@ -3383,6 +3470,10 @@ var axAIMistralDefaultConfig = () => structuredClone({
3383
3470
  model: "mistral-small-latest" /* MistralSmall */,
3384
3471
  ...axBaseAIDefaultConfig()
3385
3472
  });
3473
+ var axAIMistralBestConfig = () => structuredClone({
3474
+ ...axAIMistralDefaultConfig(),
3475
+ model: "mistral-large-latest" /* MistralLarge */
3476
+ });
3386
3477
  var AxAIMistral = class extends AxAIOpenAIBase {
3387
3478
  constructor({
3388
3479
  apiKey,
@@ -3415,6 +3506,11 @@ var axAIOllamaDefaultConfig = () => structuredClone({
3415
3506
  model: "nous-hermes2",
3416
3507
  embedModel: "all-minilm"
3417
3508
  });
3509
+ var axAIOllamaDefaultCreativeConfig = () => structuredClone({
3510
+ ...axBaseAIDefaultCreativeConfig(),
3511
+ model: "nous-hermes2",
3512
+ embedModel: "all-minilm"
3513
+ });
3418
3514
  var AxAIOllama = class extends AxAIOpenAIBase {
3419
3515
  constructor({
3420
3516
  apiKey = "not-set",
@@ -3474,6 +3570,18 @@ var axAIRekaDefaultConfig = () => structuredClone({
3474
3570
  model: "reka-core" /* RekaCore */,
3475
3571
  ...axBaseAIDefaultConfig()
3476
3572
  });
3573
+ var axAIRekaBestConfig = () => structuredClone({
3574
+ ...axAIRekaDefaultConfig(),
3575
+ model: "reka-core" /* RekaCore */
3576
+ });
3577
+ var axAIRekaCreativeConfig = () => structuredClone({
3578
+ model: "reka-core" /* RekaCore */,
3579
+ ...axBaseAIDefaultCreativeConfig()
3580
+ });
3581
+ var axAIRekaFastConfig = () => ({
3582
+ ...axAIRekaDefaultConfig(),
3583
+ model: "reka-flash" /* RekaFlash */
3584
+ });
3477
3585
  var AxAIRekaImpl = class {
3478
3586
  constructor(config) {
3479
3587
  this.config = config;
@@ -4678,16 +4786,19 @@ var validateValue = (field, value) => {
4678
4786
  };
4679
4787
  function mergeProgramUsage(usages) {
4680
4788
  const usageMap = {};
4681
- usages.forEach((usage) => {
4789
+ for (const usage of usages) {
4682
4790
  const key = `${usage.ai}:${usage.model}`;
4683
4791
  if (!usageMap[key]) {
4684
4792
  usageMap[key] = { ...usage };
4685
- return;
4793
+ continue;
4686
4794
  }
4687
- usageMap[key].promptTokens += usage.promptTokens;
4688
- usageMap[key].completionTokens += usage.completionTokens;
4689
- usageMap[key].totalTokens += usage.totalTokens;
4690
- });
4795
+ const currentUsage = usageMap[key];
4796
+ if (currentUsage) {
4797
+ currentUsage.promptTokens += usage.promptTokens;
4798
+ currentUsage.completionTokens += usage.completionTokens;
4799
+ currentUsage.totalTokens += usage.totalTokens;
4800
+ }
4801
+ }
4691
4802
  return Object.values(usageMap);
4692
4803
  }
4693
4804
  var parseMarkdownList = (input) => {
@@ -4708,7 +4819,6 @@ var parseMarkdownList = (input) => {
4708
4819
  } else if (numberedListRegex.test(trimmedLine)) {
4709
4820
  list.push(trimmedLine.replace(numberedListRegex, "").trim());
4710
4821
  } else if (list.length === 0) {
4711
- continue;
4712
4822
  } else {
4713
4823
  throw new Error("Could not parse markdown list: mixed content detected");
4714
4824
  }
@@ -4781,12 +4891,72 @@ function matchesContent(content, prefix, startIndex = 0, prefixCache = globalPre
4781
4891
  );
4782
4892
  for (let i = 0; i < prefixes.length - 1; i++) {
4783
4893
  const partialPrefix = prefixes[i];
4784
- if (contentEnd.endsWith(partialPrefix)) {
4894
+ if (partialPrefix && contentEnd.endsWith(partialPrefix)) {
4785
4895
  return -2;
4786
4896
  }
4787
4897
  }
4788
4898
  return -1;
4789
4899
  }
4900
+ var formatTime = (ms) => {
4901
+ const seconds = Math.floor(ms / 1e3);
4902
+ if (seconds < 60) return `${seconds}s`;
4903
+ const minutes = Math.floor(seconds / 60);
4904
+ const remainingSeconds = seconds % 60;
4905
+ if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
4906
+ const hours = Math.floor(minutes / 60);
4907
+ const remainingMinutes = minutes % 60;
4908
+ return `${hours}h ${remainingMinutes}m ${remainingSeconds}s`;
4909
+ };
4910
+ var calculateETA = (current, total, elapsedMs) => {
4911
+ if (current === 0) return "calculating...";
4912
+ const msPerItem = elapsedMs / current;
4913
+ const remainingItems = total - current;
4914
+ const etaMs = msPerItem * remainingItems;
4915
+ return formatTime(etaMs);
4916
+ };
4917
+ var updateDetailedProgress = (roundIndex, current, total, elapsedTime, example, stats, configInfo, result, error) => {
4918
+ process.stdout.write("\r\x1B[K");
4919
+ const percentage = (current / total * 100).toFixed(1);
4920
+ const formattedTime = formatTime(elapsedTime);
4921
+ const itemsPerSecond = elapsedTime > 0 ? (current / elapsedTime * 1e3).toFixed(2) : "0.00";
4922
+ const eta = calculateETA(current, total, elapsedTime);
4923
+ let output = `Round ${roundIndex + 1}/${configInfo.maxRounds}: ${current}/${total} (${percentage}%) [${formattedTime}, ${itemsPerSecond} it/s, ETA: ${eta}]`;
4924
+ const successRate = stats.totalCalls > 0 ? stats.successfulDemos / stats.totalCalls * 100 : 0;
4925
+ output += ` | Success: ${stats.successfulDemos}/${stats.totalCalls} (${successRate.toFixed(1)}%)`;
4926
+ if (configInfo.verboseMode || configInfo.debugMode) {
4927
+ if (configInfo.costMonitoring) {
4928
+ output += `
4929
+ Tokens: ~${stats.estimatedTokenUsage.toLocaleString()} total`;
4930
+ }
4931
+ output += `
4932
+ Batch: ${Math.floor(current / configInfo.batchSize) + 1}/${Math.ceil(total / configInfo.batchSize)}`;
4933
+ if (configInfo.earlyStoppingPatience > 0 && stats.earlyStopping) {
4934
+ output += `
4935
+ Best round: ${stats.earlyStopping.bestScoreRound + 1}, Patience: ${configInfo.earlyStoppingPatience}`;
4936
+ }
4937
+ }
4938
+ if (configInfo.debugMode) {
4939
+ const exampleKeys = Object.keys(example).map((k) => {
4940
+ const valueStr = JSON.stringify(example[k]);
4941
+ const truncated = valueStr.length > 30 ? `${valueStr.substring(0, 30)}...` : valueStr;
4942
+ return `${k}: ${truncated}`;
4943
+ }).join(", ");
4944
+ output += `
4945
+ Example: {${exampleKeys}}`;
4946
+ if (error) {
4947
+ output += `
4948
+ ERROR: ${error.message}`;
4949
+ } else if (result) {
4950
+ const resultStr = JSON.stringify(result);
4951
+ const truncatedResult = resultStr.length > 50 ? `${resultStr.substring(0, 50)}...` : resultStr;
4952
+ output += `
4953
+ Result: ${truncatedResult}`;
4954
+ }
4955
+ output += `
4956
+ Temperature: ${(0.7 + 1e-3 * current).toFixed(3)}`;
4957
+ }
4958
+ console.log(output);
4959
+ };
4790
4960
 
4791
4961
  // dsp/program.ts
4792
4962
  var AxProgramWithSignature = class {
@@ -5028,7 +5198,7 @@ ${outputFields}`);
5028
5198
  demos
5029
5199
  }) => {
5030
5200
  const renderedExamples = examples ? [
5031
- { type: "text", text: "## Examples:\n" },
5201
+ { type: "text", text: "\n\n## Examples\n" },
5032
5202
  ...this.renderExamples(examples)
5033
5203
  ] : [];
5034
5204
  const renderedDemos = demos ? this.renderDemos(demos) : [];
@@ -5111,6 +5281,9 @@ ${outputFields}`);
5111
5281
  );
5112
5282
  }
5113
5283
  const renderedItem = [...renderedInputItem, ...renderedOutputItem];
5284
+ if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
5285
+ list.push({ type: "text", text: "---\n\n" });
5286
+ }
5114
5287
  renderedItem.forEach((v) => {
5115
5288
  if ("text" in v) {
5116
5289
  v.text = v.text + "\n";
@@ -5294,10 +5467,7 @@ var processValue = (field, value) => {
5294
5467
  if (typeof value === "string") {
5295
5468
  return value;
5296
5469
  }
5297
- if (Array.isArray(value)) {
5298
- return value;
5299
- }
5300
- return JSON.stringify(value);
5470
+ return JSON.stringify(value, null, 2);
5301
5471
  };
5302
5472
  var toFieldType = (type) => {
5303
5473
  const baseType = (() => {
@@ -7038,60 +7208,147 @@ function validateModels2(services) {
7038
7208
  // dsp/optimize.ts
7039
7209
  var AxBootstrapFewShot = class {
7040
7210
  ai;
7211
+ teacherAI;
7041
7212
  program;
7042
7213
  examples;
7043
7214
  maxRounds;
7044
7215
  maxDemos;
7045
7216
  maxExamples;
7217
+ batchSize;
7218
+ earlyStoppingPatience;
7219
+ costMonitoring;
7220
+ maxTokensPerGeneration;
7221
+ verboseMode;
7222
+ debugMode;
7046
7223
  traces = [];
7224
+ stats = {
7225
+ totalCalls: 0,
7226
+ successfulDemos: 0,
7227
+ estimatedTokenUsage: 0,
7228
+ earlyStopped: false
7229
+ };
7047
7230
  constructor({
7048
7231
  ai,
7049
7232
  program,
7050
7233
  examples = [],
7051
7234
  options
7052
7235
  }) {
7053
- if (examples.length == 0) {
7236
+ if (examples.length === 0) {
7054
7237
  throw new Error("No examples found");
7055
7238
  }
7056
7239
  this.maxRounds = options?.maxRounds ?? 3;
7057
7240
  this.maxDemos = options?.maxDemos ?? 4;
7058
7241
  this.maxExamples = options?.maxExamples ?? 16;
7242
+ this.batchSize = options?.batchSize ?? 1;
7243
+ this.earlyStoppingPatience = options?.earlyStoppingPatience ?? 0;
7244
+ this.costMonitoring = options?.costMonitoring ?? false;
7245
+ this.maxTokensPerGeneration = options?.maxTokensPerGeneration ?? 0;
7246
+ this.verboseMode = options?.verboseMode ?? true;
7247
+ this.debugMode = options?.debugMode ?? false;
7059
7248
  this.ai = ai;
7249
+ this.teacherAI = options?.teacherAI;
7060
7250
  this.program = program;
7061
7251
  this.examples = examples;
7062
7252
  }
7063
7253
  async compileRound(roundIndex, metricFn, options) {
7064
7254
  const st = (/* @__PURE__ */ new Date()).getTime();
7065
7255
  const maxDemos = options?.maxDemos ?? this.maxDemos;
7066
- const aiOpt = { modelConfig: { temperature: 0.7 } };
7256
+ const aiOpt = {
7257
+ modelConfig: {
7258
+ temperature: 0.7
7259
+ }
7260
+ };
7261
+ if (this.maxTokensPerGeneration > 0) {
7262
+ aiOpt.modelConfig.max_tokens = this.maxTokensPerGeneration;
7263
+ }
7067
7264
  const examples = randomSample(this.examples, this.maxExamples);
7068
- for (let i = 0; i < examples.length; i++) {
7265
+ const previousSuccessCount = this.traces.length;
7266
+ for (let i = 0; i < examples.length; i += this.batchSize) {
7069
7267
  if (i > 0) {
7070
7268
  aiOpt.modelConfig.temperature = 0.7 + 1e-3 * i;
7071
7269
  }
7072
- const ex = examples[i];
7073
- if (!ex) {
7074
- throw new Error("Invalid example");
7075
- }
7076
- const exList = [...examples.slice(0, i), ...examples.slice(i + 1)];
7077
- this.program.setExamples(exList);
7078
- const res = await this.program.forward(this.ai, ex, aiOpt);
7079
- const success = metricFn({ prediction: res, example: ex });
7080
- if (success) {
7081
- this.traces = [...this.traces, ...this.program.getTraces()];
7270
+ const batch = examples.slice(i, i + this.batchSize);
7271
+ for (const ex of batch) {
7272
+ if (!ex) {
7273
+ continue;
7274
+ }
7275
+ const exList = examples.filter((e) => e !== ex);
7276
+ this.program.setExamples(exList);
7277
+ const aiService = this.teacherAI || this.ai;
7278
+ this.stats.totalCalls++;
7279
+ let res;
7280
+ let error;
7281
+ try {
7282
+ res = await this.program.forward(aiService, ex, aiOpt);
7283
+ if (this.costMonitoring) {
7284
+ this.stats.estimatedTokenUsage += JSON.stringify(ex).length / 4 + JSON.stringify(res).length / 4;
7285
+ }
7286
+ const success = metricFn({ prediction: res, example: ex });
7287
+ if (success) {
7288
+ this.traces = [...this.traces, ...this.program.getTraces()];
7289
+ this.stats.successfulDemos++;
7290
+ }
7291
+ } catch (err) {
7292
+ error = err;
7293
+ res = {};
7294
+ }
7295
+ const current = i + examples.length * roundIndex + (batch.indexOf(ex) + 1);
7296
+ const total = examples.length * this.maxRounds;
7297
+ const et = (/* @__PURE__ */ new Date()).getTime() - st;
7298
+ if (this.verboseMode || this.debugMode) {
7299
+ const configInfo = {
7300
+ maxRounds: this.maxRounds,
7301
+ batchSize: this.batchSize,
7302
+ earlyStoppingPatience: this.earlyStoppingPatience,
7303
+ costMonitoring: this.costMonitoring,
7304
+ verboseMode: this.verboseMode,
7305
+ debugMode: this.debugMode
7306
+ };
7307
+ updateDetailedProgress(
7308
+ roundIndex,
7309
+ current,
7310
+ total,
7311
+ et,
7312
+ ex,
7313
+ this.stats,
7314
+ configInfo,
7315
+ res,
7316
+ error
7317
+ );
7318
+ } else {
7319
+ updateProgressBar(
7320
+ current,
7321
+ total,
7322
+ this.traces.length,
7323
+ et,
7324
+ "Tuning Prompt",
7325
+ 30
7326
+ );
7327
+ }
7328
+ if (this.traces.length >= maxDemos) {
7329
+ return;
7330
+ }
7082
7331
  }
7083
- const current = i + examples.length * roundIndex;
7084
- const total = examples.length * this.maxRounds;
7085
- const et = (/* @__PURE__ */ new Date()).getTime() - st;
7086
- updateProgressBar(
7087
- current,
7088
- total,
7089
- this.traces.length,
7090
- et,
7091
- "Tuning Prompt",
7092
- 30
7093
- );
7094
- if (this.traces.length > maxDemos) {
7332
+ }
7333
+ if (this.earlyStoppingPatience > 0) {
7334
+ const newSuccessCount = this.traces.length;
7335
+ const improvement = newSuccessCount - previousSuccessCount;
7336
+ if (!this.stats.earlyStopping) {
7337
+ this.stats.earlyStopping = {
7338
+ bestScoreRound: improvement > 0 ? roundIndex : 0,
7339
+ patienceExhausted: false
7340
+ };
7341
+ } else if (improvement > 0) {
7342
+ this.stats.earlyStopping.bestScoreRound = roundIndex;
7343
+ } else if (roundIndex - this.stats.earlyStopping.bestScoreRound >= this.earlyStoppingPatience) {
7344
+ this.stats.earlyStopping.patienceExhausted = true;
7345
+ this.stats.earlyStopped = true;
7346
+ if (this.verboseMode || this.debugMode) {
7347
+ console.log(
7348
+ `
7349
+ Early stopping triggered after ${roundIndex + 1} rounds. No improvement for ${this.earlyStoppingPatience} rounds.`
7350
+ );
7351
+ }
7095
7352
  return;
7096
7353
  }
7097
7354
  }
@@ -7099,8 +7356,17 @@ var AxBootstrapFewShot = class {
7099
7356
  async compile(metricFn, options) {
7100
7357
  const maxRounds = options?.maxRounds ?? this.maxRounds;
7101
7358
  this.traces = [];
7359
+ this.stats = {
7360
+ totalCalls: 0,
7361
+ successfulDemos: 0,
7362
+ estimatedTokenUsage: 0,
7363
+ earlyStopped: false
7364
+ };
7102
7365
  for (let i = 0; i < maxRounds; i++) {
7103
7366
  await this.compileRound(i, metricFn, options);
7367
+ if (this.stats.earlyStopped) {
7368
+ break;
7369
+ }
7104
7370
  }
7105
7371
  if (this.traces.length === 0) {
7106
7372
  throw new Error(
@@ -7108,22 +7374,32 @@ var AxBootstrapFewShot = class {
7108
7374
  );
7109
7375
  }
7110
7376
  const demos = groupTracesByKeys(this.traces);
7111
- return demos;
7377
+ return {
7378
+ demos,
7379
+ stats: this.stats
7380
+ };
7381
+ }
7382
+ // Get optimization statistics
7383
+ getStats() {
7384
+ return this.stats;
7112
7385
  }
7113
7386
  };
7114
7387
  function groupTracesByKeys(programTraces) {
7115
7388
  const groupedTraces = /* @__PURE__ */ new Map();
7116
7389
  for (const programTrace of programTraces) {
7117
7390
  if (groupedTraces.has(programTrace.programId)) {
7118
- groupedTraces.get(programTrace.programId).push(programTrace.trace);
7391
+ const traces = groupedTraces.get(programTrace.programId);
7392
+ if (traces) {
7393
+ traces.push(programTrace.trace);
7394
+ }
7119
7395
  } else {
7120
7396
  groupedTraces.set(programTrace.programId, [programTrace.trace]);
7121
7397
  }
7122
7398
  }
7123
7399
  const programDemosArray = [];
7124
- groupedTraces.forEach((traces, programId) => {
7400
+ for (const [programId, traces] of groupedTraces.entries()) {
7125
7401
  programDemosArray.push({ traces, programId });
7126
- });
7402
+ }
7127
7403
  return programDemosArray;
7128
7404
  }
7129
7405
  var randomSample = (array, n) => {
@@ -8243,6 +8519,639 @@ var AxJSInterpreter = class {
8243
8519
  }
8244
8520
  };
8245
8521
 
8522
+ // dsp/mipro.ts
8523
+ var AxMiPRO = class {
8524
+ ai;
8525
+ program;
8526
+ examples;
8527
+ maxBootstrappedDemos;
8528
+ maxLabeledDemos;
8529
+ numCandidates;
8530
+ initTemperature;
8531
+ numTrials;
8532
+ minibatch;
8533
+ minibatchSize;
8534
+ minibatchFullEvalSteps;
8535
+ programAwareProposer;
8536
+ dataAwareProposer;
8537
+ viewDataBatchSize;
8538
+ tipAwareProposer;
8539
+ fewshotAwareProposer;
8540
+ seed;
8541
+ verbose;
8542
+ bootstrapper;
8543
+ earlyStoppingTrials;
8544
+ minImprovementThreshold;
8545
+ constructor({
8546
+ ai,
8547
+ program,
8548
+ examples = [],
8549
+ options
8550
+ }) {
8551
+ if (examples.length === 0) {
8552
+ throw new Error("No examples found");
8553
+ }
8554
+ const miproOptions = options || {};
8555
+ this.numCandidates = miproOptions.numCandidates ?? 5;
8556
+ this.initTemperature = miproOptions.initTemperature ?? 0.7;
8557
+ this.maxBootstrappedDemos = miproOptions.maxBootstrappedDemos ?? 3;
8558
+ this.maxLabeledDemos = miproOptions.maxLabeledDemos ?? 4;
8559
+ this.numTrials = miproOptions.numTrials ?? 30;
8560
+ this.minibatch = miproOptions.minibatch ?? true;
8561
+ this.minibatchSize = miproOptions.minibatchSize ?? 25;
8562
+ this.minibatchFullEvalSteps = miproOptions.minibatchFullEvalSteps ?? 10;
8563
+ this.programAwareProposer = miproOptions.programAwareProposer ?? true;
8564
+ this.dataAwareProposer = miproOptions.dataAwareProposer ?? true;
8565
+ this.viewDataBatchSize = miproOptions.viewDataBatchSize ?? 10;
8566
+ this.tipAwareProposer = miproOptions.tipAwareProposer ?? true;
8567
+ this.fewshotAwareProposer = miproOptions.fewshotAwareProposer ?? true;
8568
+ this.seed = miproOptions.seed;
8569
+ this.verbose = miproOptions.verbose ?? false;
8570
+ this.earlyStoppingTrials = miproOptions.earlyStoppingTrials ?? 5;
8571
+ this.minImprovementThreshold = miproOptions.minImprovementThreshold ?? 0.01;
8572
+ this.ai = ai;
8573
+ this.program = program;
8574
+ this.examples = examples;
8575
+ this.bootstrapper = new AxBootstrapFewShot({
8576
+ ai,
8577
+ program,
8578
+ examples,
8579
+ options: {
8580
+ maxDemos: this.maxBootstrappedDemos,
8581
+ maxRounds: 3,
8582
+ // Default, or adjust based on your needs
8583
+ verboseMode: this.verbose
8584
+ }
8585
+ });
8586
+ }
8587
+ /**
8588
+ * Configures the optimizer for light, medium, or heavy optimization
8589
+ * @param level The optimization level: "light", "medium", or "heavy"
8590
+ */
8591
+ configureAuto(level) {
8592
+ switch (level) {
8593
+ case "light":
8594
+ this.numCandidates = 3;
8595
+ this.numTrials = 10;
8596
+ this.minibatch = true;
8597
+ this.minibatchSize = 20;
8598
+ break;
8599
+ case "medium":
8600
+ this.numCandidates = 5;
8601
+ this.numTrials = 20;
8602
+ this.minibatch = true;
8603
+ this.minibatchSize = 25;
8604
+ break;
8605
+ case "heavy":
8606
+ this.numCandidates = 7;
8607
+ this.numTrials = 30;
8608
+ this.minibatch = true;
8609
+ this.minibatchSize = 30;
8610
+ break;
8611
+ }
8612
+ }
8613
+ /**
8614
+ * Generates creative tips for instruction generation
8615
+ */
8616
+ generateTips() {
8617
+ return [
8618
+ "Be very specific and detailed in your instructions.",
8619
+ "Focus on step-by-step reasoning in your instructions.",
8620
+ "Provide clear constraints and guidelines in your instructions.",
8621
+ "Keep your instructions concise and to the point.",
8622
+ "Emphasize accuracy and precision in your instructions.",
8623
+ "Include examples of good outputs in your instructions.",
8624
+ "Focus on handling edge cases in your instructions.",
8625
+ "Explicitly outline the reasoning process in your instructions."
8626
+ ];
8627
+ }
8628
+ /**
8629
+ * Generates instruction candidates for each predictor in the program
8630
+ * @returns Array of generated instruction candidates
8631
+ */
8632
+ async proposeInstructionCandidates() {
8633
+ const instructions = [];
8634
+ let programContext = "";
8635
+ if (this.programAwareProposer) {
8636
+ programContext = await this.generateProgramSummary();
8637
+ }
8638
+ let dataContext = "";
8639
+ if (this.dataAwareProposer) {
8640
+ dataContext = await this.generateDataSummary();
8641
+ }
8642
+ const tips = this.tipAwareProposer ? this.generateTips() : [];
8643
+ for (let i = 0; i < this.numCandidates; i++) {
8644
+ const tipIndex = tips.length > 0 ? i % tips.length : -1;
8645
+ const tipToUse = tipIndex >= 0 ? tips[tipIndex] : "";
8646
+ const instruction = await this.generateInstruction({
8647
+ programContext,
8648
+ dataContext,
8649
+ tip: tipToUse,
8650
+ candidateIndex: i
8651
+ });
8652
+ instructions.push(instruction);
8653
+ }
8654
+ return instructions;
8655
+ }
8656
+ /**
8657
+ * Generates a summary of the program structure for instruction proposal
8658
+ */
8659
+ async generateProgramSummary() {
8660
+ const prompt = `Summarize the following program structure. Focus on the signatures,
8661
+ input/output fields, and the purpose of each component. Identify key components
8662
+ that might benefit from better instructions.`;
8663
+ const programStr = JSON.stringify(this.program);
8664
+ const response = await this.ai.chat({
8665
+ chatPrompt: [
8666
+ { role: "system", content: prompt },
8667
+ { role: "user", content: programStr }
8668
+ ],
8669
+ modelConfig: { temperature: 0.2 }
8670
+ });
8671
+ if (response instanceof ReadableStream) {
8672
+ return "";
8673
+ }
8674
+ return response.results[0]?.content || "";
8675
+ }
8676
+ /**
8677
+ * Generates a summary of the dataset for instruction proposal
8678
+ */
8679
+ async generateDataSummary() {
8680
+ const sampleSize = Math.min(this.viewDataBatchSize, this.examples.length);
8681
+ const sample = this.examples.slice(0, sampleSize);
8682
+ const prompt = `Analyze the following dataset examples and provide a summary
8683
+ of key patterns, input-output relationships, and any specific challenges
8684
+ the data presents. Focus on what makes a good answer and what patterns should
8685
+ be followed.`;
8686
+ const dataStr = JSON.stringify(sample);
8687
+ const response = await this.ai.chat({
8688
+ chatPrompt: [
8689
+ { role: "system", content: prompt },
8690
+ { role: "user", content: dataStr }
8691
+ ],
8692
+ modelConfig: { temperature: 0.2 }
8693
+ });
8694
+ if (response instanceof ReadableStream) {
8695
+ return "";
8696
+ }
8697
+ return response.results[0]?.content || "";
8698
+ }
8699
+ /**
8700
+ * Generates a specific instruction candidate
8701
+ */
8702
+ async generateInstruction({
8703
+ programContext,
8704
+ dataContext,
8705
+ tip,
8706
+ candidateIndex
8707
+ }) {
8708
+ const prompt = `Create a high-quality instruction for an AI model performing the task described below.
8709
+
8710
+ ${programContext ? `PROGRAM CONTEXT:
8711
+ ${programContext}
8712
+
8713
+ ` : ""}
8714
+ ${dataContext ? `DATA CONTEXT:
8715
+ ${dataContext}
8716
+
8717
+ ` : ""}
8718
+ ${tip ? `STYLE TIP: ${tip}
8719
+
8720
+ ` : ""}
8721
+
8722
+ Your task is to craft a clear, effective instruction that will help the AI model generate
8723
+ accurate outputs for this task. Instruction #${candidateIndex + 1}/${this.numCandidates}.
8724
+
8725
+ The instruction should be detailed enough to guide the model but not overly prescriptive
8726
+ or restrictive. Focus on what makes a good response rather than listing exact steps.
8727
+
8728
+ INSTRUCTION:`;
8729
+ const response = await this.ai.chat({
8730
+ chatPrompt: [{ role: "user", content: prompt }],
8731
+ modelConfig: { temperature: 0.7 + 0.1 * candidateIndex }
8732
+ });
8733
+ if (response instanceof ReadableStream) {
8734
+ return "";
8735
+ }
8736
+ return response.results[0]?.content || "";
8737
+ }
8738
+ /**
8739
+ * Bootstraps few-shot examples for the program
8740
+ */
8741
+ async bootstrapFewShotExamples(metricFn) {
8742
+ if (this.verbose) {
8743
+ console.log("Bootstrapping few-shot examples...");
8744
+ }
8745
+ const result = await this.bootstrapper.compile(metricFn, {
8746
+ maxDemos: this.maxBootstrappedDemos
8747
+ });
8748
+ return result.demos;
8749
+ }
8750
+ /**
8751
+ * Selects labeled examples directly from the training set
8752
+ */
8753
+ selectLabeledExamples() {
8754
+ const selectedExamples = [];
8755
+ const indices = /* @__PURE__ */ new Set();
8756
+ while (indices.size < this.maxLabeledDemos && indices.size < this.examples.length) {
8757
+ const idx = Math.floor(Math.random() * this.examples.length);
8758
+ if (!indices.has(idx)) {
8759
+ indices.add(idx);
8760
+ const example = this.examples[idx];
8761
+ if (example) {
8762
+ selectedExamples.push(example);
8763
+ }
8764
+ }
8765
+ }
8766
+ return selectedExamples;
8767
+ }
8768
+ /**
8769
+ * Runs Bayesian optimization to find the best combination of few-shot examples and instructions
8770
+ */
8771
+ async runBayesianOptimization(bootstrappedDemos, labeledExamples, instructions, valset, metricFn) {
8772
+ let bestConfig = null;
8773
+ let bestScore = Number.NEGATIVE_INFINITY;
8774
+ const evaluatedConfigs = [];
8775
+ const defaultConfig = {
8776
+ instruction: instructions[0] || "",
8777
+ bootstrappedDemos: Math.min(1, bootstrappedDemos.length),
8778
+ labeledExamples: Math.min(1, labeledExamples.length)
8779
+ };
8780
+ let trialsWithoutImprovement = 0;
8781
+ let lastBestScore = Number.NEGATIVE_INFINITY;
8782
+ const initialExplorationTrials = Math.min(
8783
+ 10,
8784
+ Math.floor(this.numTrials / 3)
8785
+ );
8786
+ const configs = [];
8787
+ for (let i = 0; i < initialExplorationTrials; i++) {
8788
+ const instructionIndex = Math.floor(Math.random() * instructions.length);
8789
+ const instructionValue = instructions[instructionIndex] || "";
8790
+ const config = {
8791
+ instruction: instructionValue,
8792
+ bootstrappedDemos: Math.floor(
8793
+ Math.random() * (bootstrappedDemos.length + 1)
8794
+ ),
8795
+ labeledExamples: Math.floor(
8796
+ Math.random() * (labeledExamples.length + 1)
8797
+ )
8798
+ };
8799
+ configs.push(config);
8800
+ }
8801
+ for (let i = 0; i < configs.length; i++) {
8802
+ const config = configs[i];
8803
+ if (!config) continue;
8804
+ const score = await this.evaluateConfig(
8805
+ config,
8806
+ bootstrappedDemos,
8807
+ labeledExamples,
8808
+ valset,
8809
+ metricFn,
8810
+ i
8811
+ );
8812
+ evaluatedConfigs.push({ config, score });
8813
+ if (score > bestScore) {
8814
+ bestScore = score;
8815
+ bestConfig = config;
8816
+ if (this.verbose) {
8817
+ console.log(
8818
+ `New best configuration found with score ${bestScore} (exploration phase)`
8819
+ );
8820
+ }
8821
+ }
8822
+ updateProgressBar(
8823
+ i + 1,
8824
+ this.numTrials,
8825
+ Math.round(bestScore * 100),
8826
+ 0,
8827
+ "Running MIPROv2 optimization",
8828
+ 30
8829
+ );
8830
+ }
8831
+ for (let i = configs.length; i < this.numTrials; i++) {
8832
+ const nextConfig = this.selectNextConfiguration(
8833
+ evaluatedConfigs,
8834
+ bootstrappedDemos.length,
8835
+ labeledExamples.length,
8836
+ instructions
8837
+ );
8838
+ const score = await this.evaluateConfig(
8839
+ nextConfig,
8840
+ bootstrappedDemos,
8841
+ labeledExamples,
8842
+ valset,
8843
+ metricFn,
8844
+ i
8845
+ );
8846
+ evaluatedConfigs.push({ config: nextConfig, score });
8847
+ if (score > bestScore) {
8848
+ bestScore = score;
8849
+ bestConfig = nextConfig;
8850
+ if (this.verbose) {
8851
+ console.log(
8852
+ `New best configuration found with score ${bestScore} (exploitation phase)`
8853
+ );
8854
+ }
8855
+ trialsWithoutImprovement = 0;
8856
+ lastBestScore = bestScore;
8857
+ } else {
8858
+ if (bestScore - lastBestScore < this.minImprovementThreshold) {
8859
+ trialsWithoutImprovement++;
8860
+ if (trialsWithoutImprovement >= this.earlyStoppingTrials) {
8861
+ if (this.verbose) {
8862
+ console.log(
8863
+ `Early stopping triggered after ${i + 1} trials. No improvement for ${trialsWithoutImprovement} trials.`
8864
+ );
8865
+ }
8866
+ break;
8867
+ }
8868
+ } else {
8869
+ lastBestScore = bestScore;
8870
+ trialsWithoutImprovement = 0;
8871
+ }
8872
+ }
8873
+ updateProgressBar(
8874
+ i + 1,
8875
+ this.numTrials,
8876
+ Math.round(bestScore * 100),
8877
+ 0,
8878
+ "Running MIPROv2 optimization",
8879
+ 30
8880
+ );
8881
+ if (this.minibatch && i > 0 && (i + 1) % this.minibatchFullEvalSteps === 0 && bestConfig) {
8882
+ if (this.verbose) {
8883
+ console.log(
8884
+ `Running full evaluation on best configuration at trial ${i + 1}`
8885
+ );
8886
+ }
8887
+ const fullScore = await this.fullEvaluation(
8888
+ bestConfig,
8889
+ bootstrappedDemos,
8890
+ labeledExamples,
8891
+ valset,
8892
+ metricFn
8893
+ );
8894
+ if (this.verbose) {
8895
+ console.log(`Full evaluation score: ${fullScore}`);
8896
+ }
8897
+ bestScore = fullScore;
8898
+ }
8899
+ }
8900
+ if (!bestConfig) {
8901
+ if (this.verbose) {
8902
+ console.warn(
8903
+ "Optimization failed to find any valid configurations, using default fallback configuration"
8904
+ );
8905
+ }
8906
+ bestConfig = defaultConfig;
8907
+ try {
8908
+ bestScore = await this.evaluateConfig(
8909
+ bestConfig,
8910
+ bootstrappedDemos,
8911
+ labeledExamples,
8912
+ valset,
8913
+ metricFn,
8914
+ this.numTrials - 1
8915
+ );
8916
+ } catch (err) {
8917
+ if (this.verbose) {
8918
+ console.error("Error evaluating default configuration:", err);
8919
+ }
8920
+ bestScore = 0;
8921
+ }
8922
+ }
8923
+ return { bestConfig, bestScore };
8924
+ }
8925
+ /**
8926
+ * Evaluates a configuration on the validation set
8927
+ */
8928
+ async evaluateConfig(config, bootstrappedDemos, labeledExamples, valset, metricFn, trialIndex) {
8929
+ this.applyConfigToProgram(
8930
+ this.program,
8931
+ config,
8932
+ bootstrappedDemos,
8933
+ labeledExamples
8934
+ );
8935
+ let evalSet = valset;
8936
+ if (this.minibatch) {
8937
+ const startIdx = trialIndex * this.minibatchSize % valset.length;
8938
+ const minibatchEvalSet = [];
8939
+ for (let j = 0; j < this.minibatchSize; j++) {
8940
+ const idx = (startIdx + j) % valset.length;
8941
+ const example = valset[idx];
8942
+ if (example) {
8943
+ minibatchEvalSet.push(example);
8944
+ }
8945
+ }
8946
+ evalSet = minibatchEvalSet;
8947
+ }
8948
+ let correctCount = 0;
8949
+ for (const example of evalSet) {
8950
+ try {
8951
+ const prediction = await this.program.forward(this.ai, example);
8952
+ const correct = metricFn({ prediction, example });
8953
+ if (correct) correctCount++;
8954
+ } catch (err) {
8955
+ if (this.verbose) {
8956
+ console.error("Error evaluating example:", err);
8957
+ }
8958
+ }
8959
+ }
8960
+ return correctCount / evalSet.length;
8961
+ }
8962
+ /**
8963
+ * Run full evaluation on the entire validation set
8964
+ */
8965
+ async fullEvaluation(config, bootstrappedDemos, labeledExamples, valset, metricFn) {
8966
+ this.applyConfigToProgram(
8967
+ this.program,
8968
+ config,
8969
+ bootstrappedDemos,
8970
+ labeledExamples
8971
+ );
8972
+ let fullCorrectCount = 0;
8973
+ for (const example of valset) {
8974
+ try {
8975
+ const prediction = await this.program.forward(this.ai, example);
8976
+ const correct = metricFn({ prediction, example });
8977
+ if (correct) fullCorrectCount++;
8978
+ } catch (err) {
8979
+ if (this.verbose) {
8980
+ console.error("Error evaluating example:", err);
8981
+ }
8982
+ }
8983
+ }
8984
+ return fullCorrectCount / valset.length;
8985
+ }
8986
+ /**
8987
+ * Implements a Bayesian-inspired selection of the next configuration to try
8988
+ * This is a simplified version using Upper Confidence Bound (UCB) strategy
8989
+ */
8990
+ selectNextConfiguration(evaluatedConfigs, maxBootstrappedDemos, maxLabeledExamples, instructions) {
8991
+ if (evaluatedConfigs.length < 5) {
8992
+ const instructionIndex = Math.floor(Math.random() * instructions.length);
8993
+ return {
8994
+ instruction: instructions[instructionIndex] || "",
8995
+ bootstrappedDemos: Math.floor(
8996
+ Math.random() * (maxBootstrappedDemos + 1)
8997
+ ),
8998
+ labeledExamples: Math.floor(Math.random() * (maxLabeledExamples + 1))
8999
+ };
9000
+ }
9001
+ const sortedConfigs = [...evaluatedConfigs].sort(
9002
+ (a, b) => b.score - a.score
9003
+ );
9004
+ const topConfigs = sortedConfigs.slice(0, Math.min(3, sortedConfigs.length));
9005
+ const meanBootstrappedDemos = topConfigs.reduce((sum, c) => sum + c.config.bootstrappedDemos, 0) / topConfigs.length;
9006
+ const meanLabeledExamples = topConfigs.reduce((sum, c) => sum + c.config.labeledExamples, 0) / topConfigs.length;
9007
+ const popularInstructions = topConfigs.map((c) => c.config.instruction);
9008
+ const explorationFactor = Math.max(
9009
+ 0.2,
9010
+ 1 - evaluatedConfigs.length / this.numTrials
9011
+ );
9012
+ let newBootstrappedDemos;
9013
+ let newLabeledExamples;
9014
+ let newInstruction;
9015
+ if (Math.random() < 0.7) {
9016
+ newBootstrappedDemos = Math.min(
9017
+ maxBootstrappedDemos,
9018
+ Math.max(
9019
+ 0,
9020
+ Math.round(
9021
+ meanBootstrappedDemos + (Math.random() * 2 - 1) * explorationFactor * 2
9022
+ )
9023
+ )
9024
+ );
9025
+ } else {
9026
+ newBootstrappedDemos = Math.floor(
9027
+ Math.random() * (maxBootstrappedDemos + 1)
9028
+ );
9029
+ }
9030
+ if (Math.random() < 0.7) {
9031
+ newLabeledExamples = Math.min(
9032
+ maxLabeledExamples,
9033
+ Math.max(
9034
+ 0,
9035
+ Math.round(
9036
+ meanLabeledExamples + (Math.random() * 2 - 1) * explorationFactor * 2
9037
+ )
9038
+ )
9039
+ );
9040
+ } else {
9041
+ newLabeledExamples = Math.floor(Math.random() * (maxLabeledExamples + 1));
9042
+ }
9043
+ if (Math.random() < 0.7 && popularInstructions.length > 0) {
9044
+ const idx = Math.floor(Math.random() * popularInstructions.length);
9045
+ newInstruction = popularInstructions[idx] || "";
9046
+ } else {
9047
+ const idx = Math.floor(Math.random() * instructions.length);
9048
+ newInstruction = instructions[idx] || "";
9049
+ }
9050
+ return {
9051
+ instruction: newInstruction,
9052
+ bootstrappedDemos: newBootstrappedDemos,
9053
+ labeledExamples: newLabeledExamples
9054
+ };
9055
+ }
9056
+ /**
9057
+ * Applies a configuration to a program instance
9058
+ */
9059
+ applyConfigToProgram(program, config, bootstrappedDemos, labeledExamples) {
9060
+ this.setInstructionToProgram(program, config.instruction);
9061
+ if (config.bootstrappedDemos > 0) {
9062
+ program.setDemos(bootstrappedDemos.slice(0, config.bootstrappedDemos));
9063
+ }
9064
+ if (config.labeledExamples > 0) {
9065
+ program.setExamples(labeledExamples.slice(0, config.labeledExamples));
9066
+ }
9067
+ }
9068
+ /**
9069
+ * Sets instruction to a program
9070
+ * Note: Workaround since setInstruction may not be available directly
9071
+ */
9072
+ setInstructionToProgram(program, instruction) {
9073
+ const programWithInstruction = program;
9074
+ programWithInstruction.setInstruction?.(instruction);
9075
+ }
9076
+ /**
9077
+ * The main compile method to run MIPROv2 optimization
9078
+ * @param metricFn Evaluation metric function
9079
+ * @param options Optional configuration options
9080
+ * @returns The optimized program
9081
+ */
9082
+ async compile(metricFn, options) {
9083
+ if (options?.auto) {
9084
+ this.configureAuto(options.auto);
9085
+ }
9086
+ const trainset = this.examples;
9087
+ const valset = options?.valset || this.examples.slice(0, Math.floor(this.examples.length * 0.8));
9088
+ if (this.verbose) {
9089
+ console.log(`Starting MIPROv2 optimization with ${this.numTrials} trials`);
9090
+ console.log(
9091
+ `Using ${trainset.length} examples for training and ${valset.length} for validation`
9092
+ );
9093
+ }
9094
+ if (options?.teacher) {
9095
+ if (this.verbose) {
9096
+ console.log("Using provided teacher to assist with bootstrapping");
9097
+ }
9098
+ const bootstrapperWithTeacher = new AxBootstrapFewShot({
9099
+ ai: this.ai,
9100
+ program: this.program,
9101
+ examples: this.examples,
9102
+ options: {
9103
+ maxDemos: this.maxBootstrappedDemos,
9104
+ maxRounds: 3,
9105
+ verboseMode: this.verbose,
9106
+ teacherAI: this.ai
9107
+ // Use the same AI but with the teacher program
9108
+ }
9109
+ });
9110
+ this.bootstrapper = bootstrapperWithTeacher;
9111
+ }
9112
+ let bootstrappedDemos = [];
9113
+ if (this.maxBootstrappedDemos > 0) {
9114
+ bootstrappedDemos = await this.bootstrapFewShotExamples(metricFn);
9115
+ if (this.verbose) {
9116
+ console.log(
9117
+ `Generated ${bootstrappedDemos.length} bootstrapped demonstrations`
9118
+ );
9119
+ }
9120
+ }
9121
+ let labeledExamples = [];
9122
+ if (this.maxLabeledDemos > 0) {
9123
+ labeledExamples = this.selectLabeledExamples();
9124
+ if (this.verbose) {
9125
+ console.log(
9126
+ `Selected ${labeledExamples.length} labeled examples from training set`
9127
+ );
9128
+ }
9129
+ }
9130
+ const instructions = await this.proposeInstructionCandidates();
9131
+ if (this.verbose) {
9132
+ console.log(`Generated ${instructions.length} instruction candidates`);
9133
+ }
9134
+ const { bestConfig, bestScore } = await this.runBayesianOptimization(
9135
+ bootstrappedDemos,
9136
+ labeledExamples,
9137
+ instructions,
9138
+ valset,
9139
+ metricFn
9140
+ );
9141
+ if (this.verbose) {
9142
+ console.log(`Optimization complete. Best score: ${bestScore}`);
9143
+ console.log(`Best configuration: ${JSON.stringify(bestConfig)}`);
9144
+ }
9145
+ this.applyConfigToProgram(
9146
+ this.program,
9147
+ bestConfig,
9148
+ bootstrappedDemos,
9149
+ labeledExamples
9150
+ );
9151
+ return this.program;
9152
+ }
9153
+ };
9154
+
8246
9155
  // ai/mock/api.ts
8247
9156
  var AxMockAIService = class {
8248
9157
  constructor(config = {}) {
@@ -8551,7 +9460,7 @@ var batchArray = (arr, size) => {
8551
9460
  }
8552
9461
  return chunkedArr;
8553
9462
  };
8554
- var axStringUtil = {
9463
+ var AxStringUtil = {
8555
9464
  trimNonAlphaNum,
8556
9465
  splitIntoTwo,
8557
9466
  dedup,
@@ -8570,7 +9479,7 @@ var AxDefaultResultReranker = class extends AxGen {
8570
9479
  forward = async (ai, input, options) => {
8571
9480
  const { rankedItems } = await super.forward(ai, input, options);
8572
9481
  const sortedIndexes = rankedItems.map((item) => {
8573
- const { id: index } = axStringUtil.extractIdAndText(item);
9482
+ const { id: index } = AxStringUtil.extractIdAndText(item);
8574
9483
  return index;
8575
9484
  });
8576
9485
  const sortedItems = input.items.map((_, index) => {
@@ -8625,6 +9534,1230 @@ var AxEmbeddingAdapter = class {
8625
9534
  }
8626
9535
  };
8627
9536
 
9537
+ // dsp/stopwords.ts
9538
+ var stopwords = /* @__PURE__ */ new Set([
9539
+ "0o",
9540
+ "0s",
9541
+ "3a",
9542
+ "3b",
9543
+ "3d",
9544
+ "6b",
9545
+ "6o",
9546
+ "a",
9547
+ "a1",
9548
+ "a2",
9549
+ "a3",
9550
+ "a4",
9551
+ "ab",
9552
+ "able",
9553
+ "about",
9554
+ "above",
9555
+ "abst",
9556
+ "ac",
9557
+ "accordance",
9558
+ "according",
9559
+ "accordingly",
9560
+ "across",
9561
+ "act",
9562
+ "actually",
9563
+ "ad",
9564
+ "added",
9565
+ "adj",
9566
+ "ae",
9567
+ "af",
9568
+ "affected",
9569
+ "affecting",
9570
+ "affects",
9571
+ "after",
9572
+ "afterwards",
9573
+ "ag",
9574
+ "again",
9575
+ "against",
9576
+ "ah",
9577
+ "ain",
9578
+ "ain't",
9579
+ "aj",
9580
+ "al",
9581
+ "all",
9582
+ "allow",
9583
+ "allows",
9584
+ "almost",
9585
+ "alone",
9586
+ "along",
9587
+ "already",
9588
+ "also",
9589
+ "although",
9590
+ "always",
9591
+ "am",
9592
+ "among",
9593
+ "amongst",
9594
+ "amoungst",
9595
+ "amount",
9596
+ "an",
9597
+ "and",
9598
+ "announce",
9599
+ "another",
9600
+ "any",
9601
+ "anybody",
9602
+ "anyhow",
9603
+ "anymore",
9604
+ "anyone",
9605
+ "anything",
9606
+ "anyway",
9607
+ "anyways",
9608
+ "anywhere",
9609
+ "ao",
9610
+ "ap",
9611
+ "apart",
9612
+ "apparently",
9613
+ "appear",
9614
+ "appreciate",
9615
+ "appropriate",
9616
+ "approximately",
9617
+ "ar",
9618
+ "are",
9619
+ "aren",
9620
+ "arent",
9621
+ "aren't",
9622
+ "arise",
9623
+ "around",
9624
+ "as",
9625
+ "a's",
9626
+ "aside",
9627
+ "ask",
9628
+ "asking",
9629
+ "associated",
9630
+ "at",
9631
+ "au",
9632
+ "auth",
9633
+ "av",
9634
+ "available",
9635
+ "aw",
9636
+ "away",
9637
+ "awfully",
9638
+ "ax",
9639
+ "ay",
9640
+ "az",
9641
+ "b",
9642
+ "b1",
9643
+ "b2",
9644
+ "b3",
9645
+ "ba",
9646
+ "back",
9647
+ "bc",
9648
+ "bd",
9649
+ "be",
9650
+ "became",
9651
+ "because",
9652
+ "become",
9653
+ "becomes",
9654
+ "becoming",
9655
+ "been",
9656
+ "before",
9657
+ "beforehand",
9658
+ "begin",
9659
+ "beginning",
9660
+ "beginnings",
9661
+ "begins",
9662
+ "behind",
9663
+ "being",
9664
+ "believe",
9665
+ "below",
9666
+ "beside",
9667
+ "besides",
9668
+ "best",
9669
+ "better",
9670
+ "between",
9671
+ "beyond",
9672
+ "bi",
9673
+ "bill",
9674
+ "biol",
9675
+ "bj",
9676
+ "bk",
9677
+ "bl",
9678
+ "bn",
9679
+ "both",
9680
+ "bottom",
9681
+ "bp",
9682
+ "br",
9683
+ "brief",
9684
+ "briefly",
9685
+ "bs",
9686
+ "bt",
9687
+ "bu",
9688
+ "but",
9689
+ "bx",
9690
+ "by",
9691
+ "c",
9692
+ "c1",
9693
+ "c2",
9694
+ "c3",
9695
+ "ca",
9696
+ "call",
9697
+ "came",
9698
+ "can",
9699
+ "cannot",
9700
+ "cant",
9701
+ "can't",
9702
+ "cause",
9703
+ "causes",
9704
+ "cc",
9705
+ "cd",
9706
+ "ce",
9707
+ "certain",
9708
+ "certainly",
9709
+ "cf",
9710
+ "cg",
9711
+ "ch",
9712
+ "changes",
9713
+ "ci",
9714
+ "cit",
9715
+ "cj",
9716
+ "cl",
9717
+ "clearly",
9718
+ "cm",
9719
+ "c'mon",
9720
+ "cn",
9721
+ "co",
9722
+ "com",
9723
+ "come",
9724
+ "comes",
9725
+ "con",
9726
+ "concerning",
9727
+ "consequently",
9728
+ "consider",
9729
+ "considering",
9730
+ "contain",
9731
+ "containing",
9732
+ "contains",
9733
+ "corresponding",
9734
+ "could",
9735
+ "couldn",
9736
+ "couldnt",
9737
+ "couldn't",
9738
+ "course",
9739
+ "cp",
9740
+ "cq",
9741
+ "cr",
9742
+ "cry",
9743
+ "cs",
9744
+ "c's",
9745
+ "ct",
9746
+ "cu",
9747
+ "currently",
9748
+ "cv",
9749
+ "cx",
9750
+ "cy",
9751
+ "cz",
9752
+ "d",
9753
+ "d2",
9754
+ "da",
9755
+ "date",
9756
+ "dc",
9757
+ "dd",
9758
+ "de",
9759
+ "definitely",
9760
+ "describe",
9761
+ "described",
9762
+ "despite",
9763
+ "detail",
9764
+ "df",
9765
+ "di",
9766
+ "did",
9767
+ "didn",
9768
+ "didn't",
9769
+ "different",
9770
+ "dj",
9771
+ "dk",
9772
+ "dl",
9773
+ "do",
9774
+ "does",
9775
+ "doesn",
9776
+ "doesn't",
9777
+ "doing",
9778
+ "don",
9779
+ "done",
9780
+ "don't",
9781
+ "down",
9782
+ "downwards",
9783
+ "dp",
9784
+ "dr",
9785
+ "ds",
9786
+ "dt",
9787
+ "du",
9788
+ "due",
9789
+ "during",
9790
+ "dx",
9791
+ "dy",
9792
+ "e",
9793
+ "e2",
9794
+ "e3",
9795
+ "ea",
9796
+ "each",
9797
+ "ec",
9798
+ "ed",
9799
+ "edu",
9800
+ "ee",
9801
+ "ef",
9802
+ "effect",
9803
+ "eg",
9804
+ "ei",
9805
+ "eight",
9806
+ "eighty",
9807
+ "either",
9808
+ "ej",
9809
+ "el",
9810
+ "eleven",
9811
+ "else",
9812
+ "elsewhere",
9813
+ "em",
9814
+ "empty",
9815
+ "en",
9816
+ "end",
9817
+ "ending",
9818
+ "enough",
9819
+ "entirely",
9820
+ "eo",
9821
+ "ep",
9822
+ "eq",
9823
+ "er",
9824
+ "es",
9825
+ "especially",
9826
+ "est",
9827
+ "et",
9828
+ "et-al",
9829
+ "etc",
9830
+ "eu",
9831
+ "ev",
9832
+ "even",
9833
+ "ever",
9834
+ "every",
9835
+ "everybody",
9836
+ "everyone",
9837
+ "everything",
9838
+ "everywhere",
9839
+ "ex",
9840
+ "exactly",
9841
+ "example",
9842
+ "except",
9843
+ "ey",
9844
+ "f",
9845
+ "f2",
9846
+ "fa",
9847
+ "far",
9848
+ "fc",
9849
+ "few",
9850
+ "ff",
9851
+ "fi",
9852
+ "fifteen",
9853
+ "fifth",
9854
+ "fify",
9855
+ "fill",
9856
+ "find",
9857
+ "fire",
9858
+ "first",
9859
+ "five",
9860
+ "fix",
9861
+ "fj",
9862
+ "fl",
9863
+ "fn",
9864
+ "fo",
9865
+ "followed",
9866
+ "following",
9867
+ "follows",
9868
+ "for",
9869
+ "former",
9870
+ "formerly",
9871
+ "forth",
9872
+ "forty",
9873
+ "found",
9874
+ "four",
9875
+ "fr",
9876
+ "from",
9877
+ "front",
9878
+ "node:fs",
9879
+ "ft",
9880
+ "fu",
9881
+ "full",
9882
+ "further",
9883
+ "furthermore",
9884
+ "fy",
9885
+ "g",
9886
+ "ga",
9887
+ "gave",
9888
+ "ge",
9889
+ "get",
9890
+ "gets",
9891
+ "getting",
9892
+ "gi",
9893
+ "give",
9894
+ "given",
9895
+ "gives",
9896
+ "giving",
9897
+ "gj",
9898
+ "gl",
9899
+ "go",
9900
+ "goes",
9901
+ "going",
9902
+ "gone",
9903
+ "got",
9904
+ "gotten",
9905
+ "gr",
9906
+ "greetings",
9907
+ "gs",
9908
+ "gy",
9909
+ "h",
9910
+ "h2",
9911
+ "h3",
9912
+ "had",
9913
+ "hadn",
9914
+ "hadn't",
9915
+ "happens",
9916
+ "hardly",
9917
+ "has",
9918
+ "hasn",
9919
+ "hasnt",
9920
+ "hasn't",
9921
+ "have",
9922
+ "haven",
9923
+ "haven't",
9924
+ "having",
9925
+ "he",
9926
+ "hed",
9927
+ "he'd",
9928
+ "he'll",
9929
+ "hello",
9930
+ "help",
9931
+ "hence",
9932
+ "her",
9933
+ "here",
9934
+ "hereafter",
9935
+ "hereby",
9936
+ "herein",
9937
+ "heres",
9938
+ "here's",
9939
+ "hereupon",
9940
+ "hers",
9941
+ "herself",
9942
+ "hes",
9943
+ "he's",
9944
+ "hh",
9945
+ "hi",
9946
+ "hid",
9947
+ "him",
9948
+ "himself",
9949
+ "his",
9950
+ "hither",
9951
+ "hj",
9952
+ "ho",
9953
+ "home",
9954
+ "hopefully",
9955
+ "how",
9956
+ "howbeit",
9957
+ "however",
9958
+ "how's",
9959
+ "hr",
9960
+ "hs",
9961
+ "http",
9962
+ "hu",
9963
+ "hundred",
9964
+ "hy",
9965
+ "i",
9966
+ "i2",
9967
+ "i3",
9968
+ "i4",
9969
+ "i6",
9970
+ "i7",
9971
+ "i8",
9972
+ "ia",
9973
+ "ib",
9974
+ "ibid",
9975
+ "ic",
9976
+ "id",
9977
+ "i'd",
9978
+ "ie",
9979
+ "if",
9980
+ "ig",
9981
+ "ignored",
9982
+ "ih",
9983
+ "ii",
9984
+ "ij",
9985
+ "il",
9986
+ "i'll",
9987
+ "im",
9988
+ "i'm",
9989
+ "immediate",
9990
+ "immediately",
9991
+ "importance",
9992
+ "important",
9993
+ "in",
9994
+ "inasmuch",
9995
+ "inc",
9996
+ "indeed",
9997
+ "index",
9998
+ "indicate",
9999
+ "indicated",
10000
+ "indicates",
10001
+ "information",
10002
+ "inner",
10003
+ "insofar",
10004
+ "instead",
10005
+ "interest",
10006
+ "into",
10007
+ "invention",
10008
+ "inward",
10009
+ "io",
10010
+ "ip",
10011
+ "iq",
10012
+ "ir",
10013
+ "is",
10014
+ "isn",
10015
+ "isn't",
10016
+ "it",
10017
+ "itd",
10018
+ "it'd",
10019
+ "it'll",
10020
+ "its",
10021
+ "it's",
10022
+ "itself",
10023
+ "iv",
10024
+ "i've",
10025
+ "ix",
10026
+ "iy",
10027
+ "iz",
10028
+ "j",
10029
+ "jj",
10030
+ "jr",
10031
+ "js",
10032
+ "jt",
10033
+ "ju",
10034
+ "just",
10035
+ "k",
10036
+ "ke",
10037
+ "keep",
10038
+ "keeps",
10039
+ "kept",
10040
+ "kg",
10041
+ "kj",
10042
+ "km",
10043
+ "know",
10044
+ "known",
10045
+ "knows",
10046
+ "ko",
10047
+ "l",
10048
+ "l2",
10049
+ "la",
10050
+ "largely",
10051
+ "last",
10052
+ "lately",
10053
+ "later",
10054
+ "latter",
10055
+ "latterly",
10056
+ "lb",
10057
+ "lc",
10058
+ "le",
10059
+ "least",
10060
+ "les",
10061
+ "less",
10062
+ "lest",
10063
+ "let",
10064
+ "lets",
10065
+ "let's",
10066
+ "lf",
10067
+ "like",
10068
+ "liked",
10069
+ "likely",
10070
+ "line",
10071
+ "little",
10072
+ "lj",
10073
+ "ll",
10074
+ "ll",
10075
+ "ln",
10076
+ "lo",
10077
+ "look",
10078
+ "looking",
10079
+ "looks",
10080
+ "los",
10081
+ "lr",
10082
+ "ls",
10083
+ "lt",
10084
+ "ltd",
10085
+ "m",
10086
+ "m2",
10087
+ "ma",
10088
+ "made",
10089
+ "mainly",
10090
+ "make",
10091
+ "makes",
10092
+ "many",
10093
+ "may",
10094
+ "maybe",
10095
+ "me",
10096
+ "mean",
10097
+ "means",
10098
+ "meantime",
10099
+ "meanwhile",
10100
+ "merely",
10101
+ "mg",
10102
+ "might",
10103
+ "mightn",
10104
+ "mightn't",
10105
+ "mill",
10106
+ "million",
10107
+ "mine",
10108
+ "miss",
10109
+ "ml",
10110
+ "mn",
10111
+ "mo",
10112
+ "more",
10113
+ "moreover",
10114
+ "most",
10115
+ "mostly",
10116
+ "move",
10117
+ "mr",
10118
+ "mrs",
10119
+ "ms",
10120
+ "mt",
10121
+ "mu",
10122
+ "much",
10123
+ "mug",
10124
+ "must",
10125
+ "mustn",
10126
+ "mustn't",
10127
+ "my",
10128
+ "myself",
10129
+ "model",
10130
+ "n",
10131
+ "n2",
10132
+ "na",
10133
+ "name",
10134
+ "namely",
10135
+ "nay",
10136
+ "nc",
10137
+ "nd",
10138
+ "ne",
10139
+ "near",
10140
+ "nearly",
10141
+ "necessarily",
10142
+ "necessary",
10143
+ "need",
10144
+ "needn",
10145
+ "needn't",
10146
+ "needs",
10147
+ "neither",
10148
+ "never",
10149
+ "nevertheless",
10150
+ "new",
10151
+ "next",
10152
+ "ng",
10153
+ "ni",
10154
+ "nine",
10155
+ "ninety",
10156
+ "nj",
10157
+ "nl",
10158
+ "nn",
10159
+ "no",
10160
+ "nobody",
10161
+ "non",
10162
+ "none",
10163
+ "nonetheless",
10164
+ "noone",
10165
+ "nor",
10166
+ "normally",
10167
+ "nos",
10168
+ "not",
10169
+ "noted",
10170
+ "nothing",
10171
+ "novel",
10172
+ "now",
10173
+ "nowhere",
10174
+ "nr",
10175
+ "ns",
10176
+ "nt",
10177
+ "ny",
10178
+ "o",
10179
+ "oa",
10180
+ "ob",
10181
+ "obtain",
10182
+ "obtained",
10183
+ "obviously",
10184
+ "oc",
10185
+ "od",
10186
+ "of",
10187
+ "off",
10188
+ "often",
10189
+ "og",
10190
+ "oh",
10191
+ "oi",
10192
+ "oj",
10193
+ "ok",
10194
+ "okay",
10195
+ "ol",
10196
+ "old",
10197
+ "om",
10198
+ "omitted",
10199
+ "on",
10200
+ "once",
10201
+ "one",
10202
+ "ones",
10203
+ "only",
10204
+ "onto",
10205
+ "oo",
10206
+ "op",
10207
+ "oq",
10208
+ "or",
10209
+ "ord",
10210
+ "os",
10211
+ "ot",
10212
+ "other",
10213
+ "others",
10214
+ "otherwise",
10215
+ "ou",
10216
+ "ought",
10217
+ "our",
10218
+ "ours",
10219
+ "ourselves",
10220
+ "out",
10221
+ "outside",
10222
+ "over",
10223
+ "overall",
10224
+ "ow",
10225
+ "owing",
10226
+ "own",
10227
+ "ox",
10228
+ "oz",
10229
+ "p",
10230
+ "p1",
10231
+ "p2",
10232
+ "p3",
10233
+ "page",
10234
+ "pagecount",
10235
+ "pages",
10236
+ "par",
10237
+ "part",
10238
+ "particular",
10239
+ "particularly",
10240
+ "pas",
10241
+ "past",
10242
+ "pc",
10243
+ "pd",
10244
+ "pe",
10245
+ "per",
10246
+ "perhaps",
10247
+ "pf",
10248
+ "ph",
10249
+ "pi",
10250
+ "pj",
10251
+ "pk",
10252
+ "pl",
10253
+ "placed",
10254
+ "please",
10255
+ "plus",
10256
+ "pm",
10257
+ "pn",
10258
+ "po",
10259
+ "poorly",
10260
+ "possible",
10261
+ "possibly",
10262
+ "potentially",
10263
+ "pp",
10264
+ "pq",
10265
+ "pr",
10266
+ "predominantly",
10267
+ "present",
10268
+ "presumably",
10269
+ "previously",
10270
+ "primarily",
10271
+ "probably",
10272
+ "promptly",
10273
+ "proud",
10274
+ "provides",
10275
+ "ps",
10276
+ "pt",
10277
+ "pu",
10278
+ "put",
10279
+ "py",
10280
+ "q",
10281
+ "qj",
10282
+ "qu",
10283
+ "que",
10284
+ "quickly",
10285
+ "quite",
10286
+ "qv",
10287
+ "r",
10288
+ "r2",
10289
+ "ra",
10290
+ "ran",
10291
+ "rather",
10292
+ "rc",
10293
+ "rd",
10294
+ "re",
10295
+ "readily",
10296
+ "really",
10297
+ "reasonably",
10298
+ "recent",
10299
+ "recently",
10300
+ "ref",
10301
+ "refs",
10302
+ "regarding",
10303
+ "regardless",
10304
+ "regards",
10305
+ "related",
10306
+ "relatively",
10307
+ "research",
10308
+ "research-articl",
10309
+ "respectively",
10310
+ "resulted",
10311
+ "resulting",
10312
+ "results",
10313
+ "rf",
10314
+ "rh",
10315
+ "ri",
10316
+ "right",
10317
+ "rj",
10318
+ "rl",
10319
+ "rm",
10320
+ "rn",
10321
+ "ro",
10322
+ "rq",
10323
+ "rr",
10324
+ "rs",
10325
+ "rt",
10326
+ "ru",
10327
+ "run",
10328
+ "rv",
10329
+ "ry",
10330
+ "s",
10331
+ "s2",
10332
+ "sa",
10333
+ "said",
10334
+ "same",
10335
+ "saw",
10336
+ "say",
10337
+ "saying",
10338
+ "says",
10339
+ "sc",
10340
+ "sd",
10341
+ "se",
10342
+ "sec",
10343
+ "second",
10344
+ "secondly",
10345
+ "section",
10346
+ "see",
10347
+ "seeing",
10348
+ "seem",
10349
+ "seemed",
10350
+ "seeming",
10351
+ "seems",
10352
+ "seen",
10353
+ "self",
10354
+ "selves",
10355
+ "sensible",
10356
+ "sent",
10357
+ "serious",
10358
+ "seriously",
10359
+ "seven",
10360
+ "several",
10361
+ "sf",
10362
+ "shall",
10363
+ "shan",
10364
+ "shan't",
10365
+ "she",
10366
+ "shed",
10367
+ "she'd",
10368
+ "she'll",
10369
+ "shes",
10370
+ "she's",
10371
+ "should",
10372
+ "shouldn",
10373
+ "shouldn't",
10374
+ "should've",
10375
+ "show",
10376
+ "showed",
10377
+ "shown",
10378
+ "showns",
10379
+ "shows",
10380
+ "si",
10381
+ "side",
10382
+ "significant",
10383
+ "significantly",
10384
+ "similar",
10385
+ "similarly",
10386
+ "since",
10387
+ "sincere",
10388
+ "six",
10389
+ "sixty",
10390
+ "sj",
10391
+ "sl",
10392
+ "slightly",
10393
+ "sm",
10394
+ "sn",
10395
+ "so",
10396
+ "some",
10397
+ "somebody",
10398
+ "somehow",
10399
+ "someone",
10400
+ "somethan",
10401
+ "something",
10402
+ "sometime",
10403
+ "sometimes",
10404
+ "somewhat",
10405
+ "somewhere",
10406
+ "soon",
10407
+ "sorry",
10408
+ "sp",
10409
+ "specifically",
10410
+ "specified",
10411
+ "specify",
10412
+ "specifying",
10413
+ "sq",
10414
+ "sr",
10415
+ "ss",
10416
+ "st",
10417
+ "still",
10418
+ "stop",
10419
+ "strongly",
10420
+ "sub",
10421
+ "substantially",
10422
+ "successfully",
10423
+ "such",
10424
+ "sufficiently",
10425
+ "suggest",
10426
+ "sup",
10427
+ "sure",
10428
+ "sy",
10429
+ "system",
10430
+ "sz",
10431
+ "t",
10432
+ "t1",
10433
+ "t2",
10434
+ "t3",
10435
+ "take",
10436
+ "taken",
10437
+ "taking",
10438
+ "tb",
10439
+ "tc",
10440
+ "td",
10441
+ "te",
10442
+ "tell",
10443
+ "ten",
10444
+ "tends",
10445
+ "tf",
10446
+ "th",
10447
+ "than",
10448
+ "thank",
10449
+ "thanks",
10450
+ "thanx",
10451
+ "that",
10452
+ "that'll",
10453
+ "thats",
10454
+ "that's",
10455
+ "that've",
10456
+ "the",
10457
+ "their",
10458
+ "theirs",
10459
+ "them",
10460
+ "themselves",
10461
+ "then",
10462
+ "thence",
10463
+ "there",
10464
+ "thereafter",
10465
+ "thereby",
10466
+ "thered",
10467
+ "therefore",
10468
+ "therein",
10469
+ "there'll",
10470
+ "thereof",
10471
+ "therere",
10472
+ "theres",
10473
+ "there's",
10474
+ "thereto",
10475
+ "thereupon",
10476
+ "there've",
10477
+ "these",
10478
+ "they",
10479
+ "theyd",
10480
+ "they'd",
10481
+ "they'll",
10482
+ "theyre",
10483
+ "they're",
10484
+ "they've",
10485
+ "thickv",
10486
+ "thin",
10487
+ "think",
10488
+ "third",
10489
+ "this",
10490
+ "thorough",
10491
+ "thoroughly",
10492
+ "those",
10493
+ "thou",
10494
+ "though",
10495
+ "thoughh",
10496
+ "thousand",
10497
+ "three",
10498
+ "throug",
10499
+ "through",
10500
+ "throughout",
10501
+ "thru",
10502
+ "thus",
10503
+ "ti",
10504
+ "til",
10505
+ "tip",
10506
+ "tj",
10507
+ "tl",
10508
+ "tm",
10509
+ "tn",
10510
+ "to",
10511
+ "together",
10512
+ "too",
10513
+ "took",
10514
+ "top",
10515
+ "toward",
10516
+ "towards",
10517
+ "tp",
10518
+ "tq",
10519
+ "tr",
10520
+ "tried",
10521
+ "tries",
10522
+ "truly",
10523
+ "try",
10524
+ "trying",
10525
+ "ts",
10526
+ "t's",
10527
+ "tt",
10528
+ "tv",
10529
+ "twelve",
10530
+ "twenty",
10531
+ "twice",
10532
+ "two",
10533
+ "tx",
10534
+ "u",
10535
+ "u201d",
10536
+ "ue",
10537
+ "ui",
10538
+ "uj",
10539
+ "uk",
10540
+ "um",
10541
+ "un",
10542
+ "under",
10543
+ "unfortunately",
10544
+ "unless",
10545
+ "unlike",
10546
+ "unlikely",
10547
+ "until",
10548
+ "unto",
10549
+ "uo",
10550
+ "up",
10551
+ "upon",
10552
+ "ups",
10553
+ "ur",
10554
+ "us",
10555
+ "use",
10556
+ "used",
10557
+ "useful",
10558
+ "usefully",
10559
+ "usefulness",
10560
+ "uses",
10561
+ "using",
10562
+ "usually",
10563
+ "ut",
10564
+ "v",
10565
+ "va",
10566
+ "value",
10567
+ "various",
10568
+ "vd",
10569
+ "ve",
10570
+ "ve",
10571
+ "very",
10572
+ "via",
10573
+ "viz",
10574
+ "vj",
10575
+ "vo",
10576
+ "vol",
10577
+ "vols",
10578
+ "volumtype",
10579
+ "vq",
10580
+ "vs",
10581
+ "vt",
10582
+ "vu",
10583
+ "w",
10584
+ "wa",
10585
+ "want",
10586
+ "wants",
10587
+ "was",
10588
+ "wasn",
10589
+ "wasnt",
10590
+ "wasn't",
10591
+ "way",
10592
+ "we",
10593
+ "wed",
10594
+ "we'd",
10595
+ "welcome",
10596
+ "well",
10597
+ "we'll",
10598
+ "well-b",
10599
+ "went",
10600
+ "were",
10601
+ "we're",
10602
+ "weren",
10603
+ "werent",
10604
+ "weren't",
10605
+ "we've",
10606
+ "what",
10607
+ "whatever",
10608
+ "what'll",
10609
+ "whats",
10610
+ "what's",
10611
+ "when",
10612
+ "whence",
10613
+ "whenever",
10614
+ "when's",
10615
+ "where",
10616
+ "whereafter",
10617
+ "whereas",
10618
+ "whereby",
10619
+ "wherein",
10620
+ "wheres",
10621
+ "where's",
10622
+ "whereupon",
10623
+ "wherever",
10624
+ "whether",
10625
+ "which",
10626
+ "while",
10627
+ "whim",
10628
+ "whither",
10629
+ "who",
10630
+ "whod",
10631
+ "whoever",
10632
+ "whole",
10633
+ "who'll",
10634
+ "whom",
10635
+ "whomever",
10636
+ "whos",
10637
+ "who's",
10638
+ "whose",
10639
+ "why",
10640
+ "why's",
10641
+ "wi",
10642
+ "widely",
10643
+ "will",
10644
+ "willing",
10645
+ "wish",
10646
+ "with",
10647
+ "within",
10648
+ "without",
10649
+ "wo",
10650
+ "won",
10651
+ "wonder",
10652
+ "wont",
10653
+ "won't",
10654
+ "words",
10655
+ "world",
10656
+ "would",
10657
+ "wouldn",
10658
+ "wouldnt",
10659
+ "wouldn't",
10660
+ "www",
10661
+ "x",
10662
+ "x1",
10663
+ "x2",
10664
+ "x3",
10665
+ "xf",
10666
+ "xi",
10667
+ "xj",
10668
+ "xk",
10669
+ "xl",
10670
+ "xn",
10671
+ "xo",
10672
+ "xs",
10673
+ "xt",
10674
+ "xv",
10675
+ "xx",
10676
+ "y",
10677
+ "y2",
10678
+ "yes",
10679
+ "yet",
10680
+ "yj",
10681
+ "yl",
10682
+ "you",
10683
+ "youd",
10684
+ "you'd",
10685
+ "you'll",
10686
+ "your",
10687
+ "youre",
10688
+ "you're",
10689
+ "yours",
10690
+ "yourself",
10691
+ "yourselves",
10692
+ "you've",
10693
+ "yr",
10694
+ "ys",
10695
+ "yt",
10696
+ "z",
10697
+ "zero",
10698
+ "zi",
10699
+ "zz",
10700
+ "task"
10701
+ ]);
10702
+
10703
+ // dsp/eval.ts
10704
+ function filterTokens(tokens, exclusions) {
10705
+ return tokens.filter((token) => !exclusions.has(token));
10706
+ }
10707
+ function countTokens(tokens) {
10708
+ const counter = {};
10709
+ for (const token of tokens) {
10710
+ counter[token] = (counter[token] || 0) + 1;
10711
+ }
10712
+ return counter;
10713
+ }
10714
+ function normalizeText(s) {
10715
+ s = s.normalize("NFD");
10716
+ s = s.replace(/\b(a|an|the)\b/g, " ");
10717
+ s = s.split(/\s+/).join(" ");
10718
+ s = s.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g, "");
10719
+ return s.toLowerCase();
10720
+ }
10721
+ function emScore(prediction, groundTruth) {
10722
+ return normalizeText(prediction) === normalizeText(groundTruth);
10723
+ }
10724
+ function f1Score(prediction, groundTruth) {
10725
+ const predictionTokens = normalizeText(prediction).split(" ");
10726
+ const groundTruthTokens = normalizeText(groundTruth).split(" ");
10727
+ const predictionCounts = countTokens(predictionTokens);
10728
+ const groundTruthCounts = countTokens(groundTruthTokens);
10729
+ let numSame = 0;
10730
+ for (const token in predictionCounts) {
10731
+ const v1 = predictionCounts[token] ?? 0;
10732
+ const v2 = groundTruthCounts[token] ?? 0;
10733
+ numSame += Math.min(v1, v2);
10734
+ }
10735
+ if (numSame === 0) {
10736
+ return 0;
10737
+ }
10738
+ const precision = numSame / predictionTokens.length;
10739
+ const recall = numSame / groundTruthTokens.length;
10740
+ return 2 * precision * recall / (precision + recall);
10741
+ }
10742
+ function novelF1ScoreOptimized(history, prediction, groundTruth, returnRecall = false) {
10743
+ const historyTokens = normalizeText(history).split(" ");
10744
+ let predictionTokens = normalizeText(prediction).split(" ");
10745
+ let groundTruthTokens = normalizeText(groundTruth).split(" ");
10746
+ const exclusions = /* @__PURE__ */ new Set([...stopwords, ...historyTokens]);
10747
+ predictionTokens = filterTokens(predictionTokens, exclusions);
10748
+ groundTruthTokens = filterTokens(groundTruthTokens, exclusions);
10749
+ const numSame = 0;
10750
+ const precision = numSame / predictionTokens.length;
10751
+ const recall = numSame / groundTruthTokens.length;
10752
+ const f1 = 2 * precision * recall / (precision + recall);
10753
+ return returnRecall ? recall : f1;
10754
+ }
10755
+ var AxEvalUtil = {
10756
+ emScore,
10757
+ f1Score,
10758
+ novelF1ScoreOptimized
10759
+ };
10760
+
8628
10761
  // ../../node_modules/uuid/dist/esm-node/rng.js
8629
10762
  var import_crypto2 = __toESM(require("crypto"));
8630
10763
  var rnds8Pool = new Uint8Array(256);
@@ -9121,7 +11254,7 @@ var AxRAG = class extends AxChainOfThought {
9121
11254
  options
9122
11255
  );
9123
11256
  const val = await this.queryFn(query);
9124
- context = axStringUtil.dedup([...context, val]);
11257
+ context = AxStringUtil.dedup([...context, val]);
9125
11258
  }
9126
11259
  return super.forward(ai, { context, question }, options);
9127
11260
  }
@@ -9183,6 +11316,7 @@ var AxRAG = class extends AxChainOfThought {
9183
11316
  AxDefaultResultReranker,
9184
11317
  AxDockerSession,
9185
11318
  AxEmbeddingAdapter,
11319
+ AxEvalUtil,
9186
11320
  AxFunctionError,
9187
11321
  AxFunctionProcessor,
9188
11322
  AxGen,
@@ -9195,6 +11329,7 @@ var AxRAG = class extends AxChainOfThought {
9195
11329
  AxMCPHTTPTransport,
9196
11330
  AxMCPStdioTransport,
9197
11331
  AxMemory,
11332
+ AxMiPRO,
9198
11333
  AxMockAIService,
9199
11334
  AxMultiServiceRouter,
9200
11335
  AxProgram,
@@ -9206,6 +11341,47 @@ var AxRAG = class extends AxChainOfThought {
9206
11341
  AxSimpleClassifier,
9207
11342
  AxSimpleClassifierClass,
9208
11343
  AxSpanKindValues,
9209
- AxTestPrompt
11344
+ AxStringUtil,
11345
+ AxTestPrompt,
11346
+ axAIAnthropicDefaultConfig,
11347
+ axAIAzureOpenAIBestConfig,
11348
+ axAIAzureOpenAICreativeConfig,
11349
+ axAIAzureOpenAIDefaultConfig,
11350
+ axAIAzureOpenAIFastConfig,
11351
+ axAICohereCreativeConfig,
11352
+ axAICohereDefaultConfig,
11353
+ axAIDeepSeekCodeConfig,
11354
+ axAIDeepSeekDefaultConfig,
11355
+ axAIGoogleGeminiDefaultConfig,
11356
+ axAIGoogleGeminiDefaultCreativeConfig,
11357
+ axAIHuggingFaceCreativeConfig,
11358
+ axAIHuggingFaceDefaultConfig,
11359
+ axAIMistralBestConfig,
11360
+ axAIMistralDefaultConfig,
11361
+ axAIOllamaDefaultConfig,
11362
+ axAIOllamaDefaultCreativeConfig,
11363
+ axAIOpenAIBestConfig,
11364
+ axAIOpenAICreativeConfig,
11365
+ axAIOpenAIDefaultConfig,
11366
+ axAIOpenAIFastConfig,
11367
+ axAIRekaBestConfig,
11368
+ axAIRekaCreativeConfig,
11369
+ axAIRekaDefaultConfig,
11370
+ axAIRekaFastConfig,
11371
+ axAITogetherDefaultConfig,
11372
+ axBaseAIDefaultConfig,
11373
+ axBaseAIDefaultCreativeConfig,
11374
+ axModelInfoAnthropic,
11375
+ axModelInfoCohere,
11376
+ axModelInfoDeepSeek,
11377
+ axModelInfoGoogleGemini,
11378
+ axModelInfoGroq,
11379
+ axModelInfoHuggingFace,
11380
+ axModelInfoMistral,
11381
+ axModelInfoOpenAI,
11382
+ axModelInfoReka,
11383
+ axModelInfoTogether,
11384
+ axSpanAttributes,
11385
+ axSpanEvents
9210
11386
  });
9211
11387
  //# sourceMappingURL=index.cjs.map