@ax-llm/ax 12.0.22 → 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,15 +15109,186 @@ 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
15294
  node(name, signatureOrAxGenOrClass, options) {
@@ -15209,7 +15307,7 @@ var AxFlow = class extends AxProgramWithSignature {
15209
15307
  outputs: {}
15210
15308
  });
15211
15309
  this.nodeGenerators.set(name, new AxGen(signatureOrAxGenOrClass, options));
15212
- } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgramWithSignature) {
15310
+ } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgram) {
15213
15311
  this.nodes.set(name, {
15214
15312
  inputs: {},
15215
15313
  outputs: {}
@@ -15230,7 +15328,7 @@ var AxFlow = class extends AxProgramWithSignature {
15230
15328
  this.nodeGenerators.set(name, new AxGen(signature, options));
15231
15329
  } else {
15232
15330
  throw new Error(
15233
- `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgramWithSignature`
15331
+ `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgram`
15234
15332
  );
15235
15333
  }
15236
15334
  return this;
@@ -15265,6 +15363,9 @@ var AxFlow = class extends AxProgramWithSignature {
15265
15363
  );
15266
15364
  } else {
15267
15365
  this.flowDefinition.push(step);
15366
+ if (this.autoParallelConfig.enabled) {
15367
+ this.executionPlanner.addExecutionStep(step);
15368
+ }
15268
15369
  }
15269
15370
  return this;
15270
15371
  }
@@ -15327,7 +15428,11 @@ var AxFlow = class extends AxProgramWithSignature {
15327
15428
  const ai = dynamicContext?.ai ?? context3.mainAi;
15328
15429
  const options = dynamicContext?.options ?? context3.mainOptions;
15329
15430
  const nodeInputs = mapping(state);
15330
- const result = await nodeProgram.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
+ });
15331
15436
  return {
15332
15437
  ...state,
15333
15438
  [`${nodeName}Result`]: result
@@ -15344,6 +15449,9 @@ var AxFlow = class extends AxProgramWithSignature {
15344
15449
  );
15345
15450
  } else {
15346
15451
  this.flowDefinition.push(step);
15452
+ if (this.autoParallelConfig.enabled) {
15453
+ this.executionPlanner.addExecutionStep(step, nodeName, mapping);
15454
+ }
15347
15455
  }
15348
15456
  return this;
15349
15457
  }
@@ -15640,7 +15748,7 @@ var AxFlow = class extends AxProgramWithSignature {
15640
15748
  *
15641
15749
  * @param ai - The AI service to use as the default for all steps
15642
15750
  * @param values - The input values for the flow
15643
- * @param options - Optional forward options to use as defaults
15751
+ * @param options - Optional forward options to use as defaults (includes autoParallel override)
15644
15752
  * @returns Promise that resolves to the final output
15645
15753
  */
15646
15754
  async forward(ai, values, options) {
@@ -15649,11 +15757,36 @@ var AxFlow = class extends AxProgramWithSignature {
15649
15757
  mainAi: ai,
15650
15758
  mainOptions: options
15651
15759
  };
15652
- for (const step of this.flowDefinition) {
15653
- 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
+ }
15654
15771
  }
15655
15772
  return state;
15656
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
+ }
15657
15790
  };
15658
15791
  var AxFlowSubContextImpl = class {
15659
15792
  constructor(nodeGenerators) {
@@ -15669,7 +15802,11 @@ var AxFlowSubContextImpl = class {
15669
15802
  const ai = dynamicContext?.ai ?? context3.mainAi;
15670
15803
  const options = dynamicContext?.options ?? context3.mainOptions;
15671
15804
  const nodeInputs = mapping(state);
15672
- const result = await nodeProgram.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
+ });
15673
15810
  return {
15674
15811
  ...state,
15675
15812
  [`${nodeName}Result`]: result
@@ -15703,7 +15840,11 @@ var AxFlowTypedSubContextImpl = class {
15703
15840
  const ai = dynamicContext?.ai ?? context3.mainAi;
15704
15841
  const options = dynamicContext?.options ?? context3.mainOptions;
15705
15842
  const nodeInputs = mapping(state);
15706
- const result = await nodeProgram.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
+ });
15707
15848
  return {
15708
15849
  ...state,
15709
15850
  [`${nodeName}Result`]: result
@@ -16511,10 +16652,7 @@ var AxMiPRO = class extends AxBaseOptimizer {
16511
16652
  * Generates program summary for context-aware instruction generation
16512
16653
  */
16513
16654
  async generateProgramSummary(program, ai) {
16514
- let signature = "input -> output";
16515
- if ("getSignature" in program && typeof program.getSignature === "function") {
16516
- signature = program.getSignature();
16517
- }
16655
+ const signature = program.getSignature();
16518
16656
  const summaryPrompt = `
16519
16657
  Analyze this language model program and provide a concise summary of its purpose and structure.
16520
16658
 
@@ -19728,7 +19866,6 @@ var AxRAG = class extends AxChainOfThought {
19728
19866
  AxMockAIService,
19729
19867
  AxMultiServiceRouter,
19730
19868
  AxProgram,
19731
- AxProgramWithSignature,
19732
19869
  AxPromptTemplate,
19733
19870
  AxRAG,
19734
19871
  AxRateLimiterTokenUsage,