@ax-llm/ax 12.0.21 → 12.0.23

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,
@@ -11277,7 +11276,7 @@ var AxInstanceRegistry = class {
11277
11276
  };
11278
11277
 
11279
11278
  // dsp/program.ts
11280
- var AxProgramWithSignature = class {
11279
+ var AxProgram = class {
11281
11280
  signature;
11282
11281
  sigHash;
11283
11282
  examples;
@@ -11285,6 +11284,7 @@ var AxProgramWithSignature = class {
11285
11284
  demos;
11286
11285
  trace;
11287
11286
  usage = [];
11287
+ traceLabel;
11288
11288
  key;
11289
11289
  children;
11290
11290
  constructor(signature, options) {
@@ -11292,6 +11292,9 @@ var AxProgramWithSignature = class {
11292
11292
  if (options?.description) {
11293
11293
  this.signature.setDescription(options.description);
11294
11294
  }
11295
+ if (options?.traceLabel) {
11296
+ this.traceLabel = options.traceLabel;
11297
+ }
11295
11298
  this.signature.validate();
11296
11299
  this.sigHash = this.signature?.hash();
11297
11300
  this.children = new AxInstanceRegistry();
@@ -11397,85 +11400,6 @@ var AxProgramWithSignature = class {
11397
11400
  }
11398
11401
  }
11399
11402
  };
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
11403
 
11480
11404
  // dsp/samples.ts
11481
11405
  function checkForFunctionCalls(mem, sessionId) {
@@ -11590,7 +11514,7 @@ ${errors}`, {
11590
11514
  }
11591
11515
 
11592
11516
  // dsp/generate.ts
11593
- var AxGen = class extends AxProgramWithSignature {
11517
+ var AxGen = class extends AxProgram {
11594
11518
  promptTemplate;
11595
11519
  asserts;
11596
11520
  streamingAsserts;
@@ -11601,7 +11525,10 @@ var AxGen = class extends AxProgramWithSignature {
11601
11525
  excludeContentFromTrace = false;
11602
11526
  thoughtFieldName;
11603
11527
  constructor(signature, options) {
11604
- super(signature, { description: options?.description });
11528
+ super(signature, {
11529
+ description: options?.description,
11530
+ traceLabel: options?.traceLabel
11531
+ });
11605
11532
  this.options = options;
11606
11533
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
11607
11534
  const promptTemplateOptions = {
@@ -12045,8 +11972,8 @@ var AxGen = class extends AxProgramWithSignature {
12045
11972
  ...options?.maxSteps ? { max_steps: options.maxSteps } : {},
12046
11973
  ...options?.maxRetries ? { max_retries: options.maxRetries } : {}
12047
11974
  };
12048
- const traceLabel = options.traceLabel ?? this.options?.traceLabel;
12049
- const spanName = traceLabel ? `${traceLabel} (AxGen)` : "AxGen";
11975
+ const traceLabel = this.traceLabel && options.traceLabel ? `${this.traceLabel} > ${options.traceLabel}` : options.traceLabel ?? this.traceLabel;
11976
+ const spanName = traceLabel ? `AxGen > ${traceLabel}` : "AxGen";
12050
11977
  const span = tracer.startSpan(spanName, {
12051
11978
  kind: import_api22.SpanKind.SERVER,
12052
11979
  attributes
@@ -15182,29 +15109,213 @@ var AxDockerSession = class {
15182
15109
  };
15183
15110
 
15184
15111
  // flow/flow.ts
15185
- var AxFlow = class extends AxProgramWithSignature {
15112
+ var AxFlowDependencyAnalyzer = class {
15113
+ /**
15114
+ * Analyzes a mapping function to determine which state fields it depends on
15115
+ */
15116
+ analyzeMappingDependencies(mapping, _nodeName) {
15117
+ const dependencies = [];
15118
+ const source = mapping.toString();
15119
+ const stateAccessMatches = Array.from(source.matchAll(/state\.(\w+)/g));
15120
+ for (const match of stateAccessMatches) {
15121
+ if (match[1] && !dependencies.includes(match[1])) {
15122
+ dependencies.push(match[1]);
15123
+ }
15124
+ }
15125
+ if (dependencies.length === 0) {
15126
+ try {
15127
+ const tracker = this.createDependencyTracker(dependencies);
15128
+ mapping(tracker);
15129
+ } catch {
15130
+ }
15131
+ }
15132
+ return dependencies;
15133
+ }
15134
+ createDependencyTracker(dependencies) {
15135
+ return new Proxy(
15136
+ {},
15137
+ {
15138
+ get(target, prop) {
15139
+ if (typeof prop === "string" && !dependencies.includes(prop)) {
15140
+ dependencies.push(prop);
15141
+ }
15142
+ return new Proxy(
15143
+ {},
15144
+ {
15145
+ get: () => void 0
15146
+ }
15147
+ );
15148
+ }
15149
+ }
15150
+ );
15151
+ }
15152
+ };
15153
+ var AxFlowExecutionPlanner = class {
15154
+ steps = [];
15155
+ parallelGroups = [];
15156
+ analyzer = new AxFlowDependencyAnalyzer();
15157
+ initialFields = /* @__PURE__ */ new Set();
15158
+ /**
15159
+ * Adds an execution step to the plan
15160
+ */
15161
+ addExecutionStep(stepFunction, nodeName, mapping) {
15162
+ let dependencies = [];
15163
+ let produces = [];
15164
+ let type = "other";
15165
+ if (nodeName && mapping) {
15166
+ type = "execute";
15167
+ dependencies = this.analyzer.analyzeMappingDependencies(mapping, nodeName);
15168
+ produces = [`${nodeName}Result`];
15169
+ } else if (stepFunction.toString().includes("transform(")) {
15170
+ type = "map";
15171
+ dependencies = this.getAllProducedFields();
15172
+ }
15173
+ const step = {
15174
+ type,
15175
+ nodeName,
15176
+ dependencies,
15177
+ produces,
15178
+ stepFunction,
15179
+ stepIndex: this.steps.length
15180
+ };
15181
+ this.steps.push(step);
15182
+ }
15183
+ /**
15184
+ * Sets the initial fields and rebuilds parallel groups
15185
+ */
15186
+ setInitialFields(fields) {
15187
+ this.initialFields = new Set(fields);
15188
+ this.rebuildParallelGroups();
15189
+ }
15190
+ /**
15191
+ * Rebuilds the parallel execution groups based on dependencies
15192
+ */
15193
+ rebuildParallelGroups() {
15194
+ this.parallelGroups = [];
15195
+ const processedSteps = /* @__PURE__ */ new Set();
15196
+ const availableFields = new Set(this.initialFields);
15197
+ let currentLevel = 0;
15198
+ while (processedSteps.size < this.steps.length) {
15199
+ const currentLevelSteps = [];
15200
+ for (const step of this.steps) {
15201
+ if (processedSteps.has(step.stepIndex)) continue;
15202
+ const canRun = step.dependencies.length === 0 || step.dependencies.every((dep) => availableFields.has(dep));
15203
+ if (canRun) {
15204
+ currentLevelSteps.push(step);
15205
+ processedSteps.add(step.stepIndex);
15206
+ }
15207
+ }
15208
+ if (currentLevelSteps.length > 0) {
15209
+ for (const step of currentLevelSteps) {
15210
+ step.produces.forEach((field) => availableFields.add(field));
15211
+ }
15212
+ this.parallelGroups.push({
15213
+ level: currentLevel,
15214
+ steps: currentLevelSteps
15215
+ });
15216
+ currentLevel++;
15217
+ } else {
15218
+ break;
15219
+ }
15220
+ }
15221
+ }
15222
+ /**
15223
+ * Gets all fields produced by previous steps
15224
+ */
15225
+ getAllProducedFields() {
15226
+ const fields = [];
15227
+ for (const step of this.steps) {
15228
+ fields.push(...step.produces);
15229
+ }
15230
+ return fields;
15231
+ }
15232
+ /**
15233
+ * Creates optimized execution function
15234
+ */
15235
+ createOptimizedExecution() {
15236
+ const optimizedSteps = [];
15237
+ for (const group of this.parallelGroups) {
15238
+ if (group.steps.length === 1) {
15239
+ const step = group.steps[0];
15240
+ if (step) {
15241
+ optimizedSteps.push(step.stepFunction);
15242
+ }
15243
+ } else if (group.steps.length > 1) {
15244
+ const parallelStep = async (state, context3) => {
15245
+ const promises = group.steps.map(
15246
+ (step) => step.stepFunction(state, context3)
15247
+ );
15248
+ const results = await Promise.all(promises);
15249
+ let mergedState = state;
15250
+ for (const result of results) {
15251
+ mergedState = { ...mergedState, ...result };
15252
+ }
15253
+ return mergedState;
15254
+ };
15255
+ optimizedSteps.push(parallelStep);
15256
+ }
15257
+ }
15258
+ return optimizedSteps;
15259
+ }
15260
+ /**
15261
+ * Gets execution plan info for debugging
15262
+ */
15263
+ getExecutionPlan() {
15264
+ return {
15265
+ totalSteps: this.steps.length,
15266
+ parallelGroups: this.parallelGroups.length,
15267
+ maxParallelism: Math.max(
15268
+ ...this.parallelGroups.map((g) => g.steps.length),
15269
+ 0
15270
+ ),
15271
+ steps: this.steps,
15272
+ groups: this.parallelGroups
15273
+ };
15274
+ }
15275
+ };
15276
+ var AxFlow = class extends AxProgram {
15186
15277
  nodes = /* @__PURE__ */ new Map();
15187
15278
  flowDefinition = [];
15188
15279
  nodeGenerators = /* @__PURE__ */ new Map();
15189
15280
  loopStack = [];
15190
15281
  stepLabels = /* @__PURE__ */ new Map();
15191
15282
  branchContext = null;
15192
- constructor(signature = "userInput:string -> flowOutput:string") {
15283
+ // Automatic parallelization components
15284
+ autoParallelConfig;
15285
+ executionPlanner = new AxFlowExecutionPlanner();
15286
+ constructor(signature = "userInput:string -> flowOutput:string", options) {
15193
15287
  super(signature);
15288
+ this.autoParallelConfig = {
15289
+ enabled: options?.autoParallel !== false
15290
+ // Default to true
15291
+ };
15194
15292
  }
15195
15293
  // Implementation
15196
- node(name, signatureOrAxGen, options) {
15197
- if (signatureOrAxGen instanceof AxGen) {
15294
+ node(name, signatureOrAxGenOrClass, options) {
15295
+ if (signatureOrAxGenOrClass instanceof AxGen) {
15198
15296
  this.nodes.set(name, {
15199
15297
  inputs: {},
15200
15298
  outputs: {}
15201
15299
  });
15202
15300
  this.nodeGenerators.set(
15203
15301
  name,
15204
- signatureOrAxGen
15302
+ signatureOrAxGenOrClass
15205
15303
  );
15206
- } else {
15207
- const signature = signatureOrAxGen;
15304
+ } else if (signatureOrAxGenOrClass instanceof AxSignature) {
15305
+ this.nodes.set(name, {
15306
+ inputs: {},
15307
+ outputs: {}
15308
+ });
15309
+ this.nodeGenerators.set(name, new AxGen(signatureOrAxGenOrClass, options));
15310
+ } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgram) {
15311
+ this.nodes.set(name, {
15312
+ inputs: {},
15313
+ outputs: {}
15314
+ });
15315
+ const programInstance = new signatureOrAxGenOrClass();
15316
+ this.nodeGenerators.set(name, programInstance);
15317
+ } else if (typeof signatureOrAxGenOrClass === "string") {
15318
+ const signature = signatureOrAxGenOrClass;
15208
15319
  if (!signature) {
15209
15320
  throw new Error(
15210
15321
  `Invalid signature for node '${name}': signature cannot be empty`
@@ -15215,11 +15326,15 @@ var AxFlow = class extends AxProgramWithSignature {
15215
15326
  outputs: {}
15216
15327
  });
15217
15328
  this.nodeGenerators.set(name, new AxGen(signature, options));
15329
+ } else {
15330
+ throw new Error(
15331
+ `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgram`
15332
+ );
15218
15333
  }
15219
15334
  return this;
15220
15335
  }
15221
- n(name, signatureOrAxGen, options) {
15222
- return this.node(name, signatureOrAxGen, options);
15336
+ n(name, signatureOrAxGenOrClass, options) {
15337
+ return this.node(name, signatureOrAxGenOrClass, options);
15223
15338
  }
15224
15339
  /**
15225
15340
  * Applies a synchronous transformation to the state object.
@@ -15248,6 +15363,9 @@ var AxFlow = class extends AxProgramWithSignature {
15248
15363
  );
15249
15364
  } else {
15250
15365
  this.flowDefinition.push(step);
15366
+ if (this.autoParallelConfig.enabled) {
15367
+ this.executionPlanner.addExecutionStep(step);
15368
+ }
15251
15369
  }
15252
15370
  return this;
15253
15371
  }
@@ -15302,15 +15420,19 @@ var AxFlow = class extends AxProgramWithSignature {
15302
15420
  `Node '${nodeName}' not found. Make sure to define it with .node() first.`
15303
15421
  );
15304
15422
  }
15305
- const nodeGenerator = this.nodeGenerators.get(nodeName);
15306
- if (!nodeGenerator) {
15307
- throw new Error(`Node generator for '${nodeName}' not found.`);
15423
+ const nodeProgram = this.nodeGenerators.get(nodeName);
15424
+ if (!nodeProgram) {
15425
+ throw new Error(`Node program for '${nodeName}' not found.`);
15308
15426
  }
15309
15427
  const step = async (state, context3) => {
15310
15428
  const ai = dynamicContext?.ai ?? context3.mainAi;
15311
15429
  const options = dynamicContext?.options ?? context3.mainOptions;
15312
15430
  const nodeInputs = mapping(state);
15313
- const result = await nodeGenerator.forward(ai, nodeInputs, options);
15431
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15432
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15433
+ ...options,
15434
+ traceLabel
15435
+ });
15314
15436
  return {
15315
15437
  ...state,
15316
15438
  [`${nodeName}Result`]: result
@@ -15327,6 +15449,9 @@ var AxFlow = class extends AxProgramWithSignature {
15327
15449
  );
15328
15450
  } else {
15329
15451
  this.flowDefinition.push(step);
15452
+ if (this.autoParallelConfig.enabled) {
15453
+ this.executionPlanner.addExecutionStep(step, nodeName, mapping);
15454
+ }
15330
15455
  }
15331
15456
  return this;
15332
15457
  }
@@ -15623,7 +15748,7 @@ var AxFlow = class extends AxProgramWithSignature {
15623
15748
  *
15624
15749
  * @param ai - The AI service to use as the default for all steps
15625
15750
  * @param values - The input values for the flow
15626
- * @param options - Optional forward options to use as defaults
15751
+ * @param options - Optional forward options to use as defaults (includes autoParallel override)
15627
15752
  * @returns Promise that resolves to the final output
15628
15753
  */
15629
15754
  async forward(ai, values, options) {
@@ -15632,11 +15757,36 @@ var AxFlow = class extends AxProgramWithSignature {
15632
15757
  mainAi: ai,
15633
15758
  mainOptions: options
15634
15759
  };
15635
- for (const step of this.flowDefinition) {
15636
- state = await step(state, context3);
15760
+ const useAutoParallel = options?.autoParallel !== false && this.autoParallelConfig.enabled;
15761
+ if (useAutoParallel) {
15762
+ this.executionPlanner.setInitialFields(Object.keys(values));
15763
+ const optimizedSteps = this.executionPlanner.createOptimizedExecution();
15764
+ for (const step of optimizedSteps) {
15765
+ state = await step(state, context3);
15766
+ }
15767
+ } else {
15768
+ for (const step of this.flowDefinition) {
15769
+ state = await step(state, context3);
15770
+ }
15637
15771
  }
15638
15772
  return state;
15639
15773
  }
15774
+ /**
15775
+ * Gets execution plan information for debugging automatic parallelization
15776
+ *
15777
+ * @returns Object with execution plan details
15778
+ */
15779
+ getExecutionPlan() {
15780
+ const planInfo = this.executionPlanner.getExecutionPlan();
15781
+ return {
15782
+ totalSteps: planInfo.totalSteps,
15783
+ parallelGroups: planInfo.parallelGroups,
15784
+ maxParallelism: planInfo.maxParallelism,
15785
+ autoParallelEnabled: this.autoParallelConfig.enabled,
15786
+ steps: planInfo.steps,
15787
+ groups: planInfo.groups
15788
+ };
15789
+ }
15640
15790
  };
15641
15791
  var AxFlowSubContextImpl = class {
15642
15792
  constructor(nodeGenerators) {
@@ -15644,15 +15794,19 @@ var AxFlowSubContextImpl = class {
15644
15794
  }
15645
15795
  steps = [];
15646
15796
  execute(nodeName, mapping, dynamicContext) {
15647
- const nodeGenerator = this.nodeGenerators.get(nodeName);
15648
- if (!nodeGenerator) {
15649
- throw new Error(`Node generator for '${nodeName}' not found.`);
15797
+ const nodeProgram = this.nodeGenerators.get(nodeName);
15798
+ if (!nodeProgram) {
15799
+ throw new Error(`Node program for '${nodeName}' not found.`);
15650
15800
  }
15651
15801
  this.steps.push(async (state, context3) => {
15652
15802
  const ai = dynamicContext?.ai ?? context3.mainAi;
15653
15803
  const options = dynamicContext?.options ?? context3.mainOptions;
15654
15804
  const nodeInputs = mapping(state);
15655
- const result = await nodeGenerator.forward(ai, nodeInputs, options);
15805
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15806
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15807
+ ...options,
15808
+ traceLabel
15809
+ });
15656
15810
  return {
15657
15811
  ...state,
15658
15812
  [`${nodeName}Result`]: result
@@ -15678,15 +15832,19 @@ var AxFlowTypedSubContextImpl = class {
15678
15832
  }
15679
15833
  steps = [];
15680
15834
  execute(nodeName, mapping, dynamicContext) {
15681
- const nodeGenerator = this.nodeGenerators.get(nodeName);
15682
- if (!nodeGenerator) {
15683
- throw new Error(`Node generator for '${nodeName}' not found.`);
15835
+ const nodeProgram = this.nodeGenerators.get(nodeName);
15836
+ if (!nodeProgram) {
15837
+ throw new Error(`Node program for '${nodeName}' not found.`);
15684
15838
  }
15685
15839
  this.steps.push(async (state, context3) => {
15686
15840
  const ai = dynamicContext?.ai ?? context3.mainAi;
15687
15841
  const options = dynamicContext?.options ?? context3.mainOptions;
15688
15842
  const nodeInputs = mapping(state);
15689
- const result = await nodeGenerator.forward(ai, nodeInputs, options);
15843
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15844
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15845
+ ...options,
15846
+ traceLabel
15847
+ });
15690
15848
  return {
15691
15849
  ...state,
15692
15850
  [`${nodeName}Result`]: result
@@ -16494,10 +16652,7 @@ var AxMiPRO = class extends AxBaseOptimizer {
16494
16652
  * Generates program summary for context-aware instruction generation
16495
16653
  */
16496
16654
  async generateProgramSummary(program, ai) {
16497
- let signature = "input -> output";
16498
- if ("getSignature" in program && typeof program.getSignature === "function") {
16499
- signature = program.getSignature();
16500
- }
16655
+ const signature = program.getSignature();
16501
16656
  const summaryPrompt = `
16502
16657
  Analyze this language model program and provide a concise summary of its purpose and structure.
16503
16658
 
@@ -19711,7 +19866,6 @@ var AxRAG = class extends AxChainOfThought {
19711
19866
  AxMockAIService,
19712
19867
  AxMultiServiceRouter,
19713
19868
  AxProgram,
19714
- AxProgramWithSignature,
19715
19869
  AxPromptTemplate,
19716
19870
  AxRAG,
19717
19871
  AxRateLimiterTokenUsage,