@ax-llm/ax 12.0.22 → 12.0.24

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
@@ -117,7 +117,6 @@ __export(index_exports, {
117
117
  AxMockAIService: () => AxMockAIService,
118
118
  AxMultiServiceRouter: () => AxMultiServiceRouter,
119
119
  AxProgram: () => AxProgram,
120
- AxProgramWithSignature: () => AxProgramWithSignature,
121
120
  AxPromptTemplate: () => AxPromptTemplate,
122
121
  AxRAG: () => AxRAG,
123
122
  AxRateLimiterTokenUsage: () => AxRateLimiterTokenUsage,
@@ -4987,7 +4986,8 @@ var AxAIGoogleGemini = class extends AxBaseAI {
4987
4986
  } else {
4988
4987
  path = "publishers/google";
4989
4988
  }
4990
- apiURL = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/${path}`;
4989
+ const tld = region === "global" ? "aiplatform" : `${region}-aiplatform`;
4990
+ apiURL = `https://${tld}.googleapis.com/v1/projects/${projectId}/locations/${region}/${path}`;
4991
4991
  if (apiKey) {
4992
4992
  headers = async () => ({ Authorization: `Bearer ${apiKey}` });
4993
4993
  } else {
@@ -11277,7 +11277,7 @@ var AxInstanceRegistry = class {
11277
11277
  };
11278
11278
 
11279
11279
  // dsp/program.ts
11280
- var AxProgramWithSignature = class {
11280
+ var AxProgram = class {
11281
11281
  signature;
11282
11282
  sigHash;
11283
11283
  examples;
@@ -11285,6 +11285,7 @@ var AxProgramWithSignature = class {
11285
11285
  demos;
11286
11286
  trace;
11287
11287
  usage = [];
11288
+ traceLabel;
11288
11289
  key;
11289
11290
  children;
11290
11291
  constructor(signature, options) {
@@ -11292,6 +11293,9 @@ var AxProgramWithSignature = class {
11292
11293
  if (options?.description) {
11293
11294
  this.signature.setDescription(options.description);
11294
11295
  }
11296
+ if (options?.traceLabel) {
11297
+ this.traceLabel = options.traceLabel;
11298
+ }
11295
11299
  this.signature.validate();
11296
11300
  this.sigHash = this.signature?.hash();
11297
11301
  this.children = new AxInstanceRegistry();
@@ -11397,85 +11401,6 @@ var AxProgramWithSignature = class {
11397
11401
  }
11398
11402
  }
11399
11403
  };
11400
- var AxProgram = class {
11401
- trace;
11402
- usage = [];
11403
- key;
11404
- children;
11405
- constructor() {
11406
- this.children = new AxInstanceRegistry();
11407
- this.key = { id: this.constructor.name };
11408
- }
11409
- register(prog) {
11410
- if (this.key) {
11411
- prog.setParentId(this.key.id);
11412
- }
11413
- this.children.register(prog);
11414
- }
11415
- async forward(_ai, _values, _options) {
11416
- throw new Error("forward() not implemented");
11417
- }
11418
- // biome-ignore lint/correctness/useYield: just a placeholder
11419
- async *streamingForward(_ai, _values, _options) {
11420
- throw new Error("streamingForward() not implemented");
11421
- }
11422
- setId(id) {
11423
- this.key = { id, custom: true };
11424
- for (const child of Array.from(this.children)) {
11425
- child?.setParentId(id);
11426
- }
11427
- }
11428
- setParentId(parentId) {
11429
- if (!this.key.custom) {
11430
- this.key.id = [parentId, this.key.id].join("/");
11431
- }
11432
- }
11433
- setExamples(examples, options) {
11434
- if (!("programId" in examples)) {
11435
- return;
11436
- }
11437
- for (const child of Array.from(this.children)) {
11438
- child?.setExamples(examples, options);
11439
- }
11440
- }
11441
- getTraces() {
11442
- let traces = [];
11443
- if (this.trace) {
11444
- traces.push({ trace: this.trace, programId: this.key.id });
11445
- }
11446
- for (const child of Array.from(this.children)) {
11447
- const _traces = child?.getTraces();
11448
- traces = [...traces, ..._traces ?? []];
11449
- }
11450
- return traces;
11451
- }
11452
- getUsage() {
11453
- let usage = [...this.usage ?? []];
11454
- for (const child of Array.from(this.children)) {
11455
- const cu = child?.getUsage();
11456
- usage = [...usage, ...cu ?? []];
11457
- }
11458
- return mergeProgramUsage(usage);
11459
- }
11460
- resetUsage() {
11461
- this.usage = [];
11462
- for (const child of Array.from(this.children)) {
11463
- child?.resetUsage();
11464
- }
11465
- }
11466
- setDemos(demos) {
11467
- const hasChildren = Array.from(this.children).length > 0;
11468
- const hasMatchingDemo = demos.some((demo) => demo.programId === this.key.id);
11469
- if (hasChildren && !hasMatchingDemo) {
11470
- throw new Error(
11471
- `Program with id '${this.key.id}' has children but no matching programId found in demos`
11472
- );
11473
- }
11474
- for (const child of Array.from(this.children)) {
11475
- child?.setDemos(demos);
11476
- }
11477
- }
11478
- };
11479
11404
 
11480
11405
  // dsp/samples.ts
11481
11406
  function checkForFunctionCalls(mem, sessionId) {
@@ -11590,7 +11515,7 @@ ${errors}`, {
11590
11515
  }
11591
11516
 
11592
11517
  // dsp/generate.ts
11593
- var AxGen = class extends AxProgramWithSignature {
11518
+ var AxGen = class extends AxProgram {
11594
11519
  promptTemplate;
11595
11520
  asserts;
11596
11521
  streamingAsserts;
@@ -11601,7 +11526,10 @@ var AxGen = class extends AxProgramWithSignature {
11601
11526
  excludeContentFromTrace = false;
11602
11527
  thoughtFieldName;
11603
11528
  constructor(signature, options) {
11604
- super(signature, { description: options?.description });
11529
+ super(signature, {
11530
+ description: options?.description,
11531
+ traceLabel: options?.traceLabel
11532
+ });
11605
11533
  this.options = options;
11606
11534
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
11607
11535
  const promptTemplateOptions = {
@@ -12045,8 +11973,8 @@ var AxGen = class extends AxProgramWithSignature {
12045
11973
  ...options?.maxSteps ? { max_steps: options.maxSteps } : {},
12046
11974
  ...options?.maxRetries ? { max_retries: options.maxRetries } : {}
12047
11975
  };
12048
- const traceLabel = options.traceLabel ?? this.options?.traceLabel;
12049
- const spanName = traceLabel ? `${traceLabel} (AxGen)` : "AxGen";
11976
+ const traceLabel = this.traceLabel && options.traceLabel ? `${this.traceLabel} > ${options.traceLabel}` : options.traceLabel ?? this.traceLabel;
11977
+ const spanName = traceLabel ? `AxGen > ${traceLabel}` : "AxGen";
12050
11978
  const span = tracer.startSpan(spanName, {
12051
11979
  kind: import_api22.SpanKind.SERVER,
12052
11980
  attributes
@@ -15182,15 +15110,186 @@ var AxDockerSession = class {
15182
15110
  };
15183
15111
 
15184
15112
  // flow/flow.ts
15185
- var AxFlow = class extends AxProgramWithSignature {
15113
+ var AxFlowDependencyAnalyzer = class {
15114
+ /**
15115
+ * Analyzes a mapping function to determine which state fields it depends on
15116
+ */
15117
+ analyzeMappingDependencies(mapping, _nodeName) {
15118
+ const dependencies = [];
15119
+ const source = mapping.toString();
15120
+ const stateAccessMatches = Array.from(source.matchAll(/state\.(\w+)/g));
15121
+ for (const match of stateAccessMatches) {
15122
+ if (match[1] && !dependencies.includes(match[1])) {
15123
+ dependencies.push(match[1]);
15124
+ }
15125
+ }
15126
+ if (dependencies.length === 0) {
15127
+ try {
15128
+ const tracker = this.createDependencyTracker(dependencies);
15129
+ mapping(tracker);
15130
+ } catch {
15131
+ }
15132
+ }
15133
+ return dependencies;
15134
+ }
15135
+ createDependencyTracker(dependencies) {
15136
+ return new Proxy(
15137
+ {},
15138
+ {
15139
+ get(target, prop) {
15140
+ if (typeof prop === "string" && !dependencies.includes(prop)) {
15141
+ dependencies.push(prop);
15142
+ }
15143
+ return new Proxy(
15144
+ {},
15145
+ {
15146
+ get: () => void 0
15147
+ }
15148
+ );
15149
+ }
15150
+ }
15151
+ );
15152
+ }
15153
+ };
15154
+ var AxFlowExecutionPlanner = class {
15155
+ steps = [];
15156
+ parallelGroups = [];
15157
+ analyzer = new AxFlowDependencyAnalyzer();
15158
+ initialFields = /* @__PURE__ */ new Set();
15159
+ /**
15160
+ * Adds an execution step to the plan
15161
+ */
15162
+ addExecutionStep(stepFunction, nodeName, mapping) {
15163
+ let dependencies = [];
15164
+ let produces = [];
15165
+ let type = "other";
15166
+ if (nodeName && mapping) {
15167
+ type = "execute";
15168
+ dependencies = this.analyzer.analyzeMappingDependencies(mapping, nodeName);
15169
+ produces = [`${nodeName}Result`];
15170
+ } else if (stepFunction.toString().includes("transform(")) {
15171
+ type = "map";
15172
+ dependencies = this.getAllProducedFields();
15173
+ }
15174
+ const step = {
15175
+ type,
15176
+ nodeName,
15177
+ dependencies,
15178
+ produces,
15179
+ stepFunction,
15180
+ stepIndex: this.steps.length
15181
+ };
15182
+ this.steps.push(step);
15183
+ }
15184
+ /**
15185
+ * Sets the initial fields and rebuilds parallel groups
15186
+ */
15187
+ setInitialFields(fields) {
15188
+ this.initialFields = new Set(fields);
15189
+ this.rebuildParallelGroups();
15190
+ }
15191
+ /**
15192
+ * Rebuilds the parallel execution groups based on dependencies
15193
+ */
15194
+ rebuildParallelGroups() {
15195
+ this.parallelGroups = [];
15196
+ const processedSteps = /* @__PURE__ */ new Set();
15197
+ const availableFields = new Set(this.initialFields);
15198
+ let currentLevel = 0;
15199
+ while (processedSteps.size < this.steps.length) {
15200
+ const currentLevelSteps = [];
15201
+ for (const step of this.steps) {
15202
+ if (processedSteps.has(step.stepIndex)) continue;
15203
+ const canRun = step.dependencies.length === 0 || step.dependencies.every((dep) => availableFields.has(dep));
15204
+ if (canRun) {
15205
+ currentLevelSteps.push(step);
15206
+ processedSteps.add(step.stepIndex);
15207
+ }
15208
+ }
15209
+ if (currentLevelSteps.length > 0) {
15210
+ for (const step of currentLevelSteps) {
15211
+ step.produces.forEach((field) => availableFields.add(field));
15212
+ }
15213
+ this.parallelGroups.push({
15214
+ level: currentLevel,
15215
+ steps: currentLevelSteps
15216
+ });
15217
+ currentLevel++;
15218
+ } else {
15219
+ break;
15220
+ }
15221
+ }
15222
+ }
15223
+ /**
15224
+ * Gets all fields produced by previous steps
15225
+ */
15226
+ getAllProducedFields() {
15227
+ const fields = [];
15228
+ for (const step of this.steps) {
15229
+ fields.push(...step.produces);
15230
+ }
15231
+ return fields;
15232
+ }
15233
+ /**
15234
+ * Creates optimized execution function
15235
+ */
15236
+ createOptimizedExecution() {
15237
+ const optimizedSteps = [];
15238
+ for (const group of this.parallelGroups) {
15239
+ if (group.steps.length === 1) {
15240
+ const step = group.steps[0];
15241
+ if (step) {
15242
+ optimizedSteps.push(step.stepFunction);
15243
+ }
15244
+ } else if (group.steps.length > 1) {
15245
+ const parallelStep = async (state, context3) => {
15246
+ const promises = group.steps.map(
15247
+ (step) => step.stepFunction(state, context3)
15248
+ );
15249
+ const results = await Promise.all(promises);
15250
+ let mergedState = state;
15251
+ for (const result of results) {
15252
+ mergedState = { ...mergedState, ...result };
15253
+ }
15254
+ return mergedState;
15255
+ };
15256
+ optimizedSteps.push(parallelStep);
15257
+ }
15258
+ }
15259
+ return optimizedSteps;
15260
+ }
15261
+ /**
15262
+ * Gets execution plan info for debugging
15263
+ */
15264
+ getExecutionPlan() {
15265
+ return {
15266
+ totalSteps: this.steps.length,
15267
+ parallelGroups: this.parallelGroups.length,
15268
+ maxParallelism: Math.max(
15269
+ ...this.parallelGroups.map((g) => g.steps.length),
15270
+ 0
15271
+ ),
15272
+ steps: this.steps,
15273
+ groups: this.parallelGroups
15274
+ };
15275
+ }
15276
+ };
15277
+ var AxFlow = class extends AxProgram {
15186
15278
  nodes = /* @__PURE__ */ new Map();
15187
15279
  flowDefinition = [];
15188
15280
  nodeGenerators = /* @__PURE__ */ new Map();
15189
15281
  loopStack = [];
15190
15282
  stepLabels = /* @__PURE__ */ new Map();
15191
15283
  branchContext = null;
15192
- constructor(signature = "userInput:string -> flowOutput:string") {
15284
+ // Automatic parallelization components
15285
+ autoParallelConfig;
15286
+ executionPlanner = new AxFlowExecutionPlanner();
15287
+ constructor(signature = "userInput:string -> flowOutput:string", options) {
15193
15288
  super(signature);
15289
+ this.autoParallelConfig = {
15290
+ enabled: options?.autoParallel !== false
15291
+ // Default to true
15292
+ };
15194
15293
  }
15195
15294
  // Implementation
15196
15295
  node(name, signatureOrAxGenOrClass, options) {
@@ -15209,7 +15308,7 @@ var AxFlow = class extends AxProgramWithSignature {
15209
15308
  outputs: {}
15210
15309
  });
15211
15310
  this.nodeGenerators.set(name, new AxGen(signatureOrAxGenOrClass, options));
15212
- } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgramWithSignature) {
15311
+ } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgram) {
15213
15312
  this.nodes.set(name, {
15214
15313
  inputs: {},
15215
15314
  outputs: {}
@@ -15230,7 +15329,7 @@ var AxFlow = class extends AxProgramWithSignature {
15230
15329
  this.nodeGenerators.set(name, new AxGen(signature, options));
15231
15330
  } else {
15232
15331
  throw new Error(
15233
- `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgramWithSignature`
15332
+ `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgram`
15234
15333
  );
15235
15334
  }
15236
15335
  return this;
@@ -15265,6 +15364,9 @@ var AxFlow = class extends AxProgramWithSignature {
15265
15364
  );
15266
15365
  } else {
15267
15366
  this.flowDefinition.push(step);
15367
+ if (this.autoParallelConfig.enabled) {
15368
+ this.executionPlanner.addExecutionStep(step);
15369
+ }
15268
15370
  }
15269
15371
  return this;
15270
15372
  }
@@ -15327,7 +15429,11 @@ var AxFlow = class extends AxProgramWithSignature {
15327
15429
  const ai = dynamicContext?.ai ?? context3.mainAi;
15328
15430
  const options = dynamicContext?.options ?? context3.mainOptions;
15329
15431
  const nodeInputs = mapping(state);
15330
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15432
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15433
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15434
+ ...options,
15435
+ traceLabel
15436
+ });
15331
15437
  return {
15332
15438
  ...state,
15333
15439
  [`${nodeName}Result`]: result
@@ -15344,6 +15450,9 @@ var AxFlow = class extends AxProgramWithSignature {
15344
15450
  );
15345
15451
  } else {
15346
15452
  this.flowDefinition.push(step);
15453
+ if (this.autoParallelConfig.enabled) {
15454
+ this.executionPlanner.addExecutionStep(step, nodeName, mapping);
15455
+ }
15347
15456
  }
15348
15457
  return this;
15349
15458
  }
@@ -15640,7 +15749,7 @@ var AxFlow = class extends AxProgramWithSignature {
15640
15749
  *
15641
15750
  * @param ai - The AI service to use as the default for all steps
15642
15751
  * @param values - The input values for the flow
15643
- * @param options - Optional forward options to use as defaults
15752
+ * @param options - Optional forward options to use as defaults (includes autoParallel override)
15644
15753
  * @returns Promise that resolves to the final output
15645
15754
  */
15646
15755
  async forward(ai, values, options) {
@@ -15649,11 +15758,36 @@ var AxFlow = class extends AxProgramWithSignature {
15649
15758
  mainAi: ai,
15650
15759
  mainOptions: options
15651
15760
  };
15652
- for (const step of this.flowDefinition) {
15653
- state = await step(state, context3);
15761
+ const useAutoParallel = options?.autoParallel !== false && this.autoParallelConfig.enabled;
15762
+ if (useAutoParallel) {
15763
+ this.executionPlanner.setInitialFields(Object.keys(values));
15764
+ const optimizedSteps = this.executionPlanner.createOptimizedExecution();
15765
+ for (const step of optimizedSteps) {
15766
+ state = await step(state, context3);
15767
+ }
15768
+ } else {
15769
+ for (const step of this.flowDefinition) {
15770
+ state = await step(state, context3);
15771
+ }
15654
15772
  }
15655
15773
  return state;
15656
15774
  }
15775
+ /**
15776
+ * Gets execution plan information for debugging automatic parallelization
15777
+ *
15778
+ * @returns Object with execution plan details
15779
+ */
15780
+ getExecutionPlan() {
15781
+ const planInfo = this.executionPlanner.getExecutionPlan();
15782
+ return {
15783
+ totalSteps: planInfo.totalSteps,
15784
+ parallelGroups: planInfo.parallelGroups,
15785
+ maxParallelism: planInfo.maxParallelism,
15786
+ autoParallelEnabled: this.autoParallelConfig.enabled,
15787
+ steps: planInfo.steps,
15788
+ groups: planInfo.groups
15789
+ };
15790
+ }
15657
15791
  };
15658
15792
  var AxFlowSubContextImpl = class {
15659
15793
  constructor(nodeGenerators) {
@@ -15669,7 +15803,11 @@ var AxFlowSubContextImpl = class {
15669
15803
  const ai = dynamicContext?.ai ?? context3.mainAi;
15670
15804
  const options = dynamicContext?.options ?? context3.mainOptions;
15671
15805
  const nodeInputs = mapping(state);
15672
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15806
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15807
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15808
+ ...options,
15809
+ traceLabel
15810
+ });
15673
15811
  return {
15674
15812
  ...state,
15675
15813
  [`${nodeName}Result`]: result
@@ -15703,7 +15841,11 @@ var AxFlowTypedSubContextImpl = class {
15703
15841
  const ai = dynamicContext?.ai ?? context3.mainAi;
15704
15842
  const options = dynamicContext?.options ?? context3.mainOptions;
15705
15843
  const nodeInputs = mapping(state);
15706
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15844
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15845
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15846
+ ...options,
15847
+ traceLabel
15848
+ });
15707
15849
  return {
15708
15850
  ...state,
15709
15851
  [`${nodeName}Result`]: result
@@ -16511,10 +16653,7 @@ var AxMiPRO = class extends AxBaseOptimizer {
16511
16653
  * Generates program summary for context-aware instruction generation
16512
16654
  */
16513
16655
  async generateProgramSummary(program, ai) {
16514
- let signature = "input -> output";
16515
- if ("getSignature" in program && typeof program.getSignature === "function") {
16516
- signature = program.getSignature();
16517
- }
16656
+ const signature = program.getSignature();
16518
16657
  const summaryPrompt = `
16519
16658
  Analyze this language model program and provide a concise summary of its purpose and structure.
16520
16659
 
@@ -19728,7 +19867,6 @@ var AxRAG = class extends AxChainOfThought {
19728
19867
  AxMockAIService,
19729
19868
  AxMultiServiceRouter,
19730
19869
  AxProgram,
19731
- AxProgramWithSignature,
19732
19870
  AxPromptTemplate,
19733
19871
  AxRAG,
19734
19872
  AxRateLimiterTokenUsage,