@ax-llm/ax 11.0.23 → 11.0.25

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
@@ -649,7 +649,8 @@ ${hideContent ? "" : colorLog.whiteBright(msg.content ?? "<empty>")}`;
649
649
  }
650
650
  };
651
651
  var logChatRequestMessage = (msg) => {
652
- process.stdout.write(formatChatMessage(msg) + "\n");
652
+ process.stdout.write(`${formatChatMessage(msg)}
653
+ `);
653
654
  process.stdout.write(colorLog.blueBright("\nAssistant:\n"));
654
655
  };
655
656
  var logChatRequest = (chatPrompt) => {
@@ -967,7 +968,7 @@ var AxBaseAI = class {
967
968
  return res2;
968
969
  };
969
970
  if (options?.debug ?? this.debug) {
970
- logChatRequest(req["chatPrompt"]);
971
+ logChatRequest(req.chatPrompt);
971
972
  }
972
973
  const rt = options?.rateLimiter ?? this.rt;
973
974
  const rv = rt ? await rt(fn, { modelUsage: this.modelUsage }) : await fn();
@@ -1633,6 +1634,7 @@ var AxAIOpenAIModel = /* @__PURE__ */ ((AxAIOpenAIModel2) => {
1633
1634
  AxAIOpenAIModel2["O1Mini"] = "o1-mini";
1634
1635
  AxAIOpenAIModel2["O3Mini"] = "o3-mini";
1635
1636
  AxAIOpenAIModel2["GPT4"] = "gpt-4";
1637
+ AxAIOpenAIModel2["GPT45"] = "gpt-4.5-preview";
1636
1638
  AxAIOpenAIModel2["GPT4O"] = "gpt-4o";
1637
1639
  AxAIOpenAIModel2["GPT4OMini"] = "gpt-4o-mini";
1638
1640
  AxAIOpenAIModel2["GPT4ChatGPT4O"] = "chatgpt-4o-latest";
@@ -1653,6 +1655,12 @@ var AxAIOpenAIEmbedModel = /* @__PURE__ */ ((AxAIOpenAIEmbedModel2) => {
1653
1655
 
1654
1656
  // ai/openai/info.ts
1655
1657
  var axModelInfoOpenAI = [
1658
+ {
1659
+ name: "gpt-4.5-preview" /* GPT45 */,
1660
+ currency: "usd",
1661
+ promptTokenCostPer1M: 75,
1662
+ completionTokenCostPer1M: 150
1663
+ },
1656
1664
  {
1657
1665
  name: "o1" /* O1 */,
1658
1666
  currency: "usd",
@@ -3660,7 +3668,7 @@ var AxAI = class {
3660
3668
  };
3661
3669
 
3662
3670
  // dsp/generate.ts
3663
- import { ReadableStream as ReadableStream2 } from "stream/web";
3671
+ import { ReadableStream as ReadableStream2 } from "node:stream/web";
3664
3672
  import { SpanKind as SpanKind2 } from "@opentelemetry/api";
3665
3673
 
3666
3674
  // ai/util.ts
@@ -3754,7 +3762,7 @@ var MemoryImpl = class {
3754
3762
  }
3755
3763
  }
3756
3764
  if (this.debug) {
3757
- if (delta) {
3765
+ if (delta && typeof delta === "string") {
3758
3766
  debugResponseDelta(delta);
3759
3767
  } else if (lastItem) {
3760
3768
  debugResponse({ content, name, functionCalls });
@@ -3887,10 +3895,10 @@ var AxAssertionError = class extends Error {
3887
3895
  return extraFields;
3888
3896
  };
3889
3897
  };
3890
- var assertAssertions = (asserts, values) => {
3898
+ var assertAssertions = async (asserts, values) => {
3891
3899
  for (const assert of asserts) {
3892
3900
  const { fn, message } = assert;
3893
- const res = fn(values);
3901
+ const res = await fn(values);
3894
3902
  if (res === void 0) {
3895
3903
  continue;
3896
3904
  }
@@ -3902,7 +3910,7 @@ var assertAssertions = (asserts, values) => {
3902
3910
  }
3903
3911
  }
3904
3912
  };
3905
- var assertStreamingAssertions = (asserts, xstate, content, final = false) => {
3913
+ var assertStreamingAssertions = async (asserts, xstate, content, final = false) => {
3906
3914
  if (!xstate.currField || xstate.s === -1 || !asserts || asserts.length === 0) {
3907
3915
  return;
3908
3916
  }
@@ -3915,7 +3923,7 @@ var assertStreamingAssertions = (asserts, xstate, content, final = false) => {
3915
3923
  const currValue = content.substring(xstate.s);
3916
3924
  for (const assert of fieldAsserts) {
3917
3925
  const { message, fn } = assert;
3918
- const res = fn(currValue, final);
3926
+ const res = await fn(currValue, final);
3919
3927
  if (res === void 0) {
3920
3928
  continue;
3921
3929
  }
@@ -3928,9 +3936,6 @@ var assertStreamingAssertions = (asserts, xstate, content, final = false) => {
3928
3936
  // dsp/datetime.ts
3929
3937
  import moment from "moment-timezone";
3930
3938
 
3931
- // dsp/program.ts
3932
- import "@opentelemetry/api";
3933
-
3934
3939
  // dsp/registry.ts
3935
3940
  var AxInstanceRegistry = class {
3936
3941
  reg;
@@ -4461,7 +4466,7 @@ function validateField(field) {
4461
4466
 
4462
4467
  // dsp/util.ts
4463
4468
  var colorLog3 = new ColorLog();
4464
- var updateProgressBar = (current, total, success, elapsedTime, progressBarWidth = 20, msg) => {
4469
+ var updateProgressBar = (current, total, success, elapsedTime, msg, progressBarWidth = 20) => {
4465
4470
  const percentage = (current / total * 100).toFixed(1);
4466
4471
  const filledBarLength = Math.round(progressBarWidth * current / total);
4467
4472
  const emptyBarLength = progressBarWidth - filledBarLength;
@@ -4708,6 +4713,7 @@ var AxProgramWithSignature = class {
4708
4713
  async forward(_ai, _values, _options) {
4709
4714
  throw new Error("forward() not implemented");
4710
4715
  }
4716
+ // biome-ignore lint/correctness/useYield: just a placeholder
4711
4717
  async *streamingForward(_ai, _values, _options) {
4712
4718
  throw new Error("streamingForward() not implemented");
4713
4719
  }
@@ -4805,6 +4811,7 @@ var AxProgram = class {
4805
4811
  async forward(_ai, _values, _options) {
4806
4812
  throw new Error("forward() not implemented");
4807
4813
  }
4814
+ // biome-ignore lint/correctness/useYield: just a placeholder
4808
4815
  async *streamingForward(_ai, _values, _options) {
4809
4816
  throw new Error("streamingForward() not implemented");
4810
4817
  }
@@ -4884,9 +4891,7 @@ var AxPromptTemplate = class {
4884
4891
  task.push(
4885
4892
  `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
4886
4893
  );
4887
- const funcs = functions?.map(
4888
- (f) => "toFunction" in f ? f.toFunction() : f
4889
- );
4894
+ const funcs = functions?.map((f) => "toFunction" in f ? f.toFunction() : f)?.flat();
4890
4895
  const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
4891
4896
  if (funcList && funcList.length > 0) {
4892
4897
  task.push(`## Available Functions
@@ -5785,10 +5790,10 @@ var AxFunctionProcessor = class {
5785
5790
  (v) => v.name.localeCompare(func.name) === 0
5786
5791
  );
5787
5792
  if (!fnSpec) {
5788
- throw new Error(`Function not found: ` + func.name);
5793
+ throw new Error(`Function not found: ${func.name}`);
5789
5794
  }
5790
5795
  if (!fnSpec.func) {
5791
- throw new Error("No handler for function: " + func.name);
5796
+ throw new Error(`No handler for function: ${func.name}`);
5792
5797
  }
5793
5798
  try {
5794
5799
  return await this.executeFunction(fnSpec, func, options);
@@ -5809,9 +5814,11 @@ var parseFunctions = (newFuncs, existingFuncs) => {
5809
5814
  return f.toFunction();
5810
5815
  }
5811
5816
  return f;
5812
- });
5817
+ }).flat();
5813
5818
  for (const fn of functions.filter((v) => v.parameters)) {
5814
- validateJSONSchema(fn.parameters);
5819
+ if (fn.parameters) {
5820
+ validateJSONSchema(fn.parameters);
5821
+ }
5815
5822
  }
5816
5823
  return [...existingFuncs ?? [], ...functions];
5817
5824
  };
@@ -5857,11 +5864,11 @@ ${result}
5857
5864
  return promise;
5858
5865
  });
5859
5866
  const results = await Promise.all(promises);
5860
- results.forEach((result) => {
5867
+ for (const result of results) {
5861
5868
  if (result) {
5862
5869
  mem.add(result, sessionId);
5863
5870
  }
5864
- });
5871
+ }
5865
5872
  return functionsExecuted;
5866
5873
  };
5867
5874
  function parseFunctionCalls(ai, functionCalls, values, model) {
@@ -5945,13 +5952,14 @@ var AxGen = class extends AxProgramWithSignature {
5945
5952
  model,
5946
5953
  rateLimiter,
5947
5954
  stream,
5948
- functions,
5955
+ functions: _functions,
5949
5956
  functionCall: _functionCall
5950
5957
  } = options ?? {};
5951
5958
  const chatPrompt = mem?.history(sessionId) ?? [];
5952
5959
  if (chatPrompt.length === 0) {
5953
5960
  throw new Error("No chat prompt found");
5954
5961
  }
5962
+ const functions = _functions?.map((f) => "toFunction" in f ? f.toFunction() : f)?.flat();
5955
5963
  const functionCall = _functionCall ?? this.options?.functionCall;
5956
5964
  const res = await ai.chat(
5957
5965
  {
@@ -5976,13 +5984,14 @@ var AxGen = class extends AxProgramWithSignature {
5976
5984
  mem,
5977
5985
  options
5978
5986
  }) {
5979
- const { sessionId, traceId, model, functions } = options ?? {};
5987
+ const { sessionId, traceId, model, functions: _functions } = options ?? {};
5980
5988
  const fastFail = options?.fastFail ?? this.options?.fastFail;
5981
5989
  const modelName = model ?? ai.getDefaultModels().model;
5982
5990
  const usageInfo = {
5983
5991
  ai: ai.getName(),
5984
5992
  model: modelName
5985
5993
  };
5994
+ const functions = _functions?.map((f) => "toFunction" in f ? f.toFunction() : f)?.flat();
5986
5995
  const res = await this.forwardSendRequest({
5987
5996
  ai,
5988
5997
  mem,
@@ -6066,7 +6075,11 @@ var AxGen = class extends AxProgramWithSignature {
6066
6075
  streamingValidation
6067
6076
  );
6068
6077
  if (this.streamingAsserts.length !== 0) {
6069
- assertStreamingAssertions(this.streamingAsserts, xstate, content);
6078
+ await assertStreamingAssertions(
6079
+ this.streamingAsserts,
6080
+ xstate,
6081
+ content
6082
+ );
6070
6083
  }
6071
6084
  if (this.streamingFieldProcessors.length !== 0) {
6072
6085
  await processStreamingFieldProcessors(
@@ -6082,7 +6095,7 @@ var AxGen = class extends AxProgramWithSignature {
6082
6095
  if (skip) {
6083
6096
  continue;
6084
6097
  }
6085
- assertAssertions(this.asserts, values);
6098
+ await assertAssertions(this.asserts, values);
6086
6099
  }
6087
6100
  if (result.finishReason === "length") {
6088
6101
  throw new Error("Max tokens reached before completion");
@@ -6104,8 +6117,13 @@ var AxGen = class extends AxProgramWithSignature {
6104
6117
  this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
6105
6118
  } else {
6106
6119
  streamingExtractFinalValue(this.signature, values, xstate, content);
6107
- assertStreamingAssertions(this.streamingAsserts, xstate, content, true);
6108
- assertAssertions(this.asserts, values);
6120
+ await assertStreamingAssertions(
6121
+ this.streamingAsserts,
6122
+ xstate,
6123
+ content,
6124
+ true
6125
+ );
6126
+ await assertAssertions(this.asserts, values);
6109
6127
  if (this.fieldProcessors.length) {
6110
6128
  await processFieldProcessors(
6111
6129
  this.fieldProcessors,
@@ -6165,7 +6183,7 @@ var AxGen = class extends AxProgramWithSignature {
6165
6183
  }
6166
6184
  } else if (result.content) {
6167
6185
  extractValues(this.signature, values, result.content);
6168
- assertAssertions(this.asserts, values);
6186
+ await assertAssertions(this.asserts, values);
6169
6187
  if (this.fieldProcessors.length) {
6170
6188
  await processFieldProcessors(
6171
6189
  this.fieldProcessors,
@@ -6283,8 +6301,8 @@ var AxGen = class extends AxProgramWithSignature {
6283
6301
  }
6284
6302
  const funcNames = functions?.map((f) => f.name).join(",");
6285
6303
  const attributes = {
6286
- ["generate.signature"]: this.signature.toString(),
6287
- ["generate.functions"]: funcNames ?? ""
6304
+ "generate.signature": this.signature.toString(),
6305
+ "generate.functions": funcNames ?? ""
6288
6306
  };
6289
6307
  const span = tracer.startSpan("Generate", {
6290
6308
  kind: SpanKind2.SERVER,
@@ -6330,7 +6348,7 @@ var AxGen = class extends AxProgramWithSignature {
6330
6348
 
6331
6349
  // prompts/agent.ts
6332
6350
  function processChildAgentFunction(childFunction, parentValues, parentInputKeys, modelList, options) {
6333
- let processedFunction = { ...childFunction };
6351
+ const processedFunction = { ...childFunction };
6334
6352
  if (processedFunction.parameters) {
6335
6353
  const childKeys = processedFunction.parameters.properties ? Object.keys(processedFunction.parameters.properties) : [];
6336
6354
  const commonKeys = parentInputKeys.filter((key) => childKeys.includes(key)).filter((key) => key !== "model");
@@ -6402,7 +6420,7 @@ var AxAgent = class {
6402
6420
  this.debug = debug;
6403
6421
  if (!name || name.length < 5) {
6404
6422
  throw new Error(
6405
- `Agent name must be at least 10 characters (more descriptive)`
6423
+ "Agent name must be at least 10 characters (more descriptive)"
6406
6424
  );
6407
6425
  }
6408
6426
  if (!description || description.length < 20) {
@@ -6964,8 +6982,8 @@ var AxBootstrapFewShot = class {
6964
6982
  total,
6965
6983
  this.traces.length,
6966
6984
  et,
6967
- 30,
6968
- "Tuning Prompt"
6985
+ "Tuning Prompt",
6986
+ 30
6969
6987
  );
6970
6988
  if (this.traces.length > maxDemos) {
6971
6989
  return;
@@ -8058,13 +8076,13 @@ var AxHFDataLoader = class {
8058
8076
  };
8059
8077
 
8060
8078
  // funcs/code.ts
8061
- import * as _crypto from "crypto";
8062
- import * as _http from "http";
8063
- import * as _https from "https";
8079
+ import * as _crypto from "node:crypto";
8064
8080
  import * as _fs from "node:fs";
8065
- import * as _os from "os";
8066
- import * as _process from "process";
8067
- import { runInNewContext } from "vm";
8081
+ import * as _http from "node:http";
8082
+ import * as _https from "node:https";
8083
+ import * as _os from "node:os";
8084
+ import * as _process from "node:process";
8085
+ import { runInNewContext } from "node:vm";
8068
8086
  var AxJSInterpreterPermission = /* @__PURE__ */ ((AxJSInterpreterPermission2) => {
8069
8087
  AxJSInterpreterPermission2["FS"] = "node:fs";
8070
8088
  AxJSInterpreterPermission2["NET"] = "net";
@@ -8335,7 +8353,7 @@ var AxTestPrompt = class {
8335
8353
  successCount++;
8336
8354
  }
8337
8355
  const et = (/* @__PURE__ */ new Date()).getTime() - st;
8338
- updateProgressBar(i, total, successCount, et, 30, "Testing Prompt");
8356
+ updateProgressBar(i, total, successCount, et, "Testing Prompt", 30);
8339
8357
  }
8340
8358
  console.log(
8341
8359
  "\nPerformance: ",
@@ -8501,6 +8519,213 @@ var AxEmbeddingAdapter = class {
8501
8519
  }
8502
8520
  };
8503
8521
 
8522
+ // mcp/client.ts
8523
+ var colorLog7 = new ColorLog();
8524
+ var AxMCPClient = class {
8525
+ constructor(transport, options = {}) {
8526
+ this.transport = transport;
8527
+ this.options = options;
8528
+ }
8529
+ functions = [];
8530
+ requestId = 0;
8531
+ capabilities = {};
8532
+ async init() {
8533
+ if ("connect" in this.transport) {
8534
+ await this.transport.connect?.();
8535
+ }
8536
+ const res = await this.sendRequest("initialize", {
8537
+ protocolVersion: "2024-11-05",
8538
+ capabilities: {
8539
+ roots: { listChanged: true },
8540
+ sampling: {}
8541
+ },
8542
+ clientInfo: {
8543
+ name: "AxMCPClient",
8544
+ version: "1.0.0"
8545
+ }
8546
+ });
8547
+ if (res.capabilities.tools) {
8548
+ this.capabilities.tools = true;
8549
+ }
8550
+ if (res.capabilities.resources) {
8551
+ this.capabilities.resources = true;
8552
+ }
8553
+ if (res.capabilities.prompts) {
8554
+ this.capabilities.prompts = true;
8555
+ }
8556
+ await this.sendNotification("initialized");
8557
+ await this.discoverFunctions();
8558
+ }
8559
+ async discoverFunctions() {
8560
+ if (!this.capabilities.tools) {
8561
+ throw new Error("Tools are not supported");
8562
+ }
8563
+ const res = await this.sendRequest(
8564
+ "tools/list"
8565
+ );
8566
+ this.functions = res.tools.map(
8567
+ (fn) => ({
8568
+ name: fn.name,
8569
+ description: fn.description,
8570
+ parameters: fn.inputSchema,
8571
+ func: async (args) => {
8572
+ const result = await this.sendRequest("tools/call", { name: fn.name, arguments: args });
8573
+ return result;
8574
+ }
8575
+ })
8576
+ );
8577
+ }
8578
+ async ping() {
8579
+ await this.sendRequest("ping");
8580
+ }
8581
+ toFunction() {
8582
+ return this.functions;
8583
+ }
8584
+ async sendRequest(method, params) {
8585
+ const request = {
8586
+ jsonrpc: "2.0",
8587
+ id: ++this.requestId,
8588
+ method,
8589
+ params
8590
+ };
8591
+ if (this.options.debug) {
8592
+ console.log(
8593
+ colorLog7.blueBright(
8594
+ `> Sending request:
8595
+ ${JSON.stringify(request, null, 2)}`
8596
+ )
8597
+ );
8598
+ }
8599
+ const res = await this.transport.send(request);
8600
+ if (this.options.debug) {
8601
+ console.log(
8602
+ colorLog7.greenBright(
8603
+ `> Received response:
8604
+ ${JSON.stringify(res, null, 2)}`
8605
+ )
8606
+ );
8607
+ }
8608
+ if ("error" in res) {
8609
+ throw new Error(`RPC Error ${res.error.code}: ${res.error.message}`);
8610
+ }
8611
+ if ("result" in res) {
8612
+ return res.result;
8613
+ }
8614
+ throw new Error("Invalid response no result or error");
8615
+ }
8616
+ async sendNotification(method, params) {
8617
+ const notification = {
8618
+ jsonrpc: "2.0",
8619
+ method,
8620
+ params
8621
+ };
8622
+ if (this.options.debug) {
8623
+ console.log(
8624
+ "\u27A1\uFE0F Sending notification:",
8625
+ JSON.stringify(notification, null, 2)
8626
+ );
8627
+ }
8628
+ await this.transport.sendNotification(notification);
8629
+ }
8630
+ };
8631
+
8632
+ // mcp/httpTransport.ts
8633
+ var AxMCPHTTPTransport = class {
8634
+ endpoint = null;
8635
+ sseUrl;
8636
+ eventSource;
8637
+ constructor(sseUrl) {
8638
+ this.sseUrl = sseUrl;
8639
+ }
8640
+ async connect() {
8641
+ return new Promise((resolve, reject) => {
8642
+ this.eventSource = new EventSource(this.sseUrl);
8643
+ this.eventSource.addEventListener("endpoint", (event) => {
8644
+ try {
8645
+ const messageEvent = event;
8646
+ const data = JSON.parse(messageEvent.data);
8647
+ if (!data.uri) {
8648
+ throw new Error("Endpoint URI missing in SSE event data");
8649
+ }
8650
+ this.endpoint = data.uri;
8651
+ resolve();
8652
+ } catch (error) {
8653
+ reject(error);
8654
+ }
8655
+ });
8656
+ this.eventSource.onerror = () => {
8657
+ reject(new Error("Failed to establish SSE connection"));
8658
+ };
8659
+ });
8660
+ }
8661
+ async send(message) {
8662
+ if (!this.endpoint) {
8663
+ throw new Error(
8664
+ "HTTPTransport endpoint is not initialized. Call connect() first."
8665
+ );
8666
+ }
8667
+ const res = await fetch(this.endpoint, {
8668
+ method: "POST",
8669
+ headers: { "Content-Type": "application/json" },
8670
+ body: JSON.stringify(message)
8671
+ });
8672
+ if (!res.ok) {
8673
+ throw new Error(`HTTP error ${res.status}: ${res.statusText}`);
8674
+ }
8675
+ return res.json();
8676
+ }
8677
+ async sendNotification(message) {
8678
+ if (!this.endpoint) {
8679
+ throw new Error(
8680
+ "HTTPTransport endpoint is not initialized. Call connect() first."
8681
+ );
8682
+ }
8683
+ await fetch(this.endpoint, {
8684
+ method: "POST",
8685
+ headers: { "Content-Type": "application/json" },
8686
+ body: JSON.stringify(message)
8687
+ });
8688
+ }
8689
+ };
8690
+
8691
+ // mcp/stdioTransport.ts
8692
+ import { spawn } from "node:child_process";
8693
+ import readline from "node:readline";
8694
+ var AxMCPStdioTransport = class {
8695
+ process;
8696
+ rl;
8697
+ pendingResponses = /* @__PURE__ */ new Map();
8698
+ constructor(config) {
8699
+ this.process = spawn(config.command, config.args ?? [], {
8700
+ env: config.env ? { ...process.env, ...config.env } : process.env
8701
+ });
8702
+ this.rl = readline.createInterface({ input: this.process.stdout });
8703
+ this.rl.on("line", (line) => {
8704
+ const response = JSON.parse(line);
8705
+ const resolver = this.pendingResponses.get(response.id);
8706
+ if (resolver) {
8707
+ resolver(response);
8708
+ this.pendingResponses.delete(response.id);
8709
+ }
8710
+ });
8711
+ }
8712
+ async send(message) {
8713
+ return new Promise((resolve) => {
8714
+ this.pendingResponses.set(message.id, (res) => {
8715
+ resolve(res);
8716
+ });
8717
+ this.process.stdin.write(`${JSON.stringify(message)}
8718
+ `);
8719
+ });
8720
+ }
8721
+ async sendNotification(message) {
8722
+ this.process.stdin.write(`${JSON.stringify(message)}
8723
+ `);
8724
+ }
8725
+ async connect() {
8726
+ }
8727
+ };
8728
+
8504
8729
  // ai/multiservice.ts
8505
8730
  var AxMultiServiceRouter = class {
8506
8731
  services = /* @__PURE__ */ new Map();
@@ -8752,6 +8977,9 @@ export {
8752
8977
  AxJSInterpreter,
8753
8978
  AxJSInterpreterPermission,
8754
8979
  AxLLMRequestTypeValues,
8980
+ AxMCPClient,
8981
+ AxMCPHTTPTransport,
8982
+ AxMCPStdioTransport,
8755
8983
  AxMemory,
8756
8984
  AxMockAIService,
8757
8985
  AxMultiServiceRouter,