@ax-llm/ax 11.0.57 → 11.0.58

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
@@ -669,6 +669,46 @@ var ColorLog = class {
669
669
 
670
670
  // ai/debug.ts
671
671
  var colorLog = new ColorLog();
672
+ var defaultOutput = (message) => {
673
+ process.stdout.write(message);
674
+ };
675
+ var createDefaultLogger = (output = defaultOutput) => {
676
+ return (message, options) => {
677
+ const tags = options?.tags ?? [];
678
+ let formattedMessage = message;
679
+ if (tags.includes("error")) {
680
+ formattedMessage = colorLog.red(formattedMessage);
681
+ } else if (tags.includes("success") || tags.includes("responseContent")) {
682
+ formattedMessage = colorLog.greenBright(formattedMessage);
683
+ } else if (tags.includes("functionName")) {
684
+ formattedMessage = colorLog.whiteBright(formattedMessage);
685
+ } else if (tags.includes("functionArg") || tags.includes("systemContent") || tags.includes("assistantContent")) {
686
+ formattedMessage = colorLog.blueBright(formattedMessage);
687
+ } else if (tags.includes("warning") || tags.includes("discovery")) {
688
+ formattedMessage = colorLog.yellow(formattedMessage);
689
+ }
690
+ if (tags.includes("responseStart") || tags.includes("systemStart") || tags.includes("userStart")) {
691
+ formattedMessage = `
692
+ ${formattedMessage}`;
693
+ } else if (tags.includes("responseEnd") || tags.includes("systemEnd") || tags.includes("userEnd")) {
694
+ formattedMessage = `${formattedMessage}
695
+ `;
696
+ } else if (tags.includes("assistantStart")) {
697
+ formattedMessage = `
698
+ ${formattedMessage}
699
+ `;
700
+ } else if (tags.includes("error")) {
701
+ formattedMessage = `
702
+ ${formattedMessage}
703
+ `;
704
+ } else if (tags.includes("functionEnd")) {
705
+ formattedMessage = `${formattedMessage}
706
+ `;
707
+ }
708
+ output(formattedMessage);
709
+ };
710
+ };
711
+ var defaultLogger = createDefaultLogger();
672
712
  var formatChatMessage = (msg, hideContent, hideSystemPrompt) => {
673
713
  switch (msg.role) {
674
714
  case "system":
@@ -676,30 +716,30 @@ var formatChatMessage = (msg, hideContent, hideSystemPrompt) => {
676
716
  return "";
677
717
  }
678
718
  return `
679
- ${colorLog.blueBright("System:")}
680
- ${colorLog.whiteBright(msg.content)}`;
719
+ System:
720
+ ${msg.content}`;
681
721
  case "function":
682
722
  return `
683
- ${colorLog.blueBright("Function Result:")}
684
- ${colorLog.whiteBright(msg.result)}`;
723
+ Function Result:
724
+ ${msg.result}`;
685
725
  case "user": {
686
726
  if (typeof msg.content === "string") {
687
727
  return `
688
- ${colorLog.blueBright("User:")}
689
- ${colorLog.whiteBright(msg.content)}`;
728
+ User:
729
+ ${msg.content}`;
690
730
  }
691
731
  const items = msg.content.map((v) => {
692
732
  switch (v.type) {
693
733
  case "text":
694
- return `${colorLog.whiteBright(v.text)}`;
734
+ return v.text;
695
735
  case "image":
696
- return `(Image, ${v.mimeType}) ${colorLog.whiteBright(v.image.substring(0, 10))}`;
736
+ return `(Image, ${v.mimeType}) ${v.image.substring(0, 10)}`;
697
737
  default:
698
738
  throw new Error("Invalid content type");
699
739
  }
700
740
  });
701
741
  return `
702
- ${colorLog.blueBright("User:")}
742
+ User:
703
743
  ${items.join("\n")}`;
704
744
  }
705
745
  case "assistant": {
@@ -709,62 +749,64 @@ ${items.join("\n")}`;
709
749
  return `${fn.name}(${args})`;
710
750
  });
711
751
  return `
712
- ${colorLog.blueBright("\nFunctions:")}
713
- ${colorLog.whiteBright(fns.join("\n"))}`;
752
+ Functions:
753
+ ${fns.join("\n")}`;
714
754
  }
715
755
  return `
716
- ${colorLog.blueBright("\nAssistant:")}
717
- ${hideContent ? "" : colorLog.whiteBright(msg.content ?? "<empty>")}`;
756
+ Assistant:
757
+ ${hideContent ? "" : msg.content ?? "<empty>"}`;
718
758
  }
719
759
  default:
720
760
  throw new Error("Invalid role");
721
761
  }
722
762
  };
723
- var logChatRequestMessage = (msg, hideSystemPrompt) => {
724
- process.stdout.write(`${formatChatMessage(msg, hideSystemPrompt)}
725
- `);
726
- process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
763
+ var logChatRequestMessage = (msg, hideSystemPrompt, logger = defaultLogger) => {
764
+ const formattedMessage = formatChatMessage(msg, false, hideSystemPrompt);
765
+ if (formattedMessage) {
766
+ const tags = msg.role === "system" ? ["systemStart", "systemContent"] : msg.role === "function" ? ["functionName"] : msg.role === "user" ? ["userStart", "userContent"] : [];
767
+ logger(formattedMessage, { tags });
768
+ }
769
+ logger("Assistant:", { tags: ["assistantStart"] });
727
770
  };
728
- var logChatRequest = (chatPrompt, hideSystemPrompt) => {
729
- const items = chatPrompt?.map(
730
- (msg) => formatChatMessage(msg, hideSystemPrompt)
731
- );
732
- if (items) {
733
- process.stdout.write(items.join("\n"));
734
- process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
771
+ var logChatRequest = (chatPrompt, hideSystemPrompt, logger = defaultLogger) => {
772
+ for (const msg of chatPrompt ?? []) {
773
+ const formattedMessage = formatChatMessage(msg, false, hideSystemPrompt);
774
+ if (formattedMessage) {
775
+ const tags = msg.role === "system" ? ["systemContent"] : msg.role === "function" ? ["functionName"] : msg.role === "user" ? ["userContent"] : [];
776
+ logger(formattedMessage, { tags });
777
+ }
735
778
  }
779
+ logger("Assistant:", { tags: ["assistantStart"] });
736
780
  };
737
- var logResponseResult = (r) => {
781
+ var logResponseResult = (r, logger = defaultLogger) => {
738
782
  if (r.content) {
739
- process.stdout.write(colorLog.greenBright(r.content));
783
+ logger(r.content, { tags: ["responseContent"] });
740
784
  }
741
- if (r.functionCalls) {
785
+ if (r.functionCalls && r.functionCalls.length > 0) {
742
786
  for (const [i, f] of r.functionCalls.entries()) {
743
787
  if (f.function.name) {
744
- if (i > 0) {
745
- process.stdout.write("\n");
746
- }
747
- process.stdout.write(
748
- `Function ${i + 1} -> ${colorLog.greenBright(f.function.name)}`
749
- );
788
+ logger(`[${i + 1}] ${f.function.name}`, {
789
+ tags: ["functionName"]
790
+ });
750
791
  }
751
792
  if (f.function.params) {
752
793
  const params = typeof f.function.params === "string" ? f.function.params : JSON.stringify(f.function.params, null, 2);
753
- process.stdout.write(`${colorLog.greenBright(params)}`);
794
+ logger(params, { tags: ["functionArg"] });
754
795
  }
755
796
  }
797
+ logger("", { tags: ["functionEnd"] });
756
798
  }
757
799
  };
758
- var logResponse = (resp) => {
800
+ var logResponse = (resp, logger = defaultLogger) => {
759
801
  if (!resp.results) {
760
802
  return;
761
803
  }
762
804
  for (const r of resp.results) {
763
- logResponseResult(r);
805
+ logResponseResult(r, logger);
764
806
  }
765
807
  };
766
- var logResponseDelta = (delta) => {
767
- process.stdout.write(colorLog.greenBright(delta));
808
+ var logResponseDelta = (delta, logger = defaultLogger) => {
809
+ logger(delta, { tags: ["responseContent"] });
768
810
  };
769
811
 
770
812
  // ai/base.ts
@@ -778,6 +820,9 @@ var axBaseAIDefaultCreativeConfig = () => structuredClone({
778
820
  topP: 0.7,
779
821
  frequencyPenalty: 0.2
780
822
  });
823
+ var defaultLogger2 = (message, _options) => {
824
+ process.stdout.write(message);
825
+ };
781
826
  var AxBaseAI = class {
782
827
  constructor(aiImpl, {
783
828
  name,
@@ -817,6 +862,7 @@ var AxBaseAI = class {
817
862
  excludeContentFromTrace;
818
863
  models;
819
864
  abortSignal;
865
+ logger = defaultLogger2;
820
866
  modelInfo;
821
867
  modelUsage;
822
868
  embedModelUsage;
@@ -878,6 +924,7 @@ var AxBaseAI = class {
878
924
  this.tracer = options.tracer;
879
925
  this.excludeContentFromTrace = options.excludeContentFromTrace;
880
926
  this.abortSignal = options.abortSignal;
927
+ this.logger = options.logger ?? defaultLogger2;
881
928
  }
882
929
  getOptions() {
883
930
  return {
@@ -887,9 +934,13 @@ var AxBaseAI = class {
887
934
  tracer: this.tracer,
888
935
  timeout: this.timeout,
889
936
  excludeContentFromTrace: this.excludeContentFromTrace,
890
- abortSignal: this.abortSignal
937
+ abortSignal: this.abortSignal,
938
+ logger: this.logger
891
939
  };
892
940
  }
941
+ getLogger() {
942
+ return this.logger;
943
+ }
893
944
  getModelList() {
894
945
  const models = [];
895
946
  for (const model of this.models ?? []) {
@@ -1077,7 +1128,11 @@ var AxBaseAI = class {
1077
1128
  return res2;
1078
1129
  };
1079
1130
  if (debug) {
1080
- logChatRequest(req.chatPrompt, options?.debugHideSystemPrompt);
1131
+ logChatRequest(
1132
+ req.chatPrompt,
1133
+ options?.debugHideSystemPrompt,
1134
+ options?.logger ?? this.logger
1135
+ );
1081
1136
  }
1082
1137
  const rt = options?.rateLimiter ?? this.rt;
1083
1138
  const rv = rt ? await rt(fn, { modelUsage: this.modelUsage }) : await fn();
@@ -1108,13 +1163,14 @@ var AxBaseAI = class {
1108
1163
  setChatResponseEvents(res2, span, this.excludeContentFromTrace);
1109
1164
  }
1110
1165
  if (debug) {
1111
- logResponse(res2);
1166
+ logResponse(res2, options?.logger ?? this.logger);
1112
1167
  }
1113
1168
  return res2;
1114
1169
  };
1115
1170
  const doneCb = async (_values) => {
1116
1171
  if (debug) {
1117
- process.stdout.write("\n");
1172
+ const logger = options?.logger ?? this.logger;
1173
+ logger("", { tags: ["responseEnd"] });
1118
1174
  }
1119
1175
  if (span?.isRecording()) {
1120
1176
  span.end();
@@ -1158,7 +1214,10 @@ var AxBaseAI = class {
1158
1214
  span.end();
1159
1215
  }
1160
1216
  if (debug) {
1161
- logResponse(res);
1217
+ logResponse(res, options?.logger ?? this.logger);
1218
+ }
1219
+ if (debug) {
1220
+ this.logger("", { tags: ["responseEnd"] });
1162
1221
  }
1163
1222
  return res;
1164
1223
  }
@@ -5143,6 +5202,9 @@ var AxAI = class {
5143
5202
  getOptions() {
5144
5203
  return this.ai.getOptions();
5145
5204
  }
5205
+ getLogger() {
5206
+ return this.ai.getLogger();
5207
+ }
5146
5208
  };
5147
5209
 
5148
5210
  // ai/x-grok/types.ts
@@ -5366,7 +5428,7 @@ var MemoryImpl = class {
5366
5428
  if (this.options?.debug) {
5367
5429
  if (delta && typeof delta === "string") {
5368
5430
  debugResponseDelta(delta);
5369
- } else if (lastItem) {
5431
+ } else if (!delta && (content || functionCalls)) {
5370
5432
  debugResponse({ content, name, functionCalls });
5371
5433
  }
5372
5434
  }
@@ -6308,7 +6370,6 @@ function formatDescription(str) {
6308
6370
  }
6309
6371
 
6310
6372
  // dsp/validate.ts
6311
- var colorLog4 = new ColorLog();
6312
6373
  var ValidationError = class extends Error {
6313
6374
  fields;
6314
6375
  constructor({
@@ -6349,10 +6410,11 @@ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId)
6349
6410
  mem.addTag("error");
6350
6411
  if (ai.getOptions().debug) {
6351
6412
  const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
6352
- process.stdout.write(colorLog4.red(`
6353
- \u274C Error Correction:
6354
- ${errors}
6355
- `));
6413
+ const logger = ai.getLogger();
6414
+ logger(`\u274C Error Correction:
6415
+ ${errors}`, {
6416
+ tags: ["error"]
6417
+ });
6356
6418
  }
6357
6419
  }
6358
6420
 
@@ -6932,7 +6994,6 @@ var validateJSONSchema = (schema) => {
6932
6994
  };
6933
6995
 
6934
6996
  // dsp/functions.ts
6935
- var colorLog5 = new ColorLog();
6936
6997
  var AxFunctionError = class extends Error {
6937
6998
  constructor(fields) {
6938
6999
  super();
@@ -7101,12 +7162,11 @@ var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, t
7101
7162
  );
7102
7163
  mem.addTag("error");
7103
7164
  if (ai.getOptions().debug) {
7104
- process.stdout.write(
7105
- colorLog5.red(`
7106
- \u274C Function Error Correction:
7107
- ${result}
7108
- `)
7109
- );
7165
+ const logger = ai.getLogger();
7166
+ logger(`\u274C Function Error Correction:
7167
+ ${result}`, {
7168
+ tags: ["error"]
7169
+ });
7110
7170
  }
7111
7171
  } else {
7112
7172
  throw e;
@@ -7872,9 +7932,11 @@ var AxGen = class extends AxProgramWithSignature {
7872
7932
  values = {};
7873
7933
  excludeContentFromTrace = false;
7874
7934
  thoughtFieldName;
7935
+ logger;
7875
7936
  constructor(signature, options) {
7876
7937
  super(signature, { description: options?.description });
7877
7938
  this.options = options;
7939
+ this.logger = options?.logger;
7878
7940
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
7879
7941
  const promptTemplateOptions = {
7880
7942
  functions: options?.functions,
@@ -8162,6 +8224,10 @@ Content: ${content}`
8162
8224
  xstate
8163
8225
  );
8164
8226
  }
8227
+ if (ai.getOptions().debug) {
8228
+ const logger = ai.getLogger();
8229
+ logger("", { tags: ["responseEnd"] });
8230
+ }
8165
8231
  }
8166
8232
  async processResponse({
8167
8233
  ai,
@@ -8289,7 +8355,8 @@ Content: ${result.content}`
8289
8355
  continue multiStepLoop;
8290
8356
  }
8291
8357
  if (debug) {
8292
- process.stdout.write("\n");
8358
+ const logger = options.logger ?? this.logger ?? ai.getLogger();
8359
+ logger("", { tags: ["responseEnd"] });
8293
8360
  }
8294
8361
  return;
8295
8362
  } catch (e) {
@@ -8480,10 +8547,14 @@ function processChildAgentFunction(childFunction, parentValues, parentInputKeys,
8480
8547
  ...pick(parentValues, injectionKeys)
8481
8548
  };
8482
8549
  if (options.debug && injectionKeys.length > 0) {
8483
- process.stdout.write(
8484
- `
8485
- Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`
8486
- );
8550
+ const ai = funcOptions?.ai;
8551
+ if (ai) {
8552
+ const logger = ai.getLogger();
8553
+ logger(
8554
+ `Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`,
8555
+ { tags: ["functionArg"] }
8556
+ );
8557
+ }
8487
8558
  }
8488
8559
  return await originalFunc(updatedChildArgs, funcOptions);
8489
8560
  };
@@ -8592,18 +8663,18 @@ var AxAgent = class {
8592
8663
  }
8593
8664
  const debug = this.getDebug(ai, options);
8594
8665
  if (debug) {
8595
- process.stdout.write(`
8596
- --- Agent Engaged: ${this.name} ---
8597
- `);
8666
+ const logger = ai.getLogger();
8667
+ logger(`\u{1F916} Agent ${this.name} starting...`, {
8668
+ tags: ["assistantStart"]
8669
+ });
8598
8670
  }
8599
8671
  const ret = await boundFunc(ai, values, {
8600
8672
  ...options,
8601
8673
  model
8602
8674
  });
8603
8675
  if (debug) {
8604
- process.stdout.write(`
8605
- --- Agent Done: ${this.name} ---
8606
- `);
8676
+ const logger = ai.getLogger();
8677
+ logger(`\u{1F916} Agent ${this.name} completed.`, { tags: ["assistantEnd"] });
8607
8678
  }
8608
8679
  const sig = this.program.getSignature();
8609
8680
  const outFields = sig.getOutputFields();
@@ -9006,6 +9077,9 @@ var AxBalancer = class _AxBalancer {
9006
9077
  getOptions() {
9007
9078
  return this.currentService.getOptions();
9008
9079
  }
9080
+ getLogger() {
9081
+ return this.currentService.getLogger();
9082
+ }
9009
9083
  };
9010
9084
  function validateModels2(services) {
9011
9085
  const serviceWithModel = services.find(
@@ -11441,6 +11515,11 @@ var AxMockAIService = class {
11441
11515
  getOptions() {
11442
11516
  return this.config.options ?? {};
11443
11517
  }
11518
+ getLogger() {
11519
+ return this.config.options?.logger ?? ((message) => {
11520
+ process.stdout.write(message);
11521
+ });
11522
+ }
11444
11523
  updateMetrics(type) {
11445
11524
  const latency = this.config.latencyMs ?? 0;
11446
11525
  this.metrics.latency[type].samples.push(latency);
@@ -11463,7 +11542,7 @@ var AxMockAIService = class {
11463
11542
  };
11464
11543
 
11465
11544
  // dsp/classifier.ts
11466
- var colorLog6 = new ColorLog();
11545
+ var colorLog4 = new ColorLog();
11467
11546
  var AxSimpleClassifierClass = class {
11468
11547
  name;
11469
11548
  context;
@@ -11525,7 +11604,7 @@ var AxSimpleClassifier = class {
11525
11604
  }
11526
11605
  if (this.debug) {
11527
11606
  console.log(
11528
- colorLog6.whiteBright(`query: ${text}`) + "\n" + colorLog6.greenBright(
11607
+ colorLog4.whiteBright(`query: ${text}`) + "\n" + colorLog4.greenBright(
11529
11608
  JSON.stringify(m.map((m2) => `${m2.id}, ${m2.score}`))
11530
11609
  )
11531
11610
  );
@@ -13016,15 +13095,16 @@ function v4(options, buf, offset) {
13016
13095
  var v4_default = v4;
13017
13096
 
13018
13097
  // mcp/client.ts
13019
- var colorLog7 = new ColorLog();
13020
13098
  var AxMCPClient = class {
13021
13099
  constructor(transport, options = {}) {
13022
13100
  this.transport = transport;
13023
13101
  this.options = options;
13102
+ this.logger = options.logger ?? ((message) => console.log(message));
13024
13103
  }
13025
13104
  functions = [];
13026
13105
  activeRequests = /* @__PURE__ */ new Map();
13027
13106
  capabilities = {};
13107
+ logger;
13028
13108
  async init() {
13029
13109
  if ("connect" in this.transport) {
13030
13110
  await this.transport.connect?.();
@@ -13083,11 +13163,13 @@ var AxMCPClient = class {
13083
13163
  };
13084
13164
  });
13085
13165
  if (this.options.debug) {
13086
- console.log(
13087
- colorLog7.yellow(`> Discovered ${this.functions.length} functions:`)
13088
- );
13166
+ this.logger(`> Discovered ${this.functions.length} functions:`, {
13167
+ tags: ["discovery"]
13168
+ });
13089
13169
  for (const fn of this.functions) {
13090
- console.log(colorLog7.yellow(` - ${fn.name}: ${fn.description}`));
13170
+ this.logger(` - ${fn.name}: ${fn.description}`, {
13171
+ tags: ["discovery"]
13172
+ });
13091
13173
  }
13092
13174
  }
13093
13175
  }
@@ -13130,11 +13212,10 @@ var AxMCPClient = class {
13130
13212
  params
13131
13213
  };
13132
13214
  if (this.options.debug) {
13133
- console.log(
13134
- colorLog7.blueBright(
13135
- `> Sending request ${requestId}:
13136
- ${JSON.stringify(request, null, 2)}`
13137
- )
13215
+ this.logger(
13216
+ `> Sending request ${requestId}:
13217
+ ${JSON.stringify(request, null, 2)}`,
13218
+ { tags: ["requestStart"] }
13138
13219
  );
13139
13220
  }
13140
13221
  const responsePromise = new Promise((resolve, reject) => {
@@ -13142,11 +13223,10 @@ ${JSON.stringify(request, null, 2)}`
13142
13223
  this.transport.send(request).then((res) => {
13143
13224
  this.activeRequests.delete(requestId);
13144
13225
  if (this.options.debug) {
13145
- console.log(
13146
- colorLog7.greenBright(
13147
- `> Received response for request ${requestId}:
13148
- ${JSON.stringify(res, null, 2)}`
13149
- )
13226
+ this.logger(
13227
+ `> Received response for request ${requestId}:
13228
+ ${JSON.stringify(res, null, 2)}`,
13229
+ { tags: ["responseContent"] }
13150
13230
  );
13151
13231
  }
13152
13232
  if (res !== null && typeof res === "object" && "error" in res) {
@@ -13176,9 +13256,9 @@ ${JSON.stringify(res, null, 2)}`
13176
13256
  params
13177
13257
  };
13178
13258
  if (this.options.debug) {
13179
- console.log(
13180
- "\u27A1\uFE0F Sending notification:",
13181
- JSON.stringify(notification, null, 2)
13259
+ this.logger(
13260
+ `\u27A1\uFE0F Sending notification: ${JSON.stringify(notification, null, 2)}`,
13261
+ { tags: ["requestStart"] }
13182
13262
  );
13183
13263
  }
13184
13264
  await this.transport.sendNotification(notification);
@@ -13408,6 +13488,25 @@ var AxMultiServiceRouter = class {
13408
13488
  getOptions() {
13409
13489
  return this.options ?? {};
13410
13490
  }
13491
+ /**
13492
+ * Returns the logger from the last used service,
13493
+ * or falls back to the first service if none has been used.
13494
+ */
13495
+ getLogger() {
13496
+ let serviceInstance = this.lastUsedService;
13497
+ if (!serviceInstance) {
13498
+ const firstServiceEntry = this.services.values().next().value;
13499
+ if (firstServiceEntry) {
13500
+ serviceInstance = firstServiceEntry.service;
13501
+ }
13502
+ }
13503
+ if (!serviceInstance) {
13504
+ return (message) => {
13505
+ process.stdout.write(message);
13506
+ };
13507
+ }
13508
+ return serviceInstance.getLogger();
13509
+ }
13411
13510
  };
13412
13511
 
13413
13512
  // prompts/rag.ts