@ax-llm/ax 10.0.48 → 10.0.50

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
@@ -1587,16 +1587,18 @@ function createMessages(chatPrompt) {
1587
1587
  const items = chatPrompt.map((msg) => {
1588
1588
  switch (msg.role) {
1589
1589
  case "function":
1590
+ const content = [
1591
+ {
1592
+ type: "tool_result",
1593
+ content: msg.result,
1594
+ tool_use_id: msg.functionId,
1595
+ ...msg.isError ? { is_error: true } : {},
1596
+ ...msg.cache ? { cache: { type: "ephemeral" } } : {}
1597
+ }
1598
+ ];
1590
1599
  return {
1591
1600
  role: "user",
1592
- content: [
1593
- {
1594
- type: "tool_result",
1595
- content: msg.result,
1596
- tool_use_id: msg.functionId,
1597
- ...msg.cache ? { cache: { type: "ephemeral" } } : {}
1598
- }
1599
- ]
1601
+ content
1600
1602
  };
1601
1603
  case "user": {
1602
1604
  if (typeof msg.content === "string") {
@@ -1605,7 +1607,7 @@ function createMessages(chatPrompt) {
1605
1607
  content: msg.content
1606
1608
  };
1607
1609
  }
1608
- const content = msg.content.map((v) => {
1610
+ const content2 = msg.content.map((v) => {
1609
1611
  switch (v.type) {
1610
1612
  case "text":
1611
1613
  return {
@@ -1629,16 +1631,16 @@ function createMessages(chatPrompt) {
1629
1631
  });
1630
1632
  return {
1631
1633
  role: "user",
1632
- content
1634
+ content: content2
1633
1635
  };
1634
1636
  }
1635
1637
  case "assistant": {
1636
- let content = "";
1638
+ let content2 = "";
1637
1639
  if (typeof msg.content === "string") {
1638
- content = msg.content;
1640
+ content2 = msg.content;
1639
1641
  }
1640
1642
  if (typeof msg.functionCalls !== "undefined") {
1641
- content = msg.functionCalls.map((v) => {
1643
+ content2 = msg.functionCalls.map((v) => {
1642
1644
  let input;
1643
1645
  if (typeof v.function.params === "string") {
1644
1646
  input = JSON.parse(v.function.params);
@@ -1656,7 +1658,7 @@ function createMessages(chatPrompt) {
1656
1658
  }
1657
1659
  return {
1658
1660
  role: "assistant",
1659
- content
1661
+ content: content2
1660
1662
  };
1661
1663
  }
1662
1664
  default:
@@ -3823,7 +3825,6 @@ var AxAssertionError = class extends Error {
3823
3825
  }) {
3824
3826
  super(message);
3825
3827
  this.name = this.constructor.name;
3826
- this.stack = new Error().stack;
3827
3828
  }
3828
3829
  getFixingInstructions = () => {
3829
3830
  const extraFields = [];
@@ -4739,9 +4740,9 @@ var functionCallInstructions = `
4739
4740
  - Use the function results to generate the output fields.`;
4740
4741
  var formattingRules = `
4741
4742
  ## Output Formatting Rules
4743
+ - Output must strictly follow the defined plaintext \`key: value\` field format.
4742
4744
  - Each output key, value must strictly adhere to the specified output field formatting rules.
4743
4745
  - No preamble, postscript, or supplementary information.
4744
- - Output must be in plain text, with each \`key: value\` pair on a new line.
4745
4746
  - Do not repeat output fields.`;
4746
4747
  var AxPromptTemplate = class {
4747
4748
  sig;
@@ -5143,7 +5144,7 @@ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId)
5143
5144
  if (ai.getOptions().debug) {
5144
5145
  const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
5145
5146
  process.stdout.write(colorLog4.red(`
5146
- Error Correction:
5147
+ \u274C Error Correction:
5147
5148
  ${errors}
5148
5149
  `));
5149
5150
  }
@@ -5233,7 +5234,7 @@ var checkMissingRequiredFields = (xstate, values, currentIndex) => {
5233
5234
  });
5234
5235
  }
5235
5236
  };
5236
- var streamingExtractValues = (sig, values, xstate, content) => {
5237
+ var streamingExtractValues = (sig, values, xstate, content, streamingValidation = false) => {
5237
5238
  const fields = sig.getOutputFields();
5238
5239
  for (const [index, field] of fields.entries()) {
5239
5240
  if (field.name in values) {
@@ -5243,6 +5244,12 @@ var streamingExtractValues = (sig, values, xstate, content) => {
5243
5244
  let e = matchesContent(content, prefix, xstate.s + 1);
5244
5245
  switch (e) {
5245
5246
  case -1:
5247
+ if (streamingValidation && xstate.s == -1 && !field.isOptional) {
5248
+ throw new ValidationError({
5249
+ message: "Required field not found",
5250
+ fields: [field]
5251
+ });
5252
+ }
5246
5253
  continue;
5247
5254
  // Field is not found, continue to the next field
5248
5255
  case -2:
@@ -5259,6 +5266,7 @@ var streamingExtractValues = (sig, values, xstate, content) => {
5259
5266
  checkMissingRequiredFields(xstate, values, index);
5260
5267
  xstate.s = e + prefixLen;
5261
5268
  xstate.currField = field;
5269
+ xstate.currFieldIndex = index;
5262
5270
  if (!xstate.extractedFields.includes(field)) {
5263
5271
  xstate.extractedFields.push(field);
5264
5272
  }
@@ -5272,8 +5280,8 @@ var streamingExtractFinalValue = (sig, values, xstate, content) => {
5272
5280
  values[xstate.currField.name] = parsedValue;
5273
5281
  }
5274
5282
  }
5275
- const fields = sig.getOutputFields();
5276
- checkMissingRequiredFields(xstate, values, fields.length - 1);
5283
+ const sigFields = sig.getOutputFields();
5284
+ checkMissingRequiredFields(xstate, values, sigFields.length);
5277
5285
  };
5278
5286
  var convertValueToType = (field, val) => {
5279
5287
  switch (field.type?.name) {
@@ -5484,6 +5492,7 @@ var validateJSONSchema = (schema) => {
5484
5492
  };
5485
5493
 
5486
5494
  // dsp/functions.ts
5495
+ var colorLog5 = new ColorLog();
5487
5496
  var AxFunctionError = class extends Error {
5488
5497
  constructor(fields) {
5489
5498
  super();
@@ -5493,17 +5502,13 @@ var AxFunctionError = class extends Error {
5493
5502
  getFields = () => this.fields;
5494
5503
  };
5495
5504
  var FunctionError = class extends Error {
5496
- fields;
5497
- func;
5498
- constructor({
5499
- fields,
5500
- func
5501
- }) {
5505
+ constructor(fields, func, funcId) {
5502
5506
  super();
5503
5507
  this.fields = fields;
5504
5508
  this.func = func;
5505
- this.name = this.constructor.name;
5509
+ this.funcId = funcId;
5506
5510
  }
5511
+ getFunctionId = () => this.funcId;
5507
5512
  getFieldDescription(fieldName) {
5508
5513
  if (!this.func.parameters?.properties?.[fieldName]) {
5509
5514
  return "";
@@ -5516,15 +5521,12 @@ var FunctionError = class extends Error {
5516
5521
  return description;
5517
5522
  }
5518
5523
  getFixingInstructions = () => {
5519
- return this.fields.map((fieldError) => {
5520
- const schemaDescription = this.getFieldDescription(fieldError.field);
5521
- const fullDescription = schemaDescription ? `${fieldError.message}. ${schemaDescription}` : fieldError.message;
5522
- return {
5523
- name: "functionArgumentError",
5524
- title: `Errors in Function '${this.func.name}' Arguments`,
5525
- description: `Please fix the argument '${fieldError.field}' in function '${this.func.name}': ${fullDescription}`
5526
- };
5524
+ const bulletPoints = this.fields.map((fieldError) => {
5525
+ const schemaDescription = this.getFieldDescription(fieldError.field) || "";
5526
+ return `- \`${fieldError.field}\` - ${fieldError.message} (${schemaDescription}).`;
5527
5527
  });
5528
+ return `Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
5529
+ ${bulletPoints.join("\n")}`;
5528
5530
  };
5529
5531
  };
5530
5532
  var AxFunctionProcessor = class {
@@ -5546,16 +5548,10 @@ var AxFunctionProcessor = class {
5546
5548
  } : void 0;
5547
5549
  if (!fnSpec.parameters) {
5548
5550
  const res2 = fnSpec.func.length === 1 ? await fnSpec.func(opt) : await fnSpec.func();
5549
- return {
5550
- id: func.id,
5551
- result: JSON.stringify(res2, null, 2)
5552
- };
5551
+ return typeof res2 === "string" ? res2 : JSON.stringify(res2, null, 2);
5553
5552
  }
5554
5553
  const res = fnSpec.func.length === 2 ? await fnSpec.func(args, opt) : await fnSpec.func(args);
5555
- return {
5556
- id: func.id,
5557
- result: JSON.stringify(res, null, 2)
5558
- };
5554
+ return typeof res === "string" ? res : JSON.stringify(res, null, 2);
5559
5555
  };
5560
5556
  execute = async (func, options) => {
5561
5557
  const fnSpec = this.funcList.find(
@@ -5571,10 +5567,7 @@ var AxFunctionProcessor = class {
5571
5567
  return await this.executeFunction(fnSpec, func, options);
5572
5568
  } catch (e) {
5573
5569
  if (e instanceof AxFunctionError) {
5574
- throw new FunctionError({
5575
- fields: e.getFields(),
5576
- func: fnSpec
5577
- });
5570
+ throw new FunctionError(e.getFields(), fnSpec, func.id);
5578
5571
  }
5579
5572
  throw e;
5580
5573
  }
@@ -5598,19 +5591,44 @@ var parseFunctions = (newFuncs, existingFuncs) => {
5598
5591
  var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, traceId) => {
5599
5592
  const funcProc = new AxFunctionProcessor(functionList);
5600
5593
  const functionsExecuted = /* @__PURE__ */ new Set();
5601
- const promises = functionCalls.map(
5602
- (func) => funcProc?.execute(func, { sessionId, traceId, ai }).then((fres) => {
5594
+ const promises = functionCalls.map((func) => {
5595
+ if (!func.id) {
5596
+ throw new Error(`Function ${func.name} did not return an ID`);
5597
+ }
5598
+ const promise = funcProc.execute(func, { sessionId, traceId, ai }).then((functionResult) => {
5603
5599
  functionsExecuted.add(func.name.toLowerCase());
5604
- if (fres?.id) {
5605
- return {
5606
- role: "function",
5607
- result: fres.result ?? "",
5608
- functionId: fres.id
5609
- };
5600
+ return {
5601
+ role: "function",
5602
+ result: functionResult ?? "",
5603
+ functionId: func.id
5604
+ };
5605
+ }).catch((e) => {
5606
+ if (e instanceof FunctionError) {
5607
+ const result = e.getFixingInstructions();
5608
+ mem.add(
5609
+ {
5610
+ role: "function",
5611
+ functionId: func.id,
5612
+ isError: true,
5613
+ result
5614
+ },
5615
+ sessionId
5616
+ );
5617
+ mem.addTag("error");
5618
+ if (ai.getOptions().debug) {
5619
+ process.stdout.write(
5620
+ colorLog5.red(`
5621
+ \u274C Function Error Correction:
5622
+ ${result}
5623
+ `)
5624
+ );
5625
+ }
5626
+ } else {
5627
+ throw e;
5610
5628
  }
5611
- return null;
5612
- })
5613
- );
5629
+ });
5630
+ return promise;
5631
+ });
5614
5632
  const results = await Promise.all(promises);
5615
5633
  results.forEach((result) => {
5616
5634
  if (result) {
@@ -5748,6 +5766,7 @@ var AxGen = class extends AxProgramWithSignature {
5748
5766
  traceId,
5749
5767
  functions
5750
5768
  }) {
5769
+ const streamingValidation = !functions || functions.length == 0;
5751
5770
  const functionCalls = [];
5752
5771
  const values = {};
5753
5772
  const xstate = {
@@ -5763,14 +5782,21 @@ var AxGen = class extends AxProgramWithSignature {
5763
5782
  if (v.modelUsage) {
5764
5783
  this.usage.push({ ...usageInfo, ...v.modelUsage });
5765
5784
  }
5766
- if (result.content) {
5785
+ if (result.functionCalls) {
5786
+ mergeFunctionCalls(functionCalls, result.functionCalls);
5787
+ mem.updateResult(
5788
+ { name: result.name, content, functionCalls },
5789
+ sessionId
5790
+ );
5791
+ } else if (result.content) {
5767
5792
  content += result.content;
5768
5793
  mem.updateResult({ name: result.name, content }, sessionId);
5769
5794
  const skip = streamingExtractValues(
5770
5795
  this.signature,
5771
5796
  values,
5772
5797
  xstate,
5773
- content
5798
+ content,
5799
+ streamingValidation
5774
5800
  );
5775
5801
  if (skip) {
5776
5802
  continue;
@@ -5785,13 +5811,6 @@ var AxGen = class extends AxProgramWithSignature {
5785
5811
  assertAssertions(this.asserts, values);
5786
5812
  yield* streamValues(this.signature, values, xstate, content);
5787
5813
  }
5788
- if (result.functionCalls) {
5789
- mergeFunctionCalls(functionCalls, result.functionCalls);
5790
- mem.updateResult(
5791
- { name: result.name, content, functionCalls },
5792
- sessionId
5793
- );
5794
- }
5795
5814
  if (result.finishReason === "length") {
5796
5815
  throw new Error("Max tokens reached before completion");
5797
5816
  }
@@ -5810,17 +5829,18 @@ var AxGen = class extends AxProgramWithSignature {
5810
5829
  traceId
5811
5830
  );
5812
5831
  this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
5832
+ } else {
5833
+ streamingExtractFinalValue(this.signature, values, xstate, content);
5834
+ assertStreamingAssertions(
5835
+ this.streamingAsserts,
5836
+ values,
5837
+ xstate,
5838
+ content,
5839
+ true
5840
+ );
5841
+ assertAssertions(this.asserts, values);
5842
+ yield* streamValues(this.signature, values, xstate, content, true);
5813
5843
  }
5814
- streamingExtractFinalValue(this.signature, values, xstate, content);
5815
- assertStreamingAssertions(
5816
- this.streamingAsserts,
5817
- values,
5818
- xstate,
5819
- content,
5820
- true
5821
- );
5822
- assertAssertions(this.asserts, values);
5823
- yield* streamValues(this.signature, values, xstate, content, true);
5824
5844
  }
5825
5845
  async processResponse({
5826
5846
  ai,
@@ -5832,15 +5852,15 @@ var AxGen = class extends AxProgramWithSignature {
5832
5852
  functions
5833
5853
  }) {
5834
5854
  const values = {};
5835
- for (const result of res.results ?? []) {
5855
+ let results = res.results ?? [];
5856
+ if (res.results.length > 1) {
5857
+ results = res.results.filter((r) => r.functionCalls);
5858
+ }
5859
+ for (const result of results) {
5836
5860
  if (res.modelUsage) {
5837
5861
  this.usage.push({ ...usageInfo, ...res.modelUsage });
5838
5862
  }
5839
5863
  mem.addResult(result, sessionId);
5840
- if (result.content) {
5841
- extractValues(this.signature, values, result.content);
5842
- assertAssertions(this.asserts, values);
5843
- }
5844
5864
  if (result.functionCalls) {
5845
5865
  const funcs = parseFunctionCalls(ai, result.functionCalls, values);
5846
5866
  if (funcs) {
@@ -5857,6 +5877,9 @@ var AxGen = class extends AxProgramWithSignature {
5857
5877
  );
5858
5878
  this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
5859
5879
  }
5880
+ } else if (result.content) {
5881
+ extractValues(this.signature, values, result.content);
5882
+ assertAssertions(this.asserts, values);
5860
5883
  }
5861
5884
  if (result.finishReason === "length") {
5862
5885
  throw new Error("Max tokens reached before completion");
@@ -5910,9 +5933,6 @@ var AxGen = class extends AxProgramWithSignature {
5910
5933
  const e1 = e;
5911
5934
  errorFields = e1.getFixingInstructions();
5912
5935
  err = e;
5913
- } else if (e instanceof FunctionError) {
5914
- errorFields = e.getFixingInstructions();
5915
- err = e;
5916
5936
  } else if (e instanceof AxAIServiceStreamTerminatedError) {
5917
5937
  } else {
5918
5938
  throw e;
@@ -7514,7 +7534,7 @@ var AxJSInterpreter = class {
7514
7534
  };
7515
7535
 
7516
7536
  // dsp/router.ts
7517
- var colorLog5 = new ColorLog();
7537
+ var colorLog6 = new ColorLog();
7518
7538
  var AxRoute = class {
7519
7539
  name;
7520
7540
  context;
@@ -7566,7 +7586,7 @@ var AxRouter = class {
7566
7586
  }
7567
7587
  if (this.debug) {
7568
7588
  console.log(
7569
- colorLog5.whiteBright(`query: ${text}`) + "\n" + colorLog5.greenBright(
7589
+ colorLog6.whiteBright(`query: ${text}`) + "\n" + colorLog6.greenBright(
7570
7590
  JSON.stringify(m.map((m2) => `${m2.id}, ${m2.score}`))
7571
7591
  )
7572
7592
  );