@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.cjs CHANGED
@@ -835,6 +835,46 @@ var ColorLog = class {
835
835
 
836
836
  // ai/debug.ts
837
837
  var colorLog = new ColorLog();
838
+ var defaultOutput = (message) => {
839
+ process.stdout.write(message);
840
+ };
841
+ var createDefaultLogger = (output = defaultOutput) => {
842
+ return (message, options) => {
843
+ const tags = options?.tags ?? [];
844
+ let formattedMessage = message;
845
+ if (tags.includes("error")) {
846
+ formattedMessage = colorLog.red(formattedMessage);
847
+ } else if (tags.includes("success") || tags.includes("responseContent")) {
848
+ formattedMessage = colorLog.greenBright(formattedMessage);
849
+ } else if (tags.includes("functionName")) {
850
+ formattedMessage = colorLog.whiteBright(formattedMessage);
851
+ } else if (tags.includes("functionArg") || tags.includes("systemContent") || tags.includes("assistantContent")) {
852
+ formattedMessage = colorLog.blueBright(formattedMessage);
853
+ } else if (tags.includes("warning") || tags.includes("discovery")) {
854
+ formattedMessage = colorLog.yellow(formattedMessage);
855
+ }
856
+ if (tags.includes("responseStart") || tags.includes("systemStart") || tags.includes("userStart")) {
857
+ formattedMessage = `
858
+ ${formattedMessage}`;
859
+ } else if (tags.includes("responseEnd") || tags.includes("systemEnd") || tags.includes("userEnd")) {
860
+ formattedMessage = `${formattedMessage}
861
+ `;
862
+ } else if (tags.includes("assistantStart")) {
863
+ formattedMessage = `
864
+ ${formattedMessage}
865
+ `;
866
+ } else if (tags.includes("error")) {
867
+ formattedMessage = `
868
+ ${formattedMessage}
869
+ `;
870
+ } else if (tags.includes("functionEnd")) {
871
+ formattedMessage = `${formattedMessage}
872
+ `;
873
+ }
874
+ output(formattedMessage);
875
+ };
876
+ };
877
+ var defaultLogger = createDefaultLogger();
838
878
  var formatChatMessage = (msg, hideContent, hideSystemPrompt) => {
839
879
  switch (msg.role) {
840
880
  case "system":
@@ -842,30 +882,30 @@ var formatChatMessage = (msg, hideContent, hideSystemPrompt) => {
842
882
  return "";
843
883
  }
844
884
  return `
845
- ${colorLog.blueBright("System:")}
846
- ${colorLog.whiteBright(msg.content)}`;
885
+ System:
886
+ ${msg.content}`;
847
887
  case "function":
848
888
  return `
849
- ${colorLog.blueBright("Function Result:")}
850
- ${colorLog.whiteBright(msg.result)}`;
889
+ Function Result:
890
+ ${msg.result}`;
851
891
  case "user": {
852
892
  if (typeof msg.content === "string") {
853
893
  return `
854
- ${colorLog.blueBright("User:")}
855
- ${colorLog.whiteBright(msg.content)}`;
894
+ User:
895
+ ${msg.content}`;
856
896
  }
857
897
  const items = msg.content.map((v) => {
858
898
  switch (v.type) {
859
899
  case "text":
860
- return `${colorLog.whiteBright(v.text)}`;
900
+ return v.text;
861
901
  case "image":
862
- return `(Image, ${v.mimeType}) ${colorLog.whiteBright(v.image.substring(0, 10))}`;
902
+ return `(Image, ${v.mimeType}) ${v.image.substring(0, 10)}`;
863
903
  default:
864
904
  throw new Error("Invalid content type");
865
905
  }
866
906
  });
867
907
  return `
868
- ${colorLog.blueBright("User:")}
908
+ User:
869
909
  ${items.join("\n")}`;
870
910
  }
871
911
  case "assistant": {
@@ -875,62 +915,64 @@ ${items.join("\n")}`;
875
915
  return `${fn.name}(${args})`;
876
916
  });
877
917
  return `
878
- ${colorLog.blueBright("\nFunctions:")}
879
- ${colorLog.whiteBright(fns.join("\n"))}`;
918
+ Functions:
919
+ ${fns.join("\n")}`;
880
920
  }
881
921
  return `
882
- ${colorLog.blueBright("\nAssistant:")}
883
- ${hideContent ? "" : colorLog.whiteBright(msg.content ?? "<empty>")}`;
922
+ Assistant:
923
+ ${hideContent ? "" : msg.content ?? "<empty>"}`;
884
924
  }
885
925
  default:
886
926
  throw new Error("Invalid role");
887
927
  }
888
928
  };
889
- var logChatRequestMessage = (msg, hideSystemPrompt) => {
890
- process.stdout.write(`${formatChatMessage(msg, hideSystemPrompt)}
891
- `);
892
- process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
929
+ var logChatRequestMessage = (msg, hideSystemPrompt, logger = defaultLogger) => {
930
+ const formattedMessage = formatChatMessage(msg, false, hideSystemPrompt);
931
+ if (formattedMessage) {
932
+ const tags = msg.role === "system" ? ["systemStart", "systemContent"] : msg.role === "function" ? ["functionName"] : msg.role === "user" ? ["userStart", "userContent"] : [];
933
+ logger(formattedMessage, { tags });
934
+ }
935
+ logger("Assistant:", { tags: ["assistantStart"] });
893
936
  };
894
- var logChatRequest = (chatPrompt, hideSystemPrompt) => {
895
- const items = chatPrompt?.map(
896
- (msg) => formatChatMessage(msg, hideSystemPrompt)
897
- );
898
- if (items) {
899
- process.stdout.write(items.join("\n"));
900
- process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
937
+ var logChatRequest = (chatPrompt, hideSystemPrompt, logger = defaultLogger) => {
938
+ for (const msg of chatPrompt ?? []) {
939
+ const formattedMessage = formatChatMessage(msg, false, hideSystemPrompt);
940
+ if (formattedMessage) {
941
+ const tags = msg.role === "system" ? ["systemContent"] : msg.role === "function" ? ["functionName"] : msg.role === "user" ? ["userContent"] : [];
942
+ logger(formattedMessage, { tags });
943
+ }
901
944
  }
945
+ logger("Assistant:", { tags: ["assistantStart"] });
902
946
  };
903
- var logResponseResult = (r) => {
947
+ var logResponseResult = (r, logger = defaultLogger) => {
904
948
  if (r.content) {
905
- process.stdout.write(colorLog.greenBright(r.content));
949
+ logger(r.content, { tags: ["responseContent"] });
906
950
  }
907
- if (r.functionCalls) {
951
+ if (r.functionCalls && r.functionCalls.length > 0) {
908
952
  for (const [i, f] of r.functionCalls.entries()) {
909
953
  if (f.function.name) {
910
- if (i > 0) {
911
- process.stdout.write("\n");
912
- }
913
- process.stdout.write(
914
- `Function ${i + 1} -> ${colorLog.greenBright(f.function.name)}`
915
- );
954
+ logger(`[${i + 1}] ${f.function.name}`, {
955
+ tags: ["functionName"]
956
+ });
916
957
  }
917
958
  if (f.function.params) {
918
959
  const params = typeof f.function.params === "string" ? f.function.params : JSON.stringify(f.function.params, null, 2);
919
- process.stdout.write(`${colorLog.greenBright(params)}`);
960
+ logger(params, { tags: ["functionArg"] });
920
961
  }
921
962
  }
963
+ logger("", { tags: ["functionEnd"] });
922
964
  }
923
965
  };
924
- var logResponse = (resp) => {
966
+ var logResponse = (resp, logger = defaultLogger) => {
925
967
  if (!resp.results) {
926
968
  return;
927
969
  }
928
970
  for (const r of resp.results) {
929
- logResponseResult(r);
971
+ logResponseResult(r, logger);
930
972
  }
931
973
  };
932
- var logResponseDelta = (delta) => {
933
- process.stdout.write(colorLog.greenBright(delta));
974
+ var logResponseDelta = (delta, logger = defaultLogger) => {
975
+ logger(delta, { tags: ["responseContent"] });
934
976
  };
935
977
 
936
978
  // ai/base.ts
@@ -944,6 +986,9 @@ var axBaseAIDefaultCreativeConfig = () => structuredClone({
944
986
  topP: 0.7,
945
987
  frequencyPenalty: 0.2
946
988
  });
989
+ var defaultLogger2 = (message, _options) => {
990
+ process.stdout.write(message);
991
+ };
947
992
  var AxBaseAI = class {
948
993
  constructor(aiImpl, {
949
994
  name,
@@ -983,6 +1028,7 @@ var AxBaseAI = class {
983
1028
  excludeContentFromTrace;
984
1029
  models;
985
1030
  abortSignal;
1031
+ logger = defaultLogger2;
986
1032
  modelInfo;
987
1033
  modelUsage;
988
1034
  embedModelUsage;
@@ -1044,6 +1090,7 @@ var AxBaseAI = class {
1044
1090
  this.tracer = options.tracer;
1045
1091
  this.excludeContentFromTrace = options.excludeContentFromTrace;
1046
1092
  this.abortSignal = options.abortSignal;
1093
+ this.logger = options.logger ?? defaultLogger2;
1047
1094
  }
1048
1095
  getOptions() {
1049
1096
  return {
@@ -1053,9 +1100,13 @@ var AxBaseAI = class {
1053
1100
  tracer: this.tracer,
1054
1101
  timeout: this.timeout,
1055
1102
  excludeContentFromTrace: this.excludeContentFromTrace,
1056
- abortSignal: this.abortSignal
1103
+ abortSignal: this.abortSignal,
1104
+ logger: this.logger
1057
1105
  };
1058
1106
  }
1107
+ getLogger() {
1108
+ return this.logger;
1109
+ }
1059
1110
  getModelList() {
1060
1111
  const models = [];
1061
1112
  for (const model of this.models ?? []) {
@@ -1243,7 +1294,11 @@ var AxBaseAI = class {
1243
1294
  return res2;
1244
1295
  };
1245
1296
  if (debug) {
1246
- logChatRequest(req.chatPrompt, options?.debugHideSystemPrompt);
1297
+ logChatRequest(
1298
+ req.chatPrompt,
1299
+ options?.debugHideSystemPrompt,
1300
+ options?.logger ?? this.logger
1301
+ );
1247
1302
  }
1248
1303
  const rt = options?.rateLimiter ?? this.rt;
1249
1304
  const rv = rt ? await rt(fn, { modelUsage: this.modelUsage }) : await fn();
@@ -1274,13 +1329,14 @@ var AxBaseAI = class {
1274
1329
  setChatResponseEvents(res2, span, this.excludeContentFromTrace);
1275
1330
  }
1276
1331
  if (debug) {
1277
- logResponse(res2);
1332
+ logResponse(res2, options?.logger ?? this.logger);
1278
1333
  }
1279
1334
  return res2;
1280
1335
  };
1281
1336
  const doneCb = async (_values) => {
1282
1337
  if (debug) {
1283
- process.stdout.write("\n");
1338
+ const logger = options?.logger ?? this.logger;
1339
+ logger("", { tags: ["responseEnd"] });
1284
1340
  }
1285
1341
  if (span?.isRecording()) {
1286
1342
  span.end();
@@ -1324,7 +1380,10 @@ var AxBaseAI = class {
1324
1380
  span.end();
1325
1381
  }
1326
1382
  if (debug) {
1327
- logResponse(res);
1383
+ logResponse(res, options?.logger ?? this.logger);
1384
+ }
1385
+ if (debug) {
1386
+ this.logger("", { tags: ["responseEnd"] });
1328
1387
  }
1329
1388
  return res;
1330
1389
  }
@@ -5309,6 +5368,9 @@ var AxAI = class {
5309
5368
  getOptions() {
5310
5369
  return this.ai.getOptions();
5311
5370
  }
5371
+ getLogger() {
5372
+ return this.ai.getLogger();
5373
+ }
5312
5374
  };
5313
5375
 
5314
5376
  // ai/x-grok/types.ts
@@ -5528,7 +5590,7 @@ var MemoryImpl = class {
5528
5590
  if (this.options?.debug) {
5529
5591
  if (delta && typeof delta === "string") {
5530
5592
  debugResponseDelta(delta);
5531
- } else if (lastItem) {
5593
+ } else if (!delta && (content || functionCalls)) {
5532
5594
  debugResponse({ content, name, functionCalls });
5533
5595
  }
5534
5596
  }
@@ -6470,7 +6532,6 @@ function formatDescription(str) {
6470
6532
  }
6471
6533
 
6472
6534
  // dsp/validate.ts
6473
- var colorLog4 = new ColorLog();
6474
6535
  var ValidationError = class extends Error {
6475
6536
  fields;
6476
6537
  constructor({
@@ -6511,10 +6572,11 @@ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId)
6511
6572
  mem.addTag("error");
6512
6573
  if (ai.getOptions().debug) {
6513
6574
  const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
6514
- process.stdout.write(colorLog4.red(`
6515
- \u274C Error Correction:
6516
- ${errors}
6517
- `));
6575
+ const logger = ai.getLogger();
6576
+ logger(`\u274C Error Correction:
6577
+ ${errors}`, {
6578
+ tags: ["error"]
6579
+ });
6518
6580
  }
6519
6581
  }
6520
6582
 
@@ -7094,7 +7156,6 @@ var validateJSONSchema = (schema) => {
7094
7156
  };
7095
7157
 
7096
7158
  // dsp/functions.ts
7097
- var colorLog5 = new ColorLog();
7098
7159
  var AxFunctionError = class extends Error {
7099
7160
  constructor(fields) {
7100
7161
  super();
@@ -7263,12 +7324,11 @@ var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, t
7263
7324
  );
7264
7325
  mem.addTag("error");
7265
7326
  if (ai.getOptions().debug) {
7266
- process.stdout.write(
7267
- colorLog5.red(`
7268
- \u274C Function Error Correction:
7269
- ${result}
7270
- `)
7271
- );
7327
+ const logger = ai.getLogger();
7328
+ logger(`\u274C Function Error Correction:
7329
+ ${result}`, {
7330
+ tags: ["error"]
7331
+ });
7272
7332
  }
7273
7333
  } else {
7274
7334
  throw e;
@@ -8034,9 +8094,11 @@ var AxGen = class extends AxProgramWithSignature {
8034
8094
  values = {};
8035
8095
  excludeContentFromTrace = false;
8036
8096
  thoughtFieldName;
8097
+ logger;
8037
8098
  constructor(signature, options) {
8038
8099
  super(signature, { description: options?.description });
8039
8100
  this.options = options;
8101
+ this.logger = options?.logger;
8040
8102
  this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
8041
8103
  const promptTemplateOptions = {
8042
8104
  functions: options?.functions,
@@ -8324,6 +8386,10 @@ Content: ${content}`
8324
8386
  xstate
8325
8387
  );
8326
8388
  }
8389
+ if (ai.getOptions().debug) {
8390
+ const logger = ai.getLogger();
8391
+ logger("", { tags: ["responseEnd"] });
8392
+ }
8327
8393
  }
8328
8394
  async processResponse({
8329
8395
  ai,
@@ -8451,7 +8517,8 @@ Content: ${result.content}`
8451
8517
  continue multiStepLoop;
8452
8518
  }
8453
8519
  if (debug) {
8454
- process.stdout.write("\n");
8520
+ const logger = options.logger ?? this.logger ?? ai.getLogger();
8521
+ logger("", { tags: ["responseEnd"] });
8455
8522
  }
8456
8523
  return;
8457
8524
  } catch (e) {
@@ -8642,10 +8709,14 @@ function processChildAgentFunction(childFunction, parentValues, parentInputKeys,
8642
8709
  ...pick(parentValues, injectionKeys)
8643
8710
  };
8644
8711
  if (options.debug && injectionKeys.length > 0) {
8645
- process.stdout.write(
8646
- `
8647
- Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`
8648
- );
8712
+ const ai = funcOptions?.ai;
8713
+ if (ai) {
8714
+ const logger = ai.getLogger();
8715
+ logger(
8716
+ `Function Params: ${JSON.stringify(updatedChildArgs, null, 2)}`,
8717
+ { tags: ["functionArg"] }
8718
+ );
8719
+ }
8649
8720
  }
8650
8721
  return await originalFunc(updatedChildArgs, funcOptions);
8651
8722
  };
@@ -8754,18 +8825,18 @@ var AxAgent = class {
8754
8825
  }
8755
8826
  const debug = this.getDebug(ai, options);
8756
8827
  if (debug) {
8757
- process.stdout.write(`
8758
- --- Agent Engaged: ${this.name} ---
8759
- `);
8828
+ const logger = ai.getLogger();
8829
+ logger(`\u{1F916} Agent ${this.name} starting...`, {
8830
+ tags: ["assistantStart"]
8831
+ });
8760
8832
  }
8761
8833
  const ret = await boundFunc(ai, values, {
8762
8834
  ...options,
8763
8835
  model
8764
8836
  });
8765
8837
  if (debug) {
8766
- process.stdout.write(`
8767
- --- Agent Done: ${this.name} ---
8768
- `);
8838
+ const logger = ai.getLogger();
8839
+ logger(`\u{1F916} Agent ${this.name} completed.`, { tags: ["assistantEnd"] });
8769
8840
  }
8770
8841
  const sig = this.program.getSignature();
8771
8842
  const outFields = sig.getOutputFields();
@@ -9168,6 +9239,9 @@ var AxBalancer = class _AxBalancer {
9168
9239
  getOptions() {
9169
9240
  return this.currentService.getOptions();
9170
9241
  }
9242
+ getLogger() {
9243
+ return this.currentService.getLogger();
9244
+ }
9171
9245
  };
9172
9246
  function validateModels2(services) {
9173
9247
  const serviceWithModel = services.find(
@@ -11603,6 +11677,11 @@ var AxMockAIService = class {
11603
11677
  getOptions() {
11604
11678
  return this.config.options ?? {};
11605
11679
  }
11680
+ getLogger() {
11681
+ return this.config.options?.logger ?? ((message) => {
11682
+ process.stdout.write(message);
11683
+ });
11684
+ }
11606
11685
  updateMetrics(type) {
11607
11686
  const latency = this.config.latencyMs ?? 0;
11608
11687
  this.metrics.latency[type].samples.push(latency);
@@ -11625,7 +11704,7 @@ var AxMockAIService = class {
11625
11704
  };
11626
11705
 
11627
11706
  // dsp/classifier.ts
11628
- var colorLog6 = new ColorLog();
11707
+ var colorLog4 = new ColorLog();
11629
11708
  var AxSimpleClassifierClass = class {
11630
11709
  name;
11631
11710
  context;
@@ -11687,7 +11766,7 @@ var AxSimpleClassifier = class {
11687
11766
  }
11688
11767
  if (this.debug) {
11689
11768
  console.log(
11690
- colorLog6.whiteBright(`query: ${text}`) + "\n" + colorLog6.greenBright(
11769
+ colorLog4.whiteBright(`query: ${text}`) + "\n" + colorLog4.greenBright(
11691
11770
  JSON.stringify(m.map((m2) => `${m2.id}, ${m2.score}`))
11692
11771
  )
11693
11772
  );
@@ -13178,15 +13257,16 @@ function v4(options, buf, offset) {
13178
13257
  var v4_default = v4;
13179
13258
 
13180
13259
  // mcp/client.ts
13181
- var colorLog7 = new ColorLog();
13182
13260
  var AxMCPClient = class {
13183
13261
  constructor(transport, options = {}) {
13184
13262
  this.transport = transport;
13185
13263
  this.options = options;
13264
+ this.logger = options.logger ?? ((message) => console.log(message));
13186
13265
  }
13187
13266
  functions = [];
13188
13267
  activeRequests = /* @__PURE__ */ new Map();
13189
13268
  capabilities = {};
13269
+ logger;
13190
13270
  async init() {
13191
13271
  if ("connect" in this.transport) {
13192
13272
  await this.transport.connect?.();
@@ -13245,11 +13325,13 @@ var AxMCPClient = class {
13245
13325
  };
13246
13326
  });
13247
13327
  if (this.options.debug) {
13248
- console.log(
13249
- colorLog7.yellow(`> Discovered ${this.functions.length} functions:`)
13250
- );
13328
+ this.logger(`> Discovered ${this.functions.length} functions:`, {
13329
+ tags: ["discovery"]
13330
+ });
13251
13331
  for (const fn of this.functions) {
13252
- console.log(colorLog7.yellow(` - ${fn.name}: ${fn.description}`));
13332
+ this.logger(` - ${fn.name}: ${fn.description}`, {
13333
+ tags: ["discovery"]
13334
+ });
13253
13335
  }
13254
13336
  }
13255
13337
  }
@@ -13292,11 +13374,10 @@ var AxMCPClient = class {
13292
13374
  params
13293
13375
  };
13294
13376
  if (this.options.debug) {
13295
- console.log(
13296
- colorLog7.blueBright(
13297
- `> Sending request ${requestId}:
13298
- ${JSON.stringify(request, null, 2)}`
13299
- )
13377
+ this.logger(
13378
+ `> Sending request ${requestId}:
13379
+ ${JSON.stringify(request, null, 2)}`,
13380
+ { tags: ["requestStart"] }
13300
13381
  );
13301
13382
  }
13302
13383
  const responsePromise = new Promise((resolve, reject) => {
@@ -13304,11 +13385,10 @@ ${JSON.stringify(request, null, 2)}`
13304
13385
  this.transport.send(request).then((res) => {
13305
13386
  this.activeRequests.delete(requestId);
13306
13387
  if (this.options.debug) {
13307
- console.log(
13308
- colorLog7.greenBright(
13309
- `> Received response for request ${requestId}:
13310
- ${JSON.stringify(res, null, 2)}`
13311
- )
13388
+ this.logger(
13389
+ `> Received response for request ${requestId}:
13390
+ ${JSON.stringify(res, null, 2)}`,
13391
+ { tags: ["responseContent"] }
13312
13392
  );
13313
13393
  }
13314
13394
  if (res !== null && typeof res === "object" && "error" in res) {
@@ -13338,9 +13418,9 @@ ${JSON.stringify(res, null, 2)}`
13338
13418
  params
13339
13419
  };
13340
13420
  if (this.options.debug) {
13341
- console.log(
13342
- "\u27A1\uFE0F Sending notification:",
13343
- JSON.stringify(notification, null, 2)
13421
+ this.logger(
13422
+ `\u27A1\uFE0F Sending notification: ${JSON.stringify(notification, null, 2)}`,
13423
+ { tags: ["requestStart"] }
13344
13424
  );
13345
13425
  }
13346
13426
  await this.transport.sendNotification(notification);
@@ -13570,6 +13650,25 @@ var AxMultiServiceRouter = class {
13570
13650
  getOptions() {
13571
13651
  return this.options ?? {};
13572
13652
  }
13653
+ /**
13654
+ * Returns the logger from the last used service,
13655
+ * or falls back to the first service if none has been used.
13656
+ */
13657
+ getLogger() {
13658
+ let serviceInstance = this.lastUsedService;
13659
+ if (!serviceInstance) {
13660
+ const firstServiceEntry = this.services.values().next().value;
13661
+ if (firstServiceEntry) {
13662
+ serviceInstance = firstServiceEntry.service;
13663
+ }
13664
+ }
13665
+ if (!serviceInstance) {
13666
+ return (message) => {
13667
+ process.stdout.write(message);
13668
+ };
13669
+ }
13670
+ return serviceInstance.getLogger();
13671
+ }
13573
13672
  };
13574
13673
 
13575
13674
  // prompts/rag.ts