@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.js CHANGED
@@ -4798,7 +4798,8 @@ var AxAIGoogleGemini = class extends AxBaseAI {
4798
4798
  } else {
4799
4799
  path = "publishers/google";
4800
4800
  }
4801
- apiURL = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/${path}`;
4801
+ const tld = region === "global" ? "aiplatform" : `${region}-aiplatform`;
4802
+ apiURL = `https://${tld}.googleapis.com/v1/projects/${projectId}/locations/${region}/${path}`;
4802
4803
  if (apiKey) {
4803
4804
  headers = async () => ({ Authorization: `Bearer ${apiKey}` });
4804
4805
  } else {
@@ -11092,7 +11093,7 @@ var AxInstanceRegistry = class {
11092
11093
  };
11093
11094
 
11094
11095
  // dsp/program.ts
11095
- var AxProgramWithSignature = class {
11096
+ var AxProgram = class {
11096
11097
  signature;
11097
11098
  sigHash;
11098
11099
  examples;
@@ -11100,6 +11101,7 @@ var AxProgramWithSignature = class {
11100
11101
  demos;
11101
11102
  trace;
11102
11103
  usage = [];
11104
+ traceLabel;
11103
11105
  key;
11104
11106
  children;
11105
11107
  constructor(signature, options) {
@@ -11107,6 +11109,9 @@ var AxProgramWithSignature = class {
11107
11109
  if (options?.description) {
11108
11110
  this.signature.setDescription(options.description);
11109
11111
  }
11112
+ if (options?.traceLabel) {
11113
+ this.traceLabel = options.traceLabel;
11114
+ }
11110
11115
  this.signature.validate();
11111
11116
  this.sigHash = this.signature?.hash();
11112
11117
  this.children = new AxInstanceRegistry();
@@ -11212,85 +11217,6 @@ var AxProgramWithSignature = class {
11212
11217
  }
11213
11218
  }
11214
11219
  };
11215
- var AxProgram = class {
11216
- trace;
11217
- usage = [];
11218
- key;
11219
- children;
11220
- constructor() {
11221
- this.children = new AxInstanceRegistry();
11222
- this.key = { id: this.constructor.name };
11223
- }
11224
- register(prog) {
11225
- if (this.key) {
11226
- prog.setParentId(this.key.id);
11227
- }
11228
- this.children.register(prog);
11229
- }
11230
- async forward(_ai, _values, _options) {
11231
- throw new Error("forward() not implemented");
11232
- }
11233
- // biome-ignore lint/correctness/useYield: just a placeholder
11234
- async *streamingForward(_ai, _values, _options) {
11235
- throw new Error("streamingForward() not implemented");
11236
- }
11237
- setId(id) {
11238
- this.key = { id, custom: true };
11239
- for (const child of Array.from(this.children)) {
11240
- child?.setParentId(id);
11241
- }
11242
- }
11243
- setParentId(parentId) {
11244
- if (!this.key.custom) {
11245
- this.key.id = [parentId, this.key.id].join("/");
11246
- }
11247
- }
11248
- setExamples(examples, options) {
11249
- if (!("programId" in examples)) {
11250
- return;
11251
- }
11252
- for (const child of Array.from(this.children)) {
11253
- child?.setExamples(examples, options);
11254
- }
11255
- }
11256
- getTraces() {
11257
- let traces = [];
11258
- if (this.trace) {
11259
- traces.push({ trace: this.trace, programId: this.key.id });
11260
- }
11261
- for (const child of Array.from(this.children)) {
11262
- const _traces = child?.getTraces();
11263
- traces = [...traces, ..._traces ?? []];
11264
- }
11265
- return traces;
11266
- }
11267
- getUsage() {
11268
- let usage = [...this.usage ?? []];
11269
- for (const child of Array.from(this.children)) {
11270
- const cu = child?.getUsage();
11271
- usage = [...usage, ...cu ?? []];
11272
- }
11273
- return mergeProgramUsage(usage);
11274
- }
11275
- resetUsage() {
11276
- this.usage = [];
11277
- for (const child of Array.from(this.children)) {
11278
- child?.resetUsage();
11279
- }
11280
- }
11281
- setDemos(demos) {
11282
- const hasChildren = Array.from(this.children).length > 0;
11283
- const hasMatchingDemo = demos.some((demo) => demo.programId === this.key.id);
11284
- if (hasChildren && !hasMatchingDemo) {
11285
- throw new Error(
11286
- `Program with id '${this.key.id}' has children but no matching programId found in demos`
11287
- );
11288
- }
11289
- for (const child of Array.from(this.children)) {
11290
- child?.setDemos(demos);
11291
- }
11292
- }
11293
- };
11294
11220
 
11295
11221
  // dsp/samples.ts
11296
11222
  function checkForFunctionCalls(mem, sessionId) {
@@ -11405,7 +11331,7 @@ ${errors}`, {
11405
11331
  }
11406
11332
 
11407
11333
  // dsp/generate.ts
11408
- var AxGen = class extends AxProgramWithSignature {
11334
+ var AxGen = class extends AxProgram {
11409
11335
  promptTemplate;
11410
11336
  asserts;
11411
11337
  streamingAsserts;
@@ -11416,7 +11342,10 @@ var AxGen = class extends AxProgramWithSignature {
11416
11342
  excludeContentFromTrace = false;
11417
11343
  thoughtFieldName;
11418
11344
  constructor(signature, options) {
11419
- super(signature, { description: options?.description });
11345
+ super(signature, {
11346
+ description: options?.description,
11347
+ traceLabel: options?.traceLabel
11348
+ });
11420
11349
  this.options = options;
11421
11350
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
11422
11351
  const promptTemplateOptions = {
@@ -11860,8 +11789,8 @@ var AxGen = class extends AxProgramWithSignature {
11860
11789
  ...options?.maxSteps ? { max_steps: options.maxSteps } : {},
11861
11790
  ...options?.maxRetries ? { max_retries: options.maxRetries } : {}
11862
11791
  };
11863
- const traceLabel = options.traceLabel ?? this.options?.traceLabel;
11864
- const spanName = traceLabel ? `${traceLabel} (AxGen)` : "AxGen";
11792
+ const traceLabel = this.traceLabel && options.traceLabel ? `${this.traceLabel} > ${options.traceLabel}` : options.traceLabel ?? this.traceLabel;
11793
+ const spanName = traceLabel ? `AxGen > ${traceLabel}` : "AxGen";
11865
11794
  const span = tracer.startSpan(spanName, {
11866
11795
  kind: SpanKind2.SERVER,
11867
11796
  attributes
@@ -14997,15 +14926,186 @@ var AxDockerSession = class {
14997
14926
  };
14998
14927
 
14999
14928
  // flow/flow.ts
15000
- var AxFlow = class extends AxProgramWithSignature {
14929
+ var AxFlowDependencyAnalyzer = class {
14930
+ /**
14931
+ * Analyzes a mapping function to determine which state fields it depends on
14932
+ */
14933
+ analyzeMappingDependencies(mapping, _nodeName) {
14934
+ const dependencies = [];
14935
+ const source = mapping.toString();
14936
+ const stateAccessMatches = Array.from(source.matchAll(/state\.(\w+)/g));
14937
+ for (const match of stateAccessMatches) {
14938
+ if (match[1] && !dependencies.includes(match[1])) {
14939
+ dependencies.push(match[1]);
14940
+ }
14941
+ }
14942
+ if (dependencies.length === 0) {
14943
+ try {
14944
+ const tracker = this.createDependencyTracker(dependencies);
14945
+ mapping(tracker);
14946
+ } catch {
14947
+ }
14948
+ }
14949
+ return dependencies;
14950
+ }
14951
+ createDependencyTracker(dependencies) {
14952
+ return new Proxy(
14953
+ {},
14954
+ {
14955
+ get(target, prop) {
14956
+ if (typeof prop === "string" && !dependencies.includes(prop)) {
14957
+ dependencies.push(prop);
14958
+ }
14959
+ return new Proxy(
14960
+ {},
14961
+ {
14962
+ get: () => void 0
14963
+ }
14964
+ );
14965
+ }
14966
+ }
14967
+ );
14968
+ }
14969
+ };
14970
+ var AxFlowExecutionPlanner = class {
14971
+ steps = [];
14972
+ parallelGroups = [];
14973
+ analyzer = new AxFlowDependencyAnalyzer();
14974
+ initialFields = /* @__PURE__ */ new Set();
14975
+ /**
14976
+ * Adds an execution step to the plan
14977
+ */
14978
+ addExecutionStep(stepFunction, nodeName, mapping) {
14979
+ let dependencies = [];
14980
+ let produces = [];
14981
+ let type = "other";
14982
+ if (nodeName && mapping) {
14983
+ type = "execute";
14984
+ dependencies = this.analyzer.analyzeMappingDependencies(mapping, nodeName);
14985
+ produces = [`${nodeName}Result`];
14986
+ } else if (stepFunction.toString().includes("transform(")) {
14987
+ type = "map";
14988
+ dependencies = this.getAllProducedFields();
14989
+ }
14990
+ const step = {
14991
+ type,
14992
+ nodeName,
14993
+ dependencies,
14994
+ produces,
14995
+ stepFunction,
14996
+ stepIndex: this.steps.length
14997
+ };
14998
+ this.steps.push(step);
14999
+ }
15000
+ /**
15001
+ * Sets the initial fields and rebuilds parallel groups
15002
+ */
15003
+ setInitialFields(fields) {
15004
+ this.initialFields = new Set(fields);
15005
+ this.rebuildParallelGroups();
15006
+ }
15007
+ /**
15008
+ * Rebuilds the parallel execution groups based on dependencies
15009
+ */
15010
+ rebuildParallelGroups() {
15011
+ this.parallelGroups = [];
15012
+ const processedSteps = /* @__PURE__ */ new Set();
15013
+ const availableFields = new Set(this.initialFields);
15014
+ let currentLevel = 0;
15015
+ while (processedSteps.size < this.steps.length) {
15016
+ const currentLevelSteps = [];
15017
+ for (const step of this.steps) {
15018
+ if (processedSteps.has(step.stepIndex)) continue;
15019
+ const canRun = step.dependencies.length === 0 || step.dependencies.every((dep) => availableFields.has(dep));
15020
+ if (canRun) {
15021
+ currentLevelSteps.push(step);
15022
+ processedSteps.add(step.stepIndex);
15023
+ }
15024
+ }
15025
+ if (currentLevelSteps.length > 0) {
15026
+ for (const step of currentLevelSteps) {
15027
+ step.produces.forEach((field) => availableFields.add(field));
15028
+ }
15029
+ this.parallelGroups.push({
15030
+ level: currentLevel,
15031
+ steps: currentLevelSteps
15032
+ });
15033
+ currentLevel++;
15034
+ } else {
15035
+ break;
15036
+ }
15037
+ }
15038
+ }
15039
+ /**
15040
+ * Gets all fields produced by previous steps
15041
+ */
15042
+ getAllProducedFields() {
15043
+ const fields = [];
15044
+ for (const step of this.steps) {
15045
+ fields.push(...step.produces);
15046
+ }
15047
+ return fields;
15048
+ }
15049
+ /**
15050
+ * Creates optimized execution function
15051
+ */
15052
+ createOptimizedExecution() {
15053
+ const optimizedSteps = [];
15054
+ for (const group of this.parallelGroups) {
15055
+ if (group.steps.length === 1) {
15056
+ const step = group.steps[0];
15057
+ if (step) {
15058
+ optimizedSteps.push(step.stepFunction);
15059
+ }
15060
+ } else if (group.steps.length > 1) {
15061
+ const parallelStep = async (state, context3) => {
15062
+ const promises = group.steps.map(
15063
+ (step) => step.stepFunction(state, context3)
15064
+ );
15065
+ const results = await Promise.all(promises);
15066
+ let mergedState = state;
15067
+ for (const result of results) {
15068
+ mergedState = { ...mergedState, ...result };
15069
+ }
15070
+ return mergedState;
15071
+ };
15072
+ optimizedSteps.push(parallelStep);
15073
+ }
15074
+ }
15075
+ return optimizedSteps;
15076
+ }
15077
+ /**
15078
+ * Gets execution plan info for debugging
15079
+ */
15080
+ getExecutionPlan() {
15081
+ return {
15082
+ totalSteps: this.steps.length,
15083
+ parallelGroups: this.parallelGroups.length,
15084
+ maxParallelism: Math.max(
15085
+ ...this.parallelGroups.map((g) => g.steps.length),
15086
+ 0
15087
+ ),
15088
+ steps: this.steps,
15089
+ groups: this.parallelGroups
15090
+ };
15091
+ }
15092
+ };
15093
+ var AxFlow = class extends AxProgram {
15001
15094
  nodes = /* @__PURE__ */ new Map();
15002
15095
  flowDefinition = [];
15003
15096
  nodeGenerators = /* @__PURE__ */ new Map();
15004
15097
  loopStack = [];
15005
15098
  stepLabels = /* @__PURE__ */ new Map();
15006
15099
  branchContext = null;
15007
- constructor(signature = "userInput:string -> flowOutput:string") {
15100
+ // Automatic parallelization components
15101
+ autoParallelConfig;
15102
+ executionPlanner = new AxFlowExecutionPlanner();
15103
+ constructor(signature = "userInput:string -> flowOutput:string", options) {
15008
15104
  super(signature);
15105
+ this.autoParallelConfig = {
15106
+ enabled: options?.autoParallel !== false
15107
+ // Default to true
15108
+ };
15009
15109
  }
15010
15110
  // Implementation
15011
15111
  node(name, signatureOrAxGenOrClass, options) {
@@ -15024,7 +15124,7 @@ var AxFlow = class extends AxProgramWithSignature {
15024
15124
  outputs: {}
15025
15125
  });
15026
15126
  this.nodeGenerators.set(name, new AxGen(signatureOrAxGenOrClass, options));
15027
- } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgramWithSignature) {
15127
+ } else if (typeof signatureOrAxGenOrClass === "function" && signatureOrAxGenOrClass.prototype instanceof AxProgram) {
15028
15128
  this.nodes.set(name, {
15029
15129
  inputs: {},
15030
15130
  outputs: {}
@@ -15045,7 +15145,7 @@ var AxFlow = class extends AxProgramWithSignature {
15045
15145
  this.nodeGenerators.set(name, new AxGen(signature, options));
15046
15146
  } else {
15047
15147
  throw new Error(
15048
- `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgramWithSignature`
15148
+ `Invalid second argument for node '${name}': expected string, AxSignature, AxGen instance, or class extending AxProgram`
15049
15149
  );
15050
15150
  }
15051
15151
  return this;
@@ -15080,6 +15180,9 @@ var AxFlow = class extends AxProgramWithSignature {
15080
15180
  );
15081
15181
  } else {
15082
15182
  this.flowDefinition.push(step);
15183
+ if (this.autoParallelConfig.enabled) {
15184
+ this.executionPlanner.addExecutionStep(step);
15185
+ }
15083
15186
  }
15084
15187
  return this;
15085
15188
  }
@@ -15142,7 +15245,11 @@ var AxFlow = class extends AxProgramWithSignature {
15142
15245
  const ai = dynamicContext?.ai ?? context3.mainAi;
15143
15246
  const options = dynamicContext?.options ?? context3.mainOptions;
15144
15247
  const nodeInputs = mapping(state);
15145
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15248
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15249
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15250
+ ...options,
15251
+ traceLabel
15252
+ });
15146
15253
  return {
15147
15254
  ...state,
15148
15255
  [`${nodeName}Result`]: result
@@ -15159,6 +15266,9 @@ var AxFlow = class extends AxProgramWithSignature {
15159
15266
  );
15160
15267
  } else {
15161
15268
  this.flowDefinition.push(step);
15269
+ if (this.autoParallelConfig.enabled) {
15270
+ this.executionPlanner.addExecutionStep(step, nodeName, mapping);
15271
+ }
15162
15272
  }
15163
15273
  return this;
15164
15274
  }
@@ -15455,7 +15565,7 @@ var AxFlow = class extends AxProgramWithSignature {
15455
15565
  *
15456
15566
  * @param ai - The AI service to use as the default for all steps
15457
15567
  * @param values - The input values for the flow
15458
- * @param options - Optional forward options to use as defaults
15568
+ * @param options - Optional forward options to use as defaults (includes autoParallel override)
15459
15569
  * @returns Promise that resolves to the final output
15460
15570
  */
15461
15571
  async forward(ai, values, options) {
@@ -15464,11 +15574,36 @@ var AxFlow = class extends AxProgramWithSignature {
15464
15574
  mainAi: ai,
15465
15575
  mainOptions: options
15466
15576
  };
15467
- for (const step of this.flowDefinition) {
15468
- state = await step(state, context3);
15577
+ const useAutoParallel = options?.autoParallel !== false && this.autoParallelConfig.enabled;
15578
+ if (useAutoParallel) {
15579
+ this.executionPlanner.setInitialFields(Object.keys(values));
15580
+ const optimizedSteps = this.executionPlanner.createOptimizedExecution();
15581
+ for (const step of optimizedSteps) {
15582
+ state = await step(state, context3);
15583
+ }
15584
+ } else {
15585
+ for (const step of this.flowDefinition) {
15586
+ state = await step(state, context3);
15587
+ }
15469
15588
  }
15470
15589
  return state;
15471
15590
  }
15591
+ /**
15592
+ * Gets execution plan information for debugging automatic parallelization
15593
+ *
15594
+ * @returns Object with execution plan details
15595
+ */
15596
+ getExecutionPlan() {
15597
+ const planInfo = this.executionPlanner.getExecutionPlan();
15598
+ return {
15599
+ totalSteps: planInfo.totalSteps,
15600
+ parallelGroups: planInfo.parallelGroups,
15601
+ maxParallelism: planInfo.maxParallelism,
15602
+ autoParallelEnabled: this.autoParallelConfig.enabled,
15603
+ steps: planInfo.steps,
15604
+ groups: planInfo.groups
15605
+ };
15606
+ }
15472
15607
  };
15473
15608
  var AxFlowSubContextImpl = class {
15474
15609
  constructor(nodeGenerators) {
@@ -15484,7 +15619,11 @@ var AxFlowSubContextImpl = class {
15484
15619
  const ai = dynamicContext?.ai ?? context3.mainAi;
15485
15620
  const options = dynamicContext?.options ?? context3.mainOptions;
15486
15621
  const nodeInputs = mapping(state);
15487
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15622
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15623
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15624
+ ...options,
15625
+ traceLabel
15626
+ });
15488
15627
  return {
15489
15628
  ...state,
15490
15629
  [`${nodeName}Result`]: result
@@ -15518,7 +15657,11 @@ var AxFlowTypedSubContextImpl = class {
15518
15657
  const ai = dynamicContext?.ai ?? context3.mainAi;
15519
15658
  const options = dynamicContext?.options ?? context3.mainOptions;
15520
15659
  const nodeInputs = mapping(state);
15521
- const result = await nodeProgram.forward(ai, nodeInputs, options);
15660
+ const traceLabel = options?.traceLabel ? `Node:${nodeName} (${options.traceLabel})` : `Node:${nodeName}`;
15661
+ const result = await nodeProgram.forward(ai, nodeInputs, {
15662
+ ...options,
15663
+ traceLabel
15664
+ });
15522
15665
  return {
15523
15666
  ...state,
15524
15667
  [`${nodeName}Result`]: result
@@ -16326,10 +16469,7 @@ var AxMiPRO = class extends AxBaseOptimizer {
16326
16469
  * Generates program summary for context-aware instruction generation
16327
16470
  */
16328
16471
  async generateProgramSummary(program, ai) {
16329
- let signature = "input -> output";
16330
- if ("getSignature" in program && typeof program.getSignature === "function") {
16331
- signature = program.getSignature();
16332
- }
16472
+ const signature = program.getSignature();
16333
16473
  const summaryPrompt = `
16334
16474
  Analyze this language model program and provide a concise summary of its purpose and structure.
16335
16475
 
@@ -19542,7 +19682,6 @@ export {
19542
19682
  AxMockAIService,
19543
19683
  AxMultiServiceRouter,
19544
19684
  AxProgram,
19545
- AxProgramWithSignature,
19546
19685
  AxPromptTemplate,
19547
19686
  AxRAG,
19548
19687
  AxRateLimiterTokenUsage,