@ax-llm/ax 12.0.9 → 12.0.13

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
@@ -1212,6 +1212,9 @@ var AxBaseAI = class {
1212
1212
  }
1213
1213
  async _chat1(req, options) {
1214
1214
  const model = this.getModel(req.model) ?? req.model ?? this.defaults.model;
1215
+ if (req.chatPrompt && Array.isArray(req.chatPrompt)) {
1216
+ validateAxMessageArray(req.chatPrompt);
1217
+ }
1215
1218
  const modelConfig = {
1216
1219
  ...this.aiImpl.getModelConfig(),
1217
1220
  ...req.modelConfig
@@ -1283,7 +1286,6 @@ var AxBaseAI = class {
1283
1286
  if (chatReq.functions && chatReq.functions.length > 0) {
1284
1287
  functions = chatReq.functions.map((fn2) => this.cleanupFunctionSchema(fn2));
1285
1288
  }
1286
- validateChatPrompt(chatReq.chatPrompt);
1287
1289
  const req = {
1288
1290
  ...chatReq,
1289
1291
  model,
@@ -1334,11 +1336,14 @@ var AxBaseAI = class {
1334
1336
  const res2 = respFn(resp, state);
1335
1337
  res2.sessionId = options?.sessionId;
1336
1338
  if (!res2.modelUsage) {
1337
- res2.modelUsage = {
1338
- ai: this.name,
1339
- model,
1340
- tokens: this.aiImpl.getTokenUsage()
1341
- };
1339
+ const tokenUsage = this.aiImpl.getTokenUsage();
1340
+ if (tokenUsage) {
1341
+ res2.modelUsage = {
1342
+ ai: this.name,
1343
+ model,
1344
+ tokens: tokenUsage
1345
+ };
1346
+ }
1342
1347
  }
1343
1348
  this.modelUsage = res2.modelUsage;
1344
1349
  if (span?.isRecording()) {
@@ -1472,11 +1477,14 @@ var AxBaseAI = class {
1472
1477
  const res = this.aiImpl.createEmbedResp(resValue);
1473
1478
  res.sessionId = options?.sessionId;
1474
1479
  if (!res.modelUsage) {
1475
- res.modelUsage = {
1476
- ai: this.name,
1477
- model: embedModel,
1478
- tokens: this.aiImpl.getTokenUsage()
1479
- };
1480
+ const tokenUsage = this.aiImpl.getTokenUsage();
1481
+ if (tokenUsage) {
1482
+ res.modelUsage = {
1483
+ ai: this.name,
1484
+ model: embedModel,
1485
+ tokens: tokenUsage
1486
+ };
1487
+ }
1480
1488
  }
1481
1489
  this.embedModelUsage = res.modelUsage;
1482
1490
  if (span?.isRecording() && res.modelUsage?.tokens) {
@@ -1640,26 +1648,6 @@ function validateAxMessageArray(values) {
1640
1648
  }
1641
1649
  }
1642
1650
  }
1643
- function validateChatPrompt(chatPrompt) {
1644
- for (let i = 0; i < chatPrompt.length; i++) {
1645
- const message = chatPrompt[i];
1646
- if (message && "functionCalls" in message && Array.isArray(message.functionCalls) && message.functionCalls.length === 0) {
1647
- throw new Error(
1648
- `Chat prompt validation failed: Message at index ${i} has empty functionCalls`
1649
- );
1650
- }
1651
- if (message && "content" in message && Array.isArray(message.content) && message.content.length === 0) {
1652
- throw new Error(
1653
- `Chat prompt validation failed: Message at index ${i} has empty content`
1654
- );
1655
- }
1656
- if (message && "content" in message && typeof message.content === "string" && message.content.trim() === "") {
1657
- throw new Error(
1658
- `Chat prompt validation failed: Message at index ${i} has empty content`
1659
- );
1660
- }
1661
- }
1662
- }
1663
1651
  function validateModels(models) {
1664
1652
  const keys = /* @__PURE__ */ new Set();
1665
1653
  for (const model of models) {
@@ -1731,14 +1719,18 @@ var axModelInfoAnthropic = [
1731
1719
  currency: "usd",
1732
1720
  promptTokenCostPer1M: 15,
1733
1721
  completionTokenCostPer1M: 75,
1734
- maxTokens: 32e3
1722
+ maxTokens: 32e3,
1723
+ hasThinkingBudget: true,
1724
+ hasShowThoughts: true
1735
1725
  },
1736
1726
  {
1737
1727
  name: "claude-sonnet-4-20250514" /* Claude4Sonnet */,
1738
1728
  currency: "usd",
1739
1729
  promptTokenCostPer1M: 3,
1740
1730
  completionTokenCostPer1M: 15,
1741
- maxTokens: 64e3
1731
+ maxTokens: 64e3,
1732
+ hasThinkingBudget: true,
1733
+ hasShowThoughts: true
1742
1734
  },
1743
1735
  // 3.7
1744
1736
  {
@@ -1746,7 +1738,9 @@ var axModelInfoAnthropic = [
1746
1738
  currency: "usd",
1747
1739
  promptTokenCostPer1M: 3,
1748
1740
  completionTokenCostPer1M: 15,
1749
- maxTokens: 64e3
1741
+ maxTokens: 64e3,
1742
+ hasThinkingBudget: true,
1743
+ hasShowThoughts: true
1750
1744
  },
1751
1745
  // 3.5
1752
1746
  {
@@ -1802,13 +1796,47 @@ var axModelInfoAnthropic = [
1802
1796
  }
1803
1797
  ];
1804
1798
 
1799
+ // dsp/modelinfo.ts
1800
+ function getModelInfo({
1801
+ model,
1802
+ modelInfo,
1803
+ models
1804
+ }) {
1805
+ const modelEntry = models?.find((v) => v.key === model);
1806
+ const mappedModel = modelEntry && "model" in modelEntry ? modelEntry.model : model;
1807
+ const exactMatch = modelInfo.find((v) => v.name === model);
1808
+ if (exactMatch) return exactMatch;
1809
+ const normalizedName = mappedModel.replace(/^(anthropic\.|openai\.)/, "").replace(/-latest$/, "").replace(/-\d{8}$/, "").replace(/-v\d+:\d+$/, "").replace(/@\d{8}$/, "").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/, "").replace(/-v\d+@\d{8}$/, "").replace(/-v\d+$/, "");
1810
+ const normalizedMatch = modelInfo.find((v) => v.name === normalizedName);
1811
+ if (normalizedMatch) return normalizedMatch;
1812
+ return null;
1813
+ }
1814
+
1805
1815
  // ai/anthropic/api.ts
1806
1816
  var axAIAnthropicDefaultConfig = () => structuredClone({
1807
1817
  model: "claude-3-7-sonnet-latest" /* Claude37Sonnet */,
1818
+ maxTokens: 4e4,
1819
+ // Ensure maxTokens is higher than highest thinking budget
1820
+ thinkingTokenBudgetLevels: {
1821
+ minimal: 1024,
1822
+ low: 5e3,
1823
+ medium: 1e4,
1824
+ high: 2e4,
1825
+ highest: 32e3
1826
+ },
1808
1827
  ...axBaseAIDefaultConfig()
1809
1828
  });
1810
1829
  var axAIAnthropicVertexDefaultConfig = () => structuredClone({
1811
1830
  model: "claude-3-7-sonnet" /* Claude37Sonnet */,
1831
+ maxTokens: 4e4,
1832
+ // Ensure maxTokens is higher than highest thinking budget
1833
+ thinkingTokenBudgetLevels: {
1834
+ minimal: 1024,
1835
+ low: 5e3,
1836
+ medium: 1e4,
1837
+ high: 2e4,
1838
+ highest: 32e3
1839
+ },
1812
1840
  ...axBaseAIDefaultConfig()
1813
1841
  });
1814
1842
  var AxAIAnthropicImpl = class {
@@ -1817,6 +1845,7 @@ var AxAIAnthropicImpl = class {
1817
1845
  this.isVertex = isVertex;
1818
1846
  }
1819
1847
  tokensUsed;
1848
+ currentPromptConfig;
1820
1849
  getTokenUsage() {
1821
1850
  return this.tokensUsed;
1822
1851
  }
@@ -1835,7 +1864,8 @@ var AxAIAnthropicImpl = class {
1835
1864
  n: config.n
1836
1865
  };
1837
1866
  }
1838
- createChatReq = (req) => {
1867
+ createChatReq = (req, config) => {
1868
+ this.currentPromptConfig = config;
1839
1869
  const model = req.model;
1840
1870
  const stream = req.modelConfig?.stream ?? this.config.stream;
1841
1871
  let apiConfig;
@@ -1891,17 +1921,67 @@ var AxAIAnthropicImpl = class {
1891
1921
  const temperature = req.modelConfig?.temperature ?? this.config.temperature;
1892
1922
  const topP = req.modelConfig?.topP ?? this.config.topP;
1893
1923
  const topK = req.modelConfig?.topK ?? this.config.topK;
1924
+ const n = req.modelConfig?.n ?? this.config.n;
1925
+ if (n && n > 1) {
1926
+ throw new Error("Anthropic does not support sampling (n > 1)");
1927
+ }
1928
+ let thinkingConfig;
1929
+ if (this.config.thinking?.budget_tokens) {
1930
+ thinkingConfig = this.config.thinking;
1931
+ }
1932
+ if (config?.thinkingTokenBudget) {
1933
+ const levels = this.config.thinkingTokenBudgetLevels;
1934
+ switch (config.thinkingTokenBudget) {
1935
+ case "none":
1936
+ thinkingConfig = void 0;
1937
+ break;
1938
+ case "minimal":
1939
+ thinkingConfig = {
1940
+ type: "enabled",
1941
+ budget_tokens: levels?.minimal ?? 1024
1942
+ };
1943
+ break;
1944
+ case "low":
1945
+ thinkingConfig = {
1946
+ type: "enabled",
1947
+ budget_tokens: levels?.low ?? 5e3
1948
+ };
1949
+ break;
1950
+ case "medium":
1951
+ thinkingConfig = {
1952
+ type: "enabled",
1953
+ budget_tokens: levels?.medium ?? 1e4
1954
+ };
1955
+ break;
1956
+ case "high":
1957
+ thinkingConfig = {
1958
+ type: "enabled",
1959
+ budget_tokens: levels?.high ?? 2e4
1960
+ };
1961
+ break;
1962
+ case "highest":
1963
+ thinkingConfig = {
1964
+ type: "enabled",
1965
+ budget_tokens: levels?.highest ?? 32e3
1966
+ };
1967
+ break;
1968
+ }
1969
+ }
1894
1970
  const reqValue = {
1895
1971
  ...this.isVertex ? { anthropic_version: "vertex-2023-10-16" } : { model },
1896
1972
  ...maxTokens ? { max_tokens: maxTokens } : {},
1897
1973
  ...stopSequences && stopSequences.length > 0 ? { stop_sequences: stopSequences } : {},
1898
- ...temperature ? { temperature } : {},
1899
- ...topP ? { top_p: topP } : {},
1900
- ...topK ? { top_k: topK } : {},
1974
+ // Only include temperature when thinking is not enabled
1975
+ ...temperature && !thinkingConfig ? { temperature } : {},
1976
+ // Only include top_p when thinking is not enabled, or when it's >= 0.95
1977
+ ...topP && (!thinkingConfig || topP >= 0.95) ? { top_p: topP } : {},
1978
+ // Only include top_k when thinking is not enabled
1979
+ ...topK && !thinkingConfig ? { top_k: topK } : {},
1901
1980
  ...toolsChoice,
1902
1981
  ...tools && tools.length > 0 ? { tools } : {},
1903
1982
  ...stream ? { stream: true } : {},
1904
1983
  ...system ? { system } : {},
1984
+ ...thinkingConfig ? { thinking: thinkingConfig } : {},
1905
1985
  messages
1906
1986
  };
1907
1987
  return [apiConfig, reqValue];
@@ -1911,9 +1991,11 @@ var AxAIAnthropicImpl = class {
1911
1991
  throw new Error(`Anthropic Chat API Error: ${resp.error.message}`);
1912
1992
  }
1913
1993
  const finishReason = mapFinishReason(resp.stop_reason);
1914
- const results = resp.content.map((msg) => {
1994
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
1995
+ const results = resp.content.map((msg, index) => {
1915
1996
  if (msg.type === "tool_use") {
1916
1997
  return {
1998
+ index,
1917
1999
  id: msg.id,
1918
2000
  functionCalls: [
1919
2001
  {
@@ -1928,12 +2010,23 @@ var AxAIAnthropicImpl = class {
1928
2010
  finishReason
1929
2011
  };
1930
2012
  }
2013
+ if ((msg.type === "thinking" || msg.type === "redacted_thinking") && showThoughts) {
2014
+ return {
2015
+ index,
2016
+ thought: msg.thinking,
2017
+ id: resp.id,
2018
+ finishReason
2019
+ };
2020
+ }
1931
2021
  return {
2022
+ index,
1932
2023
  content: msg.type === "text" ? msg.text : "",
1933
2024
  id: resp.id,
1934
2025
  finishReason
1935
2026
  };
1936
- });
2027
+ }).filter(
2028
+ (result) => result.content !== "" || result.thought !== void 0 || result.functionCalls !== void 0
2029
+ );
1937
2030
  this.tokensUsed = {
1938
2031
  promptTokens: resp.usage.input_tokens,
1939
2032
  completionTokens: resp.usage.output_tokens,
@@ -1953,9 +2046,10 @@ var AxAIAnthropicImpl = class {
1953
2046
  const { error } = resp;
1954
2047
  throw new Error(error.message);
1955
2048
  }
2049
+ const index = 0;
1956
2050
  if (resp.type === "message_start") {
1957
2051
  const { message } = resp;
1958
- const results = [{ content: "", id: message.id }];
2052
+ const results = [{ index, content: "", id: message.id }];
1959
2053
  this.tokensUsed = {
1960
2054
  promptTokens: message.usage?.input_tokens ?? 0,
1961
2055
  completionTokens: message.usage?.output_tokens ?? 0,
@@ -1967,7 +2061,18 @@ var AxAIAnthropicImpl = class {
1967
2061
  const { content_block: contentBlock } = resp;
1968
2062
  if (contentBlock.type === "text") {
1969
2063
  return {
1970
- results: [{ content: contentBlock.text }]
2064
+ results: [{ index, content: contentBlock.text }]
2065
+ };
2066
+ }
2067
+ if (contentBlock.type === "thinking") {
2068
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
2069
+ if (showThoughts) {
2070
+ return {
2071
+ results: [{ index, thought: contentBlock.thinking }]
2072
+ };
2073
+ }
2074
+ return {
2075
+ results: [{ index, content: "" }]
1971
2076
  };
1972
2077
  }
1973
2078
  if (contentBlock.type === "tool_use") {
@@ -1984,7 +2089,7 @@ var AxAIAnthropicImpl = class {
1984
2089
  }
1985
2090
  ];
1986
2091
  return {
1987
- results: [{ functionCalls }]
2092
+ results: [{ index, functionCalls }]
1988
2093
  };
1989
2094
  }
1990
2095
  }
@@ -1993,7 +2098,23 @@ var AxAIAnthropicImpl = class {
1993
2098
  const { delta } = resp;
1994
2099
  if (delta.type === "text_delta") {
1995
2100
  return {
1996
- results: [{ content: delta.text }]
2101
+ results: [{ index, content: delta.text }]
2102
+ };
2103
+ }
2104
+ if (delta.type === "thinking_delta") {
2105
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
2106
+ if (showThoughts) {
2107
+ return {
2108
+ results: [{ index, thought: delta.thinking }]
2109
+ };
2110
+ }
2111
+ return {
2112
+ results: [{ index, content: "" }]
2113
+ };
2114
+ }
2115
+ if (delta.type === "signature_delta") {
2116
+ return {
2117
+ results: [{ index, content: "" }]
1997
2118
  };
1998
2119
  }
1999
2120
  if (delta.type === "input_json_delta") {
@@ -2012,7 +2133,7 @@ var AxAIAnthropicImpl = class {
2012
2133
  }
2013
2134
  ];
2014
2135
  return {
2015
- results: [{ functionCalls }]
2136
+ results: [{ index, functionCalls }]
2016
2137
  };
2017
2138
  }
2018
2139
  }
@@ -2024,12 +2145,16 @@ var AxAIAnthropicImpl = class {
2024
2145
  totalTokens: usage.output_tokens
2025
2146
  };
2026
2147
  const results = [
2027
- { content: "", finishReason: mapFinishReason(delta.stop_reason) }
2148
+ {
2149
+ index,
2150
+ content: "",
2151
+ finishReason: mapFinishReason(delta.stop_reason)
2152
+ }
2028
2153
  ];
2029
2154
  return { results };
2030
2155
  }
2031
2156
  return {
2032
- results: [{ content: "" }]
2157
+ results: [{ index, content: "" }]
2033
2158
  };
2034
2159
  };
2035
2160
  };
@@ -2071,6 +2196,20 @@ var AxAIAnthropic = class extends AxBaseAI {
2071
2196
  ...config
2072
2197
  };
2073
2198
  const aiImpl = new AxAIAnthropicImpl(_config, isVertex);
2199
+ const supportFor = (model) => {
2200
+ const mi = getModelInfo({
2201
+ model,
2202
+ modelInfo: axModelInfoAnthropic,
2203
+ models
2204
+ });
2205
+ return {
2206
+ functions: true,
2207
+ streaming: true,
2208
+ hasThinkingBudget: mi?.hasThinkingBudget ?? false,
2209
+ hasShowThoughts: mi?.hasShowThoughts ?? false,
2210
+ functionCot: true
2211
+ };
2212
+ };
2074
2213
  super(aiImpl, {
2075
2214
  name: "Anthropic",
2076
2215
  apiURL,
@@ -2078,7 +2217,7 @@ var AxAIAnthropic = class extends AxBaseAI {
2078
2217
  modelInfo: axModelInfoAnthropic,
2079
2218
  defaults: { model: _config.model },
2080
2219
  options,
2081
- supportFor: { functions: true, streaming: true, functionCot: true },
2220
+ supportFor,
2082
2221
  models
2083
2222
  });
2084
2223
  }
@@ -2208,22 +2347,6 @@ function mapFinishReason(stopReason) {
2208
2347
  }
2209
2348
  }
2210
2349
 
2211
- // dsp/modelinfo.ts
2212
- function getModelInfo({
2213
- model,
2214
- modelInfo,
2215
- models
2216
- }) {
2217
- const modelEntry = models?.find((v) => v.key === model);
2218
- const mappedModel = modelEntry && "model" in modelEntry ? modelEntry.model : model;
2219
- const exactMatch = modelInfo.find((v) => v.name === model);
2220
- if (exactMatch) return exactMatch;
2221
- const normalizedName = mappedModel.replace(/^(anthropic\.|openai\.)/, "").replace(/-latest$/, "").replace(/-\d{8}$/, "").replace(/-v\d+:\d+$/, "").replace(/@\d{8}$/, "").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/, "").replace(/-v\d+@\d{8}$/, "").replace(/-v\d+$/, "");
2222
- const normalizedMatch = modelInfo.find((v) => v.name === normalizedName);
2223
- if (normalizedMatch) return normalizedMatch;
2224
- return null;
2225
- }
2226
-
2227
2350
  // ai/openai/chat_types.ts
2228
2351
  var AxAIOpenAIModel = /* @__PURE__ */ ((AxAIOpenAIModel2) => {
2229
2352
  AxAIOpenAIModel2["O1"] = "o1";
@@ -2558,6 +2681,7 @@ var AxAIOpenAIImpl = class {
2558
2681
  })
2559
2682
  );
2560
2683
  return {
2684
+ index: choice.index,
2561
2685
  id: `${choice.index}`,
2562
2686
  content: choice.message.content,
2563
2687
  thought: choice.message.reasoning_content,
@@ -2583,6 +2707,7 @@ var AxAIOpenAIImpl = class {
2583
2707
  }
2584
2708
  const results = choices.map(
2585
2709
  ({
2710
+ index,
2586
2711
  delta: {
2587
2712
  content,
2588
2713
  role,
@@ -2592,11 +2717,11 @@ var AxAIOpenAIImpl = class {
2592
2717
  finish_reason: oaiFinishReason
2593
2718
  }) => {
2594
2719
  const finishReason = mapFinishReason2(oaiFinishReason);
2595
- const functionCalls = toolCalls?.map(({ id: _id, index, function: { name, arguments: params } }) => {
2596
- if (typeof _id === "string" && typeof index === "number" && !sstate.indexIdMap[index]) {
2597
- sstate.indexIdMap[index] = _id;
2720
+ const functionCalls = toolCalls?.map(({ id: _id, index: index2, function: { name, arguments: params } }) => {
2721
+ if (typeof _id === "string" && typeof index2 === "number" && !sstate.indexIdMap[index2]) {
2722
+ sstate.indexIdMap[index2] = _id;
2598
2723
  }
2599
- const id2 = sstate.indexIdMap[index];
2724
+ const id2 = sstate.indexIdMap[index2];
2600
2725
  if (!id2) {
2601
2726
  return null;
2602
2727
  }
@@ -2607,6 +2732,7 @@ var AxAIOpenAIImpl = class {
2607
2732
  };
2608
2733
  }).filter((v) => v !== null);
2609
2734
  return {
2735
+ index,
2610
2736
  content,
2611
2737
  role,
2612
2738
  thought,
@@ -2641,7 +2767,7 @@ var mapFinishReason2 = (finishReason) => {
2641
2767
  }
2642
2768
  };
2643
2769
  function createMessages2(req) {
2644
- return req.chatPrompt.map((msg) => {
2770
+ const openaiReq = req.chatPrompt.map((msg) => {
2645
2771
  switch (msg.role) {
2646
2772
  case "system":
2647
2773
  return { role: "system", content: msg.content };
@@ -2690,7 +2816,7 @@ function createMessages2(req) {
2690
2816
  tool_calls: toolCalls
2691
2817
  };
2692
2818
  }
2693
- if (!msg.content) {
2819
+ if (msg.content === void 0) {
2694
2820
  throw new Error(
2695
2821
  "Assistant content is required when no tool calls are provided"
2696
2822
  );
@@ -2710,6 +2836,7 @@ function createMessages2(req) {
2710
2836
  throw new Error("Invalid role");
2711
2837
  }
2712
2838
  });
2839
+ return openaiReq;
2713
2840
  }
2714
2841
  var AxAIOpenAIBase = class extends AxBaseAI {
2715
2842
  constructor({
@@ -3063,6 +3190,7 @@ var AxAICohereImpl = class {
3063
3190
  }
3064
3191
  const results = [
3065
3192
  {
3193
+ index: 0,
3066
3194
  id: resp.generation_id,
3067
3195
  content: resp.text,
3068
3196
  functionCalls,
@@ -3695,7 +3823,7 @@ var AxAIGoogleGeminiImpl = class {
3695
3823
  createChatResp = (resp) => {
3696
3824
  const results = resp.candidates?.map(
3697
3825
  (candidate) => {
3698
- const result = {};
3826
+ const result = { index: 0 };
3699
3827
  switch (candidate.finishReason) {
3700
3828
  case "MAX_TOKENS":
3701
3829
  result.finishReason = "length";
@@ -4092,6 +4220,7 @@ ${fc}`;
4092
4220
  return {
4093
4221
  results: [
4094
4222
  {
4223
+ index: 0,
4095
4224
  content: resp.generated_text
4096
4225
  }
4097
4226
  ]
@@ -4733,7 +4862,7 @@ var AxAIOpenAIResponsesImpl = class {
4733
4862
  }
4734
4863
  }
4735
4864
  return {
4736
- results: [currentResult],
4865
+ results: [{ ...currentResult, index: 0 }],
4737
4866
  remoteId: id
4738
4867
  };
4739
4868
  }
@@ -4741,6 +4870,7 @@ var AxAIOpenAIResponsesImpl = class {
4741
4870
  createChatStreamResp(streamEvent) {
4742
4871
  const event = streamEvent;
4743
4872
  const baseResult = {
4873
+ index: 0,
4744
4874
  id: "",
4745
4875
  content: "",
4746
4876
  finishReason: "stop"
@@ -5308,7 +5438,7 @@ var AxAIRekaImpl = class {
5308
5438
  completionTokens: usage.output_tokens,
5309
5439
  totalTokens: usage.input_tokens + usage.output_tokens
5310
5440
  } : void 0;
5311
- const results = responses.map((res) => {
5441
+ const results = responses.map((res, index) => {
5312
5442
  const finishReason = mapFinishReason3(res.finish_reason);
5313
5443
  let content;
5314
5444
  if (typeof res.message.content === "string") {
@@ -5317,6 +5447,7 @@ var AxAIRekaImpl = class {
5317
5447
  content = res.message.content.text;
5318
5448
  }
5319
5449
  return {
5450
+ index,
5320
5451
  id: `${id}`,
5321
5452
  content,
5322
5453
  finishReason
@@ -5331,7 +5462,7 @@ var AxAIRekaImpl = class {
5331
5462
  completionTokens: usage.output_tokens,
5332
5463
  totalTokens: usage.input_tokens + usage.output_tokens
5333
5464
  } : void 0;
5334
- const results = responses.map((res) => {
5465
+ const results = responses.map((res, index) => {
5335
5466
  const finishReason = mapFinishReason3(res.finish_reason);
5336
5467
  let content;
5337
5468
  if (typeof res.chunk.content === "string") {
@@ -5340,6 +5471,7 @@ var AxAIRekaImpl = class {
5340
5471
  content = res.chunk.content.text;
5341
5472
  }
5342
5473
  return {
5474
+ index,
5343
5475
  id: `${id}`,
5344
5476
  content,
5345
5477
  finishReason
@@ -5693,116 +5825,339 @@ var AxAIGrok = class extends AxAIOpenAIBase {
5693
5825
  };
5694
5826
 
5695
5827
  // dsp/generate.ts
5696
- import { ReadableStream as ReadableStream2 } from "stream/web";
5828
+ import { ReadableStream as ReadableStream3 } from "stream/web";
5697
5829
  import {
5698
5830
  context as context2,
5699
5831
  SpanKind as SpanKind2,
5700
5832
  trace
5701
5833
  } from "@opentelemetry/api";
5702
5834
 
5703
- // ai/util.ts
5704
- function mergeFunctionCalls(functionCalls, functionCallDeltas) {
5705
- for (const _fc of functionCallDeltas) {
5706
- const fc = functionCalls.find((fc2) => fc2.id === _fc.id);
5707
- if (fc) {
5708
- if (typeof _fc.function.name == "string" && _fc.function.name.length > 0) {
5709
- fc.function.name += _fc.function.name;
5835
+ // ai/validate.ts
5836
+ function axValidateChatRequestMessage(item) {
5837
+ if (!item) {
5838
+ throw new Error("Chat request message item cannot be null or undefined");
5839
+ }
5840
+ if (!item.role) {
5841
+ throw new Error("Chat request message must have a role");
5842
+ }
5843
+ switch (item.role) {
5844
+ case "system":
5845
+ if (!item.content || item.content.trim() === "") {
5846
+ throw new Error(
5847
+ "System message content cannot be empty or whitespace-only"
5848
+ );
5710
5849
  }
5711
- if (typeof _fc.function.params == "string" && _fc.function.params.length > 0) {
5712
- fc.function.params += _fc.function.params;
5850
+ break;
5851
+ case "user":
5852
+ if (!item.content) {
5853
+ throw new Error("User message content cannot be undefined");
5713
5854
  }
5714
- if (typeof _fc.function.params == "object") {
5715
- fc.function.params = _fc.function.params;
5855
+ if (typeof item.content === "string") {
5856
+ if (item.content.trim() === "") {
5857
+ throw new Error(
5858
+ "User message content cannot be empty or whitespace-only"
5859
+ );
5860
+ }
5861
+ } else if (Array.isArray(item.content)) {
5862
+ if (item.content.length === 0) {
5863
+ throw new Error("User message content array cannot be empty");
5864
+ }
5865
+ for (let index = 0; index < item.content.length; index++) {
5866
+ const contentItem = item.content[index];
5867
+ if (!contentItem || typeof contentItem !== "object") {
5868
+ throw new Error(
5869
+ `User message content item at index ${index} must be an object`
5870
+ );
5871
+ }
5872
+ if (!contentItem.type) {
5873
+ throw new Error(
5874
+ `User message content item at index ${index} must have a type`
5875
+ );
5876
+ }
5877
+ switch (contentItem.type) {
5878
+ case "text":
5879
+ if (!contentItem.text || contentItem.text.trim() === "") {
5880
+ throw new Error(
5881
+ `User message text content at index ${index} cannot be empty or whitespace-only`
5882
+ );
5883
+ }
5884
+ break;
5885
+ case "image":
5886
+ if (!contentItem.image || contentItem.image.trim() === "") {
5887
+ throw new Error(
5888
+ `User message image content at index ${index} cannot be empty`
5889
+ );
5890
+ }
5891
+ if (!contentItem.mimeType || contentItem.mimeType.trim() === "") {
5892
+ throw new Error(
5893
+ `User message image content at index ${index} must have a mimeType`
5894
+ );
5895
+ }
5896
+ break;
5897
+ case "audio":
5898
+ if (!contentItem.data || contentItem.data.trim() === "") {
5899
+ throw new Error(
5900
+ `User message audio content at index ${index} cannot be empty`
5901
+ );
5902
+ }
5903
+ break;
5904
+ default:
5905
+ throw new Error(
5906
+ `User message content item at index ${index} has unsupported type: ${contentItem.type}`
5907
+ );
5908
+ }
5909
+ }
5910
+ } else {
5911
+ throw new Error(
5912
+ "User message content must be a string or array of content objects"
5913
+ );
5716
5914
  }
5717
- } else {
5718
- functionCalls.push(_fc);
5719
- }
5915
+ break;
5916
+ case "assistant":
5917
+ if (!item.content && !item.functionCalls) {
5918
+ throw new Error(
5919
+ "Assistant message must have either content or function calls"
5920
+ );
5921
+ }
5922
+ if (item.content && typeof item.content !== "string") {
5923
+ throw new Error("Assistant message content must be a string");
5924
+ }
5925
+ if (item.functionCalls && !Array.isArray(item.functionCalls)) {
5926
+ throw new Error("Assistant message function calls must be an array");
5927
+ }
5928
+ break;
5929
+ case "function":
5930
+ if (!item.functionId || item.functionId.trim() === "") {
5931
+ throw new Error("Function message must have a non-empty functionId");
5932
+ }
5933
+ if (item.result === void 0 || item.result === null) {
5934
+ throw new Error("Function message must have a result");
5935
+ }
5936
+ if (typeof item.result !== "string") {
5937
+ throw new Error("Function message result must be a string");
5938
+ }
5939
+ break;
5940
+ default:
5941
+ throw new Error(
5942
+ `Unsupported message role: ${item.role}`
5943
+ );
5720
5944
  }
5721
5945
  }
5722
-
5723
- // mem/memory.ts
5724
- var defaultLimit = 1e4;
5725
- var MemoryImpl = class {
5726
- constructor(limit = defaultLimit, options) {
5727
- this.limit = limit;
5728
- this.options = options;
5729
- if (limit <= 0) {
5730
- throw Error("argument 'limit' must be greater than 0");
5731
- }
5732
- }
5733
- data = [];
5734
- addMemory(value) {
5735
- if (Array.isArray(value)) {
5736
- this.data.push(...value.map((chat) => ({ chat: structuredClone(chat) })));
5737
- } else {
5738
- this.data.push({
5739
- chat: structuredClone(value)
5740
- });
5741
- }
5742
- if (this.data.length > this.limit) {
5743
- const removeCount = this.data.length - this.limit;
5744
- this.data.splice(0, removeCount);
5745
- }
5946
+ function axValidateChatResponseResult(results) {
5947
+ const resultsArray = Array.isArray(results) ? results : [results];
5948
+ if (resultsArray.length === 0) {
5949
+ throw new Error("Chat response results cannot be empty");
5746
5950
  }
5747
- add(value) {
5748
- this.addMemory(value);
5749
- if (this.options?.debug) {
5750
- debugRequest(value, this.options?.debugHideSystemPrompt);
5951
+ for (let arrayIndex = 0; arrayIndex < resultsArray.length; arrayIndex++) {
5952
+ const result = resultsArray[arrayIndex];
5953
+ if (!result) {
5954
+ throw new Error(
5955
+ `Chat response result at index ${arrayIndex} cannot be null or undefined`
5956
+ );
5751
5957
  }
5752
- }
5753
- addResultMessage({
5754
- content,
5755
- name,
5756
- functionCalls
5757
- }) {
5758
- const isContentEmpty = typeof content === "string" && content.trim() === "";
5759
- if (isContentEmpty) {
5760
- this.addMemory({ name, role: "assistant", functionCalls });
5761
- } else {
5762
- this.addMemory({ content, name, role: "assistant", functionCalls });
5958
+ if (typeof result.index !== "number") {
5959
+ throw new Error(
5960
+ `Chat response result at index ${arrayIndex} must have a numeric index`
5961
+ );
5763
5962
  }
5764
- }
5765
- addResult({
5766
- content,
5767
- name,
5768
- functionCalls
5769
- }) {
5770
- this.addResultMessage({ content, name, functionCalls });
5771
- if (this.options?.debug) {
5772
- debugResponse({ content, name, functionCalls });
5963
+ if (result.index < 0) {
5964
+ throw new Error(
5965
+ `Chat response result at index ${arrayIndex} must have a non-negative index`
5966
+ );
5773
5967
  }
5774
- }
5775
- updateResult({
5776
- content,
5777
- name,
5778
- functionCalls,
5779
- delta
5780
- }) {
5781
- const lastItem = this.data.at(-1);
5782
- if (!lastItem || lastItem.chat.role !== "assistant") {
5783
- throw new Error("No assistant message to update");
5968
+ if (!result.content && !result.thought && !result.functionCalls && !result.finishReason) {
5969
+ throw new Error(
5970
+ `Chat response result at index ${arrayIndex} must have at least one of: content, thought, functionCalls, or finishReason`
5971
+ );
5784
5972
  }
5785
- if (typeof content === "string" && content.trim() !== "") {
5786
- lastItem.chat.content = content;
5973
+ if (result.content !== void 0 && typeof result.content !== "string") {
5974
+ throw new Error(
5975
+ `Chat response result content at index ${arrayIndex} must be a string`
5976
+ );
5787
5977
  }
5788
- if (name && name.trim() !== "") {
5789
- lastItem.chat.name = name;
5978
+ if (result.thought !== void 0 && typeof result.thought !== "string") {
5979
+ throw new Error(
5980
+ `Chat response result thought at index ${arrayIndex} must be a string`
5981
+ );
5790
5982
  }
5791
- if (functionCalls && functionCalls.length > 0) {
5792
- lastItem.chat.functionCalls = functionCalls;
5983
+ if (result.name !== void 0) {
5984
+ if (typeof result.name !== "string") {
5985
+ throw new Error(
5986
+ `Chat response result name at index ${arrayIndex} must be a string`
5987
+ );
5988
+ }
5989
+ if (result.name.trim() === "") {
5990
+ throw new Error(
5991
+ `Chat response result name at index ${arrayIndex} cannot be empty or whitespace-only`
5992
+ );
5993
+ }
5793
5994
  }
5794
- if (this.options?.debug) {
5795
- if (delta && typeof delta === "string") {
5796
- debugResponseDelta(delta);
5797
- } else if (!delta && (content || functionCalls)) {
5798
- debugResponse({ content, name, functionCalls });
5995
+ if (result.id !== void 0) {
5996
+ if (typeof result.id !== "string") {
5997
+ throw new Error(
5998
+ `Chat response result id at index ${arrayIndex} must be a string`
5999
+ );
6000
+ }
6001
+ if (result.id.trim() === "") {
6002
+ throw new Error(
6003
+ `Chat response result id at index ${arrayIndex} cannot be empty or whitespace-only`
6004
+ );
5799
6005
  }
5800
6006
  }
5801
- }
5802
- addTag(name) {
5803
- const lastItem = this.data.at(-1);
5804
- if (!lastItem) {
5805
- return;
6007
+ if (result.functionCalls !== void 0) {
6008
+ if (!Array.isArray(result.functionCalls)) {
6009
+ throw new Error(
6010
+ `Chat response result functionCalls at index ${arrayIndex} must be an array`
6011
+ );
6012
+ }
6013
+ for (let callIndex = 0; callIndex < result.functionCalls.length; callIndex++) {
6014
+ const functionCall = result.functionCalls[callIndex];
6015
+ if (!functionCall) {
6016
+ throw new Error(
6017
+ `Function call at index ${callIndex} in result ${arrayIndex} cannot be null or undefined`
6018
+ );
6019
+ }
6020
+ if (!functionCall.id || typeof functionCall.id !== "string" || functionCall.id.trim() === "") {
6021
+ throw new Error(
6022
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a non-empty string id`
6023
+ );
6024
+ }
6025
+ if (functionCall.type !== "function") {
6026
+ throw new Error(
6027
+ `Function call at index ${callIndex} in result ${arrayIndex} must have type 'function'`
6028
+ );
6029
+ }
6030
+ if (!functionCall.function) {
6031
+ throw new Error(
6032
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a function object`
6033
+ );
6034
+ }
6035
+ if (!functionCall.function.name || typeof functionCall.function.name !== "string" || functionCall.function.name.trim() === "") {
6036
+ throw new Error(
6037
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a non-empty function name`
6038
+ );
6039
+ }
6040
+ if (functionCall.function.params !== void 0) {
6041
+ if (typeof functionCall.function.params !== "string" && typeof functionCall.function.params !== "object") {
6042
+ throw new Error(
6043
+ `Function call params at index ${callIndex} in result ${arrayIndex} must be a string or object`
6044
+ );
6045
+ }
6046
+ }
6047
+ }
6048
+ }
6049
+ if (result.finishReason !== void 0) {
6050
+ const validFinishReasons = [
6051
+ "stop",
6052
+ "length",
6053
+ "function_call",
6054
+ "content_filter",
6055
+ "error"
6056
+ ];
6057
+ if (!validFinishReasons.includes(result.finishReason)) {
6058
+ throw new Error(
6059
+ `Chat response result finishReason at index ${arrayIndex} must be one of: ${validFinishReasons.join(", ")}`
6060
+ );
6061
+ }
6062
+ }
6063
+ }
6064
+ }
6065
+
6066
+ // mem/memory.ts
6067
+ var MemoryImpl = class {
6068
+ constructor(options) {
6069
+ this.options = options;
6070
+ }
6071
+ data = [];
6072
+ addRequest(items, index) {
6073
+ this.data.push(
6074
+ ...items.map((item) => {
6075
+ const value = structuredClone(item);
6076
+ return {
6077
+ role: item.role,
6078
+ chat: [{ index, value }]
6079
+ };
6080
+ })
6081
+ );
6082
+ if (this.options?.debug) {
6083
+ debugRequest(items, this.options?.debugHideSystemPrompt);
6084
+ }
6085
+ }
6086
+ addFunctionResults(results) {
6087
+ const chat = results.map(({ index, ...value }) => ({
6088
+ index,
6089
+ value: structuredClone(value)
6090
+ }));
6091
+ const lastItem = this.getLast();
6092
+ if (lastItem?.role === "function") {
6093
+ lastItem.chat.push(...chat);
6094
+ } else {
6095
+ this.data.push({ role: "function", chat });
6096
+ }
6097
+ }
6098
+ addResponse(results) {
6099
+ const chat = results.map(({ index, ...value }) => ({
6100
+ index,
6101
+ value: structuredClone(value)
6102
+ }));
6103
+ this.data.push({ role: "assistant", chat });
6104
+ if (this.options?.debug) {
6105
+ for (const result of results) {
6106
+ debugResponse(result);
6107
+ }
6108
+ }
6109
+ }
6110
+ updateResult({
6111
+ content,
6112
+ name,
6113
+ functionCalls,
6114
+ delta,
6115
+ index
6116
+ }) {
6117
+ const lastItem = this.data.at(-1);
6118
+ const log = () => {
6119
+ if (this.options?.debug) {
6120
+ if (delta && typeof delta === "string") {
6121
+ debugResponseDelta(delta);
6122
+ } else if (!delta && (content || functionCalls)) {
6123
+ debugResponse({ content, name, functionCalls, index });
6124
+ }
6125
+ }
6126
+ };
6127
+ if (!lastItem || lastItem.role !== "assistant") {
6128
+ this.data.push({
6129
+ role: "assistant",
6130
+ chat: [
6131
+ { index, value: structuredClone({ content, name, functionCalls }) }
6132
+ ]
6133
+ });
6134
+ log();
6135
+ return;
6136
+ }
6137
+ const chat = lastItem.chat.find((v) => v.index === index);
6138
+ if (!chat) {
6139
+ lastItem.chat.push({
6140
+ index,
6141
+ value: structuredClone({ content, name, functionCalls })
6142
+ });
6143
+ log();
6144
+ return;
6145
+ }
6146
+ if ("content" in chat.value && typeof content === "string" && content.trim() !== "") {
6147
+ chat.value.content = content;
6148
+ }
6149
+ if ("name" in chat.value && name && name.trim() !== "") {
6150
+ chat.value.name = name;
6151
+ }
6152
+ if ("functionCalls" in chat.value && functionCalls && functionCalls.length > 0) {
6153
+ chat.value.functionCalls = functionCalls;
6154
+ }
6155
+ log();
6156
+ }
6157
+ addTag(name) {
6158
+ const lastItem = this.data.at(-1);
6159
+ if (!lastItem) {
6160
+ return;
5806
6161
  }
5807
6162
  if (!lastItem.tags) {
5808
6163
  lastItem.tags = [];
@@ -5816,8 +6171,7 @@ var MemoryImpl = class {
5816
6171
  if (tagIndex === -1) {
5817
6172
  throw new Error(`Tag "${name}" not found`);
5818
6173
  }
5819
- const removedItems = this.data.splice(tagIndex);
5820
- return removedItems.map((item) => item.chat);
6174
+ return this.data.splice(tagIndex);
5821
6175
  }
5822
6176
  removeByTag(name) {
5823
6177
  const indices = this.data.reduce((acc, item, index) => {
@@ -5829,28 +6183,40 @@ var MemoryImpl = class {
5829
6183
  if (indices.length === 0) {
5830
6184
  throw new Error(`No items found with tag "${name}"`);
5831
6185
  }
5832
- return indices.reverse().map((index) => this.data.splice(index, 1).at(0)?.chat).filter(Boolean).reverse();
6186
+ return indices.reverse().map((index) => this.data.splice(index, 1).at(0)).filter((item) => item !== void 0).reverse();
5833
6187
  }
5834
- history() {
5835
- return this.data.map((item) => item.chat);
6188
+ history(index) {
6189
+ const result = [];
6190
+ for (const { role, chat } of this.data) {
6191
+ let values;
6192
+ if (role === "function") {
6193
+ values = chat.filter((v) => v.index === index).map((v) => v.value);
6194
+ } else {
6195
+ values = chat.find((v) => v.index === index)?.value;
6196
+ }
6197
+ if (Array.isArray(values)) {
6198
+ result.push(
6199
+ ...values.map(
6200
+ (v) => ({ ...v, role })
6201
+ )
6202
+ );
6203
+ } else if (values) {
6204
+ result.push({ ...values, role });
6205
+ }
6206
+ }
6207
+ return result;
5836
6208
  }
5837
6209
  getLast() {
5838
- const lastItem = this.data.at(-1);
5839
- if (!lastItem) return void 0;
5840
- return {
5841
- chat: lastItem.chat,
5842
- tags: lastItem.tags
5843
- };
6210
+ return this.data.at(-1);
5844
6211
  }
5845
6212
  reset() {
5846
6213
  this.data = [];
5847
6214
  }
5848
6215
  };
5849
6216
  var AxMemory = class {
5850
- constructor(limit = defaultLimit, options) {
5851
- this.limit = limit;
6217
+ constructor(options) {
5852
6218
  this.options = options;
5853
- this.defaultMemory = new MemoryImpl(limit, options);
6219
+ this.defaultMemory = new MemoryImpl(options);
5854
6220
  }
5855
6221
  memories = /* @__PURE__ */ new Map();
5856
6222
  defaultMemory;
@@ -5859,15 +6225,22 @@ var AxMemory = class {
5859
6225
  return this.defaultMemory;
5860
6226
  }
5861
6227
  if (!this.memories.has(sessionId)) {
5862
- this.memories.set(sessionId, new MemoryImpl(this.limit, this.options));
6228
+ this.memories.set(sessionId, new MemoryImpl(this.options));
5863
6229
  }
5864
6230
  return this.memories.get(sessionId);
5865
6231
  }
5866
- add(value, sessionId) {
5867
- this.getMemory(sessionId).add(value);
6232
+ addRequest(value, sessionId) {
6233
+ for (const item of value) {
6234
+ axValidateChatRequestMessage(item);
6235
+ }
6236
+ this.getMemory(sessionId).addRequest(value, 0);
6237
+ }
6238
+ addResponse(results, sessionId) {
6239
+ axValidateChatResponseResult(results);
6240
+ this.getMemory(sessionId).addResponse(results);
5868
6241
  }
5869
- addResult(result, sessionId) {
5870
- this.getMemory(sessionId).addResult(result);
6242
+ addFunctionResults(results, sessionId) {
6243
+ this.getMemory(sessionId).addFunctionResults(results);
5871
6244
  }
5872
6245
  updateResult(result, sessionId) {
5873
6246
  this.getMemory(sessionId).updateResult(result);
@@ -5878,8 +6251,8 @@ var AxMemory = class {
5878
6251
  rewindToTag(name, sessionId) {
5879
6252
  return this.getMemory(sessionId).rewindToTag(name);
5880
6253
  }
5881
- history(sessionId) {
5882
- return this.getMemory(sessionId).history();
6254
+ history(index, sessionId) {
6255
+ return this.getMemory(sessionId).history(index);
5883
6256
  }
5884
6257
  getLast(sessionId) {
5885
6258
  return this.getMemory(sessionId).getLast();
@@ -5888,7 +6261,7 @@ var AxMemory = class {
5888
6261
  if (!sessionId) {
5889
6262
  this.defaultMemory.reset();
5890
6263
  } else {
5891
- this.memories.set(sessionId, new MemoryImpl(this.limit, this.options));
6264
+ this.memories.set(sessionId, new MemoryImpl(this.options));
5892
6265
  }
5893
6266
  }
5894
6267
  };
@@ -5969,8 +6342,156 @@ var assertStreamingAssertions = async (asserts, xstate, content, final = false)
5969
6342
  }
5970
6343
  };
5971
6344
 
6345
+ // dsp/errors.ts
6346
+ var ValidationError = class extends Error {
6347
+ fields;
6348
+ constructor({
6349
+ message,
6350
+ fields
6351
+ }) {
6352
+ super(message);
6353
+ this.fields = fields;
6354
+ this.name = this.constructor.name;
6355
+ }
6356
+ getFixingInstructions = () => {
6357
+ const toFieldType2 = (type) => {
6358
+ const baseType = (() => {
6359
+ switch (type?.name) {
6360
+ case "string":
6361
+ return "string";
6362
+ case "number":
6363
+ return "number";
6364
+ case "boolean":
6365
+ return "boolean";
6366
+ case "date":
6367
+ return 'date ("YYYY-MM-DD" format)';
6368
+ case "datetime":
6369
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6370
+ case "json":
6371
+ return "JSON object";
6372
+ case "class":
6373
+ return "classification class";
6374
+ case "code":
6375
+ return "code";
6376
+ default:
6377
+ return "string";
6378
+ }
6379
+ })();
6380
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
6381
+ };
6382
+ return this.fields.map((field) => ({
6383
+ name: "outputError",
6384
+ title: "Output Correction Required",
6385
+ description: `The section labeled '${field.title}' does not match the expected format of '${toFieldType2(field.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`
6386
+ }));
6387
+ };
6388
+ toString() {
6389
+ const toFieldType2 = (type) => {
6390
+ const baseType = (() => {
6391
+ switch (type?.name) {
6392
+ case "string":
6393
+ return "string";
6394
+ case "number":
6395
+ return "number";
6396
+ case "boolean":
6397
+ return "boolean";
6398
+ case "date":
6399
+ return 'date ("YYYY-MM-DD" format)';
6400
+ case "datetime":
6401
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6402
+ case "json":
6403
+ return "JSON object";
6404
+ case "class":
6405
+ return "classification class";
6406
+ case "code":
6407
+ return "code";
6408
+ default:
6409
+ return "string";
6410
+ }
6411
+ })();
6412
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
6413
+ };
6414
+ return [
6415
+ `${this.name}: ${this.message}`,
6416
+ ...this.fields.map(
6417
+ (field) => ` - ${field.title}: Expected format '${toFieldType2(field.type)}'`
6418
+ )
6419
+ ].join("\n");
6420
+ }
6421
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, _options) {
6422
+ return this.toString();
6423
+ }
6424
+ };
6425
+
5972
6426
  // dsp/datetime.ts
5973
6427
  import moment from "moment-timezone";
6428
+ function parseLLMFriendlyDate(field, dateStr, required = false) {
6429
+ try {
6430
+ return _parseLLMFriendlyDate(dateStr);
6431
+ } catch (err) {
6432
+ if (field.isOptional && !required) {
6433
+ return;
6434
+ }
6435
+ const message = err.message;
6436
+ throw new ValidationError({ fields: [field], message, value: dateStr });
6437
+ }
6438
+ }
6439
+ function _parseLLMFriendlyDate(dateStr) {
6440
+ if (!moment(dateStr, "YYYY-MM-DD", true).isValid()) {
6441
+ throw new Error(
6442
+ 'Invalid date format. Please provide the date in "YYYY-MM-DD" format.'
6443
+ );
6444
+ }
6445
+ const date = moment.utc(dateStr, "YYYY-MM-DD").startOf("day");
6446
+ return date.toDate();
6447
+ }
6448
+ function parseLLMFriendlyDateTime(field, dateStr, required = false) {
6449
+ try {
6450
+ return _parseLLMFriendlyDateTime(dateStr);
6451
+ } catch (err) {
6452
+ if (field.isOptional && !required) {
6453
+ return;
6454
+ }
6455
+ const message = err.message;
6456
+ throw new ValidationError({ fields: [field], message, value: dateStr });
6457
+ }
6458
+ }
6459
+ function _parseLLMFriendlyDateTime(dateTimeStr) {
6460
+ const dateTimeRegex = /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/;
6461
+ const match = dateTimeStr.match(dateTimeRegex);
6462
+ if (!match) {
6463
+ throw new Error(
6464
+ 'Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.'
6465
+ );
6466
+ }
6467
+ const [, dateTime, timeZone] = match;
6468
+ if (!dateTime || !timeZone) {
6469
+ throw new Error(
6470
+ 'Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.'
6471
+ );
6472
+ }
6473
+ const zone = moment.tz.zone(timeZone);
6474
+ if (!zone) {
6475
+ throw new Error(
6476
+ `Unrecognized time zone ${timeZone}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`
6477
+ );
6478
+ }
6479
+ const date = moment.tz(
6480
+ dateTime,
6481
+ ["YYYY-MM-DD HH:mm", "YYYY-MM-DD HH:mm:ss"],
6482
+ zone.name
6483
+ );
6484
+ if (!date.isValid()) {
6485
+ throw new Error(
6486
+ "Invalid date and time values. Please ensure all components are correct."
6487
+ );
6488
+ }
6489
+ return date.utc().toDate();
6490
+ }
6491
+ var formatDateWithTimezone = (date) => {
6492
+ const momentDate = moment(date).utc();
6493
+ return momentDate.format(`YYYY-MM-DD HH:mm:ss UTC`);
6494
+ };
5974
6495
 
5975
6496
  // dsp/util.ts
5976
6497
  var colorLog3 = new ColorLog();
@@ -6133,18 +6654,24 @@ var parseMarkdownList = (input) => {
6133
6654
  }
6134
6655
  return list;
6135
6656
  };
6136
- function mergeDeltas(base, delta) {
6657
+ function mergeDeltas(base, currentDelta) {
6658
+ const { index, delta, version } = currentDelta;
6659
+ const target = base.find((b) => b.index === index)?.delta;
6660
+ if (!target) {
6661
+ base.push({ index, delta, version });
6662
+ return base;
6663
+ }
6137
6664
  for (const key of Object.keys(delta)) {
6138
- const baseValue = base[key];
6665
+ const baseValue = target[key];
6139
6666
  const deltaValue = delta[key];
6140
6667
  if (baseValue === void 0 && Array.isArray(deltaValue)) {
6141
- base[key] = [...deltaValue];
6668
+ target[key] = [...deltaValue];
6142
6669
  } else if (Array.isArray(baseValue) && Array.isArray(deltaValue)) {
6143
- base[key] = [...baseValue ?? [], ...deltaValue];
6670
+ target[key] = [...baseValue, ...deltaValue];
6144
6671
  } else if ((baseValue === void 0 || typeof baseValue === "string") && typeof deltaValue === "string") {
6145
- base[key] = (baseValue ?? "") + deltaValue;
6672
+ target[key] = `${baseValue ?? ""}${deltaValue}`;
6146
6673
  } else {
6147
- base[key] = deltaValue;
6674
+ target[key] = deltaValue;
6148
6675
  }
6149
6676
  }
6150
6677
  return base;
@@ -6261,994 +6788,433 @@ var updateDetailedProgress = (roundIndex, current, total, elapsedTime, example,
6261
6788
  console.log(output);
6262
6789
  };
6263
6790
 
6264
- // dsp/prompt.ts
6265
- var functionCallInstructions = `
6266
- ## Function Call Instructions
6267
- - Complete the task, using the functions defined earlier in this prompt.
6268
- - Call functions step-by-step, using the output of one function as input to the next.
6269
- - Use the function results to generate the output fields.`;
6270
- var formattingRules = `
6271
- ## Strict Output Formatting Rules
6272
- - Output must strictly follow the defined plain-text \`field name: value\` field format.
6273
- - Output field, values must strictly adhere to the specified output field formatting rules.
6274
- - Do not add any text before or after the output fields, just the field name and value.
6275
- - Do not use code blocks.`;
6276
- var AxPromptTemplate = class {
6277
- sig;
6278
- fieldTemplates;
6279
- task;
6280
- thoughtFieldName;
6281
- functions;
6282
- constructor(sig, options, fieldTemplates) {
6283
- this.sig = sig;
6284
- this.fieldTemplates = fieldTemplates;
6285
- this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
6286
- this.functions = options?.functions;
6287
- const task = [];
6288
- const inArgs = renderDescFields(this.sig.getInputFields());
6289
- const outArgs = renderDescFields(this.sig.getOutputFields());
6290
- task.push(
6291
- `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
6292
- );
6293
- const funcs = this.functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
6294
- const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
6295
- if (funcList && funcList.length > 0) {
6296
- task.push(`## Available Functions
6297
- ${funcList}`);
6298
- }
6299
- const inputFields = renderInputFields(this.sig.getInputFields());
6300
- task.push(`## Input Fields
6301
- ${inputFields}`);
6302
- const outputFields = renderOutputFields(this.sig.getOutputFields());
6303
- task.push(`## Output Fields
6304
- ${outputFields}`);
6305
- if (funcList && funcList.length > 0) {
6306
- task.push(functionCallInstructions.trim());
6307
- }
6308
- task.push(formattingRules.trim());
6309
- const desc = this.sig.getDescription();
6310
- if (desc) {
6311
- const text = formatDescription(desc);
6312
- task.push(text);
6791
+ // dsp/extract.ts
6792
+ var extractValues = (sig, values, content, strictMode = false) => {
6793
+ const xstate = { extractedFields: [], streamedIndex: {}, s: -1 };
6794
+ streamingExtractValues(sig, values, xstate, content, { strictMode });
6795
+ streamingExtractFinalValue(sig, values, xstate, content);
6796
+ for (const field of sig.getOutputFields()) {
6797
+ if (field.isInternal) {
6798
+ delete values[field.name];
6313
6799
  }
6314
- this.task = {
6315
- type: "text",
6316
- text: task.join("\n\n")
6317
- };
6318
6800
  }
6319
- renderSingleValueUserContent = (values, renderedExamples, renderedDemos, examplesInSystemPrompt) => {
6320
- const completion = this.renderInputFields(values);
6321
- const promptList = examplesInSystemPrompt ? completion : [...renderedExamples, ...renderedDemos, ...completion];
6322
- const prompt = promptList.filter((v) => v !== void 0);
6323
- return prompt.every((v) => v.type === "text") ? prompt.map((v) => v.text).join("\n") : prompt.reduce(combineConsecutiveStrings("\n"), []);
6324
- };
6325
- render = (values, {
6326
- examples,
6327
- demos
6328
- }) => {
6329
- const renderedExamples = examples ? [
6330
- { type: "text", text: "\n\n## Examples\n" },
6331
- ...this.renderExamples(examples)
6332
- ] : [];
6333
- const renderedDemos = demos ? this.renderDemos(demos) : [];
6334
- const allTextExamples = renderedExamples.every((v) => v.type === "text");
6335
- const allTextDemos = renderedDemos.every((v) => v.type === "text");
6336
- const examplesInSystemPrompt = allTextExamples && allTextDemos;
6337
- let systemContent = this.task.text;
6338
- if (examplesInSystemPrompt) {
6339
- const combinedItems = [
6340
- { type: "text", text: systemContent },
6341
- ...renderedExamples,
6342
- ...renderedDemos
6343
- ];
6344
- combinedItems.reduce(combineConsecutiveStrings(""), []);
6345
- if (combinedItems && combinedItems[0]) {
6346
- systemContent = combinedItems[0].text;
6347
- }
6801
+ };
6802
+ var checkMissingRequiredFields = (xstate, values, outputFields) => {
6803
+ const missingFields = [];
6804
+ for (const field of outputFields) {
6805
+ if (field && !field.isOptional && values[field.name] === void 0) {
6806
+ missingFields.push(field);
6348
6807
  }
6349
- const systemPrompt = {
6350
- role: "system",
6351
- content: systemContent
6352
- };
6353
- if (Array.isArray(values)) {
6354
- let messages = [];
6355
- const history = values;
6356
- for (const [index, message] of history.entries()) {
6357
- let content;
6358
- if (index === 0) {
6359
- content = this.renderSingleValueUserContent(
6360
- message.values,
6361
- renderedExamples,
6362
- renderedDemos,
6363
- examplesInSystemPrompt
6364
- );
6365
- } else {
6366
- content = this.renderSingleValueUserContent(
6367
- message.values,
6368
- [],
6369
- [],
6370
- false
6371
- );
6372
- }
6373
- if (message.role === "user") {
6374
- messages.push({ role: "user", content });
6808
+ }
6809
+ if (missingFields.length > 0) {
6810
+ throw new ValidationError({
6811
+ message: `Required ${missingFields.length === 1 ? "field" : "fields"} not found`,
6812
+ fields: missingFields
6813
+ });
6814
+ }
6815
+ };
6816
+ var streamingExtractValues = (sig, values, xstate, content, { strictMode, skipEarlyFail } = {}) => {
6817
+ const fields = sig.getOutputFields();
6818
+ let expectedField;
6819
+ for (const [index, field] of fields.entries()) {
6820
+ if (index === xstate.currFieldIndex && !xstate.inAssumedField) {
6821
+ continue;
6822
+ }
6823
+ if (field.name in values && !(index === xstate.currFieldIndex && xstate.inAssumedField)) {
6824
+ continue;
6825
+ }
6826
+ const isFirst = xstate.extractedFields.length === 0;
6827
+ const prefix = (isFirst ? "" : "\n") + field.title + ":";
6828
+ let e = matchesContent(content, prefix, xstate.s);
6829
+ let prefixLen = prefix.length;
6830
+ switch (e) {
6831
+ case -1:
6832
+ if (skipEarlyFail) {
6375
6833
  continue;
6376
6834
  }
6377
- if (message.role !== "assistant") {
6378
- throw new Error("Invalid message role");
6835
+ if (!strictMode && fields.length === 1 && xstate.currField === void 0) {
6836
+ xstate.inAssumedField = true;
6837
+ expectedField = field;
6838
+ prefixLen = 0;
6839
+ e = 0;
6840
+ break;
6379
6841
  }
6380
- if (typeof content !== "string") {
6381
- throw new Error(
6382
- "Assistant message cannot contain non-text content like images, files,etc"
6383
- );
6842
+ if (xstate.currField === void 0 && !field.isOptional) {
6843
+ throw new ValidationError({
6844
+ message: "Expected (Required) field not found",
6845
+ fields: [field]
6846
+ });
6384
6847
  }
6385
- messages.push({ role: "assistant", content });
6386
- }
6387
- return [systemPrompt, ...messages];
6848
+ expectedField = field.isOptional ? void 0 : field;
6849
+ continue;
6850
+ // Field is not found, continue to the next field
6851
+ case -2:
6852
+ return true;
6853
+ // Partial match at end, skip and gather more content
6854
+ case -3:
6855
+ return true;
6856
+ // String is only whitespace, skip and gather more content
6857
+ case -4:
6858
+ xstate.inBlock = true;
6859
+ return true;
6388
6860
  }
6389
- const userContent = this.renderSingleValueUserContent(
6390
- values,
6391
- renderedExamples,
6392
- renderedDemos,
6393
- examplesInSystemPrompt
6394
- );
6395
- return [systemPrompt, { role: "user", content: userContent }];
6396
- };
6397
- renderExtraFields = (extraFields) => {
6398
- const prompt = [];
6399
- if (!extraFields || extraFields.length === 0) {
6400
- return prompt;
6861
+ if (expectedField && expectedField.name !== field.name) {
6862
+ throw new ValidationError({
6863
+ message: "Expected (Required) field not found",
6864
+ fields: [expectedField]
6865
+ });
6401
6866
  }
6402
- const groupedFields = extraFields.reduce(
6403
- (acc, field) => {
6404
- const title = field.title;
6405
- if (!acc[title]) {
6406
- acc[title] = [];
6407
- }
6408
- acc[title].push(field);
6409
- return acc;
6410
- },
6411
- {}
6412
- );
6413
- const formattedGroupedFields = Object.entries(groupedFields).map(([title, fields]) => {
6414
- if (fields.length === 1) {
6415
- const field = fields[0];
6416
- return {
6417
- title,
6418
- name: field.name,
6419
- description: field.description
6420
- };
6421
- } else if (fields.length > 1) {
6422
- const valuesList = fields.map((field) => `- ${field.description}`).join("\n");
6423
- return {
6424
- title,
6425
- name: fields[0].name,
6426
- description: valuesList
6427
- };
6867
+ if (xstate.currField !== void 0 && xstate.inAssumedField) {
6868
+ xstate.inAssumedField = false;
6869
+ xstate.streamedIndex[xstate.currField.name] = 0;
6870
+ xstate.currField = void 0;
6871
+ }
6872
+ if (xstate.currField) {
6873
+ const val = content.substring(xstate.s, e).trim();
6874
+ const parsedValue = validateAndParseFieldValue(xstate.currField, val);
6875
+ if (parsedValue !== void 0) {
6876
+ values[xstate.currField.name] = parsedValue;
6428
6877
  }
6429
- }).filter(Boolean);
6430
- formattedGroupedFields.forEach((field) => {
6431
- const fn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
6432
- prompt.push(...fn(field, field.description));
6433
- });
6434
- return prompt;
6435
- };
6436
- renderExamples = (data) => {
6437
- const list = [];
6438
- const exampleContext = {
6439
- isExample: true
6440
- };
6441
- for (const [index, item] of data.entries()) {
6442
- const renderedInputItem = this.sig.getInputFields().map(
6443
- (field) => this.renderInField(field, item, {
6444
- ...exampleContext,
6445
- isInputField: true
6446
- })
6447
- ).filter((v) => v !== void 0).flat();
6448
- const renderedOutputItem = this.sig.getOutputFields().map(
6449
- (field) => this.renderInField(field, item, {
6450
- ...exampleContext,
6451
- isInputField: false
6452
- })
6453
- ).filter((v) => v !== void 0).flat();
6454
- const renderedItem = [...renderedInputItem, ...renderedOutputItem];
6455
- if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
6456
- list.push({ type: "text", text: "---\n\n" });
6878
+ if (xstate.prevFields) {
6879
+ xstate.prevFields?.push({ field: xstate.currField, s: xstate.s, e });
6880
+ } else {
6881
+ xstate.prevFields = [{ field: xstate.currField, s: xstate.s, e }];
6457
6882
  }
6458
- renderedItem.forEach((v) => {
6459
- if ("text" in v) {
6460
- v.text = v.text + "\n";
6461
- }
6462
- list.push(v);
6463
- });
6464
6883
  }
6465
- return list;
6466
- };
6467
- renderDemos = (data) => {
6468
- const list = [];
6469
- const inputFields = this.sig.getInputFields();
6470
- const outputFields = this.sig.getOutputFields();
6471
- const demoContext = {
6472
- isExample: true
6473
- };
6474
- for (const item of data) {
6475
- const inputRenderedItems = inputFields.map(
6476
- (field) => this.renderInField(field, item, {
6477
- ...demoContext,
6478
- isInputField: true
6479
- })
6480
- ).filter((v) => v !== void 0).flat();
6481
- const outputRenderedItems = outputFields.map(
6482
- (field) => this.renderInField(field, item, {
6483
- ...demoContext,
6484
- isInputField: false
6485
- })
6486
- ).filter((v) => v !== void 0).flat();
6487
- const renderedItem = [...inputRenderedItems, ...outputRenderedItems];
6488
- renderedItem.slice(0, -1).forEach((v) => {
6489
- if ("text" in v) {
6490
- v.text = v.text + "\n";
6491
- }
6492
- list.push(v);
6493
- });
6884
+ xstate.s = e + prefixLen;
6885
+ xstate.currField = field;
6886
+ xstate.currFieldIndex = index;
6887
+ if (!xstate.extractedFields.includes(field)) {
6888
+ xstate.extractedFields.push(field);
6494
6889
  }
6495
- return list;
6496
- };
6497
- renderInputFields = (values) => {
6498
- const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values, void 0)).filter((v) => v !== void 0).flat();
6499
- renderedItems.filter((v) => v.type === "text").forEach((v) => {
6500
- v.text = v.text + "\n";
6501
- });
6502
- return renderedItems;
6503
- };
6504
- renderInField = (field, values, context3) => {
6505
- const value = values[field.name];
6506
- if (isEmptyValue(field, value, context3)) {
6507
- return;
6890
+ if (xstate.streamedIndex[field.name] === void 0) {
6891
+ xstate.streamedIndex[field.name] = 0;
6508
6892
  }
6509
- if (field.type) {
6510
- validateValue(field, value);
6893
+ }
6894
+ };
6895
+ var streamingExtractFinalValue = (sig, values, xstate, content) => {
6896
+ if (xstate.currField) {
6897
+ let val = content.substring(xstate.s).trim();
6898
+ const parsedValue = validateAndParseFieldValue(xstate.currField, val);
6899
+ if (parsedValue !== void 0) {
6900
+ values[xstate.currField.name] = parsedValue;
6511
6901
  }
6512
- const processedValue = processValue(field, value);
6513
- const textFieldFn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
6514
- return textFieldFn(field, processedValue);
6515
- };
6516
- defaultRenderInField = (field, value) => {
6517
- if (field.type?.name === "image") {
6518
- const validateImage = (value2) => {
6519
- if (!value2) {
6520
- throw new Error("Image field value is required.");
6521
- }
6522
- if (typeof value2 !== "object") {
6523
- throw new Error("Image field value must be an object.");
6524
- }
6525
- if (!("mimeType" in value2)) {
6526
- throw new Error("Image field must have mimeType");
6527
- }
6528
- if (!("data" in value2)) {
6529
- throw new Error("Image field must have data");
6530
- }
6531
- return value2;
6532
- };
6533
- let result = [
6534
- { type: "text", text: `${field.title}: ` }
6535
- ];
6536
- if (field.type.isArray) {
6537
- if (!Array.isArray(value)) {
6538
- throw new Error("Image field value must be an array.");
6902
+ }
6903
+ checkMissingRequiredFields(xstate, values, sig.getOutputFields());
6904
+ };
6905
+ var convertValueToType = (field, val, required = false) => {
6906
+ switch (field.type?.name) {
6907
+ case "code":
6908
+ return extractBlock(val);
6909
+ case "string":
6910
+ return val;
6911
+ case "number": {
6912
+ const v = Number(val);
6913
+ if (Number.isNaN(v)) {
6914
+ if (field.isOptional && !required) {
6915
+ return;
6539
6916
  }
6540
- result = result.concat(
6541
- value.map((v) => {
6542
- const validated = validateImage(v);
6543
- return {
6544
- type: "image",
6545
- mimeType: validated.mimeType,
6546
- image: validated.data
6547
- };
6548
- })
6549
- );
6550
- } else {
6551
- const validated = validateImage(value);
6552
- result.push({
6553
- type: "image",
6554
- mimeType: validated.mimeType,
6555
- image: validated.data
6556
- });
6917
+ throw new Error("Invalid number");
6557
6918
  }
6558
- return result;
6919
+ return v;
6559
6920
  }
6560
- if (field.type?.name === "audio") {
6561
- const validateAudio = (value2) => {
6562
- if (!value2) {
6563
- throw new Error("Audio field value is required.");
6564
- }
6565
- if (typeof value2 !== "object") {
6566
- throw new Error("Audio field value must be an object.");
6567
- }
6568
- if (!("data" in value2)) {
6569
- throw new Error("Audio field must have data");
6570
- }
6571
- return value2;
6572
- };
6573
- let result = [
6574
- { type: "text", text: `${field.title}: ` }
6575
- ];
6576
- if (field.type.isArray) {
6577
- if (!Array.isArray(value)) {
6578
- throw new Error("Audio field value must be an array.");
6579
- }
6580
- result = result.concat(
6581
- value.map((v) => {
6582
- const validated = validateAudio(v);
6583
- return {
6584
- type: "audio",
6585
- format: validated.format ?? "wav",
6586
- data: validated.data
6587
- };
6588
- })
6589
- );
6921
+ case "boolean": {
6922
+ if (typeof val === "boolean") {
6923
+ return val;
6924
+ }
6925
+ const v = val.toLowerCase();
6926
+ if (v === "true") {
6927
+ return true;
6928
+ } else if (v === "false") {
6929
+ return false;
6590
6930
  } else {
6591
- const validated = validateAudio(value);
6592
- result.push({
6593
- type: "audio",
6594
- format: validated.format ?? "wav",
6595
- data: validated.data
6596
- });
6931
+ if (field.isOptional && !required) {
6932
+ return;
6933
+ }
6934
+ throw new Error("Invalid boolean");
6597
6935
  }
6598
- return result;
6599
- }
6600
- const text = [field.title, ": "];
6601
- if (Array.isArray(value)) {
6602
- text.push("\n");
6603
- text.push(value.map((v) => `- ${v}`).join("\n"));
6604
- } else {
6605
- text.push(value);
6606
- }
6607
- return [{ type: "text", text: text.join("") }];
6608
- };
6609
- };
6610
- var renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
6611
- var renderInputFields = (fields) => {
6612
- const rows = fields.map((field) => {
6613
- const name = field.title;
6614
- const type = field.type?.name ? toFieldType(field.type) : "string";
6615
- const requiredMsg = field.isOptional ? `This optional ${type} field may be omitted` : `A ${type} field`;
6616
- const description = field.description ? ` ${formatDescription(field.description)}` : "";
6617
- return `${name}: (${requiredMsg})${description}`.trim();
6618
- });
6619
- return rows.join("\n");
6620
- };
6621
- var renderOutputFields = (fields) => {
6622
- const rows = fields.map((field) => {
6623
- const name = field.title;
6624
- const type = field.type?.name ? toFieldType(field.type) : "string";
6625
- const requiredMsg = field.isOptional ? `Only include this ${type} field if its value is available` : `This ${type} field must be included`;
6626
- let description = "";
6627
- if (field.description && field.description.length > 0) {
6628
- const value = field.type?.name === "class" ? field.description : formatDescription(field.description);
6629
- description = ` ${value}`;
6630
6936
  }
6631
- if (field.type?.options && field.type.options.length > 0) {
6632
- if (description.length > 0) {
6633
- description += `. `;
6937
+ case "date":
6938
+ return parseLLMFriendlyDate(field, val, required);
6939
+ case "datetime":
6940
+ return parseLLMFriendlyDateTime(field, val, required);
6941
+ case "class":
6942
+ const className = val;
6943
+ if (field.type.options && !field.type.options.includes(className)) {
6944
+ if (field.isOptional) {
6945
+ return;
6946
+ }
6947
+ throw new Error(
6948
+ `Invalid class '${val}', expected one of the following: ${field.type.options.join(", ")}`
6949
+ );
6634
6950
  }
6635
- description += `Allowed values: ${field.type.options.join(", ")}`;
6636
- }
6637
- return `${name}: (${requiredMsg})${description}`.trim();
6638
- });
6639
- return rows.join("\n");
6951
+ return className;
6952
+ default:
6953
+ return val;
6954
+ }
6640
6955
  };
6641
- var processValue = (field, value) => {
6642
- if (field.type?.name === "date" && value instanceof Date) {
6643
- const v = value.toISOString();
6644
- return v.slice(0, v.indexOf("T"));
6956
+ function* yieldDelta(content, field, s2, e, xstate, index) {
6957
+ const { name: fieldName, isInternal } = field;
6958
+ const { isArray: fieldIsArray, name: fieldTypeName } = field.type ?? {};
6959
+ if (isInternal || fieldIsArray || fieldTypeName && fieldTypeName !== "string" && fieldTypeName !== "code") {
6960
+ return;
6645
6961
  }
6646
- if (field.type?.name === "datetime" && value instanceof Date) {
6647
- return formatDateWithTimezone(value);
6962
+ const pos = xstate.streamedIndex[fieldName] ?? 0;
6963
+ const isFirstChunk = pos === 0;
6964
+ const d1 = content.substring(s2 + pos, e);
6965
+ if (d1.length === 0) {
6966
+ return;
6648
6967
  }
6649
- if (field.type?.name === "image" && typeof value === "object") {
6650
- return value;
6968
+ let d2 = d1.replace(/\s+$/, "");
6969
+ if (xstate.currField?.type?.name === "code") {
6970
+ d2 = d2.replace(/\s*```\s*$/, "");
6651
6971
  }
6652
- if (field.type?.name === "audio" && typeof value === "object") {
6653
- return value;
6972
+ let d3 = isFirstChunk ? d2.trimStart() : d2;
6973
+ if (xstate.currField?.type?.name === "code") {
6974
+ d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
6654
6975
  }
6655
- if (typeof value === "string") {
6656
- return value;
6976
+ if (d3.length > 0) {
6977
+ yield { index, delta: { [fieldName]: d3 } };
6978
+ xstate.streamedIndex[fieldName] = pos + d2.length;
6657
6979
  }
6658
- return JSON.stringify(value, null, 2);
6659
- };
6660
- var toFieldType = (type) => {
6661
- const baseType = (() => {
6662
- switch (type?.name) {
6663
- case "string":
6664
- return "string";
6665
- case "number":
6666
- return "number";
6667
- case "boolean":
6668
- return "boolean";
6669
- case "date":
6670
- return 'date ("YYYY-MM-DD" format)';
6671
- case "datetime":
6672
- return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6673
- case "json":
6674
- return "JSON object";
6675
- case "class":
6676
- return "classification class";
6677
- case "code":
6678
- return "code";
6679
- default:
6680
- return "string";
6681
- }
6682
- })();
6683
- return type?.isArray ? `json array of ${baseType} items` : baseType;
6684
- };
6685
- function combineConsecutiveStrings(separator) {
6686
- return (acc, current) => {
6687
- if (current.type === "text") {
6688
- const previous = acc.length > 0 ? acc[acc.length - 1] : null;
6689
- if (previous && previous.type === "text") {
6690
- previous.text += separator + current.text;
6691
- } else {
6692
- acc.push(current);
6693
- }
6694
- } else {
6695
- acc.push(current);
6696
- }
6697
- return acc;
6698
- };
6699
6980
  }
6700
- var isEmptyValue = (field, value, context3) => {
6701
- if (typeof value === "boolean") {
6702
- return false;
6981
+ function* streamValues(sig, content, values, xstate, index) {
6982
+ for (const prevField of xstate.prevFields ?? []) {
6983
+ const { field, s: s2, e } = prevField;
6984
+ yield* yieldDelta(content, field, s2, e, xstate, index);
6703
6985
  }
6704
- if (!value || (Array.isArray(value) || typeof value === "string") && value.length === 0) {
6705
- if (context3?.isExample) {
6706
- return true;
6707
- }
6708
- if (field.isOptional || field.isInternal) {
6709
- return true;
6710
- }
6711
- const fieldType = context3?.isInputField !== false ? "input" : "output";
6712
- throw new Error(`Value for ${fieldType} field '${field.name}' is required.`);
6986
+ xstate.prevFields = void 0;
6987
+ if (!xstate.currField || xstate.currField.isInternal) {
6988
+ return;
6713
6989
  }
6714
- return false;
6715
- };
6716
- function formatDescription(str) {
6717
- const value = str.trim();
6718
- return value.length > 0 ? `${value.charAt(0).toUpperCase()}${value.slice(1)}${value.endsWith(".") ? "" : "."}` : "";
6719
- }
6720
-
6721
- // dsp/validate.ts
6722
- var ValidationError = class extends Error {
6723
- fields;
6724
- constructor({
6725
- message,
6726
- fields
6727
- }) {
6728
- super(message);
6729
- this.fields = fields;
6730
- this.name = this.constructor.name;
6731
- }
6732
- getFixingInstructions = () => {
6733
- return this.fields.map((field) => ({
6734
- name: "outputError",
6735
- title: "Output Correction Required",
6736
- description: `The section labeled '${field.title}' either was not generated by the LLM or does not match the expected format of '${toFieldType(field.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`
6737
- }));
6738
- };
6739
- toString() {
6740
- return [
6741
- `${this.name}: ${this.message}`,
6742
- ...this.fields.map(
6743
- (field) => ` - ${field.title}: Expected format '${toFieldType(field.type)}'`
6744
- )
6745
- ].join("\n");
6746
- }
6747
- [Symbol.for("nodejs.util.inspect.custom")](_depth, _options) {
6748
- return this.toString();
6749
- }
6750
- };
6751
- function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId) {
6752
- mem.add(
6753
- {
6754
- role: "user",
6755
- content: promptTemplate.renderExtraFields(errorFields)
6756
- },
6757
- sessionId
6990
+ yield* yieldDelta(
6991
+ content,
6992
+ xstate.currField,
6993
+ xstate.s,
6994
+ content.length,
6995
+ xstate,
6996
+ index
6758
6997
  );
6759
- mem.addTag("error");
6760
- if (ai.getOptions().debug) {
6761
- const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
6762
- const logger = ai.getLogger();
6763
- logger(`\u274C Error Correction:
6764
- ${errors}`, {
6765
- tags: ["error"]
6766
- });
6998
+ const outputFields = sig.getOutputFields();
6999
+ for (const key of Object.keys(values)) {
7000
+ const field = outputFields.find((f2) => f2.name === key);
7001
+ if (!field || field.isInternal) {
7002
+ continue;
7003
+ }
7004
+ const value = values[key];
7005
+ if (Array.isArray(value)) {
7006
+ const s2 = xstate.streamedIndex?.[key] ?? 0;
7007
+ const v = value.slice(s2);
7008
+ if (v && v.length > 0) {
7009
+ yield { index, delta: { [key]: v } };
7010
+ xstate.streamedIndex[key] = s2 + v.length;
7011
+ }
7012
+ continue;
7013
+ }
7014
+ if (!xstate.streamedIndex[key]) {
7015
+ yield { index, delta: { [key]: value } };
7016
+ xstate.streamedIndex[key] = 1;
7017
+ }
6767
7018
  }
6768
7019
  }
6769
-
6770
- // dsp/datetime.ts
6771
- function parseLLMFriendlyDate(field, dateStr, required = false) {
6772
- try {
6773
- return _parseLLMFriendlyDate(dateStr);
6774
- } catch (err) {
6775
- if (field.isOptional && !required) {
7020
+ function validateAndParseFieldValue(field, fieldValue) {
7021
+ if (!fieldValue || fieldValue === "" || /^(null|undefined)\s*$/i.test(fieldValue)) {
7022
+ if (field.isOptional) {
6776
7023
  return;
6777
7024
  }
6778
- const message = err.message;
6779
- throw new ValidationError({ fields: [field], message, value: dateStr });
7025
+ throw new ValidationError({
7026
+ message: "Required field is missing",
7027
+ fields: [field],
7028
+ value: fieldValue
7029
+ });
6780
7030
  }
6781
- }
6782
- function _parseLLMFriendlyDate(dateStr) {
6783
- if (!moment(dateStr, "YYYY-MM-DD", true).isValid()) {
6784
- throw new Error(
6785
- 'Invalid date format. Please provide the date in "YYYY-MM-DD" format.'
6786
- );
7031
+ let value;
7032
+ if (field.type?.name === "json") {
7033
+ try {
7034
+ const text = extractBlock(fieldValue);
7035
+ value = JSON.parse(text);
7036
+ return value;
7037
+ } catch (e) {
7038
+ throw new ValidationError({
7039
+ message: "Invalid JSON: " + e.message,
7040
+ fields: [field],
7041
+ value: fieldValue
7042
+ });
7043
+ }
7044
+ }
7045
+ if (field.type?.isArray) {
7046
+ try {
7047
+ try {
7048
+ value = JSON.parse(fieldValue);
7049
+ } catch {
7050
+ value = parseMarkdownList(fieldValue);
7051
+ }
7052
+ if (!Array.isArray(value)) {
7053
+ throw new Error("Expected an array");
7054
+ }
7055
+ } catch (e) {
7056
+ throw new ValidationError({
7057
+ message: "Invalid Array: " + e.message,
7058
+ fields: [field],
7059
+ value: fieldValue
7060
+ });
7061
+ }
6787
7062
  }
6788
- const date = moment.utc(dateStr, "YYYY-MM-DD").startOf("day");
6789
- return date.toDate();
6790
- }
6791
- function parseLLMFriendlyDateTime(field, dateStr, required = false) {
6792
7063
  try {
6793
- return _parseLLMFriendlyDateTime(dateStr);
6794
- } catch (err) {
6795
- if (field.isOptional && !required) {
6796
- return;
7064
+ if (Array.isArray(value)) {
7065
+ for (const [index, item] of value.entries()) {
7066
+ if (item !== void 0) {
7067
+ const v = typeof item === "string" ? item.trim() : item;
7068
+ value[index] = convertValueToType(field, v, true);
7069
+ }
7070
+ }
7071
+ } else {
7072
+ value = convertValueToType(field, fieldValue);
6797
7073
  }
6798
- const message = err.message;
6799
- throw new ValidationError({ fields: [field], message, value: dateStr });
7074
+ } catch (e) {
7075
+ throw new ValidationError({
7076
+ message: e.message,
7077
+ fields: [field],
7078
+ value: fieldValue
7079
+ });
6800
7080
  }
7081
+ if (typeof value === "string" && value === "") {
7082
+ return void 0;
7083
+ }
7084
+ return value;
6801
7085
  }
6802
- function _parseLLMFriendlyDateTime(dateTimeStr) {
6803
- const dateTimeRegex = /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/;
6804
- const match = dateTimeStr.match(dateTimeRegex);
7086
+ var extractBlock = (input) => {
7087
+ const markdownBlockPattern = /```([A-Za-z]*)\n([\s\S]*?)\n```/g;
7088
+ const match = markdownBlockPattern.exec(input);
6805
7089
  if (!match) {
6806
- throw new Error(
6807
- 'Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.'
6808
- );
6809
- }
6810
- const [, dateTime, timeZone] = match;
6811
- if (!dateTime || !timeZone) {
6812
- throw new Error(
6813
- 'Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.'
6814
- );
7090
+ return input;
6815
7091
  }
6816
- const zone = moment.tz.zone(timeZone);
6817
- if (!zone) {
6818
- throw new Error(
6819
- `Unrecognized time zone ${timeZone}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`
6820
- );
7092
+ if (match.length === 3) {
7093
+ return match[2];
6821
7094
  }
6822
- const date = moment.tz(
6823
- dateTime,
6824
- ["YYYY-MM-DD HH:mm", "YYYY-MM-DD HH:mm:ss"],
6825
- zone.name
6826
- );
6827
- if (!date.isValid()) {
6828
- throw new Error(
6829
- "Invalid date and time values. Please ensure all components are correct."
6830
- );
7095
+ if (match.length === 2) {
7096
+ return match[1];
6831
7097
  }
6832
- return date.utc().toDate();
6833
- }
6834
- var formatDateWithTimezone = (date) => {
6835
- const momentDate = moment(date).utc();
6836
- return momentDate.format(`YYYY-MM-DD HH:mm:ss UTC`);
7098
+ return input;
6837
7099
  };
6838
7100
 
6839
- // dsp/extract.ts
6840
- var extractValues = (sig, values, content, strictMode = false) => {
6841
- const xstate = { extractedFields: [], streamedIndex: {}, s: -1 };
6842
- streamingExtractValues(sig, values, xstate, content, strictMode);
6843
- streamingExtractFinalValue(sig, values, xstate, content);
6844
- for (const field of sig.getOutputFields()) {
6845
- if (field.isInternal) {
6846
- delete values[field.name];
6847
- }
6848
- }
6849
- };
6850
- var checkMissingRequiredFields = (xstate, values, outputFields) => {
6851
- const missingFields = [];
6852
- for (const field of outputFields) {
6853
- if (field && !field.isOptional && values[field.name] === void 0) {
6854
- missingFields.push(field);
7101
+ // dsp/fieldProcessor.ts
7102
+ async function processFieldProcessors(fieldProcessors, values, mem, sessionId) {
7103
+ for (const processor of fieldProcessors) {
7104
+ if (values[processor.field.name] === void 0) {
7105
+ continue;
6855
7106
  }
6856
- }
6857
- if (missingFields.length > 0) {
6858
- throw new ValidationError({
6859
- message: `Required ${missingFields.length === 1 ? "field" : "fields"} not found`,
6860
- fields: missingFields
7107
+ const processFn = processor.process;
7108
+ const result = await processFn(values[processor.field.name], {
7109
+ sessionId,
7110
+ values,
7111
+ done: true
6861
7112
  });
7113
+ addToMemory(processor.field, mem, result, sessionId);
6862
7114
  }
6863
- };
6864
- var streamingExtractValues = (sig, values, xstate, content, strictMode = false) => {
6865
- const fields = sig.getOutputFields();
6866
- let expectedField;
6867
- for (const [index, field] of fields.entries()) {
6868
- if (index === xstate.currFieldIndex) {
7115
+ }
7116
+ async function processStreamingFieldProcessors(fieldProcessors, content, xstate, mem, values, sessionId, done = false) {
7117
+ for (const processor of fieldProcessors) {
7118
+ if (xstate.currField?.name !== processor.field.name) {
6869
7119
  continue;
6870
7120
  }
6871
- if (field.name in values) {
6872
- continue;
7121
+ let value = content.substring(xstate.s);
7122
+ if (xstate.currField?.type?.name === "code") {
7123
+ value = value.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7124
+ value = value.replace(/\s*```\s*$/, "");
6873
7125
  }
6874
- const isFirst = xstate.extractedFields.length === 0;
6875
- const prefix = (isFirst ? "" : "\n") + field.title + ":";
6876
- let e = matchesContent(content, prefix, xstate.s);
6877
- let prefixLen = prefix.length;
6878
- switch (e) {
6879
- case -1:
6880
- if (!strictMode && fields.length === 1 && xstate.currField === void 0) {
6881
- prefixLen = 0;
6882
- e = 0;
6883
- break;
6884
- }
6885
- if (xstate.currField === void 0 && !field.isOptional) {
6886
- throw new ValidationError({
6887
- message: "Expected (Required) field not found",
6888
- fields: [field]
6889
- });
6890
- }
6891
- expectedField = field.isOptional ? void 0 : field;
6892
- continue;
6893
- // Field is not found, continue to the next field
6894
- case -2:
6895
- return true;
6896
- // Partial match at end, skip and gather more content
6897
- case -3:
6898
- return true;
6899
- // String is only whitespace, skip and gather more content
6900
- case -4:
6901
- xstate.inBlock = true;
6902
- return true;
6903
- }
6904
- if (expectedField && expectedField.name !== field.name) {
6905
- throw new ValidationError({
6906
- message: "Expected (Required) field not found",
6907
- fields: [expectedField]
6908
- });
6909
- }
6910
- if (xstate.currField) {
6911
- const val = content.substring(xstate.s, e).trim();
6912
- const parsedValue = validateAndParseFieldValue(xstate.currField, val);
6913
- if (parsedValue !== void 0) {
6914
- values[xstate.currField.name] = parsedValue;
6915
- }
6916
- if (xstate.prevFields) {
6917
- xstate.prevFields?.push({ field: xstate.currField, s: xstate.s, e });
6918
- } else {
6919
- xstate.prevFields = [{ field: xstate.currField, s: xstate.s, e }];
6920
- }
6921
- }
6922
- xstate.s = e + prefixLen;
6923
- xstate.currField = field;
6924
- xstate.currFieldIndex = index;
6925
- if (!xstate.extractedFields.includes(field)) {
6926
- xstate.extractedFields.push(field);
6927
- }
6928
- if (xstate.streamedIndex[field.name] === void 0) {
6929
- xstate.streamedIndex[field.name] = 0;
6930
- }
6931
- }
6932
- };
6933
- var streamingExtractFinalValue = (sig, values, xstate, content) => {
6934
- if (xstate.currField) {
6935
- let val = content.substring(xstate.s).trim();
6936
- const parsedValue = validateAndParseFieldValue(xstate.currField, val);
6937
- if (parsedValue !== void 0) {
6938
- values[xstate.currField.name] = parsedValue;
6939
- }
6940
- }
6941
- checkMissingRequiredFields(xstate, values, sig.getOutputFields());
6942
- };
6943
- var convertValueToType = (field, val, required = false) => {
6944
- switch (field.type?.name) {
6945
- case "code":
6946
- return extractBlock(val);
6947
- case "string":
6948
- return val;
6949
- case "number": {
6950
- const v = Number(val);
6951
- if (Number.isNaN(v)) {
6952
- if (field.isOptional && !required) {
6953
- return;
6954
- }
6955
- throw new Error("Invalid number");
6956
- }
6957
- return v;
6958
- }
6959
- case "boolean": {
6960
- if (typeof val === "boolean") {
6961
- return val;
6962
- }
6963
- const v = val.toLowerCase();
6964
- if (v === "true") {
6965
- return true;
6966
- } else if (v === "false") {
6967
- return false;
6968
- } else {
6969
- if (field.isOptional && !required) {
6970
- return;
6971
- }
6972
- throw new Error("Invalid boolean");
6973
- }
6974
- }
6975
- case "date":
6976
- return parseLLMFriendlyDate(field, val, required);
6977
- case "datetime":
6978
- return parseLLMFriendlyDateTime(field, val, required);
6979
- case "class":
6980
- const className = val;
6981
- if (field.type.options && !field.type.options.includes(className)) {
6982
- if (field.isOptional) {
6983
- return;
6984
- }
6985
- throw new Error(
6986
- `Invalid class '${val}', expected one of the following: ${field.type.options.join(", ")}`
6987
- );
6988
- }
6989
- return className;
6990
- default:
6991
- return val;
6992
- }
6993
- };
6994
- function* yieldDelta(content, field, s2, e, xstate) {
6995
- const { name: fieldName, isInternal } = field;
6996
- const { isArray: fieldIsArray, name: fieldTypeName } = field.type ?? {};
6997
- if (isInternal || fieldIsArray || fieldTypeName && fieldTypeName !== "string" && fieldTypeName !== "code") {
6998
- return;
6999
- }
7000
- const pos = xstate.streamedIndex[fieldName] ?? 0;
7001
- const isFirstChunk = pos === 0;
7002
- const d1 = content.substring(s2 + pos, e);
7003
- if (d1.length === 0) {
7004
- return;
7005
- }
7006
- let d2 = d1.replace(/\s+$/, "");
7007
- if (xstate.currField?.type?.name === "code") {
7008
- d2 = d2.replace(/\s*```\s*$/, "");
7009
- }
7010
- let d3 = isFirstChunk ? d2.trimStart() : d2;
7011
- if (xstate.currField?.type?.name === "code") {
7012
- d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7013
- }
7014
- if (d3.length > 0) {
7015
- yield { [fieldName]: d3 };
7016
- xstate.streamedIndex[fieldName] = pos + d2.length;
7126
+ const processFn = processor.process;
7127
+ const result = await processFn(value, {
7128
+ sessionId,
7129
+ values,
7130
+ done
7131
+ });
7132
+ addToMemory(xstate.currField, mem, result, sessionId);
7017
7133
  }
7018
7134
  }
7019
- function* streamValues(sig, content, values, xstate) {
7020
- for (const prevField of xstate.prevFields ?? []) {
7021
- const { field, s: s2, e } = prevField;
7022
- yield* yieldDelta(content, field, s2, e, xstate);
7023
- }
7024
- xstate.prevFields = void 0;
7025
- if (!xstate.currField || xstate.currField.isInternal) {
7135
+ var addToMemory = (field, mem, result, sessionId) => {
7136
+ if (result === void 0 || typeof result === "string" && (result === "" || /^(null|undefined)\s*$/i.test(result))) {
7026
7137
  return;
7027
7138
  }
7028
- yield* yieldDelta(
7029
- content,
7030
- xstate.currField,
7031
- xstate.s,
7032
- content.length,
7033
- xstate
7139
+ let resultText = JSON.stringify(
7140
+ result,
7141
+ (key, value) => typeof value === "bigint" ? Number(value) : value,
7142
+ 2
7034
7143
  );
7035
- const outputFields = sig.getOutputFields();
7036
- for (const key of Object.keys(values)) {
7037
- const field = outputFields.find((f2) => f2.name === key);
7038
- if (!field || field.isInternal) {
7039
- continue;
7040
- }
7041
- const value = values[key];
7042
- if (Array.isArray(value)) {
7043
- const s2 = xstate.streamedIndex?.[key] ?? 0;
7044
- const v = value.slice(s2);
7045
- if (v && v.length > 0) {
7046
- yield { [key]: v };
7047
- xstate.streamedIndex[key] = s2 + v.length;
7048
- }
7049
- continue;
7050
- }
7051
- if (!xstate.streamedIndex[key]) {
7052
- yield { [key]: value };
7053
- xstate.streamedIndex[key] = 1;
7054
- }
7144
+ const text = getFieldProcessingMessage(field, resultText);
7145
+ mem.addRequest(
7146
+ [{ role: "user", content: [{ type: "text", text }] }],
7147
+ sessionId
7148
+ );
7149
+ mem.addTag(`processor`, sessionId);
7150
+ };
7151
+ function getFieldProcessingMessage(field, resultText) {
7152
+ const isCodeField = field.type?.name === "code";
7153
+ const fieldTitle = field.title;
7154
+ if (isCodeField) {
7155
+ return `Code in the field "${fieldTitle}" was executed. The code execution produced the following output: ${resultText}`;
7156
+ } else {
7157
+ return `The field "${fieldTitle}" was processed. The field contents were transformed into the following output: ${resultText}`;
7055
7158
  }
7056
7159
  }
7057
- function validateAndParseFieldValue(field, fieldValue) {
7058
- if (!fieldValue || fieldValue === "" || /^(null|undefined)\s*$/i.test(fieldValue)) {
7059
- if (field.isOptional) {
7160
+
7161
+ // dsp/jsonschema.ts
7162
+ var validateJSONSchema = (schema) => {
7163
+ const errors = [];
7164
+ const validateSchemaObject = (schema2, path = "") => {
7165
+ if (!schema2 || typeof schema2 !== "object") {
7060
7166
  return;
7061
7167
  }
7062
- throw new ValidationError({
7063
- message: "Required field is missing",
7064
- fields: [field],
7065
- value: fieldValue
7066
- });
7067
- }
7068
- let value;
7069
- if (field.type?.name === "json") {
7070
- try {
7071
- const text = extractBlock(fieldValue);
7072
- value = JSON.parse(text);
7073
- return value;
7074
- } catch (e) {
7075
- throw new ValidationError({
7076
- message: "Invalid JSON: " + e.message,
7077
- fields: [field],
7078
- value: fieldValue
7168
+ const validTypes = [
7169
+ "array",
7170
+ "integer",
7171
+ "number",
7172
+ "string",
7173
+ "boolean",
7174
+ "null",
7175
+ "object"
7176
+ ];
7177
+ if (schema2.anyOf && Array.isArray(schema2.anyOf)) {
7178
+ if (schema2.anyOf.length === 0) {
7179
+ errors.push({
7180
+ path: path || "root",
7181
+ issue: "anyOf array is empty",
7182
+ fix: "Add at least one schema to the anyOf array",
7183
+ example: 'anyOf: [{ type: "string" }, { type: "null" }]'
7184
+ });
7185
+ }
7186
+ schema2.anyOf.forEach((subSchema, index) => {
7187
+ validateSchemaObject(subSchema, `${path}anyOf[${index}].`);
7079
7188
  });
7189
+ return;
7080
7190
  }
7081
- }
7082
- if (field.type?.isArray) {
7083
- try {
7084
- try {
7085
- value = JSON.parse(fieldValue);
7086
- } catch {
7087
- value = parseMarkdownList(fieldValue);
7191
+ if (schema2.oneOf && Array.isArray(schema2.oneOf)) {
7192
+ if (schema2.oneOf.length === 0) {
7193
+ errors.push({
7194
+ path: path || "root",
7195
+ issue: "oneOf array is empty",
7196
+ fix: "Add at least one schema to the oneOf array",
7197
+ example: 'oneOf: [{ type: "string" }, { type: "number" }]'
7198
+ });
7088
7199
  }
7089
- if (!Array.isArray(value)) {
7090
- throw new Error("Expected an array");
7200
+ schema2.oneOf.forEach((subSchema, index) => {
7201
+ validateSchemaObject(subSchema, `${path}oneOf[${index}].`);
7202
+ });
7203
+ return;
7204
+ }
7205
+ if (schema2.allOf && Array.isArray(schema2.allOf)) {
7206
+ if (schema2.allOf.length === 0) {
7207
+ errors.push({
7208
+ path: path || "root",
7209
+ issue: "allOf array is empty",
7210
+ fix: "Add at least one schema to the allOf array",
7211
+ example: 'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'
7212
+ });
7091
7213
  }
7092
- } catch (e) {
7093
- throw new ValidationError({
7094
- message: "Invalid Array: " + e.message,
7095
- fields: [field],
7096
- value: fieldValue
7214
+ schema2.allOf.forEach((subSchema, index) => {
7215
+ validateSchemaObject(subSchema, `${path}allOf[${index}].`);
7097
7216
  });
7098
- }
7099
- }
7100
- try {
7101
- if (Array.isArray(value)) {
7102
- for (const [index, item] of value.entries()) {
7103
- if (item !== void 0) {
7104
- const v = typeof item === "string" ? item.trim() : item;
7105
- value[index] = convertValueToType(field, v, true);
7106
- }
7107
- }
7108
- } else {
7109
- value = convertValueToType(field, fieldValue);
7110
- }
7111
- } catch (e) {
7112
- throw new ValidationError({
7113
- message: e.message,
7114
- fields: [field],
7115
- value: fieldValue
7116
- });
7117
- }
7118
- if (typeof value === "string" && value === "") {
7119
- return void 0;
7120
- }
7121
- return value;
7122
- }
7123
- var extractBlock = (input) => {
7124
- const markdownBlockPattern = /```([A-Za-z]*)\n([\s\S]*?)\n```/g;
7125
- const match = markdownBlockPattern.exec(input);
7126
- if (!match) {
7127
- return input;
7128
- }
7129
- if (match.length === 3) {
7130
- return match[2];
7131
- }
7132
- if (match.length === 2) {
7133
- return match[1];
7134
- }
7135
- return input;
7136
- };
7137
-
7138
- // dsp/fieldProcessor.ts
7139
- async function processFieldProcessors(fieldProcessors, values, mem, sessionId) {
7140
- for (const processor of fieldProcessors) {
7141
- if (values[processor.field.name] === void 0) {
7142
- continue;
7143
- }
7144
- const processFn = processor.process;
7145
- const result = await processFn(values[processor.field.name], {
7146
- sessionId,
7147
- values,
7148
- done: true
7149
- });
7150
- addToMemory(processor.field, mem, result, sessionId);
7151
- }
7152
- }
7153
- async function processStreamingFieldProcessors(fieldProcessors, content, xstate, mem, values, sessionId, done = false) {
7154
- for (const processor of fieldProcessors) {
7155
- if (xstate.currField?.name !== processor.field.name) {
7156
- continue;
7157
- }
7158
- let value = content.substring(xstate.s);
7159
- if (xstate.currField?.type?.name === "code") {
7160
- value = value.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7161
- value = value.replace(/\s*```\s*$/, "");
7162
- }
7163
- const processFn = processor.process;
7164
- const result = await processFn(value, {
7165
- sessionId,
7166
- values,
7167
- done
7168
- });
7169
- addToMemory(xstate.currField, mem, result, sessionId);
7170
- }
7171
- }
7172
- var addToMemory = (field, mem, result, sessionId) => {
7173
- if (result === void 0 || typeof result === "string" && (result === "" || /^(null|undefined)\s*$/i.test(result))) {
7174
- return;
7175
- }
7176
- let resultText = JSON.stringify(
7177
- result,
7178
- (key, value) => typeof value === "bigint" ? Number(value) : value,
7179
- 2
7180
- );
7181
- const text = getFieldProcessingMessage(field, resultText);
7182
- mem.add({ role: "user", content: [{ type: "text", text }] }, sessionId);
7183
- mem.addTag(`processor`, sessionId);
7184
- };
7185
- function getFieldProcessingMessage(field, resultText) {
7186
- const isCodeField = field.type?.name === "code";
7187
- const fieldTitle = field.title;
7188
- if (isCodeField) {
7189
- return `Code in the field "${fieldTitle}" was executed. The code execution produced the following output: ${resultText}`;
7190
- } else {
7191
- return `The field "${fieldTitle}" was processed. The field contents were transformed into the following output: ${resultText}`;
7192
- }
7193
- }
7194
-
7195
- // dsp/jsonschema.ts
7196
- var validateJSONSchema = (schema) => {
7197
- const errors = [];
7198
- const validateSchemaObject = (schema2, path = "") => {
7199
- if (!schema2 || typeof schema2 !== "object") {
7200
- return;
7201
- }
7202
- const validTypes = [
7203
- "array",
7204
- "integer",
7205
- "number",
7206
- "string",
7207
- "boolean",
7208
- "null",
7209
- "object"
7210
- ];
7211
- if (schema2.anyOf && Array.isArray(schema2.anyOf)) {
7212
- if (schema2.anyOf.length === 0) {
7213
- errors.push({
7214
- path: path || "root",
7215
- issue: "anyOf array is empty",
7216
- fix: "Add at least one schema to the anyOf array",
7217
- example: 'anyOf: [{ type: "string" }, { type: "null" }]'
7218
- });
7219
- }
7220
- schema2.anyOf.forEach((subSchema, index) => {
7221
- validateSchemaObject(subSchema, `${path}anyOf[${index}].`);
7222
- });
7223
- return;
7224
- }
7225
- if (schema2.oneOf && Array.isArray(schema2.oneOf)) {
7226
- if (schema2.oneOf.length === 0) {
7227
- errors.push({
7228
- path: path || "root",
7229
- issue: "oneOf array is empty",
7230
- fix: "Add at least one schema to the oneOf array",
7231
- example: 'oneOf: [{ type: "string" }, { type: "number" }]'
7232
- });
7233
- }
7234
- schema2.oneOf.forEach((subSchema, index) => {
7235
- validateSchemaObject(subSchema, `${path}oneOf[${index}].`);
7236
- });
7237
- return;
7238
- }
7239
- if (schema2.allOf && Array.isArray(schema2.allOf)) {
7240
- if (schema2.allOf.length === 0) {
7241
- errors.push({
7242
- path: path || "root",
7243
- issue: "allOf array is empty",
7244
- fix: "Add at least one schema to the allOf array",
7245
- example: 'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'
7246
- });
7247
- }
7248
- schema2.allOf.forEach((subSchema, index) => {
7249
- validateSchemaObject(subSchema, `${path}allOf[${index}].`);
7250
- });
7251
- return;
7217
+ return;
7252
7218
  }
7253
7219
  if (!schema2.type) {
7254
7220
  return;
@@ -7438,10 +7404,10 @@ var AxFunctionProcessor = class {
7438
7404
  } : void 0;
7439
7405
  if (!fnSpec.parameters) {
7440
7406
  const res2 = fnSpec.func.length === 1 ? await fnSpec.func(opt) : await fnSpec.func();
7441
- return typeof res2 === "string" ? res2 : JSON.stringify(res2, null, 2);
7407
+ return typeof res2 === "string" ? res2 : res2 === void 0 || res2 === null ? "" : JSON.stringify(res2, null, 2);
7442
7408
  }
7443
7409
  const res = fnSpec.func.length === 2 ? await fnSpec.func(args, opt) : await fnSpec.func(args);
7444
- return typeof res === "string" ? res : JSON.stringify(res, null, 2);
7410
+ return typeof res === "string" ? res : res === void 0 || res === null ? "" : JSON.stringify(res, null, 2);
7445
7411
  };
7446
7412
  execute = async (func, options) => {
7447
7413
  const fnSpec = this.funcList.find(
@@ -7480,7 +7446,17 @@ var parseFunctions = (newFuncs, existingFuncs) => {
7480
7446
  }
7481
7447
  return [...existingFuncs ?? [], ...functions];
7482
7448
  };
7483
- var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, traceId, span, excludeContentFromTelemetry) => {
7449
+ var processFunctions = async ({
7450
+ ai,
7451
+ functionList,
7452
+ functionCalls,
7453
+ mem,
7454
+ sessionId,
7455
+ traceId,
7456
+ span,
7457
+ excludeContentFromTrace,
7458
+ index
7459
+ }) => {
7484
7460
  const funcProc = new AxFunctionProcessor(functionList);
7485
7461
  const functionsExecuted = /* @__PURE__ */ new Set();
7486
7462
  const promises = functionCalls.map((func) => {
@@ -7493,59 +7469,56 @@ var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, t
7493
7469
  const eventData = {
7494
7470
  name: func.name
7495
7471
  };
7496
- if (!excludeContentFromTelemetry) {
7472
+ if (!excludeContentFromTrace) {
7497
7473
  eventData.args = func.args;
7498
7474
  eventData.result = functionResult ?? "";
7499
7475
  }
7500
7476
  span.addEvent("function.call", eventData);
7501
7477
  }
7502
7478
  return {
7503
- role: "function",
7504
7479
  result: functionResult ?? "",
7505
- functionId: func.id
7480
+ role: "function",
7481
+ functionId: func.id,
7482
+ index
7506
7483
  };
7507
7484
  }).catch((e) => {
7508
- if (e instanceof FunctionError) {
7509
- const result = e.getFixingInstructions();
7510
- if (span) {
7511
- const errorEventData = {
7512
- name: func.name,
7513
- message: e.toString()
7514
- };
7515
- if (!excludeContentFromTelemetry) {
7516
- errorEventData.args = func.args;
7517
- errorEventData.fixing_instructions = result;
7518
- }
7519
- span.addEvent("function.error", errorEventData);
7485
+ if (!(e instanceof FunctionError)) {
7486
+ throw e;
7487
+ }
7488
+ const result = e.getFixingInstructions();
7489
+ if (span) {
7490
+ const errorEventData = {
7491
+ name: func.name,
7492
+ message: e.toString()
7493
+ };
7494
+ if (!excludeContentFromTrace) {
7495
+ errorEventData.args = func.args;
7496
+ errorEventData.fixing_instructions = result;
7520
7497
  }
7521
- mem.add(
7522
- {
7523
- role: "function",
7524
- functionId: func.id,
7525
- isError: true,
7526
- result
7527
- },
7528
- sessionId
7529
- );
7530
- mem.addTag("error");
7531
- if (ai.getOptions().debug) {
7532
- const logger = ai.getLogger();
7533
- logger(`\u274C Function Error Correction:
7498
+ span.addEvent("function.error", errorEventData);
7499
+ }
7500
+ if (ai.getOptions().debug) {
7501
+ const logger = ai.getLogger();
7502
+ logger(`\u274C Function Error Correction:
7534
7503
  ${result}`, {
7535
- tags: ["error"]
7536
- });
7537
- }
7538
- } else {
7539
- throw e;
7504
+ tags: ["error"]
7505
+ });
7540
7506
  }
7507
+ return {
7508
+ functionId: func.id,
7509
+ isError: true,
7510
+ index,
7511
+ result,
7512
+ role: "function"
7513
+ };
7541
7514
  });
7542
7515
  return promise;
7543
7516
  });
7544
7517
  const results = await Promise.all(promises);
7545
- for (const result of results) {
7546
- if (result) {
7547
- mem.add(result, sessionId);
7548
- }
7518
+ const functionResults = results.filter((result) => result !== void 0);
7519
+ mem.addFunctionResults(functionResults, sessionId);
7520
+ if (functionResults.some((result) => result.isError)) {
7521
+ mem.addTag("error", sessionId);
7549
7522
  }
7550
7523
  return functionsExecuted;
7551
7524
  };
@@ -7564,23 +7537,28 @@ function parseFunctionCalls(ai, functionCalls, values, model) {
7564
7537
  return funcs;
7565
7538
  }
7566
7539
 
7567
- // dsp/registry.ts
7568
- var AxInstanceRegistry = class {
7569
- reg;
7570
- // To track keys for iteration
7571
- constructor() {
7572
- this.reg = /* @__PURE__ */ new Set();
7573
- }
7574
- register(instance) {
7575
- this.reg.add(instance);
7576
- }
7577
- *[Symbol.iterator]() {
7578
- const items = Array.from(this.reg);
7579
- for (let i = 0; i < items.length; i++) {
7580
- yield items[i];
7540
+ // dsp/processResponse.ts
7541
+ import "stream/web";
7542
+
7543
+ // ai/util.ts
7544
+ function mergeFunctionCalls(functionCalls, functionCallDeltas) {
7545
+ for (const _fc of functionCallDeltas) {
7546
+ const fc = functionCalls.find((fc2) => fc2.id === _fc.id);
7547
+ if (fc) {
7548
+ if (typeof _fc.function.name == "string" && _fc.function.name.length > 0) {
7549
+ fc.function.name += _fc.function.name;
7550
+ }
7551
+ if (typeof _fc.function.params == "string" && _fc.function.params.length > 0) {
7552
+ fc.function.params += _fc.function.params;
7553
+ }
7554
+ if (typeof _fc.function.params == "object") {
7555
+ fc.function.params = _fc.function.params;
7556
+ }
7557
+ } else {
7558
+ functionCalls.push(_fc);
7581
7559
  }
7582
7560
  }
7583
- };
7561
+ }
7584
7562
 
7585
7563
  // dsp/sig.ts
7586
7564
  import { createHash } from "crypto";
@@ -8790,32 +8768,828 @@ function validateFieldType(field, context3) {
8790
8768
  );
8791
8769
  }
8792
8770
  }
8793
- const uniqueOptions = new Set(
8794
- type.options.map((opt) => opt.trim().toLowerCase())
8795
- );
8796
- if (uniqueOptions.size !== type.options.length) {
8797
- throw new AxSignatureValidationError(
8798
- "Duplicate class options found",
8799
- field.name,
8800
- "Each class option must be unique (case-insensitive)"
8801
- );
8771
+ const uniqueOptions = new Set(
8772
+ type.options.map((opt) => opt.trim().toLowerCase())
8773
+ );
8774
+ if (uniqueOptions.size !== type.options.length) {
8775
+ throw new AxSignatureValidationError(
8776
+ "Duplicate class options found",
8777
+ field.name,
8778
+ "Each class option must be unique (case-insensitive)"
8779
+ );
8780
+ }
8781
+ }
8782
+ if (type.name === "code" && type.isArray) {
8783
+ throw new AxSignatureValidationError(
8784
+ "Arrays of code are not commonly supported",
8785
+ field.name,
8786
+ "Consider using a single code field or an array of strings instead"
8787
+ );
8788
+ }
8789
+ if (field.isInternal && context3 === "input") {
8790
+ throw new AxSignatureValidationError(
8791
+ "Internal marker (!) is not allowed on input fields",
8792
+ field.name,
8793
+ "Internal markers are only allowed on output fields"
8794
+ );
8795
+ }
8796
+ }
8797
+
8798
+ // dsp/processResponse.ts
8799
+ async function* processStreamingResponse({
8800
+ res,
8801
+ usage,
8802
+ states,
8803
+ ...args
8804
+ }) {
8805
+ const skipEarlyFail = (args.ai.getFeatures().functionCot ?? false) && args.functions !== void 0 && args.functions.length > 0;
8806
+ for await (const v of res) {
8807
+ if (v.modelUsage) {
8808
+ usage.push(v.modelUsage);
8809
+ }
8810
+ for (const result of v.results) {
8811
+ if (result.content === "" && (!result.functionCalls || result.functionCalls.length === 0)) {
8812
+ continue;
8813
+ }
8814
+ const state = states.find((s2) => s2.index === result.index);
8815
+ if (!state) {
8816
+ throw new Error(`No state found for result (index: ${result.index})`);
8817
+ }
8818
+ yield* _processStreamingResponse({
8819
+ ...args,
8820
+ result,
8821
+ skipEarlyFail,
8822
+ state
8823
+ });
8824
+ }
8825
+ }
8826
+ for (const state of states) {
8827
+ yield* finalizeStreamingResponse({
8828
+ ...args,
8829
+ state
8830
+ });
8831
+ }
8832
+ }
8833
+ async function* _processStreamingResponse({
8834
+ result,
8835
+ mem,
8836
+ sessionId,
8837
+ strictMode,
8838
+ skipEarlyFail,
8839
+ state,
8840
+ signature,
8841
+ streamingFieldProcessors,
8842
+ thoughtFieldName,
8843
+ streamingAsserts,
8844
+ asserts
8845
+ }) {
8846
+ if (result.functionCalls && result.functionCalls.length > 0) {
8847
+ mergeFunctionCalls(state.functionCalls, result.functionCalls);
8848
+ mem.updateResult(
8849
+ {
8850
+ name: result.name,
8851
+ content: result.content,
8852
+ functionCalls: state.functionCalls,
8853
+ delta: result.functionCalls?.[0]?.function?.params,
8854
+ index: result.index
8855
+ },
8856
+ sessionId
8857
+ );
8858
+ } else if (result.content && result.content.length > 0) {
8859
+ if (result.thought && result.thought.length > 0) {
8860
+ yield {
8861
+ index: result.index,
8862
+ delta: { [thoughtFieldName]: result.thought }
8863
+ };
8864
+ }
8865
+ state.content += result.content;
8866
+ mem.updateResult(
8867
+ {
8868
+ name: result.name,
8869
+ content: state.content,
8870
+ delta: result.content,
8871
+ index: result.index
8872
+ },
8873
+ sessionId
8874
+ );
8875
+ const skip = streamingExtractValues(
8876
+ signature,
8877
+ state.values,
8878
+ state.xstate,
8879
+ state.content,
8880
+ { strictMode, skipEarlyFail }
8881
+ );
8882
+ if (skip) {
8883
+ return;
8884
+ }
8885
+ if (streamingAsserts.length !== 0) {
8886
+ await assertStreamingAssertions(
8887
+ streamingAsserts,
8888
+ state.xstate,
8889
+ state.content
8890
+ );
8891
+ }
8892
+ if (streamingFieldProcessors.length !== 0) {
8893
+ await processStreamingFieldProcessors(
8894
+ streamingFieldProcessors,
8895
+ state.content,
8896
+ state.xstate,
8897
+ mem,
8898
+ state.values,
8899
+ sessionId
8900
+ );
8901
+ }
8902
+ yield* streamValues(
8903
+ signature,
8904
+ state.content,
8905
+ state.values,
8906
+ state.xstate,
8907
+ result.index
8908
+ );
8909
+ await assertAssertions(asserts, state.values);
8910
+ } else if (result.thought && result.thought.length > 0) {
8911
+ state.values[thoughtFieldName] = (state.values[thoughtFieldName] ?? "") + result.thought;
8912
+ yield {
8913
+ index: result.index,
8914
+ delta: { [thoughtFieldName]: result.thought }
8915
+ };
8916
+ }
8917
+ if (result.finishReason === "length") {
8918
+ throw new Error(
8919
+ `Max tokens reached before completion
8920
+ Content: ${state.content}`
8921
+ );
8922
+ }
8923
+ }
8924
+ async function* finalizeStreamingResponse({
8925
+ state,
8926
+ signature,
8927
+ ai,
8928
+ model,
8929
+ functions,
8930
+ mem,
8931
+ sessionId,
8932
+ traceId,
8933
+ span,
8934
+ excludeContentFromTrace,
8935
+ streamingAsserts,
8936
+ asserts,
8937
+ fieldProcessors,
8938
+ streamingFieldProcessors
8939
+ }) {
8940
+ const funcs = parseFunctionCalls(ai, state.functionCalls, state.values, model);
8941
+ if (funcs) {
8942
+ if (!functions) {
8943
+ throw new Error("Functions are not defined");
8944
+ }
8945
+ const fx = await processFunctions({
8946
+ ai,
8947
+ functionList: functions,
8948
+ functionCalls: funcs,
8949
+ mem,
8950
+ sessionId,
8951
+ traceId,
8952
+ span,
8953
+ index: state.index,
8954
+ excludeContentFromTrace
8955
+ });
8956
+ state.functionsExecuted = /* @__PURE__ */ new Set([...state.functionsExecuted, ...fx]);
8957
+ } else {
8958
+ streamingExtractFinalValue(
8959
+ signature,
8960
+ state.values,
8961
+ state.xstate,
8962
+ state.content
8963
+ );
8964
+ await assertStreamingAssertions(
8965
+ streamingAsserts,
8966
+ state.xstate,
8967
+ state.content,
8968
+ true
8969
+ );
8970
+ await assertAssertions(asserts, state.values);
8971
+ if (fieldProcessors.length) {
8972
+ await processFieldProcessors(
8973
+ fieldProcessors,
8974
+ state.values,
8975
+ mem,
8976
+ sessionId
8977
+ );
8978
+ }
8979
+ if (streamingFieldProcessors.length !== 0) {
8980
+ await processStreamingFieldProcessors(
8981
+ streamingFieldProcessors,
8982
+ state.content,
8983
+ state.xstate,
8984
+ mem,
8985
+ state.values,
8986
+ sessionId,
8987
+ true
8988
+ );
8989
+ }
8990
+ yield* streamValues(
8991
+ signature,
8992
+ state.content,
8993
+ state.values,
8994
+ state.xstate,
8995
+ state.index
8996
+ );
8997
+ }
8998
+ }
8999
+ async function* processResponse({
9000
+ ai,
9001
+ res,
9002
+ mem,
9003
+ sessionId,
9004
+ traceId,
9005
+ functions,
9006
+ span,
9007
+ strictMode,
9008
+ states,
9009
+ usage,
9010
+ excludeContentFromTrace,
9011
+ asserts,
9012
+ fieldProcessors,
9013
+ thoughtFieldName,
9014
+ signature
9015
+ }) {
9016
+ let results = res.results ?? [];
9017
+ mem.addResponse(results, sessionId);
9018
+ for (const result of results) {
9019
+ const state = states[result.index];
9020
+ if (!state) {
9021
+ throw new Error(`No state found for result (index: ${result.index})`);
9022
+ }
9023
+ if (res.modelUsage) {
9024
+ usage.push(res.modelUsage);
9025
+ }
9026
+ if (result.functionCalls?.length) {
9027
+ const funcs = parseFunctionCalls(ai, result.functionCalls, state.values);
9028
+ if (funcs) {
9029
+ if (!functions) {
9030
+ throw new Error("Functions are not defined");
9031
+ }
9032
+ const fx = await processFunctions({
9033
+ ai,
9034
+ functionList: functions,
9035
+ functionCalls: funcs,
9036
+ mem,
9037
+ sessionId,
9038
+ traceId,
9039
+ span,
9040
+ excludeContentFromTrace,
9041
+ index: result.index
9042
+ });
9043
+ state.functionsExecuted = /* @__PURE__ */ new Set([...state.functionsExecuted, ...fx]);
9044
+ }
9045
+ } else if (result.content) {
9046
+ if (result.thought && result.thought.length > 0) {
9047
+ state.values[thoughtFieldName] = result.thought;
9048
+ }
9049
+ extractValues(signature, state.values, result.content, strictMode);
9050
+ await assertAssertions(asserts, state.values);
9051
+ if (fieldProcessors.length) {
9052
+ await processFieldProcessors(
9053
+ fieldProcessors,
9054
+ state.values,
9055
+ mem,
9056
+ sessionId
9057
+ );
9058
+ }
9059
+ }
9060
+ if (result.finishReason === "length") {
9061
+ throw new Error(
9062
+ `Max tokens reached before completion
9063
+ Content: ${result.content}`
9064
+ );
9065
+ }
9066
+ }
9067
+ const values = states.map((s2) => s2.values);
9068
+ for (const v of values) {
9069
+ for (const field of signature.getOutputFields()) {
9070
+ if (field.isInternal) {
9071
+ delete v[field.name];
9072
+ }
9073
+ }
9074
+ }
9075
+ const outputFields = signature.getOutputFields();
9076
+ const deltas = values.map((v, index) => {
9077
+ const delta = {};
9078
+ for (const field of outputFields) {
9079
+ if (field.isInternal) {
9080
+ continue;
9081
+ }
9082
+ delta[field.name] = v[field.name];
9083
+ }
9084
+ if (v[thoughtFieldName] !== void 0) {
9085
+ delta[thoughtFieldName] = v[thoughtFieldName];
9086
+ }
9087
+ return { index, delta };
9088
+ });
9089
+ for (const delta of deltas) {
9090
+ yield delta;
9091
+ }
9092
+ }
9093
+ function shouldContinueSteps(mem, stopFunction, states, sessionId) {
9094
+ const lastMemItem = mem.getLast(sessionId);
9095
+ if (!lastMemItem) {
9096
+ return true;
9097
+ }
9098
+ for (const [index, state] of states.entries()) {
9099
+ const stopFunctionExecuted = stopFunction && state.functionsExecuted.has(stopFunction);
9100
+ const chat = lastMemItem.chat[index];
9101
+ if (!chat) {
9102
+ throw new Error(`No chat message found for result (index: ${index})`);
9103
+ }
9104
+ const isFunction = lastMemItem.role === "function";
9105
+ const isProcessor = lastMemItem.tags ? lastMemItem.tags.some((tag) => tag === "processor") : false;
9106
+ if (isFunction && stopFunction && stopFunctionExecuted) {
9107
+ return false;
9108
+ }
9109
+ if (!(isFunction || isProcessor)) {
9110
+ return false;
9111
+ }
9112
+ }
9113
+ return true;
9114
+ }
9115
+
9116
+ // dsp/prompt.ts
9117
+ var functionCallInstructions = `
9118
+ ## Function Call Instructions
9119
+ - Complete the task, using the functions defined earlier in this prompt.
9120
+ - Output fields should only be generated after all functions have been called.
9121
+ - Use the function results to generate the output fields.`;
9122
+ var formattingRules = `
9123
+ ## Strict Output Formatting Rules
9124
+ - Output must strictly follow the defined plain-text \`field name: value\` field format.
9125
+ - Output field, values must strictly adhere to the specified output field formatting rules.
9126
+ - No formatting rules should override these **Strict Output Formatting Rules**
9127
+ - Do not add any text before or after the output fields, just the field name and value.
9128
+ - Do not use code blocks.`;
9129
+ var AxPromptTemplate = class {
9130
+ sig;
9131
+ fieldTemplates;
9132
+ task;
9133
+ thoughtFieldName;
9134
+ functions;
9135
+ constructor(sig, options, fieldTemplates) {
9136
+ this.sig = sig;
9137
+ this.fieldTemplates = fieldTemplates;
9138
+ this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
9139
+ this.functions = options?.functions;
9140
+ const task = [];
9141
+ const inArgs = renderDescFields(this.sig.getInputFields());
9142
+ const outArgs = renderDescFields(this.sig.getOutputFields());
9143
+ task.push(
9144
+ `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
9145
+ );
9146
+ const funcs = this.functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
9147
+ const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
9148
+ if (funcList && funcList.length > 0) {
9149
+ task.push(`## Available Functions
9150
+ ${funcList}`);
9151
+ }
9152
+ const inputFields = renderInputFields(this.sig.getInputFields());
9153
+ task.push(`## Input Fields
9154
+ ${inputFields}`);
9155
+ const outputFields = renderOutputFields(this.sig.getOutputFields());
9156
+ task.push(`## Output Fields
9157
+ ${outputFields}`);
9158
+ if (funcList && funcList.length > 0) {
9159
+ task.push(functionCallInstructions.trim());
9160
+ }
9161
+ task.push(formattingRules.trim());
9162
+ const desc = this.sig.getDescription();
9163
+ if (desc) {
9164
+ const text = formatDescription(desc);
9165
+ task.push(text);
9166
+ }
9167
+ this.task = {
9168
+ type: "text",
9169
+ text: task.join("\n\n")
9170
+ };
9171
+ }
9172
+ renderSingleValueUserContent = (values, renderedExamples, renderedDemos, examplesInSystemPrompt) => {
9173
+ const completion = this.renderInputFields(values);
9174
+ const promptList = examplesInSystemPrompt ? completion : [...renderedExamples, ...renderedDemos, ...completion];
9175
+ const prompt = promptList.filter((v) => v !== void 0);
9176
+ return prompt.every((v) => v.type === "text") ? prompt.map((v) => v.text).join("\n") : prompt.reduce(combineConsecutiveStrings("\n"), []);
9177
+ };
9178
+ render = (values, {
9179
+ examples,
9180
+ demos
9181
+ }) => {
9182
+ const renderedExamples = examples ? [
9183
+ { type: "text", text: "\n\n## Examples\n" },
9184
+ ...this.renderExamples(examples)
9185
+ ] : [];
9186
+ const renderedDemos = demos ? this.renderDemos(demos) : [];
9187
+ const allTextExamples = renderedExamples.every((v) => v.type === "text");
9188
+ const allTextDemos = renderedDemos.every((v) => v.type === "text");
9189
+ const examplesInSystemPrompt = allTextExamples && allTextDemos;
9190
+ let systemContent = this.task.text;
9191
+ if (examplesInSystemPrompt) {
9192
+ const combinedItems = [
9193
+ { type: "text", text: systemContent },
9194
+ ...renderedExamples,
9195
+ ...renderedDemos
9196
+ ];
9197
+ combinedItems.reduce(combineConsecutiveStrings(""), []);
9198
+ if (combinedItems && combinedItems[0]) {
9199
+ systemContent = combinedItems[0].text;
9200
+ }
9201
+ }
9202
+ const systemPrompt = {
9203
+ role: "system",
9204
+ content: systemContent
9205
+ };
9206
+ if (Array.isArray(values)) {
9207
+ let messages = [];
9208
+ const history = values;
9209
+ let firstItem = true;
9210
+ for (const message of history) {
9211
+ let content;
9212
+ if (firstItem) {
9213
+ content = this.renderSingleValueUserContent(
9214
+ message.values,
9215
+ renderedExamples,
9216
+ renderedDemos,
9217
+ examplesInSystemPrompt
9218
+ );
9219
+ firstItem = false;
9220
+ } else {
9221
+ content = this.renderSingleValueUserContent(
9222
+ message.values,
9223
+ [],
9224
+ [],
9225
+ false
9226
+ );
9227
+ }
9228
+ if (message.role === "user") {
9229
+ messages.push({ role: "user", content });
9230
+ continue;
9231
+ }
9232
+ if (message.role !== "assistant") {
9233
+ throw new Error("Invalid message role");
9234
+ }
9235
+ if (typeof content !== "string") {
9236
+ throw new Error(
9237
+ "Assistant message cannot contain non-text content like images, files,etc"
9238
+ );
9239
+ }
9240
+ messages.push({ role: "assistant", content });
9241
+ }
9242
+ return [systemPrompt, ...messages];
9243
+ }
9244
+ const userContent = this.renderSingleValueUserContent(
9245
+ values,
9246
+ renderedExamples,
9247
+ renderedDemos,
9248
+ examplesInSystemPrompt
9249
+ );
9250
+ return [systemPrompt, { role: "user", content: userContent }];
9251
+ };
9252
+ renderExtraFields = (extraFields) => {
9253
+ const prompt = [];
9254
+ if (!extraFields || extraFields.length === 0) {
9255
+ return prompt;
9256
+ }
9257
+ const groupedFields = extraFields.reduce(
9258
+ (acc, field) => {
9259
+ const title = field.title;
9260
+ if (!acc[title]) {
9261
+ acc[title] = [];
9262
+ }
9263
+ acc[title].push(field);
9264
+ return acc;
9265
+ },
9266
+ {}
9267
+ );
9268
+ const formattedGroupedFields = Object.entries(groupedFields).map(([title, fields]) => {
9269
+ if (fields.length === 1) {
9270
+ const field = fields[0];
9271
+ return {
9272
+ title,
9273
+ name: field.name,
9274
+ description: field.description
9275
+ };
9276
+ } else if (fields.length > 1) {
9277
+ const valuesList = fields.map((field) => `- ${field.description}`).join("\n");
9278
+ return {
9279
+ title,
9280
+ name: fields[0].name,
9281
+ description: valuesList
9282
+ };
9283
+ }
9284
+ }).filter(Boolean);
9285
+ formattedGroupedFields.forEach((field) => {
9286
+ const fn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
9287
+ prompt.push(...fn(field, field.description));
9288
+ });
9289
+ return prompt;
9290
+ };
9291
+ renderExamples = (data) => {
9292
+ const list = [];
9293
+ const exampleContext = {
9294
+ isExample: true
9295
+ };
9296
+ for (const [index, item] of data.entries()) {
9297
+ const renderedInputItem = this.sig.getInputFields().map(
9298
+ (field) => this.renderInField(field, item, {
9299
+ ...exampleContext,
9300
+ isInputField: true
9301
+ })
9302
+ ).filter((v) => v !== void 0).flat();
9303
+ const renderedOutputItem = this.sig.getOutputFields().map(
9304
+ (field) => this.renderInField(field, item, {
9305
+ ...exampleContext,
9306
+ isInputField: false
9307
+ })
9308
+ ).filter((v) => v !== void 0).flat();
9309
+ const renderedItem = [...renderedInputItem, ...renderedOutputItem];
9310
+ if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
9311
+ list.push({ type: "text", text: "---\n\n" });
9312
+ }
9313
+ renderedItem.forEach((v) => {
9314
+ if ("text" in v) {
9315
+ v.text = v.text + "\n";
9316
+ }
9317
+ list.push(v);
9318
+ });
9319
+ }
9320
+ return list;
9321
+ };
9322
+ renderDemos = (data) => {
9323
+ const list = [];
9324
+ const inputFields = this.sig.getInputFields();
9325
+ const outputFields = this.sig.getOutputFields();
9326
+ const demoContext = {
9327
+ isExample: true
9328
+ };
9329
+ for (const item of data) {
9330
+ const inputRenderedItems = inputFields.map(
9331
+ (field) => this.renderInField(field, item, {
9332
+ ...demoContext,
9333
+ isInputField: true
9334
+ })
9335
+ ).filter((v) => v !== void 0).flat();
9336
+ const outputRenderedItems = outputFields.map(
9337
+ (field) => this.renderInField(field, item, {
9338
+ ...demoContext,
9339
+ isInputField: false
9340
+ })
9341
+ ).filter((v) => v !== void 0).flat();
9342
+ const renderedItem = [...inputRenderedItems, ...outputRenderedItems];
9343
+ renderedItem.slice(0, -1).forEach((v) => {
9344
+ if ("text" in v) {
9345
+ v.text = v.text + "\n";
9346
+ }
9347
+ list.push(v);
9348
+ });
9349
+ }
9350
+ return list;
9351
+ };
9352
+ renderInputFields = (values) => {
9353
+ const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values, void 0)).filter((v) => v !== void 0).flat();
9354
+ renderedItems.filter((v) => v.type === "text").forEach((v) => {
9355
+ v.text = v.text + "\n";
9356
+ });
9357
+ return renderedItems;
9358
+ };
9359
+ renderInField = (field, values, context3) => {
9360
+ const value = values[field.name];
9361
+ if (isEmptyValue(field, value, context3)) {
9362
+ return;
9363
+ }
9364
+ if (field.type) {
9365
+ validateValue(field, value);
9366
+ }
9367
+ const processedValue = processValue(field, value);
9368
+ const textFieldFn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
9369
+ return textFieldFn(field, processedValue);
9370
+ };
9371
+ defaultRenderInField = (field, value) => {
9372
+ if (field.type?.name === "image") {
9373
+ const validateImage = (value2) => {
9374
+ if (!value2) {
9375
+ throw new Error("Image field value is required.");
9376
+ }
9377
+ if (typeof value2 !== "object") {
9378
+ throw new Error("Image field value must be an object.");
9379
+ }
9380
+ if (!("mimeType" in value2)) {
9381
+ throw new Error("Image field must have mimeType");
9382
+ }
9383
+ if (!("data" in value2)) {
9384
+ throw new Error("Image field must have data");
9385
+ }
9386
+ return value2;
9387
+ };
9388
+ let result = [
9389
+ { type: "text", text: `${field.title}: ` }
9390
+ ];
9391
+ if (field.type.isArray) {
9392
+ if (!Array.isArray(value)) {
9393
+ throw new Error("Image field value must be an array.");
9394
+ }
9395
+ result = result.concat(
9396
+ value.map((v) => {
9397
+ const validated = validateImage(v);
9398
+ return {
9399
+ type: "image",
9400
+ mimeType: validated.mimeType,
9401
+ image: validated.data
9402
+ };
9403
+ })
9404
+ );
9405
+ } else {
9406
+ const validated = validateImage(value);
9407
+ result.push({
9408
+ type: "image",
9409
+ mimeType: validated.mimeType,
9410
+ image: validated.data
9411
+ });
9412
+ }
9413
+ return result;
9414
+ }
9415
+ if (field.type?.name === "audio") {
9416
+ const validateAudio = (value2) => {
9417
+ if (!value2) {
9418
+ throw new Error("Audio field value is required.");
9419
+ }
9420
+ if (typeof value2 !== "object") {
9421
+ throw new Error("Audio field value must be an object.");
9422
+ }
9423
+ if (!("data" in value2)) {
9424
+ throw new Error("Audio field must have data");
9425
+ }
9426
+ return value2;
9427
+ };
9428
+ let result = [
9429
+ { type: "text", text: `${field.title}: ` }
9430
+ ];
9431
+ if (field.type.isArray) {
9432
+ if (!Array.isArray(value)) {
9433
+ throw new Error("Audio field value must be an array.");
9434
+ }
9435
+ result = result.concat(
9436
+ value.map((v) => {
9437
+ const validated = validateAudio(v);
9438
+ return {
9439
+ type: "audio",
9440
+ format: validated.format ?? "wav",
9441
+ data: validated.data
9442
+ };
9443
+ })
9444
+ );
9445
+ } else {
9446
+ const validated = validateAudio(value);
9447
+ result.push({
9448
+ type: "audio",
9449
+ format: validated.format ?? "wav",
9450
+ data: validated.data
9451
+ });
9452
+ }
9453
+ return result;
9454
+ }
9455
+ const text = [field.title, ": "];
9456
+ if (Array.isArray(value)) {
9457
+ text.push("\n");
9458
+ text.push(value.map((v) => `- ${v}`).join("\n"));
9459
+ } else {
9460
+ text.push(value);
9461
+ }
9462
+ return [{ type: "text", text: text.join("") }];
9463
+ };
9464
+ };
9465
+ var renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
9466
+ var renderInputFields = (fields) => {
9467
+ const rows = fields.map((field) => {
9468
+ const name = field.title;
9469
+ const type = field.type?.name ? toFieldType(field.type) : "string";
9470
+ const requiredMsg = field.isOptional ? `This optional ${type} field may be omitted` : `A ${type} field`;
9471
+ const description = field.description ? ` ${formatDescription(field.description)}` : "";
9472
+ return `${name}: (${requiredMsg})${description}`.trim();
9473
+ });
9474
+ return rows.join("\n");
9475
+ };
9476
+ var renderOutputFields = (fields) => {
9477
+ const rows = fields.map((field) => {
9478
+ const name = field.title;
9479
+ const type = field.type?.name ? toFieldType(field.type) : "string";
9480
+ const requiredMsg = field.isOptional ? `Only include this ${type} field if its value is available` : `This ${type} field must be included`;
9481
+ let description = "";
9482
+ if (field.description && field.description.length > 0) {
9483
+ const value = field.type?.name === "class" ? field.description : formatDescription(field.description);
9484
+ description = ` ${value}`;
9485
+ }
9486
+ if (field.type?.options && field.type.options.length > 0) {
9487
+ if (description.length > 0) {
9488
+ description += `. `;
9489
+ }
9490
+ description += `Allowed values: ${field.type.options.join(", ")}`;
9491
+ }
9492
+ return `${name}: (${requiredMsg})${description}`.trim();
9493
+ });
9494
+ return rows.join("\n");
9495
+ };
9496
+ var processValue = (field, value) => {
9497
+ if (field.type?.name === "date" && value instanceof Date) {
9498
+ const v = value.toISOString();
9499
+ return v.slice(0, v.indexOf("T"));
9500
+ }
9501
+ if (field.type?.name === "datetime" && value instanceof Date) {
9502
+ return formatDateWithTimezone(value);
9503
+ }
9504
+ if (field.type?.name === "image" && typeof value === "object") {
9505
+ return value;
9506
+ }
9507
+ if (field.type?.name === "audio" && typeof value === "object") {
9508
+ return value;
9509
+ }
9510
+ if (typeof value === "string") {
9511
+ return value;
9512
+ }
9513
+ return JSON.stringify(value, null, 2);
9514
+ };
9515
+ var toFieldType = (type) => {
9516
+ const baseType = (() => {
9517
+ switch (type?.name) {
9518
+ case "string":
9519
+ return "string";
9520
+ case "number":
9521
+ return "number";
9522
+ case "boolean":
9523
+ return "boolean";
9524
+ case "date":
9525
+ return 'date ("YYYY-MM-DD" format)';
9526
+ case "datetime":
9527
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
9528
+ case "json":
9529
+ return "JSON object";
9530
+ case "class":
9531
+ return "classification class";
9532
+ case "code":
9533
+ return "code";
9534
+ default:
9535
+ return "string";
9536
+ }
9537
+ })();
9538
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
9539
+ };
9540
+ function combineConsecutiveStrings(separator) {
9541
+ return (acc, current) => {
9542
+ if (current.type === "text") {
9543
+ const previous = acc.length > 0 ? acc[acc.length - 1] : null;
9544
+ if (previous && previous.type === "text") {
9545
+ previous.text += separator + current.text;
9546
+ } else {
9547
+ acc.push(current);
9548
+ }
9549
+ } else {
9550
+ acc.push(current);
9551
+ }
9552
+ return acc;
9553
+ };
9554
+ }
9555
+ var isEmptyValue = (field, value, context3) => {
9556
+ if (typeof value === "boolean") {
9557
+ return false;
9558
+ }
9559
+ if (!value || (Array.isArray(value) || typeof value === "string") && value.length === 0) {
9560
+ if (context3?.isExample) {
9561
+ return true;
8802
9562
  }
9563
+ if (field.isOptional || field.isInternal) {
9564
+ return true;
9565
+ }
9566
+ const fieldType = context3?.isInputField !== false ? "input" : "output";
9567
+ throw new Error(`Value for ${fieldType} field '${field.name}' is required.`);
8803
9568
  }
8804
- if (type.name === "code" && type.isArray) {
8805
- throw new AxSignatureValidationError(
8806
- "Arrays of code are not commonly supported",
8807
- field.name,
8808
- "Consider using a single code field or an array of strings instead"
8809
- );
9569
+ return false;
9570
+ };
9571
+ function formatDescription(str) {
9572
+ const value = str.trim();
9573
+ return value.length > 0 ? `${value.charAt(0).toUpperCase()}${value.slice(1)}${value.endsWith(".") ? "" : "."}` : "";
9574
+ }
9575
+
9576
+ // dsp/registry.ts
9577
+ var AxInstanceRegistry = class {
9578
+ reg;
9579
+ // To track keys for iteration
9580
+ constructor() {
9581
+ this.reg = /* @__PURE__ */ new Set();
8810
9582
  }
8811
- if (field.isInternal && context3 === "input") {
8812
- throw new AxSignatureValidationError(
8813
- "Internal marker (!) is not allowed on input fields",
8814
- field.name,
8815
- "Internal markers are only allowed on output fields"
8816
- );
9583
+ register(instance) {
9584
+ this.reg.add(instance);
8817
9585
  }
8818
- }
9586
+ *[Symbol.iterator]() {
9587
+ const items = Array.from(this.reg);
9588
+ for (let i = 0; i < items.length; i++) {
9589
+ yield items[i];
9590
+ }
9591
+ }
9592
+ };
8819
9593
 
8820
9594
  // dsp/program.ts
8821
9595
  var AxProgramWithSignature = class {
@@ -9018,6 +9792,118 @@ var AxProgram = class {
9018
9792
  }
9019
9793
  };
9020
9794
 
9795
+ // dsp/samples.ts
9796
+ function checkForFunctionCalls(mem, sessionId) {
9797
+ const history = mem.history(0, sessionId);
9798
+ const hasFunctionResults = history.some((msg) => msg.role === "function");
9799
+ const hasFunctionCalls = history.some(
9800
+ (msg) => msg.role === "assistant" && "functionCalls" in msg && Array.isArray(msg.functionCalls) && msg.functionCalls.length > 0
9801
+ );
9802
+ return hasFunctionCalls && hasFunctionResults;
9803
+ }
9804
+ function extractFunctionResults(mem, sessionId) {
9805
+ const history = mem.history(0, sessionId);
9806
+ const results = [];
9807
+ const assistantMessages = history.filter(
9808
+ (msg) => msg.role === "assistant" && "functionCalls" in msg && Array.isArray(msg.functionCalls) && msg.functionCalls.length > 0
9809
+ );
9810
+ const functionMessages = history.filter((msg) => msg.role === "function");
9811
+ for (const assistantMsg of assistantMessages) {
9812
+ if ("functionCalls" in assistantMsg && assistantMsg.functionCalls) {
9813
+ for (const funcCall of assistantMsg.functionCalls) {
9814
+ const funcResult = functionMessages.find(
9815
+ (msg) => "functionId" in msg && msg.functionId === funcCall.id
9816
+ );
9817
+ if (funcResult && "result" in funcResult && "functionId" in funcResult) {
9818
+ results.push({
9819
+ index: results.length,
9820
+ // Use sequential index for function results
9821
+ functionName: funcCall.function.name,
9822
+ functionId: funcCall.id,
9823
+ args: funcCall.function.params || "",
9824
+ result: String(funcResult.result),
9825
+ isError: "isError" in funcResult ? Boolean(funcResult.isError) : false
9826
+ });
9827
+ }
9828
+ }
9829
+ }
9830
+ }
9831
+ return results;
9832
+ }
9833
+ async function selectFromSamples(buffer, options, mem, sessionId) {
9834
+ if (!options?.resultPicker || buffer.length <= 1) {
9835
+ return 0;
9836
+ }
9837
+ const resultPicker = options.resultPicker;
9838
+ const hasFunctionCalls = mem ? checkForFunctionCalls(mem, sessionId) : false;
9839
+ if (hasFunctionCalls && mem) {
9840
+ const functionResults = extractFunctionResults(mem, sessionId);
9841
+ const selectedIndex = await resultPicker({
9842
+ type: "function",
9843
+ results: functionResults
9844
+ });
9845
+ if (selectedIndex < 0 || selectedIndex >= functionResults.length) {
9846
+ throw new Error(
9847
+ `Result picker returned invalid index: ${selectedIndex}. Must be between 0 and ${functionResults.length - 1}`
9848
+ );
9849
+ }
9850
+ return selectedIndex;
9851
+ } else {
9852
+ const fieldResults = buffer.map((b, index) => ({
9853
+ index,
9854
+ sample: b.delta
9855
+ }));
9856
+ const selectedIndex = await resultPicker({
9857
+ type: "fields",
9858
+ results: fieldResults
9859
+ });
9860
+ if (selectedIndex < 0 || selectedIndex >= buffer.length) {
9861
+ throw new Error(
9862
+ `Result picker returned invalid index: ${selectedIndex}. Must be between 0 and ${buffer.length - 1}`
9863
+ );
9864
+ }
9865
+ return selectedIndex;
9866
+ }
9867
+ }
9868
+ async function selectFromSamplesInMemory(mem, sessionId, options) {
9869
+ const lastMemory = mem?.getLast(sessionId);
9870
+ if (!lastMemory || lastMemory.role !== "assistant") {
9871
+ return 0;
9872
+ }
9873
+ if (lastMemory.chat.length <= 1) {
9874
+ return 0;
9875
+ }
9876
+ const buffer = lastMemory.chat.map((chat) => ({
9877
+ version: 0,
9878
+ index: chat.index,
9879
+ delta: chat.value
9880
+ }));
9881
+ const selectedIndex = await selectFromSamples(buffer, options, mem, sessionId);
9882
+ return selectedIndex;
9883
+ }
9884
+
9885
+ // dsp/validate.ts
9886
+ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId) {
9887
+ mem.addRequest(
9888
+ [
9889
+ {
9890
+ role: "user",
9891
+ content: promptTemplate.renderExtraFields(errorFields)
9892
+ }
9893
+ ],
9894
+ sessionId
9895
+ );
9896
+ mem.addTag("error", sessionId);
9897
+ if (ai.getOptions().debug) {
9898
+ const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
9899
+ const logger = ai.getLogger();
9900
+ logger(`\u274C Error Correction:
9901
+ ${errors}`, {
9902
+ tags: ["error"]
9903
+ });
9904
+ }
9905
+ }
9906
+
9021
9907
  // dsp/generate.ts
9022
9908
  var AxGen = class extends AxProgramWithSignature {
9023
9909
  promptTemplate;
@@ -9025,10 +9911,8 @@ var AxGen = class extends AxProgramWithSignature {
9025
9911
  streamingAsserts;
9026
9912
  options;
9027
9913
  functions;
9028
- functionsExecuted = /* @__PURE__ */ new Set();
9029
9914
  fieldProcessors = [];
9030
9915
  streamingFieldProcessors = [];
9031
- values = {};
9032
9916
  excludeContentFromTrace = false;
9033
9917
  thoughtFieldName;
9034
9918
  constructor(signature, options) {
@@ -9051,6 +9935,20 @@ var AxGen = class extends AxProgramWithSignature {
9051
9935
  this.functions = parseFunctions(options.functions);
9052
9936
  }
9053
9937
  }
9938
+ createStates(n) {
9939
+ return Array.from({ length: n }, (_, index) => ({
9940
+ index,
9941
+ functionCalls: [],
9942
+ values: {},
9943
+ content: "",
9944
+ functionsExecuted: /* @__PURE__ */ new Set(),
9945
+ xstate: {
9946
+ extractedFields: [],
9947
+ streamedIndex: {},
9948
+ s: -1
9949
+ }
9950
+ }));
9951
+ }
9054
9952
  addAssert = (fn, message) => {
9055
9953
  this.asserts.push({ fn, message });
9056
9954
  };
@@ -9091,7 +9989,6 @@ var AxGen = class extends AxProgramWithSignature {
9091
9989
  const {
9092
9990
  sessionId,
9093
9991
  traceId,
9094
- modelConfig,
9095
9992
  model,
9096
9993
  rateLimiter,
9097
9994
  stream,
@@ -9100,7 +9997,10 @@ var AxGen = class extends AxProgramWithSignature {
9100
9997
  thinkingTokenBudget,
9101
9998
  showThoughts
9102
9999
  } = options ?? {};
9103
- const chatPrompt = mem?.history(sessionId) ?? [];
10000
+ const selectedIndex = await selectFromSamplesInMemory(mem, sessionId, {
10001
+ resultPicker: options?.resultPicker
10002
+ });
10003
+ const chatPrompt = mem?.history(selectedIndex, sessionId) ?? [];
9104
10004
  if (chatPrompt.length === 0) {
9105
10005
  throw new Error("No chat prompt found");
9106
10006
  }
@@ -9109,6 +10009,11 @@ var AxGen = class extends AxProgramWithSignature {
9109
10009
  if (!firstStep && (functionCall === "required" || typeof functionCall === "function")) {
9110
10010
  functionCall = void 0;
9111
10011
  }
10012
+ const modelConfig = {
10013
+ ...options?.modelConfig,
10014
+ ...options?.sampleCount ? { n: options.sampleCount } : {},
10015
+ ...options?.sampleCount && options?.modelConfig?.temperature == 1 ? { temperature: 0.8 } : {}
10016
+ };
9112
10017
  const res = await ai.chat(
9113
10018
  {
9114
10019
  chatPrompt,
@@ -9143,7 +10048,9 @@ var AxGen = class extends AxProgramWithSignature {
9143
10048
  const { sessionId, traceId, functions: _functions } = options ?? {};
9144
10049
  const strictMode = options?.strictMode ?? false;
9145
10050
  const model = options.model;
9146
- const functions = _functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
10051
+ const states = this.createStates(options.sampleCount ?? 1);
10052
+ const usage = this.usage;
10053
+ const functions = _functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat() ?? [];
9147
10054
  const res = await this.forwardSendRequest({
9148
10055
  ai,
9149
10056
  mem,
@@ -9151,8 +10058,8 @@ var AxGen = class extends AxProgramWithSignature {
9151
10058
  traceContext,
9152
10059
  firstStep
9153
10060
  });
9154
- if (res instanceof ReadableStream2) {
9155
- yield* this.processStreamingResponse({
10061
+ if (res instanceof ReadableStream3) {
10062
+ yield* processStreamingResponse({
9156
10063
  ai,
9157
10064
  model,
9158
10065
  res,
@@ -9161,11 +10068,20 @@ var AxGen = class extends AxProgramWithSignature {
9161
10068
  sessionId,
9162
10069
  functions,
9163
10070
  strictMode,
9164
- span
10071
+ span,
10072
+ states,
10073
+ usage,
10074
+ asserts: this.asserts,
10075
+ streamingAsserts: this.streamingAsserts,
10076
+ fieldProcessors: this.fieldProcessors,
10077
+ streamingFieldProcessors: this.streamingFieldProcessors,
10078
+ thoughtFieldName: this.thoughtFieldName,
10079
+ excludeContentFromTrace: this.excludeContentFromTrace,
10080
+ signature: this.signature
9165
10081
  });
9166
10082
  this.getLogger(ai, options)?.("", { tags: ["responseEnd"] });
9167
10083
  } else {
9168
- yield await this.processResponse({
10084
+ yield* processResponse({
9169
10085
  ai,
9170
10086
  model,
9171
10087
  res,
@@ -9174,233 +10090,18 @@ var AxGen = class extends AxProgramWithSignature {
9174
10090
  sessionId,
9175
10091
  functions,
9176
10092
  span,
9177
- strictMode
10093
+ strictMode,
10094
+ states,
10095
+ usage,
10096
+ asserts: this.asserts,
10097
+ fieldProcessors: this.fieldProcessors,
10098
+ thoughtFieldName: this.thoughtFieldName,
10099
+ excludeContentFromTrace: this.excludeContentFromTrace,
10100
+ signature: this.signature
9178
10101
  });
9179
10102
  }
9180
10103
  }
9181
- async *processStreamingResponse({
9182
- ai,
9183
- model,
9184
- res,
9185
- mem,
9186
- sessionId,
9187
- traceId,
9188
- functions,
9189
- strictMode,
9190
- span
9191
- }) {
9192
- const functionCalls = [];
9193
- this.values = {};
9194
- const xstate = {
9195
- extractedFields: [],
9196
- streamedIndex: {},
9197
- s: -1
9198
- };
9199
- let content = "";
9200
- mem.addResult(
9201
- {
9202
- content: "",
9203
- functionCalls: []
9204
- },
9205
- sessionId
9206
- );
9207
- for await (const v of res) {
9208
- const result = v.results[0];
9209
- if (!result) {
9210
- continue;
9211
- }
9212
- if (v.modelUsage) {
9213
- this.usage.push(v.modelUsage);
9214
- }
9215
- if (result.functionCalls && result.functionCalls.length > 0) {
9216
- mergeFunctionCalls(functionCalls, result.functionCalls);
9217
- mem.updateResult(
9218
- {
9219
- name: result.name,
9220
- content,
9221
- functionCalls,
9222
- delta: result.functionCalls?.[0]?.function?.params
9223
- },
9224
- sessionId
9225
- );
9226
- } else if (result.content && result.content.length > 0) {
9227
- if (result.thought && result.thought.length > 0) {
9228
- yield {
9229
- [this.thoughtFieldName]: result.thought
9230
- };
9231
- }
9232
- content += result.content;
9233
- mem.updateResult(
9234
- { name: result.name, content, delta: result.content },
9235
- sessionId
9236
- );
9237
- const skip = streamingExtractValues(
9238
- this.signature,
9239
- this.values,
9240
- xstate,
9241
- content,
9242
- strictMode
9243
- );
9244
- if (skip) {
9245
- continue;
9246
- }
9247
- if (this.streamingAsserts.length !== 0) {
9248
- await assertStreamingAssertions(
9249
- this.streamingAsserts,
9250
- xstate,
9251
- content
9252
- );
9253
- }
9254
- if (this.streamingFieldProcessors.length !== 0) {
9255
- await processStreamingFieldProcessors(
9256
- this.streamingFieldProcessors,
9257
- content,
9258
- xstate,
9259
- mem,
9260
- this.values,
9261
- sessionId
9262
- );
9263
- }
9264
- yield* streamValues(
9265
- this.signature,
9266
- content,
9267
- this.values,
9268
- xstate
9269
- );
9270
- await assertAssertions(this.asserts, this.values);
9271
- } else if (result.thought && result.thought.length > 0) {
9272
- this.values[this.thoughtFieldName] = (this.values[this.thoughtFieldName] ?? "") + result.thought;
9273
- yield {
9274
- [this.thoughtFieldName]: result.thought
9275
- };
9276
- }
9277
- if (result.finishReason === "length") {
9278
- throw new Error(
9279
- `Max tokens reached before completion
9280
- Content: ${content}`
9281
- );
9282
- }
9283
- }
9284
- const funcs = parseFunctionCalls(ai, functionCalls, this.values, model);
9285
- if (funcs) {
9286
- if (!functions) {
9287
- throw new Error("Functions are not defined");
9288
- }
9289
- const fx = await processFunctions(
9290
- ai,
9291
- functions,
9292
- funcs,
9293
- mem,
9294
- sessionId,
9295
- traceId,
9296
- span,
9297
- this.excludeContentFromTrace
9298
- );
9299
- this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
9300
- } else {
9301
- streamingExtractFinalValue(this.signature, this.values, xstate, content);
9302
- await assertStreamingAssertions(
9303
- this.streamingAsserts,
9304
- xstate,
9305
- content,
9306
- true
9307
- );
9308
- await assertAssertions(this.asserts, this.values);
9309
- if (this.fieldProcessors.length) {
9310
- await processFieldProcessors(
9311
- this.fieldProcessors,
9312
- this.values,
9313
- mem,
9314
- sessionId
9315
- );
9316
- }
9317
- if (this.streamingFieldProcessors.length !== 0) {
9318
- await processStreamingFieldProcessors(
9319
- this.streamingFieldProcessors,
9320
- content,
9321
- xstate,
9322
- mem,
9323
- this.values,
9324
- sessionId,
9325
- true
9326
- );
9327
- }
9328
- yield* streamValues(
9329
- this.signature,
9330
- content,
9331
- this.values,
9332
- xstate
9333
- );
9334
- }
9335
- }
9336
- async processResponse({
9337
- ai,
9338
- res,
9339
- mem,
9340
- sessionId,
9341
- traceId,
9342
- functions,
9343
- span,
9344
- strictMode
9345
- }) {
9346
- this.values = {};
9347
- let results = res.results ?? [];
9348
- if (results.length > 1) {
9349
- results = results.filter((r) => r.functionCalls);
9350
- }
9351
- for (const result of results) {
9352
- if (res.modelUsage) {
9353
- this.usage.push(res.modelUsage);
9354
- }
9355
- mem.addResult(result, sessionId);
9356
- if (result.functionCalls?.length) {
9357
- const funcs = parseFunctionCalls(ai, result.functionCalls, this.values);
9358
- if (funcs) {
9359
- if (!functions) {
9360
- throw new Error("Functions are not defined");
9361
- }
9362
- const fx = await processFunctions(
9363
- ai,
9364
- functions,
9365
- funcs,
9366
- mem,
9367
- sessionId,
9368
- traceId,
9369
- span,
9370
- this.excludeContentFromTrace
9371
- );
9372
- this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
9373
- }
9374
- } else if (result.content) {
9375
- if (result.thought && result.thought.length > 0) {
9376
- this.values[this.thoughtFieldName] = result.thought;
9377
- }
9378
- extractValues(this.signature, this.values, result.content, strictMode);
9379
- await assertAssertions(this.asserts, this.values);
9380
- if (this.fieldProcessors.length) {
9381
- await processFieldProcessors(
9382
- this.fieldProcessors,
9383
- this.values,
9384
- mem,
9385
- sessionId
9386
- );
9387
- }
9388
- }
9389
- if (result.finishReason === "length") {
9390
- throw new Error(
9391
- `Max tokens reached before completion
9392
- Content: ${result.content}`
9393
- );
9394
- }
9395
- }
9396
- for (const field of this.signature.getOutputFields()) {
9397
- if (field.isInternal) {
9398
- delete this.values[field.name];
9399
- }
9400
- }
9401
- return { ...this.values };
9402
- }
9403
- async *_forward2(ai, values, options, span, traceContext) {
10104
+ async *_forward2(ai, values, states, options, span, traceContext) {
9404
10105
  const stopFunction = (options?.stopFunction ?? this.options?.stopFunction)?.toLowerCase();
9405
10106
  const maxRetries = options.maxRetries ?? this.options?.maxRetries ?? 10;
9406
10107
  const maxSteps = options.maxSteps ?? this.options?.maxSteps ?? 10;
@@ -9409,7 +10110,7 @@ Content: ${result.content}`
9409
10110
  debug: this.isDebug(ai, options),
9410
10111
  debugHideSystemPrompt
9411
10112
  };
9412
- const mem = options.mem ?? this.options?.mem ?? new AxMemory(1e4, memOptions);
10113
+ const mem = options.mem ?? this.options?.mem ?? new AxMemory(memOptions);
9413
10114
  let err;
9414
10115
  if (options?.functions && options.functions.length > 0) {
9415
10116
  const promptTemplateClass = this.options?.promptTemplate ?? AxPromptTemplate;
@@ -9436,7 +10137,7 @@ Content: ${result.content}`
9436
10137
  demos: this.demos
9437
10138
  });
9438
10139
  }
9439
- mem.add(prompt, options?.sessionId);
10140
+ mem.addRequest(prompt, options.sessionId);
9440
10141
  multiStepLoop: for (let n = 0; n < maxSteps; n++) {
9441
10142
  const firstStep = n === 0;
9442
10143
  for (let errCount = 0; errCount < maxRetries; errCount++) {
@@ -9449,15 +10150,20 @@ Content: ${result.content}`
9449
10150
  span,
9450
10151
  traceContext
9451
10152
  });
9452
- for await (const delta of generator) {
9453
- if (delta !== void 0) {
9454
- yield { version: errCount, delta };
10153
+ for await (const result of generator) {
10154
+ if (result !== void 0) {
10155
+ yield {
10156
+ version: errCount,
10157
+ index: result.index,
10158
+ delta: result.delta
10159
+ };
9455
10160
  }
9456
10161
  }
9457
- const lastMemItem = mem.getLast(options?.sessionId);
9458
- const shouldContinue = this.shouldContinueSteps(
9459
- lastMemItem,
9460
- stopFunction
10162
+ const shouldContinue = shouldContinueSteps(
10163
+ mem,
10164
+ stopFunction,
10165
+ states,
10166
+ options?.sessionId
9461
10167
  );
9462
10168
  if (shouldContinue) {
9463
10169
  continue multiStepLoop;
@@ -9513,26 +10219,15 @@ Content: ${result.content}`
9513
10219
  this.signature
9514
10220
  );
9515
10221
  }
9516
- shouldContinueSteps(lastMemItem, stopFunction) {
9517
- const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
9518
- const isFunction = lastMemItem?.chat?.role === "function";
9519
- const isProcessor = lastMemItem?.tags ? lastMemItem.tags.some((tag) => tag === "processor") : false;
9520
- if (isFunction && stopFunction && stopFunctionExecuted) {
9521
- return false;
9522
- }
9523
- if (isFunction || isProcessor) {
9524
- return true;
9525
- }
9526
- return false;
9527
- }
9528
10222
  async *_forward1(ai, values, options) {
10223
+ const states = this.createStates(options.sampleCount ?? 1);
9529
10224
  const tracer = options?.tracer ?? this.options?.tracer ?? ai.getOptions().tracer;
9530
10225
  let functions = this.functions;
9531
10226
  if (options?.functions) {
9532
10227
  functions = parseFunctions(options.functions, this.functions);
9533
10228
  }
9534
10229
  if (!tracer) {
9535
- yield* this._forward2(ai, values, {
10230
+ yield* this._forward2(ai, values, states, {
9536
10231
  ...options,
9537
10232
  functions
9538
10233
  });
@@ -9564,6 +10259,7 @@ Content: ${result.content}`
9564
10259
  yield* this._forward2(
9565
10260
  ai,
9566
10261
  values,
10262
+ states,
9567
10263
  {
9568
10264
  ...options,
9569
10265
  functions
@@ -9572,8 +10268,10 @@ Content: ${result.content}`
9572
10268
  traceContext
9573
10269
  );
9574
10270
  if (!this.excludeContentFromTrace) {
10271
+ const valuesList = states.map((s2) => s2.values);
10272
+ const values2 = valuesList.length === 1 ? valuesList[0] : valuesList;
9575
10273
  span.addEvent("output", {
9576
- content: JSON.stringify(this.values, null, 2)
10274
+ content: JSON.stringify(values2, null, 2)
9577
10275
  });
9578
10276
  }
9579
10277
  } finally {
@@ -9582,23 +10280,67 @@ Content: ${result.content}`
9582
10280
  }
9583
10281
  async forward(ai, values, options) {
9584
10282
  const generator = this._forward1(ai, values, options ?? {});
9585
- let buffer = {};
10283
+ let buffer = [];
9586
10284
  let currentVersion = 0;
9587
- for await (const item of generator) {
9588
- if (item.version !== currentVersion) {
9589
- buffer = {};
10285
+ for await (const delta of generator) {
10286
+ if (delta.version !== currentVersion) {
10287
+ buffer = [];
9590
10288
  }
9591
- currentVersion = item.version;
9592
- buffer = mergeDeltas(buffer, item.delta);
10289
+ currentVersion = delta.version;
10290
+ buffer = mergeDeltas(buffer, delta);
9593
10291
  }
9594
- this.trace = { ...values, ...buffer };
9595
- return buffer;
10292
+ const selectedIndex = await selectFromSamples(
10293
+ buffer,
10294
+ {
10295
+ resultPicker: options?.resultPicker
10296
+ },
10297
+ // Pass memory to enable function result selection
10298
+ options?.mem,
10299
+ options?.sessionId
10300
+ );
10301
+ const selectedResult = buffer[selectedIndex];
10302
+ const result = selectedResult?.delta ?? {};
10303
+ this.trace = { ...values, ...result };
10304
+ return result;
9596
10305
  }
9597
10306
  async *streamingForward(ai, values, options) {
9598
- yield* this._forward1(ai, values, {
10307
+ if (!options?.resultPicker) {
10308
+ yield* this._forward1(ai, values, {
10309
+ ...options,
10310
+ stream: true
10311
+ });
10312
+ return;
10313
+ }
10314
+ const generator = this._forward1(ai, values, {
9599
10315
  ...options,
9600
10316
  stream: true
9601
10317
  });
10318
+ let buffer = [];
10319
+ let currentVersion = 0;
10320
+ for await (const delta of generator) {
10321
+ if (delta.version !== currentVersion) {
10322
+ buffer = [];
10323
+ }
10324
+ currentVersion = delta.version;
10325
+ buffer = mergeDeltas(buffer, delta);
10326
+ }
10327
+ const selectedIndex = await selectFromSamples(
10328
+ buffer,
10329
+ {
10330
+ resultPicker: options?.resultPicker
10331
+ },
10332
+ // Pass memory to enable function result selection
10333
+ options?.mem,
10334
+ options?.sessionId
10335
+ );
10336
+ const selectedResult = buffer[selectedIndex];
10337
+ if (selectedResult) {
10338
+ yield {
10339
+ version: currentVersion,
10340
+ index: selectedIndex,
10341
+ delta: selectedResult.delta
10342
+ };
10343
+ }
9602
10344
  }
9603
10345
  setExamples(examples, options) {
9604
10346
  super.setExamples(examples, options);
@@ -9613,9 +10355,13 @@ Content: ${result.content}`
9613
10355
  var AxGenerateError = class extends Error {
9614
10356
  details;
9615
10357
  constructor(message, details, options) {
9616
- super(message, options);
10358
+ super(message);
9617
10359
  this.name = "AxGenerateError";
9618
10360
  this.details = details;
10361
+ if (options?.cause) {
10362
+ ;
10363
+ this.cause = options.cause;
10364
+ }
9619
10365
  }
9620
10366
  };
9621
10367
  function enhanceError(e, ai, signature) {
@@ -11690,23 +12436,6 @@ var getTopInPercent = (entries, percent = 0.1) => {
11690
12436
  return sortedEntries.slice(0, topTenPercentCount);
11691
12437
  };
11692
12438
 
11693
- // docs/rewriter.ts
11694
- var AxDefaultQueryRewriter = class extends AxGen {
11695
- constructor(options) {
11696
- const signature = `"You are a query rewriter assistant tasked with rewriting a given query to improve its clarity, specificity, and relevance. Your role involves analyzing the query to identify any ambiguities, generalizations, or irrelevant information and then rephrasing it to make it more focused and precise. The rewritten query should be concise, easy to understand, and directly related to the original query. Output only the rewritten query."
11697
- query: string -> rewrittenQuery: string`;
11698
- super(signature, options);
11699
- }
11700
- };
11701
- var AxRewriter = class extends AxGen {
11702
- constructor(options) {
11703
- super(
11704
- '"Rewrite a given text to be clear and concise" original -> rewritten "improved text"',
11705
- options
11706
- );
11707
- }
11708
- };
11709
-
11710
12439
  // funcs/docker.ts
11711
12440
  var AxDockerSession = class {
11712
12441
  apiUrl;
@@ -13297,6 +14026,7 @@ var AxMockAIService = class {
13297
14026
  return this.config.chatResponse ?? {
13298
14027
  results: [
13299
14028
  {
14029
+ index: 0,
13300
14030
  content: "Mock response",
13301
14031
  finishReason: "stop"
13302
14032
  }
@@ -15597,7 +16327,6 @@ export {
15597
16327
  AxDBPinecone,
15598
16328
  AxDBWeaviate,
15599
16329
  AxDefaultCostTracker,
15600
- AxDefaultQueryRewriter,
15601
16330
  AxDefaultResultReranker,
15602
16331
  AxDockerSession,
15603
16332
  AxEmbeddingAdapter,
@@ -15624,7 +16353,6 @@ export {
15624
16353
  AxPromptTemplate,
15625
16354
  AxRAG,
15626
16355
  AxRateLimiterTokenUsage,
15627
- AxRewriter,
15628
16356
  AxSignature,
15629
16357
  AxSimpleClassifier,
15630
16358
  AxSimpleClassifierClass,
@@ -15684,6 +16412,8 @@ export {
15684
16412
  axModelInfoTogether,
15685
16413
  axSpanAttributes,
15686
16414
  axSpanEvents,
16415
+ axValidateChatRequestMessage,
16416
+ axValidateChatResponseResult,
15687
16417
  f,
15688
16418
  s
15689
16419
  };