@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.cjs CHANGED
@@ -92,7 +92,6 @@ __export(index_exports, {
92
92
  AxDBPinecone: () => AxDBPinecone,
93
93
  AxDBWeaviate: () => AxDBWeaviate,
94
94
  AxDefaultCostTracker: () => AxDefaultCostTracker,
95
- AxDefaultQueryRewriter: () => AxDefaultQueryRewriter,
96
95
  AxDefaultResultReranker: () => AxDefaultResultReranker,
97
96
  AxDockerSession: () => AxDockerSession,
98
97
  AxEmbeddingAdapter: () => AxEmbeddingAdapter,
@@ -119,7 +118,6 @@ __export(index_exports, {
119
118
  AxPromptTemplate: () => AxPromptTemplate,
120
119
  AxRAG: () => AxRAG,
121
120
  AxRateLimiterTokenUsage: () => AxRateLimiterTokenUsage,
122
- AxRewriter: () => AxRewriter,
123
121
  AxSignature: () => AxSignature,
124
122
  AxSimpleClassifier: () => AxSimpleClassifier,
125
123
  AxSimpleClassifierClass: () => AxSimpleClassifierClass,
@@ -179,6 +177,8 @@ __export(index_exports, {
179
177
  axModelInfoTogether: () => axModelInfoTogether,
180
178
  axSpanAttributes: () => axSpanAttributes,
181
179
  axSpanEvents: () => axSpanEvents,
180
+ axValidateChatRequestMessage: () => axValidateChatRequestMessage,
181
+ axValidateChatResponseResult: () => axValidateChatResponseResult,
182
182
  f: () => f,
183
183
  s: () => s
184
184
  });
@@ -1390,6 +1390,9 @@ var AxBaseAI = class {
1390
1390
  }
1391
1391
  async _chat1(req, options) {
1392
1392
  const model = this.getModel(req.model) ?? req.model ?? this.defaults.model;
1393
+ if (req.chatPrompt && Array.isArray(req.chatPrompt)) {
1394
+ validateAxMessageArray(req.chatPrompt);
1395
+ }
1393
1396
  const modelConfig = {
1394
1397
  ...this.aiImpl.getModelConfig(),
1395
1398
  ...req.modelConfig
@@ -1461,7 +1464,6 @@ var AxBaseAI = class {
1461
1464
  if (chatReq.functions && chatReq.functions.length > 0) {
1462
1465
  functions = chatReq.functions.map((fn2) => this.cleanupFunctionSchema(fn2));
1463
1466
  }
1464
- validateChatPrompt(chatReq.chatPrompt);
1465
1467
  const req = {
1466
1468
  ...chatReq,
1467
1469
  model,
@@ -1512,11 +1514,14 @@ var AxBaseAI = class {
1512
1514
  const res2 = respFn(resp, state);
1513
1515
  res2.sessionId = options?.sessionId;
1514
1516
  if (!res2.modelUsage) {
1515
- res2.modelUsage = {
1516
- ai: this.name,
1517
- model,
1518
- tokens: this.aiImpl.getTokenUsage()
1519
- };
1517
+ const tokenUsage = this.aiImpl.getTokenUsage();
1518
+ if (tokenUsage) {
1519
+ res2.modelUsage = {
1520
+ ai: this.name,
1521
+ model,
1522
+ tokens: tokenUsage
1523
+ };
1524
+ }
1520
1525
  }
1521
1526
  this.modelUsage = res2.modelUsage;
1522
1527
  if (span?.isRecording()) {
@@ -1650,11 +1655,14 @@ var AxBaseAI = class {
1650
1655
  const res = this.aiImpl.createEmbedResp(resValue);
1651
1656
  res.sessionId = options?.sessionId;
1652
1657
  if (!res.modelUsage) {
1653
- res.modelUsage = {
1654
- ai: this.name,
1655
- model: embedModel,
1656
- tokens: this.aiImpl.getTokenUsage()
1657
- };
1658
+ const tokenUsage = this.aiImpl.getTokenUsage();
1659
+ if (tokenUsage) {
1660
+ res.modelUsage = {
1661
+ ai: this.name,
1662
+ model: embedModel,
1663
+ tokens: tokenUsage
1664
+ };
1665
+ }
1658
1666
  }
1659
1667
  this.embedModelUsage = res.modelUsage;
1660
1668
  if (span?.isRecording() && res.modelUsage?.tokens) {
@@ -1818,26 +1826,6 @@ function validateAxMessageArray(values) {
1818
1826
  }
1819
1827
  }
1820
1828
  }
1821
- function validateChatPrompt(chatPrompt) {
1822
- for (let i = 0; i < chatPrompt.length; i++) {
1823
- const message = chatPrompt[i];
1824
- if (message && "functionCalls" in message && Array.isArray(message.functionCalls) && message.functionCalls.length === 0) {
1825
- throw new Error(
1826
- `Chat prompt validation failed: Message at index ${i} has empty functionCalls`
1827
- );
1828
- }
1829
- if (message && "content" in message && Array.isArray(message.content) && message.content.length === 0) {
1830
- throw new Error(
1831
- `Chat prompt validation failed: Message at index ${i} has empty content`
1832
- );
1833
- }
1834
- if (message && "content" in message && typeof message.content === "string" && message.content.trim() === "") {
1835
- throw new Error(
1836
- `Chat prompt validation failed: Message at index ${i} has empty content`
1837
- );
1838
- }
1839
- }
1840
- }
1841
1829
  function validateModels(models) {
1842
1830
  const keys = /* @__PURE__ */ new Set();
1843
1831
  for (const model of models) {
@@ -1909,14 +1897,18 @@ var axModelInfoAnthropic = [
1909
1897
  currency: "usd",
1910
1898
  promptTokenCostPer1M: 15,
1911
1899
  completionTokenCostPer1M: 75,
1912
- maxTokens: 32e3
1900
+ maxTokens: 32e3,
1901
+ hasThinkingBudget: true,
1902
+ hasShowThoughts: true
1913
1903
  },
1914
1904
  {
1915
1905
  name: "claude-sonnet-4-20250514" /* Claude4Sonnet */,
1916
1906
  currency: "usd",
1917
1907
  promptTokenCostPer1M: 3,
1918
1908
  completionTokenCostPer1M: 15,
1919
- maxTokens: 64e3
1909
+ maxTokens: 64e3,
1910
+ hasThinkingBudget: true,
1911
+ hasShowThoughts: true
1920
1912
  },
1921
1913
  // 3.7
1922
1914
  {
@@ -1924,7 +1916,9 @@ var axModelInfoAnthropic = [
1924
1916
  currency: "usd",
1925
1917
  promptTokenCostPer1M: 3,
1926
1918
  completionTokenCostPer1M: 15,
1927
- maxTokens: 64e3
1919
+ maxTokens: 64e3,
1920
+ hasThinkingBudget: true,
1921
+ hasShowThoughts: true
1928
1922
  },
1929
1923
  // 3.5
1930
1924
  {
@@ -1980,13 +1974,47 @@ var axModelInfoAnthropic = [
1980
1974
  }
1981
1975
  ];
1982
1976
 
1977
+ // dsp/modelinfo.ts
1978
+ function getModelInfo({
1979
+ model,
1980
+ modelInfo,
1981
+ models
1982
+ }) {
1983
+ const modelEntry = models?.find((v) => v.key === model);
1984
+ const mappedModel = modelEntry && "model" in modelEntry ? modelEntry.model : model;
1985
+ const exactMatch = modelInfo.find((v) => v.name === model);
1986
+ if (exactMatch) return exactMatch;
1987
+ 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+$/, "");
1988
+ const normalizedMatch = modelInfo.find((v) => v.name === normalizedName);
1989
+ if (normalizedMatch) return normalizedMatch;
1990
+ return null;
1991
+ }
1992
+
1983
1993
  // ai/anthropic/api.ts
1984
1994
  var axAIAnthropicDefaultConfig = () => structuredClone({
1985
1995
  model: "claude-3-7-sonnet-latest" /* Claude37Sonnet */,
1996
+ maxTokens: 4e4,
1997
+ // Ensure maxTokens is higher than highest thinking budget
1998
+ thinkingTokenBudgetLevels: {
1999
+ minimal: 1024,
2000
+ low: 5e3,
2001
+ medium: 1e4,
2002
+ high: 2e4,
2003
+ highest: 32e3
2004
+ },
1986
2005
  ...axBaseAIDefaultConfig()
1987
2006
  });
1988
2007
  var axAIAnthropicVertexDefaultConfig = () => structuredClone({
1989
2008
  model: "claude-3-7-sonnet" /* Claude37Sonnet */,
2009
+ maxTokens: 4e4,
2010
+ // Ensure maxTokens is higher than highest thinking budget
2011
+ thinkingTokenBudgetLevels: {
2012
+ minimal: 1024,
2013
+ low: 5e3,
2014
+ medium: 1e4,
2015
+ high: 2e4,
2016
+ highest: 32e3
2017
+ },
1990
2018
  ...axBaseAIDefaultConfig()
1991
2019
  });
1992
2020
  var AxAIAnthropicImpl = class {
@@ -1995,6 +2023,7 @@ var AxAIAnthropicImpl = class {
1995
2023
  this.isVertex = isVertex;
1996
2024
  }
1997
2025
  tokensUsed;
2026
+ currentPromptConfig;
1998
2027
  getTokenUsage() {
1999
2028
  return this.tokensUsed;
2000
2029
  }
@@ -2013,7 +2042,8 @@ var AxAIAnthropicImpl = class {
2013
2042
  n: config.n
2014
2043
  };
2015
2044
  }
2016
- createChatReq = (req) => {
2045
+ createChatReq = (req, config) => {
2046
+ this.currentPromptConfig = config;
2017
2047
  const model = req.model;
2018
2048
  const stream = req.modelConfig?.stream ?? this.config.stream;
2019
2049
  let apiConfig;
@@ -2069,17 +2099,67 @@ var AxAIAnthropicImpl = class {
2069
2099
  const temperature = req.modelConfig?.temperature ?? this.config.temperature;
2070
2100
  const topP = req.modelConfig?.topP ?? this.config.topP;
2071
2101
  const topK = req.modelConfig?.topK ?? this.config.topK;
2102
+ const n = req.modelConfig?.n ?? this.config.n;
2103
+ if (n && n > 1) {
2104
+ throw new Error("Anthropic does not support sampling (n > 1)");
2105
+ }
2106
+ let thinkingConfig;
2107
+ if (this.config.thinking?.budget_tokens) {
2108
+ thinkingConfig = this.config.thinking;
2109
+ }
2110
+ if (config?.thinkingTokenBudget) {
2111
+ const levels = this.config.thinkingTokenBudgetLevels;
2112
+ switch (config.thinkingTokenBudget) {
2113
+ case "none":
2114
+ thinkingConfig = void 0;
2115
+ break;
2116
+ case "minimal":
2117
+ thinkingConfig = {
2118
+ type: "enabled",
2119
+ budget_tokens: levels?.minimal ?? 1024
2120
+ };
2121
+ break;
2122
+ case "low":
2123
+ thinkingConfig = {
2124
+ type: "enabled",
2125
+ budget_tokens: levels?.low ?? 5e3
2126
+ };
2127
+ break;
2128
+ case "medium":
2129
+ thinkingConfig = {
2130
+ type: "enabled",
2131
+ budget_tokens: levels?.medium ?? 1e4
2132
+ };
2133
+ break;
2134
+ case "high":
2135
+ thinkingConfig = {
2136
+ type: "enabled",
2137
+ budget_tokens: levels?.high ?? 2e4
2138
+ };
2139
+ break;
2140
+ case "highest":
2141
+ thinkingConfig = {
2142
+ type: "enabled",
2143
+ budget_tokens: levels?.highest ?? 32e3
2144
+ };
2145
+ break;
2146
+ }
2147
+ }
2072
2148
  const reqValue = {
2073
2149
  ...this.isVertex ? { anthropic_version: "vertex-2023-10-16" } : { model },
2074
2150
  ...maxTokens ? { max_tokens: maxTokens } : {},
2075
2151
  ...stopSequences && stopSequences.length > 0 ? { stop_sequences: stopSequences } : {},
2076
- ...temperature ? { temperature } : {},
2077
- ...topP ? { top_p: topP } : {},
2078
- ...topK ? { top_k: topK } : {},
2152
+ // Only include temperature when thinking is not enabled
2153
+ ...temperature && !thinkingConfig ? { temperature } : {},
2154
+ // Only include top_p when thinking is not enabled, or when it's >= 0.95
2155
+ ...topP && (!thinkingConfig || topP >= 0.95) ? { top_p: topP } : {},
2156
+ // Only include top_k when thinking is not enabled
2157
+ ...topK && !thinkingConfig ? { top_k: topK } : {},
2079
2158
  ...toolsChoice,
2080
2159
  ...tools && tools.length > 0 ? { tools } : {},
2081
2160
  ...stream ? { stream: true } : {},
2082
2161
  ...system ? { system } : {},
2162
+ ...thinkingConfig ? { thinking: thinkingConfig } : {},
2083
2163
  messages
2084
2164
  };
2085
2165
  return [apiConfig, reqValue];
@@ -2089,9 +2169,11 @@ var AxAIAnthropicImpl = class {
2089
2169
  throw new Error(`Anthropic Chat API Error: ${resp.error.message}`);
2090
2170
  }
2091
2171
  const finishReason = mapFinishReason(resp.stop_reason);
2092
- const results = resp.content.map((msg) => {
2172
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
2173
+ const results = resp.content.map((msg, index) => {
2093
2174
  if (msg.type === "tool_use") {
2094
2175
  return {
2176
+ index,
2095
2177
  id: msg.id,
2096
2178
  functionCalls: [
2097
2179
  {
@@ -2106,12 +2188,23 @@ var AxAIAnthropicImpl = class {
2106
2188
  finishReason
2107
2189
  };
2108
2190
  }
2191
+ if ((msg.type === "thinking" || msg.type === "redacted_thinking") && showThoughts) {
2192
+ return {
2193
+ index,
2194
+ thought: msg.thinking,
2195
+ id: resp.id,
2196
+ finishReason
2197
+ };
2198
+ }
2109
2199
  return {
2200
+ index,
2110
2201
  content: msg.type === "text" ? msg.text : "",
2111
2202
  id: resp.id,
2112
2203
  finishReason
2113
2204
  };
2114
- });
2205
+ }).filter(
2206
+ (result) => result.content !== "" || result.thought !== void 0 || result.functionCalls !== void 0
2207
+ );
2115
2208
  this.tokensUsed = {
2116
2209
  promptTokens: resp.usage.input_tokens,
2117
2210
  completionTokens: resp.usage.output_tokens,
@@ -2131,9 +2224,10 @@ var AxAIAnthropicImpl = class {
2131
2224
  const { error } = resp;
2132
2225
  throw new Error(error.message);
2133
2226
  }
2227
+ const index = 0;
2134
2228
  if (resp.type === "message_start") {
2135
2229
  const { message } = resp;
2136
- const results = [{ content: "", id: message.id }];
2230
+ const results = [{ index, content: "", id: message.id }];
2137
2231
  this.tokensUsed = {
2138
2232
  promptTokens: message.usage?.input_tokens ?? 0,
2139
2233
  completionTokens: message.usage?.output_tokens ?? 0,
@@ -2145,7 +2239,18 @@ var AxAIAnthropicImpl = class {
2145
2239
  const { content_block: contentBlock } = resp;
2146
2240
  if (contentBlock.type === "text") {
2147
2241
  return {
2148
- results: [{ content: contentBlock.text }]
2242
+ results: [{ index, content: contentBlock.text }]
2243
+ };
2244
+ }
2245
+ if (contentBlock.type === "thinking") {
2246
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
2247
+ if (showThoughts) {
2248
+ return {
2249
+ results: [{ index, thought: contentBlock.thinking }]
2250
+ };
2251
+ }
2252
+ return {
2253
+ results: [{ index, content: "" }]
2149
2254
  };
2150
2255
  }
2151
2256
  if (contentBlock.type === "tool_use") {
@@ -2162,7 +2267,7 @@ var AxAIAnthropicImpl = class {
2162
2267
  }
2163
2268
  ];
2164
2269
  return {
2165
- results: [{ functionCalls }]
2270
+ results: [{ index, functionCalls }]
2166
2271
  };
2167
2272
  }
2168
2273
  }
@@ -2171,7 +2276,23 @@ var AxAIAnthropicImpl = class {
2171
2276
  const { delta } = resp;
2172
2277
  if (delta.type === "text_delta") {
2173
2278
  return {
2174
- results: [{ content: delta.text }]
2279
+ results: [{ index, content: delta.text }]
2280
+ };
2281
+ }
2282
+ if (delta.type === "thinking_delta") {
2283
+ const showThoughts = this.currentPromptConfig?.thinkingTokenBudget !== "none" && this.currentPromptConfig?.showThoughts !== false;
2284
+ if (showThoughts) {
2285
+ return {
2286
+ results: [{ index, thought: delta.thinking }]
2287
+ };
2288
+ }
2289
+ return {
2290
+ results: [{ index, content: "" }]
2291
+ };
2292
+ }
2293
+ if (delta.type === "signature_delta") {
2294
+ return {
2295
+ results: [{ index, content: "" }]
2175
2296
  };
2176
2297
  }
2177
2298
  if (delta.type === "input_json_delta") {
@@ -2190,7 +2311,7 @@ var AxAIAnthropicImpl = class {
2190
2311
  }
2191
2312
  ];
2192
2313
  return {
2193
- results: [{ functionCalls }]
2314
+ results: [{ index, functionCalls }]
2194
2315
  };
2195
2316
  }
2196
2317
  }
@@ -2202,12 +2323,16 @@ var AxAIAnthropicImpl = class {
2202
2323
  totalTokens: usage.output_tokens
2203
2324
  };
2204
2325
  const results = [
2205
- { content: "", finishReason: mapFinishReason(delta.stop_reason) }
2326
+ {
2327
+ index,
2328
+ content: "",
2329
+ finishReason: mapFinishReason(delta.stop_reason)
2330
+ }
2206
2331
  ];
2207
2332
  return { results };
2208
2333
  }
2209
2334
  return {
2210
- results: [{ content: "" }]
2335
+ results: [{ index, content: "" }]
2211
2336
  };
2212
2337
  };
2213
2338
  };
@@ -2249,6 +2374,20 @@ var AxAIAnthropic = class extends AxBaseAI {
2249
2374
  ...config
2250
2375
  };
2251
2376
  const aiImpl = new AxAIAnthropicImpl(_config, isVertex);
2377
+ const supportFor = (model) => {
2378
+ const mi = getModelInfo({
2379
+ model,
2380
+ modelInfo: axModelInfoAnthropic,
2381
+ models
2382
+ });
2383
+ return {
2384
+ functions: true,
2385
+ streaming: true,
2386
+ hasThinkingBudget: mi?.hasThinkingBudget ?? false,
2387
+ hasShowThoughts: mi?.hasShowThoughts ?? false,
2388
+ functionCot: true
2389
+ };
2390
+ };
2252
2391
  super(aiImpl, {
2253
2392
  name: "Anthropic",
2254
2393
  apiURL,
@@ -2256,7 +2395,7 @@ var AxAIAnthropic = class extends AxBaseAI {
2256
2395
  modelInfo: axModelInfoAnthropic,
2257
2396
  defaults: { model: _config.model },
2258
2397
  options,
2259
- supportFor: { functions: true, streaming: true, functionCot: true },
2398
+ supportFor,
2260
2399
  models
2261
2400
  });
2262
2401
  }
@@ -2386,22 +2525,6 @@ function mapFinishReason(stopReason) {
2386
2525
  }
2387
2526
  }
2388
2527
 
2389
- // dsp/modelinfo.ts
2390
- function getModelInfo({
2391
- model,
2392
- modelInfo,
2393
- models
2394
- }) {
2395
- const modelEntry = models?.find((v) => v.key === model);
2396
- const mappedModel = modelEntry && "model" in modelEntry ? modelEntry.model : model;
2397
- const exactMatch = modelInfo.find((v) => v.name === model);
2398
- if (exactMatch) return exactMatch;
2399
- 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+$/, "");
2400
- const normalizedMatch = modelInfo.find((v) => v.name === normalizedName);
2401
- if (normalizedMatch) return normalizedMatch;
2402
- return null;
2403
- }
2404
-
2405
2528
  // ai/openai/chat_types.ts
2406
2529
  var AxAIOpenAIModel = /* @__PURE__ */ ((AxAIOpenAIModel2) => {
2407
2530
  AxAIOpenAIModel2["O1"] = "o1";
@@ -2736,6 +2859,7 @@ var AxAIOpenAIImpl = class {
2736
2859
  })
2737
2860
  );
2738
2861
  return {
2862
+ index: choice.index,
2739
2863
  id: `${choice.index}`,
2740
2864
  content: choice.message.content,
2741
2865
  thought: choice.message.reasoning_content,
@@ -2761,6 +2885,7 @@ var AxAIOpenAIImpl = class {
2761
2885
  }
2762
2886
  const results = choices.map(
2763
2887
  ({
2888
+ index,
2764
2889
  delta: {
2765
2890
  content,
2766
2891
  role,
@@ -2770,11 +2895,11 @@ var AxAIOpenAIImpl = class {
2770
2895
  finish_reason: oaiFinishReason
2771
2896
  }) => {
2772
2897
  const finishReason = mapFinishReason2(oaiFinishReason);
2773
- const functionCalls = toolCalls?.map(({ id: _id, index, function: { name, arguments: params } }) => {
2774
- if (typeof _id === "string" && typeof index === "number" && !sstate.indexIdMap[index]) {
2775
- sstate.indexIdMap[index] = _id;
2898
+ const functionCalls = toolCalls?.map(({ id: _id, index: index2, function: { name, arguments: params } }) => {
2899
+ if (typeof _id === "string" && typeof index2 === "number" && !sstate.indexIdMap[index2]) {
2900
+ sstate.indexIdMap[index2] = _id;
2776
2901
  }
2777
- const id2 = sstate.indexIdMap[index];
2902
+ const id2 = sstate.indexIdMap[index2];
2778
2903
  if (!id2) {
2779
2904
  return null;
2780
2905
  }
@@ -2785,6 +2910,7 @@ var AxAIOpenAIImpl = class {
2785
2910
  };
2786
2911
  }).filter((v) => v !== null);
2787
2912
  return {
2913
+ index,
2788
2914
  content,
2789
2915
  role,
2790
2916
  thought,
@@ -2819,7 +2945,7 @@ var mapFinishReason2 = (finishReason) => {
2819
2945
  }
2820
2946
  };
2821
2947
  function createMessages2(req) {
2822
- return req.chatPrompt.map((msg) => {
2948
+ const openaiReq = req.chatPrompt.map((msg) => {
2823
2949
  switch (msg.role) {
2824
2950
  case "system":
2825
2951
  return { role: "system", content: msg.content };
@@ -2868,7 +2994,7 @@ function createMessages2(req) {
2868
2994
  tool_calls: toolCalls
2869
2995
  };
2870
2996
  }
2871
- if (!msg.content) {
2997
+ if (msg.content === void 0) {
2872
2998
  throw new Error(
2873
2999
  "Assistant content is required when no tool calls are provided"
2874
3000
  );
@@ -2888,6 +3014,7 @@ function createMessages2(req) {
2888
3014
  throw new Error("Invalid role");
2889
3015
  }
2890
3016
  });
3017
+ return openaiReq;
2891
3018
  }
2892
3019
  var AxAIOpenAIBase = class extends AxBaseAI {
2893
3020
  constructor({
@@ -3241,6 +3368,7 @@ var AxAICohereImpl = class {
3241
3368
  }
3242
3369
  const results = [
3243
3370
  {
3371
+ index: 0,
3244
3372
  id: resp.generation_id,
3245
3373
  content: resp.text,
3246
3374
  functionCalls,
@@ -3873,7 +4001,7 @@ var AxAIGoogleGeminiImpl = class {
3873
4001
  createChatResp = (resp) => {
3874
4002
  const results = resp.candidates?.map(
3875
4003
  (candidate) => {
3876
- const result = {};
4004
+ const result = { index: 0 };
3877
4005
  switch (candidate.finishReason) {
3878
4006
  case "MAX_TOKENS":
3879
4007
  result.finishReason = "length";
@@ -4270,6 +4398,7 @@ ${fc}`;
4270
4398
  return {
4271
4399
  results: [
4272
4400
  {
4401
+ index: 0,
4273
4402
  content: resp.generated_text
4274
4403
  }
4275
4404
  ]
@@ -4911,7 +5040,7 @@ var AxAIOpenAIResponsesImpl = class {
4911
5040
  }
4912
5041
  }
4913
5042
  return {
4914
- results: [currentResult],
5043
+ results: [{ ...currentResult, index: 0 }],
4915
5044
  remoteId: id
4916
5045
  };
4917
5046
  }
@@ -4919,6 +5048,7 @@ var AxAIOpenAIResponsesImpl = class {
4919
5048
  createChatStreamResp(streamEvent) {
4920
5049
  const event = streamEvent;
4921
5050
  const baseResult = {
5051
+ index: 0,
4922
5052
  id: "",
4923
5053
  content: "",
4924
5054
  finishReason: "stop"
@@ -5486,7 +5616,7 @@ var AxAIRekaImpl = class {
5486
5616
  completionTokens: usage.output_tokens,
5487
5617
  totalTokens: usage.input_tokens + usage.output_tokens
5488
5618
  } : void 0;
5489
- const results = responses.map((res) => {
5619
+ const results = responses.map((res, index) => {
5490
5620
  const finishReason = mapFinishReason3(res.finish_reason);
5491
5621
  let content;
5492
5622
  if (typeof res.message.content === "string") {
@@ -5495,6 +5625,7 @@ var AxAIRekaImpl = class {
5495
5625
  content = res.message.content.text;
5496
5626
  }
5497
5627
  return {
5628
+ index,
5498
5629
  id: `${id}`,
5499
5630
  content,
5500
5631
  finishReason
@@ -5509,7 +5640,7 @@ var AxAIRekaImpl = class {
5509
5640
  completionTokens: usage.output_tokens,
5510
5641
  totalTokens: usage.input_tokens + usage.output_tokens
5511
5642
  } : void 0;
5512
- const results = responses.map((res) => {
5643
+ const results = responses.map((res, index) => {
5513
5644
  const finishReason = mapFinishReason3(res.finish_reason);
5514
5645
  let content;
5515
5646
  if (typeof res.chunk.content === "string") {
@@ -5518,6 +5649,7 @@ var AxAIRekaImpl = class {
5518
5649
  content = res.chunk.content.text;
5519
5650
  }
5520
5651
  return {
5652
+ index,
5521
5653
  id: `${id}`,
5522
5654
  content,
5523
5655
  finishReason
@@ -5871,111 +6003,334 @@ var AxAIGrok = class extends AxAIOpenAIBase {
5871
6003
  };
5872
6004
 
5873
6005
  // dsp/generate.ts
5874
- var import_web5 = require("stream/web");
6006
+ var import_web6 = require("stream/web");
5875
6007
  var import_api22 = require("@opentelemetry/api");
5876
6008
 
5877
- // ai/util.ts
5878
- function mergeFunctionCalls(functionCalls, functionCallDeltas) {
5879
- for (const _fc of functionCallDeltas) {
5880
- const fc = functionCalls.find((fc2) => fc2.id === _fc.id);
5881
- if (fc) {
5882
- if (typeof _fc.function.name == "string" && _fc.function.name.length > 0) {
5883
- fc.function.name += _fc.function.name;
6009
+ // ai/validate.ts
6010
+ function axValidateChatRequestMessage(item) {
6011
+ if (!item) {
6012
+ throw new Error("Chat request message item cannot be null or undefined");
6013
+ }
6014
+ if (!item.role) {
6015
+ throw new Error("Chat request message must have a role");
6016
+ }
6017
+ switch (item.role) {
6018
+ case "system":
6019
+ if (!item.content || item.content.trim() === "") {
6020
+ throw new Error(
6021
+ "System message content cannot be empty or whitespace-only"
6022
+ );
5884
6023
  }
5885
- if (typeof _fc.function.params == "string" && _fc.function.params.length > 0) {
5886
- fc.function.params += _fc.function.params;
6024
+ break;
6025
+ case "user":
6026
+ if (!item.content) {
6027
+ throw new Error("User message content cannot be undefined");
5887
6028
  }
5888
- if (typeof _fc.function.params == "object") {
5889
- fc.function.params = _fc.function.params;
6029
+ if (typeof item.content === "string") {
6030
+ if (item.content.trim() === "") {
6031
+ throw new Error(
6032
+ "User message content cannot be empty or whitespace-only"
6033
+ );
6034
+ }
6035
+ } else if (Array.isArray(item.content)) {
6036
+ if (item.content.length === 0) {
6037
+ throw new Error("User message content array cannot be empty");
6038
+ }
6039
+ for (let index = 0; index < item.content.length; index++) {
6040
+ const contentItem = item.content[index];
6041
+ if (!contentItem || typeof contentItem !== "object") {
6042
+ throw new Error(
6043
+ `User message content item at index ${index} must be an object`
6044
+ );
6045
+ }
6046
+ if (!contentItem.type) {
6047
+ throw new Error(
6048
+ `User message content item at index ${index} must have a type`
6049
+ );
6050
+ }
6051
+ switch (contentItem.type) {
6052
+ case "text":
6053
+ if (!contentItem.text || contentItem.text.trim() === "") {
6054
+ throw new Error(
6055
+ `User message text content at index ${index} cannot be empty or whitespace-only`
6056
+ );
6057
+ }
6058
+ break;
6059
+ case "image":
6060
+ if (!contentItem.image || contentItem.image.trim() === "") {
6061
+ throw new Error(
6062
+ `User message image content at index ${index} cannot be empty`
6063
+ );
6064
+ }
6065
+ if (!contentItem.mimeType || contentItem.mimeType.trim() === "") {
6066
+ throw new Error(
6067
+ `User message image content at index ${index} must have a mimeType`
6068
+ );
6069
+ }
6070
+ break;
6071
+ case "audio":
6072
+ if (!contentItem.data || contentItem.data.trim() === "") {
6073
+ throw new Error(
6074
+ `User message audio content at index ${index} cannot be empty`
6075
+ );
6076
+ }
6077
+ break;
6078
+ default:
6079
+ throw new Error(
6080
+ `User message content item at index ${index} has unsupported type: ${contentItem.type}`
6081
+ );
6082
+ }
6083
+ }
6084
+ } else {
6085
+ throw new Error(
6086
+ "User message content must be a string or array of content objects"
6087
+ );
5890
6088
  }
5891
- } else {
5892
- functionCalls.push(_fc);
5893
- }
6089
+ break;
6090
+ case "assistant":
6091
+ if (!item.content && !item.functionCalls) {
6092
+ throw new Error(
6093
+ "Assistant message must have either content or function calls"
6094
+ );
6095
+ }
6096
+ if (item.content && typeof item.content !== "string") {
6097
+ throw new Error("Assistant message content must be a string");
6098
+ }
6099
+ if (item.functionCalls && !Array.isArray(item.functionCalls)) {
6100
+ throw new Error("Assistant message function calls must be an array");
6101
+ }
6102
+ break;
6103
+ case "function":
6104
+ if (!item.functionId || item.functionId.trim() === "") {
6105
+ throw new Error("Function message must have a non-empty functionId");
6106
+ }
6107
+ if (item.result === void 0 || item.result === null) {
6108
+ throw new Error("Function message must have a result");
6109
+ }
6110
+ if (typeof item.result !== "string") {
6111
+ throw new Error("Function message result must be a string");
6112
+ }
6113
+ break;
6114
+ default:
6115
+ throw new Error(
6116
+ `Unsupported message role: ${item.role}`
6117
+ );
5894
6118
  }
5895
6119
  }
5896
-
5897
- // mem/memory.ts
5898
- var defaultLimit = 1e4;
5899
- var MemoryImpl = class {
5900
- constructor(limit = defaultLimit, options) {
5901
- this.limit = limit;
5902
- this.options = options;
5903
- if (limit <= 0) {
5904
- throw Error("argument 'limit' must be greater than 0");
5905
- }
5906
- }
5907
- data = [];
5908
- addMemory(value) {
5909
- if (Array.isArray(value)) {
5910
- this.data.push(...value.map((chat) => ({ chat: structuredClone(chat) })));
5911
- } else {
5912
- this.data.push({
5913
- chat: structuredClone(value)
5914
- });
5915
- }
5916
- if (this.data.length > this.limit) {
5917
- const removeCount = this.data.length - this.limit;
5918
- this.data.splice(0, removeCount);
5919
- }
6120
+ function axValidateChatResponseResult(results) {
6121
+ const resultsArray = Array.isArray(results) ? results : [results];
6122
+ if (resultsArray.length === 0) {
6123
+ throw new Error("Chat response results cannot be empty");
5920
6124
  }
5921
- add(value) {
5922
- this.addMemory(value);
5923
- if (this.options?.debug) {
5924
- debugRequest(value, this.options?.debugHideSystemPrompt);
6125
+ for (let arrayIndex = 0; arrayIndex < resultsArray.length; arrayIndex++) {
6126
+ const result = resultsArray[arrayIndex];
6127
+ if (!result) {
6128
+ throw new Error(
6129
+ `Chat response result at index ${arrayIndex} cannot be null or undefined`
6130
+ );
5925
6131
  }
5926
- }
5927
- addResultMessage({
5928
- content,
5929
- name,
5930
- functionCalls
5931
- }) {
5932
- const isContentEmpty = typeof content === "string" && content.trim() === "";
5933
- if (isContentEmpty) {
5934
- this.addMemory({ name, role: "assistant", functionCalls });
5935
- } else {
5936
- this.addMemory({ content, name, role: "assistant", functionCalls });
6132
+ if (typeof result.index !== "number") {
6133
+ throw new Error(
6134
+ `Chat response result at index ${arrayIndex} must have a numeric index`
6135
+ );
5937
6136
  }
5938
- }
5939
- addResult({
5940
- content,
5941
- name,
5942
- functionCalls
5943
- }) {
5944
- this.addResultMessage({ content, name, functionCalls });
5945
- if (this.options?.debug) {
5946
- debugResponse({ content, name, functionCalls });
6137
+ if (result.index < 0) {
6138
+ throw new Error(
6139
+ `Chat response result at index ${arrayIndex} must have a non-negative index`
6140
+ );
5947
6141
  }
5948
- }
5949
- updateResult({
5950
- content,
5951
- name,
5952
- functionCalls,
5953
- delta
5954
- }) {
5955
- const lastItem = this.data.at(-1);
5956
- if (!lastItem || lastItem.chat.role !== "assistant") {
5957
- throw new Error("No assistant message to update");
6142
+ if (!result.content && !result.thought && !result.functionCalls && !result.finishReason) {
6143
+ throw new Error(
6144
+ `Chat response result at index ${arrayIndex} must have at least one of: content, thought, functionCalls, or finishReason`
6145
+ );
5958
6146
  }
5959
- if (typeof content === "string" && content.trim() !== "") {
5960
- lastItem.chat.content = content;
6147
+ if (result.content !== void 0 && typeof result.content !== "string") {
6148
+ throw new Error(
6149
+ `Chat response result content at index ${arrayIndex} must be a string`
6150
+ );
5961
6151
  }
5962
- if (name && name.trim() !== "") {
5963
- lastItem.chat.name = name;
6152
+ if (result.thought !== void 0 && typeof result.thought !== "string") {
6153
+ throw new Error(
6154
+ `Chat response result thought at index ${arrayIndex} must be a string`
6155
+ );
5964
6156
  }
5965
- if (functionCalls && functionCalls.length > 0) {
5966
- lastItem.chat.functionCalls = functionCalls;
6157
+ if (result.name !== void 0) {
6158
+ if (typeof result.name !== "string") {
6159
+ throw new Error(
6160
+ `Chat response result name at index ${arrayIndex} must be a string`
6161
+ );
6162
+ }
6163
+ if (result.name.trim() === "") {
6164
+ throw new Error(
6165
+ `Chat response result name at index ${arrayIndex} cannot be empty or whitespace-only`
6166
+ );
6167
+ }
5967
6168
  }
5968
- if (this.options?.debug) {
5969
- if (delta && typeof delta === "string") {
5970
- debugResponseDelta(delta);
5971
- } else if (!delta && (content || functionCalls)) {
5972
- debugResponse({ content, name, functionCalls });
6169
+ if (result.id !== void 0) {
6170
+ if (typeof result.id !== "string") {
6171
+ throw new Error(
6172
+ `Chat response result id at index ${arrayIndex} must be a string`
6173
+ );
6174
+ }
6175
+ if (result.id.trim() === "") {
6176
+ throw new Error(
6177
+ `Chat response result id at index ${arrayIndex} cannot be empty or whitespace-only`
6178
+ );
5973
6179
  }
5974
6180
  }
5975
- }
5976
- addTag(name) {
5977
- const lastItem = this.data.at(-1);
5978
- if (!lastItem) {
6181
+ if (result.functionCalls !== void 0) {
6182
+ if (!Array.isArray(result.functionCalls)) {
6183
+ throw new Error(
6184
+ `Chat response result functionCalls at index ${arrayIndex} must be an array`
6185
+ );
6186
+ }
6187
+ for (let callIndex = 0; callIndex < result.functionCalls.length; callIndex++) {
6188
+ const functionCall = result.functionCalls[callIndex];
6189
+ if (!functionCall) {
6190
+ throw new Error(
6191
+ `Function call at index ${callIndex} in result ${arrayIndex} cannot be null or undefined`
6192
+ );
6193
+ }
6194
+ if (!functionCall.id || typeof functionCall.id !== "string" || functionCall.id.trim() === "") {
6195
+ throw new Error(
6196
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a non-empty string id`
6197
+ );
6198
+ }
6199
+ if (functionCall.type !== "function") {
6200
+ throw new Error(
6201
+ `Function call at index ${callIndex} in result ${arrayIndex} must have type 'function'`
6202
+ );
6203
+ }
6204
+ if (!functionCall.function) {
6205
+ throw new Error(
6206
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a function object`
6207
+ );
6208
+ }
6209
+ if (!functionCall.function.name || typeof functionCall.function.name !== "string" || functionCall.function.name.trim() === "") {
6210
+ throw new Error(
6211
+ `Function call at index ${callIndex} in result ${arrayIndex} must have a non-empty function name`
6212
+ );
6213
+ }
6214
+ if (functionCall.function.params !== void 0) {
6215
+ if (typeof functionCall.function.params !== "string" && typeof functionCall.function.params !== "object") {
6216
+ throw new Error(
6217
+ `Function call params at index ${callIndex} in result ${arrayIndex} must be a string or object`
6218
+ );
6219
+ }
6220
+ }
6221
+ }
6222
+ }
6223
+ if (result.finishReason !== void 0) {
6224
+ const validFinishReasons = [
6225
+ "stop",
6226
+ "length",
6227
+ "function_call",
6228
+ "content_filter",
6229
+ "error"
6230
+ ];
6231
+ if (!validFinishReasons.includes(result.finishReason)) {
6232
+ throw new Error(
6233
+ `Chat response result finishReason at index ${arrayIndex} must be one of: ${validFinishReasons.join(", ")}`
6234
+ );
6235
+ }
6236
+ }
6237
+ }
6238
+ }
6239
+
6240
+ // mem/memory.ts
6241
+ var MemoryImpl = class {
6242
+ constructor(options) {
6243
+ this.options = options;
6244
+ }
6245
+ data = [];
6246
+ addRequest(items, index) {
6247
+ this.data.push(
6248
+ ...items.map((item) => {
6249
+ const value = structuredClone(item);
6250
+ return {
6251
+ role: item.role,
6252
+ chat: [{ index, value }]
6253
+ };
6254
+ })
6255
+ );
6256
+ if (this.options?.debug) {
6257
+ debugRequest(items, this.options?.debugHideSystemPrompt);
6258
+ }
6259
+ }
6260
+ addFunctionResults(results) {
6261
+ const chat = results.map(({ index, ...value }) => ({
6262
+ index,
6263
+ value: structuredClone(value)
6264
+ }));
6265
+ const lastItem = this.getLast();
6266
+ if (lastItem?.role === "function") {
6267
+ lastItem.chat.push(...chat);
6268
+ } else {
6269
+ this.data.push({ role: "function", chat });
6270
+ }
6271
+ }
6272
+ addResponse(results) {
6273
+ const chat = results.map(({ index, ...value }) => ({
6274
+ index,
6275
+ value: structuredClone(value)
6276
+ }));
6277
+ this.data.push({ role: "assistant", chat });
6278
+ if (this.options?.debug) {
6279
+ for (const result of results) {
6280
+ debugResponse(result);
6281
+ }
6282
+ }
6283
+ }
6284
+ updateResult({
6285
+ content,
6286
+ name,
6287
+ functionCalls,
6288
+ delta,
6289
+ index
6290
+ }) {
6291
+ const lastItem = this.data.at(-1);
6292
+ const log = () => {
6293
+ if (this.options?.debug) {
6294
+ if (delta && typeof delta === "string") {
6295
+ debugResponseDelta(delta);
6296
+ } else if (!delta && (content || functionCalls)) {
6297
+ debugResponse({ content, name, functionCalls, index });
6298
+ }
6299
+ }
6300
+ };
6301
+ if (!lastItem || lastItem.role !== "assistant") {
6302
+ this.data.push({
6303
+ role: "assistant",
6304
+ chat: [
6305
+ { index, value: structuredClone({ content, name, functionCalls }) }
6306
+ ]
6307
+ });
6308
+ log();
6309
+ return;
6310
+ }
6311
+ const chat = lastItem.chat.find((v) => v.index === index);
6312
+ if (!chat) {
6313
+ lastItem.chat.push({
6314
+ index,
6315
+ value: structuredClone({ content, name, functionCalls })
6316
+ });
6317
+ log();
6318
+ return;
6319
+ }
6320
+ if ("content" in chat.value && typeof content === "string" && content.trim() !== "") {
6321
+ chat.value.content = content;
6322
+ }
6323
+ if ("name" in chat.value && name && name.trim() !== "") {
6324
+ chat.value.name = name;
6325
+ }
6326
+ if ("functionCalls" in chat.value && functionCalls && functionCalls.length > 0) {
6327
+ chat.value.functionCalls = functionCalls;
6328
+ }
6329
+ log();
6330
+ }
6331
+ addTag(name) {
6332
+ const lastItem = this.data.at(-1);
6333
+ if (!lastItem) {
5979
6334
  return;
5980
6335
  }
5981
6336
  if (!lastItem.tags) {
@@ -5990,8 +6345,7 @@ var MemoryImpl = class {
5990
6345
  if (tagIndex === -1) {
5991
6346
  throw new Error(`Tag "${name}" not found`);
5992
6347
  }
5993
- const removedItems = this.data.splice(tagIndex);
5994
- return removedItems.map((item) => item.chat);
6348
+ return this.data.splice(tagIndex);
5995
6349
  }
5996
6350
  removeByTag(name) {
5997
6351
  const indices = this.data.reduce((acc, item, index) => {
@@ -6003,28 +6357,40 @@ var MemoryImpl = class {
6003
6357
  if (indices.length === 0) {
6004
6358
  throw new Error(`No items found with tag "${name}"`);
6005
6359
  }
6006
- return indices.reverse().map((index) => this.data.splice(index, 1).at(0)?.chat).filter(Boolean).reverse();
6360
+ return indices.reverse().map((index) => this.data.splice(index, 1).at(0)).filter((item) => item !== void 0).reverse();
6007
6361
  }
6008
- history() {
6009
- return this.data.map((item) => item.chat);
6362
+ history(index) {
6363
+ const result = [];
6364
+ for (const { role, chat } of this.data) {
6365
+ let values;
6366
+ if (role === "function") {
6367
+ values = chat.filter((v) => v.index === index).map((v) => v.value);
6368
+ } else {
6369
+ values = chat.find((v) => v.index === index)?.value;
6370
+ }
6371
+ if (Array.isArray(values)) {
6372
+ result.push(
6373
+ ...values.map(
6374
+ (v) => ({ ...v, role })
6375
+ )
6376
+ );
6377
+ } else if (values) {
6378
+ result.push({ ...values, role });
6379
+ }
6380
+ }
6381
+ return result;
6010
6382
  }
6011
6383
  getLast() {
6012
- const lastItem = this.data.at(-1);
6013
- if (!lastItem) return void 0;
6014
- return {
6015
- chat: lastItem.chat,
6016
- tags: lastItem.tags
6017
- };
6384
+ return this.data.at(-1);
6018
6385
  }
6019
6386
  reset() {
6020
6387
  this.data = [];
6021
6388
  }
6022
6389
  };
6023
6390
  var AxMemory = class {
6024
- constructor(limit = defaultLimit, options) {
6025
- this.limit = limit;
6391
+ constructor(options) {
6026
6392
  this.options = options;
6027
- this.defaultMemory = new MemoryImpl(limit, options);
6393
+ this.defaultMemory = new MemoryImpl(options);
6028
6394
  }
6029
6395
  memories = /* @__PURE__ */ new Map();
6030
6396
  defaultMemory;
@@ -6033,15 +6399,22 @@ var AxMemory = class {
6033
6399
  return this.defaultMemory;
6034
6400
  }
6035
6401
  if (!this.memories.has(sessionId)) {
6036
- this.memories.set(sessionId, new MemoryImpl(this.limit, this.options));
6402
+ this.memories.set(sessionId, new MemoryImpl(this.options));
6037
6403
  }
6038
6404
  return this.memories.get(sessionId);
6039
6405
  }
6040
- add(value, sessionId) {
6041
- this.getMemory(sessionId).add(value);
6406
+ addRequest(value, sessionId) {
6407
+ for (const item of value) {
6408
+ axValidateChatRequestMessage(item);
6409
+ }
6410
+ this.getMemory(sessionId).addRequest(value, 0);
6411
+ }
6412
+ addResponse(results, sessionId) {
6413
+ axValidateChatResponseResult(results);
6414
+ this.getMemory(sessionId).addResponse(results);
6042
6415
  }
6043
- addResult(result, sessionId) {
6044
- this.getMemory(sessionId).addResult(result);
6416
+ addFunctionResults(results, sessionId) {
6417
+ this.getMemory(sessionId).addFunctionResults(results);
6045
6418
  }
6046
6419
  updateResult(result, sessionId) {
6047
6420
  this.getMemory(sessionId).updateResult(result);
@@ -6052,8 +6425,8 @@ var AxMemory = class {
6052
6425
  rewindToTag(name, sessionId) {
6053
6426
  return this.getMemory(sessionId).rewindToTag(name);
6054
6427
  }
6055
- history(sessionId) {
6056
- return this.getMemory(sessionId).history();
6428
+ history(index, sessionId) {
6429
+ return this.getMemory(sessionId).history(index);
6057
6430
  }
6058
6431
  getLast(sessionId) {
6059
6432
  return this.getMemory(sessionId).getLast();
@@ -6062,7 +6435,7 @@ var AxMemory = class {
6062
6435
  if (!sessionId) {
6063
6436
  this.defaultMemory.reset();
6064
6437
  } else {
6065
- this.memories.set(sessionId, new MemoryImpl(this.limit, this.options));
6438
+ this.memories.set(sessionId, new MemoryImpl(this.options));
6066
6439
  }
6067
6440
  }
6068
6441
  };
@@ -6143,8 +6516,156 @@ var assertStreamingAssertions = async (asserts, xstate, content, final = false)
6143
6516
  }
6144
6517
  };
6145
6518
 
6519
+ // dsp/errors.ts
6520
+ var ValidationError = class extends Error {
6521
+ fields;
6522
+ constructor({
6523
+ message,
6524
+ fields
6525
+ }) {
6526
+ super(message);
6527
+ this.fields = fields;
6528
+ this.name = this.constructor.name;
6529
+ }
6530
+ getFixingInstructions = () => {
6531
+ const toFieldType2 = (type) => {
6532
+ const baseType = (() => {
6533
+ switch (type?.name) {
6534
+ case "string":
6535
+ return "string";
6536
+ case "number":
6537
+ return "number";
6538
+ case "boolean":
6539
+ return "boolean";
6540
+ case "date":
6541
+ return 'date ("YYYY-MM-DD" format)';
6542
+ case "datetime":
6543
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6544
+ case "json":
6545
+ return "JSON object";
6546
+ case "class":
6547
+ return "classification class";
6548
+ case "code":
6549
+ return "code";
6550
+ default:
6551
+ return "string";
6552
+ }
6553
+ })();
6554
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
6555
+ };
6556
+ return this.fields.map((field) => ({
6557
+ name: "outputError",
6558
+ title: "Output Correction Required",
6559
+ 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.`
6560
+ }));
6561
+ };
6562
+ toString() {
6563
+ const toFieldType2 = (type) => {
6564
+ const baseType = (() => {
6565
+ switch (type?.name) {
6566
+ case "string":
6567
+ return "string";
6568
+ case "number":
6569
+ return "number";
6570
+ case "boolean":
6571
+ return "boolean";
6572
+ case "date":
6573
+ return 'date ("YYYY-MM-DD" format)';
6574
+ case "datetime":
6575
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6576
+ case "json":
6577
+ return "JSON object";
6578
+ case "class":
6579
+ return "classification class";
6580
+ case "code":
6581
+ return "code";
6582
+ default:
6583
+ return "string";
6584
+ }
6585
+ })();
6586
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
6587
+ };
6588
+ return [
6589
+ `${this.name}: ${this.message}`,
6590
+ ...this.fields.map(
6591
+ (field) => ` - ${field.title}: Expected format '${toFieldType2(field.type)}'`
6592
+ )
6593
+ ].join("\n");
6594
+ }
6595
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, _options) {
6596
+ return this.toString();
6597
+ }
6598
+ };
6599
+
6146
6600
  // dsp/datetime.ts
6147
6601
  var import_moment_timezone = __toESM(require("moment-timezone"), 1);
6602
+ function parseLLMFriendlyDate(field, dateStr, required = false) {
6603
+ try {
6604
+ return _parseLLMFriendlyDate(dateStr);
6605
+ } catch (err) {
6606
+ if (field.isOptional && !required) {
6607
+ return;
6608
+ }
6609
+ const message = err.message;
6610
+ throw new ValidationError({ fields: [field], message, value: dateStr });
6611
+ }
6612
+ }
6613
+ function _parseLLMFriendlyDate(dateStr) {
6614
+ if (!(0, import_moment_timezone.default)(dateStr, "YYYY-MM-DD", true).isValid()) {
6615
+ throw new Error(
6616
+ 'Invalid date format. Please provide the date in "YYYY-MM-DD" format.'
6617
+ );
6618
+ }
6619
+ const date = import_moment_timezone.default.utc(dateStr, "YYYY-MM-DD").startOf("day");
6620
+ return date.toDate();
6621
+ }
6622
+ function parseLLMFriendlyDateTime(field, dateStr, required = false) {
6623
+ try {
6624
+ return _parseLLMFriendlyDateTime(dateStr);
6625
+ } catch (err) {
6626
+ if (field.isOptional && !required) {
6627
+ return;
6628
+ }
6629
+ const message = err.message;
6630
+ throw new ValidationError({ fields: [field], message, value: dateStr });
6631
+ }
6632
+ }
6633
+ function _parseLLMFriendlyDateTime(dateTimeStr) {
6634
+ const dateTimeRegex = /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/;
6635
+ const match = dateTimeStr.match(dateTimeRegex);
6636
+ if (!match) {
6637
+ throw new Error(
6638
+ '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.'
6639
+ );
6640
+ }
6641
+ const [, dateTime, timeZone] = match;
6642
+ if (!dateTime || !timeZone) {
6643
+ throw new Error(
6644
+ '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.'
6645
+ );
6646
+ }
6647
+ const zone = import_moment_timezone.default.tz.zone(timeZone);
6648
+ if (!zone) {
6649
+ throw new Error(
6650
+ `Unrecognized time zone ${timeZone}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`
6651
+ );
6652
+ }
6653
+ const date = import_moment_timezone.default.tz(
6654
+ dateTime,
6655
+ ["YYYY-MM-DD HH:mm", "YYYY-MM-DD HH:mm:ss"],
6656
+ zone.name
6657
+ );
6658
+ if (!date.isValid()) {
6659
+ throw new Error(
6660
+ "Invalid date and time values. Please ensure all components are correct."
6661
+ );
6662
+ }
6663
+ return date.utc().toDate();
6664
+ }
6665
+ var formatDateWithTimezone = (date) => {
6666
+ const momentDate = (0, import_moment_timezone.default)(date).utc();
6667
+ return momentDate.format(`YYYY-MM-DD HH:mm:ss UTC`);
6668
+ };
6148
6669
 
6149
6670
  // dsp/util.ts
6150
6671
  var colorLog3 = new ColorLog();
@@ -6307,18 +6828,24 @@ var parseMarkdownList = (input) => {
6307
6828
  }
6308
6829
  return list;
6309
6830
  };
6310
- function mergeDeltas(base, delta) {
6831
+ function mergeDeltas(base, currentDelta) {
6832
+ const { index, delta, version } = currentDelta;
6833
+ const target = base.find((b) => b.index === index)?.delta;
6834
+ if (!target) {
6835
+ base.push({ index, delta, version });
6836
+ return base;
6837
+ }
6311
6838
  for (const key of Object.keys(delta)) {
6312
- const baseValue = base[key];
6839
+ const baseValue = target[key];
6313
6840
  const deltaValue = delta[key];
6314
6841
  if (baseValue === void 0 && Array.isArray(deltaValue)) {
6315
- base[key] = [...deltaValue];
6842
+ target[key] = [...deltaValue];
6316
6843
  } else if (Array.isArray(baseValue) && Array.isArray(deltaValue)) {
6317
- base[key] = [...baseValue ?? [], ...deltaValue];
6844
+ target[key] = [...baseValue, ...deltaValue];
6318
6845
  } else if ((baseValue === void 0 || typeof baseValue === "string") && typeof deltaValue === "string") {
6319
- base[key] = (baseValue ?? "") + deltaValue;
6846
+ target[key] = `${baseValue ?? ""}${deltaValue}`;
6320
6847
  } else {
6321
- base[key] = deltaValue;
6848
+ target[key] = deltaValue;
6322
6849
  }
6323
6850
  }
6324
6851
  return base;
@@ -6435,994 +6962,433 @@ var updateDetailedProgress = (roundIndex, current, total, elapsedTime, example,
6435
6962
  console.log(output);
6436
6963
  };
6437
6964
 
6438
- // dsp/prompt.ts
6439
- var functionCallInstructions = `
6440
- ## Function Call Instructions
6441
- - Complete the task, using the functions defined earlier in this prompt.
6442
- - Call functions step-by-step, using the output of one function as input to the next.
6443
- - Use the function results to generate the output fields.`;
6444
- var formattingRules = `
6445
- ## Strict Output Formatting Rules
6446
- - Output must strictly follow the defined plain-text \`field name: value\` field format.
6447
- - Output field, values must strictly adhere to the specified output field formatting rules.
6448
- - Do not add any text before or after the output fields, just the field name and value.
6449
- - Do not use code blocks.`;
6450
- var AxPromptTemplate = class {
6451
- sig;
6452
- fieldTemplates;
6453
- task;
6454
- thoughtFieldName;
6455
- functions;
6456
- constructor(sig, options, fieldTemplates) {
6457
- this.sig = sig;
6458
- this.fieldTemplates = fieldTemplates;
6459
- this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
6460
- this.functions = options?.functions;
6461
- const task = [];
6462
- const inArgs = renderDescFields(this.sig.getInputFields());
6463
- const outArgs = renderDescFields(this.sig.getOutputFields());
6464
- task.push(
6465
- `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
6466
- );
6467
- const funcs = this.functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
6468
- const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
6469
- if (funcList && funcList.length > 0) {
6470
- task.push(`## Available Functions
6471
- ${funcList}`);
6472
- }
6473
- const inputFields = renderInputFields(this.sig.getInputFields());
6474
- task.push(`## Input Fields
6475
- ${inputFields}`);
6476
- const outputFields = renderOutputFields(this.sig.getOutputFields());
6477
- task.push(`## Output Fields
6478
- ${outputFields}`);
6479
- if (funcList && funcList.length > 0) {
6480
- task.push(functionCallInstructions.trim());
6481
- }
6482
- task.push(formattingRules.trim());
6483
- const desc = this.sig.getDescription();
6484
- if (desc) {
6485
- const text = formatDescription(desc);
6486
- task.push(text);
6965
+ // dsp/extract.ts
6966
+ var extractValues = (sig, values, content, strictMode = false) => {
6967
+ const xstate = { extractedFields: [], streamedIndex: {}, s: -1 };
6968
+ streamingExtractValues(sig, values, xstate, content, { strictMode });
6969
+ streamingExtractFinalValue(sig, values, xstate, content);
6970
+ for (const field of sig.getOutputFields()) {
6971
+ if (field.isInternal) {
6972
+ delete values[field.name];
6487
6973
  }
6488
- this.task = {
6489
- type: "text",
6490
- text: task.join("\n\n")
6491
- };
6492
6974
  }
6493
- renderSingleValueUserContent = (values, renderedExamples, renderedDemos, examplesInSystemPrompt) => {
6494
- const completion = this.renderInputFields(values);
6495
- const promptList = examplesInSystemPrompt ? completion : [...renderedExamples, ...renderedDemos, ...completion];
6496
- const prompt = promptList.filter((v) => v !== void 0);
6497
- return prompt.every((v) => v.type === "text") ? prompt.map((v) => v.text).join("\n") : prompt.reduce(combineConsecutiveStrings("\n"), []);
6498
- };
6499
- render = (values, {
6500
- examples,
6501
- demos
6502
- }) => {
6503
- const renderedExamples = examples ? [
6504
- { type: "text", text: "\n\n## Examples\n" },
6505
- ...this.renderExamples(examples)
6506
- ] : [];
6507
- const renderedDemos = demos ? this.renderDemos(demos) : [];
6508
- const allTextExamples = renderedExamples.every((v) => v.type === "text");
6509
- const allTextDemos = renderedDemos.every((v) => v.type === "text");
6510
- const examplesInSystemPrompt = allTextExamples && allTextDemos;
6511
- let systemContent = this.task.text;
6512
- if (examplesInSystemPrompt) {
6513
- const combinedItems = [
6514
- { type: "text", text: systemContent },
6515
- ...renderedExamples,
6516
- ...renderedDemos
6517
- ];
6518
- combinedItems.reduce(combineConsecutiveStrings(""), []);
6519
- if (combinedItems && combinedItems[0]) {
6520
- systemContent = combinedItems[0].text;
6521
- }
6975
+ };
6976
+ var checkMissingRequiredFields = (xstate, values, outputFields) => {
6977
+ const missingFields = [];
6978
+ for (const field of outputFields) {
6979
+ if (field && !field.isOptional && values[field.name] === void 0) {
6980
+ missingFields.push(field);
6522
6981
  }
6523
- const systemPrompt = {
6524
- role: "system",
6525
- content: systemContent
6526
- };
6527
- if (Array.isArray(values)) {
6528
- let messages = [];
6529
- const history = values;
6530
- for (const [index, message] of history.entries()) {
6531
- let content;
6532
- if (index === 0) {
6533
- content = this.renderSingleValueUserContent(
6534
- message.values,
6535
- renderedExamples,
6536
- renderedDemos,
6537
- examplesInSystemPrompt
6538
- );
6539
- } else {
6540
- content = this.renderSingleValueUserContent(
6541
- message.values,
6542
- [],
6543
- [],
6544
- false
6545
- );
6546
- }
6547
- if (message.role === "user") {
6548
- messages.push({ role: "user", content });
6982
+ }
6983
+ if (missingFields.length > 0) {
6984
+ throw new ValidationError({
6985
+ message: `Required ${missingFields.length === 1 ? "field" : "fields"} not found`,
6986
+ fields: missingFields
6987
+ });
6988
+ }
6989
+ };
6990
+ var streamingExtractValues = (sig, values, xstate, content, { strictMode, skipEarlyFail } = {}) => {
6991
+ const fields = sig.getOutputFields();
6992
+ let expectedField;
6993
+ for (const [index, field] of fields.entries()) {
6994
+ if (index === xstate.currFieldIndex && !xstate.inAssumedField) {
6995
+ continue;
6996
+ }
6997
+ if (field.name in values && !(index === xstate.currFieldIndex && xstate.inAssumedField)) {
6998
+ continue;
6999
+ }
7000
+ const isFirst = xstate.extractedFields.length === 0;
7001
+ const prefix = (isFirst ? "" : "\n") + field.title + ":";
7002
+ let e = matchesContent(content, prefix, xstate.s);
7003
+ let prefixLen = prefix.length;
7004
+ switch (e) {
7005
+ case -1:
7006
+ if (skipEarlyFail) {
6549
7007
  continue;
6550
7008
  }
6551
- if (message.role !== "assistant") {
6552
- throw new Error("Invalid message role");
7009
+ if (!strictMode && fields.length === 1 && xstate.currField === void 0) {
7010
+ xstate.inAssumedField = true;
7011
+ expectedField = field;
7012
+ prefixLen = 0;
7013
+ e = 0;
7014
+ break;
6553
7015
  }
6554
- if (typeof content !== "string") {
6555
- throw new Error(
6556
- "Assistant message cannot contain non-text content like images, files,etc"
6557
- );
7016
+ if (xstate.currField === void 0 && !field.isOptional) {
7017
+ throw new ValidationError({
7018
+ message: "Expected (Required) field not found",
7019
+ fields: [field]
7020
+ });
6558
7021
  }
6559
- messages.push({ role: "assistant", content });
6560
- }
6561
- return [systemPrompt, ...messages];
7022
+ expectedField = field.isOptional ? void 0 : field;
7023
+ continue;
7024
+ // Field is not found, continue to the next field
7025
+ case -2:
7026
+ return true;
7027
+ // Partial match at end, skip and gather more content
7028
+ case -3:
7029
+ return true;
7030
+ // String is only whitespace, skip and gather more content
7031
+ case -4:
7032
+ xstate.inBlock = true;
7033
+ return true;
6562
7034
  }
6563
- const userContent = this.renderSingleValueUserContent(
6564
- values,
6565
- renderedExamples,
6566
- renderedDemos,
6567
- examplesInSystemPrompt
6568
- );
6569
- return [systemPrompt, { role: "user", content: userContent }];
6570
- };
6571
- renderExtraFields = (extraFields) => {
6572
- const prompt = [];
6573
- if (!extraFields || extraFields.length === 0) {
6574
- return prompt;
7035
+ if (expectedField && expectedField.name !== field.name) {
7036
+ throw new ValidationError({
7037
+ message: "Expected (Required) field not found",
7038
+ fields: [expectedField]
7039
+ });
6575
7040
  }
6576
- const groupedFields = extraFields.reduce(
6577
- (acc, field) => {
6578
- const title = field.title;
6579
- if (!acc[title]) {
6580
- acc[title] = [];
6581
- }
6582
- acc[title].push(field);
6583
- return acc;
6584
- },
6585
- {}
6586
- );
6587
- const formattedGroupedFields = Object.entries(groupedFields).map(([title, fields]) => {
6588
- if (fields.length === 1) {
6589
- const field = fields[0];
6590
- return {
6591
- title,
6592
- name: field.name,
6593
- description: field.description
6594
- };
6595
- } else if (fields.length > 1) {
6596
- const valuesList = fields.map((field) => `- ${field.description}`).join("\n");
6597
- return {
6598
- title,
6599
- name: fields[0].name,
6600
- description: valuesList
6601
- };
7041
+ if (xstate.currField !== void 0 && xstate.inAssumedField) {
7042
+ xstate.inAssumedField = false;
7043
+ xstate.streamedIndex[xstate.currField.name] = 0;
7044
+ xstate.currField = void 0;
7045
+ }
7046
+ if (xstate.currField) {
7047
+ const val = content.substring(xstate.s, e).trim();
7048
+ const parsedValue = validateAndParseFieldValue(xstate.currField, val);
7049
+ if (parsedValue !== void 0) {
7050
+ values[xstate.currField.name] = parsedValue;
6602
7051
  }
6603
- }).filter(Boolean);
6604
- formattedGroupedFields.forEach((field) => {
6605
- const fn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
6606
- prompt.push(...fn(field, field.description));
6607
- });
6608
- return prompt;
6609
- };
6610
- renderExamples = (data) => {
6611
- const list = [];
6612
- const exampleContext = {
6613
- isExample: true
6614
- };
6615
- for (const [index, item] of data.entries()) {
6616
- const renderedInputItem = this.sig.getInputFields().map(
6617
- (field) => this.renderInField(field, item, {
6618
- ...exampleContext,
6619
- isInputField: true
6620
- })
6621
- ).filter((v) => v !== void 0).flat();
6622
- const renderedOutputItem = this.sig.getOutputFields().map(
6623
- (field) => this.renderInField(field, item, {
6624
- ...exampleContext,
6625
- isInputField: false
6626
- })
6627
- ).filter((v) => v !== void 0).flat();
6628
- const renderedItem = [...renderedInputItem, ...renderedOutputItem];
6629
- if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
6630
- list.push({ type: "text", text: "---\n\n" });
7052
+ if (xstate.prevFields) {
7053
+ xstate.prevFields?.push({ field: xstate.currField, s: xstate.s, e });
7054
+ } else {
7055
+ xstate.prevFields = [{ field: xstate.currField, s: xstate.s, e }];
6631
7056
  }
6632
- renderedItem.forEach((v) => {
6633
- if ("text" in v) {
6634
- v.text = v.text + "\n";
6635
- }
6636
- list.push(v);
6637
- });
6638
7057
  }
6639
- return list;
6640
- };
6641
- renderDemos = (data) => {
6642
- const list = [];
6643
- const inputFields = this.sig.getInputFields();
6644
- const outputFields = this.sig.getOutputFields();
6645
- const demoContext = {
6646
- isExample: true
6647
- };
6648
- for (const item of data) {
6649
- const inputRenderedItems = inputFields.map(
6650
- (field) => this.renderInField(field, item, {
6651
- ...demoContext,
6652
- isInputField: true
6653
- })
6654
- ).filter((v) => v !== void 0).flat();
6655
- const outputRenderedItems = outputFields.map(
6656
- (field) => this.renderInField(field, item, {
6657
- ...demoContext,
6658
- isInputField: false
6659
- })
6660
- ).filter((v) => v !== void 0).flat();
6661
- const renderedItem = [...inputRenderedItems, ...outputRenderedItems];
6662
- renderedItem.slice(0, -1).forEach((v) => {
6663
- if ("text" in v) {
6664
- v.text = v.text + "\n";
6665
- }
6666
- list.push(v);
6667
- });
7058
+ xstate.s = e + prefixLen;
7059
+ xstate.currField = field;
7060
+ xstate.currFieldIndex = index;
7061
+ if (!xstate.extractedFields.includes(field)) {
7062
+ xstate.extractedFields.push(field);
6668
7063
  }
6669
- return list;
6670
- };
6671
- renderInputFields = (values) => {
6672
- const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values, void 0)).filter((v) => v !== void 0).flat();
6673
- renderedItems.filter((v) => v.type === "text").forEach((v) => {
6674
- v.text = v.text + "\n";
6675
- });
6676
- return renderedItems;
6677
- };
6678
- renderInField = (field, values, context3) => {
6679
- const value = values[field.name];
6680
- if (isEmptyValue(field, value, context3)) {
6681
- return;
7064
+ if (xstate.streamedIndex[field.name] === void 0) {
7065
+ xstate.streamedIndex[field.name] = 0;
6682
7066
  }
6683
- if (field.type) {
6684
- validateValue(field, value);
7067
+ }
7068
+ };
7069
+ var streamingExtractFinalValue = (sig, values, xstate, content) => {
7070
+ if (xstate.currField) {
7071
+ let val = content.substring(xstate.s).trim();
7072
+ const parsedValue = validateAndParseFieldValue(xstate.currField, val);
7073
+ if (parsedValue !== void 0) {
7074
+ values[xstate.currField.name] = parsedValue;
6685
7075
  }
6686
- const processedValue = processValue(field, value);
6687
- const textFieldFn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
6688
- return textFieldFn(field, processedValue);
6689
- };
6690
- defaultRenderInField = (field, value) => {
6691
- if (field.type?.name === "image") {
6692
- const validateImage = (value2) => {
6693
- if (!value2) {
6694
- throw new Error("Image field value is required.");
6695
- }
6696
- if (typeof value2 !== "object") {
6697
- throw new Error("Image field value must be an object.");
6698
- }
6699
- if (!("mimeType" in value2)) {
6700
- throw new Error("Image field must have mimeType");
6701
- }
6702
- if (!("data" in value2)) {
6703
- throw new Error("Image field must have data");
6704
- }
6705
- return value2;
6706
- };
6707
- let result = [
6708
- { type: "text", text: `${field.title}: ` }
6709
- ];
6710
- if (field.type.isArray) {
6711
- if (!Array.isArray(value)) {
6712
- throw new Error("Image field value must be an array.");
7076
+ }
7077
+ checkMissingRequiredFields(xstate, values, sig.getOutputFields());
7078
+ };
7079
+ var convertValueToType = (field, val, required = false) => {
7080
+ switch (field.type?.name) {
7081
+ case "code":
7082
+ return extractBlock(val);
7083
+ case "string":
7084
+ return val;
7085
+ case "number": {
7086
+ const v = Number(val);
7087
+ if (Number.isNaN(v)) {
7088
+ if (field.isOptional && !required) {
7089
+ return;
6713
7090
  }
6714
- result = result.concat(
6715
- value.map((v) => {
6716
- const validated = validateImage(v);
6717
- return {
6718
- type: "image",
6719
- mimeType: validated.mimeType,
6720
- image: validated.data
6721
- };
6722
- })
6723
- );
6724
- } else {
6725
- const validated = validateImage(value);
6726
- result.push({
6727
- type: "image",
6728
- mimeType: validated.mimeType,
6729
- image: validated.data
6730
- });
7091
+ throw new Error("Invalid number");
6731
7092
  }
6732
- return result;
7093
+ return v;
6733
7094
  }
6734
- if (field.type?.name === "audio") {
6735
- const validateAudio = (value2) => {
6736
- if (!value2) {
6737
- throw new Error("Audio field value is required.");
6738
- }
6739
- if (typeof value2 !== "object") {
6740
- throw new Error("Audio field value must be an object.");
6741
- }
6742
- if (!("data" in value2)) {
6743
- throw new Error("Audio field must have data");
6744
- }
6745
- return value2;
6746
- };
6747
- let result = [
6748
- { type: "text", text: `${field.title}: ` }
6749
- ];
6750
- if (field.type.isArray) {
6751
- if (!Array.isArray(value)) {
6752
- throw new Error("Audio field value must be an array.");
6753
- }
6754
- result = result.concat(
6755
- value.map((v) => {
6756
- const validated = validateAudio(v);
6757
- return {
6758
- type: "audio",
6759
- format: validated.format ?? "wav",
6760
- data: validated.data
6761
- };
6762
- })
6763
- );
7095
+ case "boolean": {
7096
+ if (typeof val === "boolean") {
7097
+ return val;
7098
+ }
7099
+ const v = val.toLowerCase();
7100
+ if (v === "true") {
7101
+ return true;
7102
+ } else if (v === "false") {
7103
+ return false;
6764
7104
  } else {
6765
- const validated = validateAudio(value);
6766
- result.push({
6767
- type: "audio",
6768
- format: validated.format ?? "wav",
6769
- data: validated.data
6770
- });
7105
+ if (field.isOptional && !required) {
7106
+ return;
7107
+ }
7108
+ throw new Error("Invalid boolean");
6771
7109
  }
6772
- return result;
6773
- }
6774
- const text = [field.title, ": "];
6775
- if (Array.isArray(value)) {
6776
- text.push("\n");
6777
- text.push(value.map((v) => `- ${v}`).join("\n"));
6778
- } else {
6779
- text.push(value);
6780
- }
6781
- return [{ type: "text", text: text.join("") }];
6782
- };
6783
- };
6784
- var renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
6785
- var renderInputFields = (fields) => {
6786
- const rows = fields.map((field) => {
6787
- const name = field.title;
6788
- const type = field.type?.name ? toFieldType(field.type) : "string";
6789
- const requiredMsg = field.isOptional ? `This optional ${type} field may be omitted` : `A ${type} field`;
6790
- const description = field.description ? ` ${formatDescription(field.description)}` : "";
6791
- return `${name}: (${requiredMsg})${description}`.trim();
6792
- });
6793
- return rows.join("\n");
6794
- };
6795
- var renderOutputFields = (fields) => {
6796
- const rows = fields.map((field) => {
6797
- const name = field.title;
6798
- const type = field.type?.name ? toFieldType(field.type) : "string";
6799
- const requiredMsg = field.isOptional ? `Only include this ${type} field if its value is available` : `This ${type} field must be included`;
6800
- let description = "";
6801
- if (field.description && field.description.length > 0) {
6802
- const value = field.type?.name === "class" ? field.description : formatDescription(field.description);
6803
- description = ` ${value}`;
6804
7110
  }
6805
- if (field.type?.options && field.type.options.length > 0) {
6806
- if (description.length > 0) {
6807
- description += `. `;
7111
+ case "date":
7112
+ return parseLLMFriendlyDate(field, val, required);
7113
+ case "datetime":
7114
+ return parseLLMFriendlyDateTime(field, val, required);
7115
+ case "class":
7116
+ const className = val;
7117
+ if (field.type.options && !field.type.options.includes(className)) {
7118
+ if (field.isOptional) {
7119
+ return;
7120
+ }
7121
+ throw new Error(
7122
+ `Invalid class '${val}', expected one of the following: ${field.type.options.join(", ")}`
7123
+ );
6808
7124
  }
6809
- description += `Allowed values: ${field.type.options.join(", ")}`;
6810
- }
6811
- return `${name}: (${requiredMsg})${description}`.trim();
6812
- });
6813
- return rows.join("\n");
7125
+ return className;
7126
+ default:
7127
+ return val;
7128
+ }
6814
7129
  };
6815
- var processValue = (field, value) => {
6816
- if (field.type?.name === "date" && value instanceof Date) {
6817
- const v = value.toISOString();
6818
- return v.slice(0, v.indexOf("T"));
7130
+ function* yieldDelta(content, field, s2, e, xstate, index) {
7131
+ const { name: fieldName, isInternal } = field;
7132
+ const { isArray: fieldIsArray, name: fieldTypeName } = field.type ?? {};
7133
+ if (isInternal || fieldIsArray || fieldTypeName && fieldTypeName !== "string" && fieldTypeName !== "code") {
7134
+ return;
6819
7135
  }
6820
- if (field.type?.name === "datetime" && value instanceof Date) {
6821
- return formatDateWithTimezone(value);
7136
+ const pos = xstate.streamedIndex[fieldName] ?? 0;
7137
+ const isFirstChunk = pos === 0;
7138
+ const d1 = content.substring(s2 + pos, e);
7139
+ if (d1.length === 0) {
7140
+ return;
6822
7141
  }
6823
- if (field.type?.name === "image" && typeof value === "object") {
6824
- return value;
7142
+ let d2 = d1.replace(/\s+$/, "");
7143
+ if (xstate.currField?.type?.name === "code") {
7144
+ d2 = d2.replace(/\s*```\s*$/, "");
6825
7145
  }
6826
- if (field.type?.name === "audio" && typeof value === "object") {
6827
- return value;
7146
+ let d3 = isFirstChunk ? d2.trimStart() : d2;
7147
+ if (xstate.currField?.type?.name === "code") {
7148
+ d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
6828
7149
  }
6829
- if (typeof value === "string") {
6830
- return value;
7150
+ if (d3.length > 0) {
7151
+ yield { index, delta: { [fieldName]: d3 } };
7152
+ xstate.streamedIndex[fieldName] = pos + d2.length;
6831
7153
  }
6832
- return JSON.stringify(value, null, 2);
6833
- };
6834
- var toFieldType = (type) => {
6835
- const baseType = (() => {
6836
- switch (type?.name) {
6837
- case "string":
6838
- return "string";
6839
- case "number":
6840
- return "number";
6841
- case "boolean":
6842
- return "boolean";
6843
- case "date":
6844
- return 'date ("YYYY-MM-DD" format)';
6845
- case "datetime":
6846
- return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
6847
- case "json":
6848
- return "JSON object";
6849
- case "class":
6850
- return "classification class";
6851
- case "code":
6852
- return "code";
6853
- default:
6854
- return "string";
6855
- }
6856
- })();
6857
- return type?.isArray ? `json array of ${baseType} items` : baseType;
6858
- };
6859
- function combineConsecutiveStrings(separator) {
6860
- return (acc, current) => {
6861
- if (current.type === "text") {
6862
- const previous = acc.length > 0 ? acc[acc.length - 1] : null;
6863
- if (previous && previous.type === "text") {
6864
- previous.text += separator + current.text;
6865
- } else {
6866
- acc.push(current);
6867
- }
6868
- } else {
6869
- acc.push(current);
6870
- }
6871
- return acc;
6872
- };
6873
7154
  }
6874
- var isEmptyValue = (field, value, context3) => {
6875
- if (typeof value === "boolean") {
6876
- return false;
7155
+ function* streamValues(sig, content, values, xstate, index) {
7156
+ for (const prevField of xstate.prevFields ?? []) {
7157
+ const { field, s: s2, e } = prevField;
7158
+ yield* yieldDelta(content, field, s2, e, xstate, index);
6877
7159
  }
6878
- if (!value || (Array.isArray(value) || typeof value === "string") && value.length === 0) {
6879
- if (context3?.isExample) {
6880
- return true;
6881
- }
6882
- if (field.isOptional || field.isInternal) {
6883
- return true;
6884
- }
6885
- const fieldType = context3?.isInputField !== false ? "input" : "output";
6886
- throw new Error(`Value for ${fieldType} field '${field.name}' is required.`);
7160
+ xstate.prevFields = void 0;
7161
+ if (!xstate.currField || xstate.currField.isInternal) {
7162
+ return;
6887
7163
  }
6888
- return false;
6889
- };
6890
- function formatDescription(str) {
6891
- const value = str.trim();
6892
- return value.length > 0 ? `${value.charAt(0).toUpperCase()}${value.slice(1)}${value.endsWith(".") ? "" : "."}` : "";
6893
- }
6894
-
6895
- // dsp/validate.ts
6896
- var ValidationError = class extends Error {
6897
- fields;
6898
- constructor({
6899
- message,
6900
- fields
6901
- }) {
6902
- super(message);
6903
- this.fields = fields;
6904
- this.name = this.constructor.name;
6905
- }
6906
- getFixingInstructions = () => {
6907
- return this.fields.map((field) => ({
6908
- name: "outputError",
6909
- title: "Output Correction Required",
6910
- 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.`
6911
- }));
6912
- };
6913
- toString() {
6914
- return [
6915
- `${this.name}: ${this.message}`,
6916
- ...this.fields.map(
6917
- (field) => ` - ${field.title}: Expected format '${toFieldType(field.type)}'`
6918
- )
6919
- ].join("\n");
6920
- }
6921
- [Symbol.for("nodejs.util.inspect.custom")](_depth, _options) {
6922
- return this.toString();
6923
- }
6924
- };
6925
- function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId) {
6926
- mem.add(
6927
- {
6928
- role: "user",
6929
- content: promptTemplate.renderExtraFields(errorFields)
6930
- },
6931
- sessionId
7164
+ yield* yieldDelta(
7165
+ content,
7166
+ xstate.currField,
7167
+ xstate.s,
7168
+ content.length,
7169
+ xstate,
7170
+ index
6932
7171
  );
6933
- mem.addTag("error");
6934
- if (ai.getOptions().debug) {
6935
- const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
6936
- const logger = ai.getLogger();
6937
- logger(`\u274C Error Correction:
6938
- ${errors}`, {
6939
- tags: ["error"]
6940
- });
7172
+ const outputFields = sig.getOutputFields();
7173
+ for (const key of Object.keys(values)) {
7174
+ const field = outputFields.find((f2) => f2.name === key);
7175
+ if (!field || field.isInternal) {
7176
+ continue;
7177
+ }
7178
+ const value = values[key];
7179
+ if (Array.isArray(value)) {
7180
+ const s2 = xstate.streamedIndex?.[key] ?? 0;
7181
+ const v = value.slice(s2);
7182
+ if (v && v.length > 0) {
7183
+ yield { index, delta: { [key]: v } };
7184
+ xstate.streamedIndex[key] = s2 + v.length;
7185
+ }
7186
+ continue;
7187
+ }
7188
+ if (!xstate.streamedIndex[key]) {
7189
+ yield { index, delta: { [key]: value } };
7190
+ xstate.streamedIndex[key] = 1;
7191
+ }
6941
7192
  }
6942
7193
  }
6943
-
6944
- // dsp/datetime.ts
6945
- function parseLLMFriendlyDate(field, dateStr, required = false) {
6946
- try {
6947
- return _parseLLMFriendlyDate(dateStr);
6948
- } catch (err) {
6949
- if (field.isOptional && !required) {
7194
+ function validateAndParseFieldValue(field, fieldValue) {
7195
+ if (!fieldValue || fieldValue === "" || /^(null|undefined)\s*$/i.test(fieldValue)) {
7196
+ if (field.isOptional) {
6950
7197
  return;
6951
7198
  }
6952
- const message = err.message;
6953
- throw new ValidationError({ fields: [field], message, value: dateStr });
7199
+ throw new ValidationError({
7200
+ message: "Required field is missing",
7201
+ fields: [field],
7202
+ value: fieldValue
7203
+ });
6954
7204
  }
6955
- }
6956
- function _parseLLMFriendlyDate(dateStr) {
6957
- if (!(0, import_moment_timezone.default)(dateStr, "YYYY-MM-DD", true).isValid()) {
6958
- throw new Error(
6959
- 'Invalid date format. Please provide the date in "YYYY-MM-DD" format.'
6960
- );
7205
+ let value;
7206
+ if (field.type?.name === "json") {
7207
+ try {
7208
+ const text = extractBlock(fieldValue);
7209
+ value = JSON.parse(text);
7210
+ return value;
7211
+ } catch (e) {
7212
+ throw new ValidationError({
7213
+ message: "Invalid JSON: " + e.message,
7214
+ fields: [field],
7215
+ value: fieldValue
7216
+ });
7217
+ }
7218
+ }
7219
+ if (field.type?.isArray) {
7220
+ try {
7221
+ try {
7222
+ value = JSON.parse(fieldValue);
7223
+ } catch {
7224
+ value = parseMarkdownList(fieldValue);
7225
+ }
7226
+ if (!Array.isArray(value)) {
7227
+ throw new Error("Expected an array");
7228
+ }
7229
+ } catch (e) {
7230
+ throw new ValidationError({
7231
+ message: "Invalid Array: " + e.message,
7232
+ fields: [field],
7233
+ value: fieldValue
7234
+ });
7235
+ }
6961
7236
  }
6962
- const date = import_moment_timezone.default.utc(dateStr, "YYYY-MM-DD").startOf("day");
6963
- return date.toDate();
6964
- }
6965
- function parseLLMFriendlyDateTime(field, dateStr, required = false) {
6966
7237
  try {
6967
- return _parseLLMFriendlyDateTime(dateStr);
6968
- } catch (err) {
6969
- if (field.isOptional && !required) {
6970
- return;
7238
+ if (Array.isArray(value)) {
7239
+ for (const [index, item] of value.entries()) {
7240
+ if (item !== void 0) {
7241
+ const v = typeof item === "string" ? item.trim() : item;
7242
+ value[index] = convertValueToType(field, v, true);
7243
+ }
7244
+ }
7245
+ } else {
7246
+ value = convertValueToType(field, fieldValue);
6971
7247
  }
6972
- const message = err.message;
6973
- throw new ValidationError({ fields: [field], message, value: dateStr });
7248
+ } catch (e) {
7249
+ throw new ValidationError({
7250
+ message: e.message,
7251
+ fields: [field],
7252
+ value: fieldValue
7253
+ });
7254
+ }
7255
+ if (typeof value === "string" && value === "") {
7256
+ return void 0;
6974
7257
  }
7258
+ return value;
6975
7259
  }
6976
- function _parseLLMFriendlyDateTime(dateTimeStr) {
6977
- const dateTimeRegex = /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/;
6978
- const match = dateTimeStr.match(dateTimeRegex);
7260
+ var extractBlock = (input) => {
7261
+ const markdownBlockPattern = /```([A-Za-z]*)\n([\s\S]*?)\n```/g;
7262
+ const match = markdownBlockPattern.exec(input);
6979
7263
  if (!match) {
6980
- throw new Error(
6981
- '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.'
6982
- );
6983
- }
6984
- const [, dateTime, timeZone] = match;
6985
- if (!dateTime || !timeZone) {
6986
- throw new Error(
6987
- '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.'
6988
- );
7264
+ return input;
6989
7265
  }
6990
- const zone = import_moment_timezone.default.tz.zone(timeZone);
6991
- if (!zone) {
6992
- throw new Error(
6993
- `Unrecognized time zone ${timeZone}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`
6994
- );
7266
+ if (match.length === 3) {
7267
+ return match[2];
6995
7268
  }
6996
- const date = import_moment_timezone.default.tz(
6997
- dateTime,
6998
- ["YYYY-MM-DD HH:mm", "YYYY-MM-DD HH:mm:ss"],
6999
- zone.name
7000
- );
7001
- if (!date.isValid()) {
7002
- throw new Error(
7003
- "Invalid date and time values. Please ensure all components are correct."
7004
- );
7269
+ if (match.length === 2) {
7270
+ return match[1];
7005
7271
  }
7006
- return date.utc().toDate();
7007
- }
7008
- var formatDateWithTimezone = (date) => {
7009
- const momentDate = (0, import_moment_timezone.default)(date).utc();
7010
- return momentDate.format(`YYYY-MM-DD HH:mm:ss UTC`);
7272
+ return input;
7011
7273
  };
7012
7274
 
7013
- // dsp/extract.ts
7014
- var extractValues = (sig, values, content, strictMode = false) => {
7015
- const xstate = { extractedFields: [], streamedIndex: {}, s: -1 };
7016
- streamingExtractValues(sig, values, xstate, content, strictMode);
7017
- streamingExtractFinalValue(sig, values, xstate, content);
7018
- for (const field of sig.getOutputFields()) {
7019
- if (field.isInternal) {
7020
- delete values[field.name];
7021
- }
7022
- }
7023
- };
7024
- var checkMissingRequiredFields = (xstate, values, outputFields) => {
7025
- const missingFields = [];
7026
- for (const field of outputFields) {
7027
- if (field && !field.isOptional && values[field.name] === void 0) {
7028
- missingFields.push(field);
7275
+ // dsp/fieldProcessor.ts
7276
+ async function processFieldProcessors(fieldProcessors, values, mem, sessionId) {
7277
+ for (const processor of fieldProcessors) {
7278
+ if (values[processor.field.name] === void 0) {
7279
+ continue;
7029
7280
  }
7030
- }
7031
- if (missingFields.length > 0) {
7032
- throw new ValidationError({
7033
- message: `Required ${missingFields.length === 1 ? "field" : "fields"} not found`,
7034
- fields: missingFields
7281
+ const processFn = processor.process;
7282
+ const result = await processFn(values[processor.field.name], {
7283
+ sessionId,
7284
+ values,
7285
+ done: true
7035
7286
  });
7287
+ addToMemory(processor.field, mem, result, sessionId);
7036
7288
  }
7037
- };
7038
- var streamingExtractValues = (sig, values, xstate, content, strictMode = false) => {
7039
- const fields = sig.getOutputFields();
7040
- let expectedField;
7041
- for (const [index, field] of fields.entries()) {
7042
- if (index === xstate.currFieldIndex) {
7289
+ }
7290
+ async function processStreamingFieldProcessors(fieldProcessors, content, xstate, mem, values, sessionId, done = false) {
7291
+ for (const processor of fieldProcessors) {
7292
+ if (xstate.currField?.name !== processor.field.name) {
7043
7293
  continue;
7044
7294
  }
7045
- if (field.name in values) {
7046
- continue;
7295
+ let value = content.substring(xstate.s);
7296
+ if (xstate.currField?.type?.name === "code") {
7297
+ value = value.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7298
+ value = value.replace(/\s*```\s*$/, "");
7047
7299
  }
7048
- const isFirst = xstate.extractedFields.length === 0;
7049
- const prefix = (isFirst ? "" : "\n") + field.title + ":";
7050
- let e = matchesContent(content, prefix, xstate.s);
7051
- let prefixLen = prefix.length;
7052
- switch (e) {
7053
- case -1:
7054
- if (!strictMode && fields.length === 1 && xstate.currField === void 0) {
7055
- prefixLen = 0;
7056
- e = 0;
7057
- break;
7058
- }
7059
- if (xstate.currField === void 0 && !field.isOptional) {
7060
- throw new ValidationError({
7061
- message: "Expected (Required) field not found",
7062
- fields: [field]
7063
- });
7064
- }
7065
- expectedField = field.isOptional ? void 0 : field;
7066
- continue;
7067
- // Field is not found, continue to the next field
7068
- case -2:
7069
- return true;
7070
- // Partial match at end, skip and gather more content
7071
- case -3:
7072
- return true;
7073
- // String is only whitespace, skip and gather more content
7074
- case -4:
7075
- xstate.inBlock = true;
7076
- return true;
7077
- }
7078
- if (expectedField && expectedField.name !== field.name) {
7079
- throw new ValidationError({
7080
- message: "Expected (Required) field not found",
7081
- fields: [expectedField]
7082
- });
7083
- }
7084
- if (xstate.currField) {
7085
- const val = content.substring(xstate.s, e).trim();
7086
- const parsedValue = validateAndParseFieldValue(xstate.currField, val);
7087
- if (parsedValue !== void 0) {
7088
- values[xstate.currField.name] = parsedValue;
7089
- }
7090
- if (xstate.prevFields) {
7091
- xstate.prevFields?.push({ field: xstate.currField, s: xstate.s, e });
7092
- } else {
7093
- xstate.prevFields = [{ field: xstate.currField, s: xstate.s, e }];
7094
- }
7095
- }
7096
- xstate.s = e + prefixLen;
7097
- xstate.currField = field;
7098
- xstate.currFieldIndex = index;
7099
- if (!xstate.extractedFields.includes(field)) {
7100
- xstate.extractedFields.push(field);
7101
- }
7102
- if (xstate.streamedIndex[field.name] === void 0) {
7103
- xstate.streamedIndex[field.name] = 0;
7104
- }
7105
- }
7106
- };
7107
- var streamingExtractFinalValue = (sig, values, xstate, content) => {
7108
- if (xstate.currField) {
7109
- let val = content.substring(xstate.s).trim();
7110
- const parsedValue = validateAndParseFieldValue(xstate.currField, val);
7111
- if (parsedValue !== void 0) {
7112
- values[xstate.currField.name] = parsedValue;
7113
- }
7114
- }
7115
- checkMissingRequiredFields(xstate, values, sig.getOutputFields());
7116
- };
7117
- var convertValueToType = (field, val, required = false) => {
7118
- switch (field.type?.name) {
7119
- case "code":
7120
- return extractBlock(val);
7121
- case "string":
7122
- return val;
7123
- case "number": {
7124
- const v = Number(val);
7125
- if (Number.isNaN(v)) {
7126
- if (field.isOptional && !required) {
7127
- return;
7128
- }
7129
- throw new Error("Invalid number");
7130
- }
7131
- return v;
7132
- }
7133
- case "boolean": {
7134
- if (typeof val === "boolean") {
7135
- return val;
7136
- }
7137
- const v = val.toLowerCase();
7138
- if (v === "true") {
7139
- return true;
7140
- } else if (v === "false") {
7141
- return false;
7142
- } else {
7143
- if (field.isOptional && !required) {
7144
- return;
7145
- }
7146
- throw new Error("Invalid boolean");
7147
- }
7148
- }
7149
- case "date":
7150
- return parseLLMFriendlyDate(field, val, required);
7151
- case "datetime":
7152
- return parseLLMFriendlyDateTime(field, val, required);
7153
- case "class":
7154
- const className = val;
7155
- if (field.type.options && !field.type.options.includes(className)) {
7156
- if (field.isOptional) {
7157
- return;
7158
- }
7159
- throw new Error(
7160
- `Invalid class '${val}', expected one of the following: ${field.type.options.join(", ")}`
7161
- );
7162
- }
7163
- return className;
7164
- default:
7165
- return val;
7166
- }
7167
- };
7168
- function* yieldDelta(content, field, s2, e, xstate) {
7169
- const { name: fieldName, isInternal } = field;
7170
- const { isArray: fieldIsArray, name: fieldTypeName } = field.type ?? {};
7171
- if (isInternal || fieldIsArray || fieldTypeName && fieldTypeName !== "string" && fieldTypeName !== "code") {
7172
- return;
7173
- }
7174
- const pos = xstate.streamedIndex[fieldName] ?? 0;
7175
- const isFirstChunk = pos === 0;
7176
- const d1 = content.substring(s2 + pos, e);
7177
- if (d1.length === 0) {
7178
- return;
7179
- }
7180
- let d2 = d1.replace(/\s+$/, "");
7181
- if (xstate.currField?.type?.name === "code") {
7182
- d2 = d2.replace(/\s*```\s*$/, "");
7183
- }
7184
- let d3 = isFirstChunk ? d2.trimStart() : d2;
7185
- if (xstate.currField?.type?.name === "code") {
7186
- d3 = d3.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7187
- }
7188
- if (d3.length > 0) {
7189
- yield { [fieldName]: d3 };
7190
- xstate.streamedIndex[fieldName] = pos + d2.length;
7300
+ const processFn = processor.process;
7301
+ const result = await processFn(value, {
7302
+ sessionId,
7303
+ values,
7304
+ done
7305
+ });
7306
+ addToMemory(xstate.currField, mem, result, sessionId);
7191
7307
  }
7192
7308
  }
7193
- function* streamValues(sig, content, values, xstate) {
7194
- for (const prevField of xstate.prevFields ?? []) {
7195
- const { field, s: s2, e } = prevField;
7196
- yield* yieldDelta(content, field, s2, e, xstate);
7197
- }
7198
- xstate.prevFields = void 0;
7199
- if (!xstate.currField || xstate.currField.isInternal) {
7309
+ var addToMemory = (field, mem, result, sessionId) => {
7310
+ if (result === void 0 || typeof result === "string" && (result === "" || /^(null|undefined)\s*$/i.test(result))) {
7200
7311
  return;
7201
7312
  }
7202
- yield* yieldDelta(
7203
- content,
7204
- xstate.currField,
7205
- xstate.s,
7206
- content.length,
7207
- xstate
7313
+ let resultText = JSON.stringify(
7314
+ result,
7315
+ (key, value) => typeof value === "bigint" ? Number(value) : value,
7316
+ 2
7208
7317
  );
7209
- const outputFields = sig.getOutputFields();
7210
- for (const key of Object.keys(values)) {
7211
- const field = outputFields.find((f2) => f2.name === key);
7212
- if (!field || field.isInternal) {
7213
- continue;
7214
- }
7215
- const value = values[key];
7216
- if (Array.isArray(value)) {
7217
- const s2 = xstate.streamedIndex?.[key] ?? 0;
7218
- const v = value.slice(s2);
7219
- if (v && v.length > 0) {
7220
- yield { [key]: v };
7221
- xstate.streamedIndex[key] = s2 + v.length;
7222
- }
7223
- continue;
7224
- }
7225
- if (!xstate.streamedIndex[key]) {
7226
- yield { [key]: value };
7227
- xstate.streamedIndex[key] = 1;
7228
- }
7318
+ const text = getFieldProcessingMessage(field, resultText);
7319
+ mem.addRequest(
7320
+ [{ role: "user", content: [{ type: "text", text }] }],
7321
+ sessionId
7322
+ );
7323
+ mem.addTag(`processor`, sessionId);
7324
+ };
7325
+ function getFieldProcessingMessage(field, resultText) {
7326
+ const isCodeField = field.type?.name === "code";
7327
+ const fieldTitle = field.title;
7328
+ if (isCodeField) {
7329
+ return `Code in the field "${fieldTitle}" was executed. The code execution produced the following output: ${resultText}`;
7330
+ } else {
7331
+ return `The field "${fieldTitle}" was processed. The field contents were transformed into the following output: ${resultText}`;
7229
7332
  }
7230
7333
  }
7231
- function validateAndParseFieldValue(field, fieldValue) {
7232
- if (!fieldValue || fieldValue === "" || /^(null|undefined)\s*$/i.test(fieldValue)) {
7233
- if (field.isOptional) {
7334
+
7335
+ // dsp/jsonschema.ts
7336
+ var validateJSONSchema = (schema) => {
7337
+ const errors = [];
7338
+ const validateSchemaObject = (schema2, path = "") => {
7339
+ if (!schema2 || typeof schema2 !== "object") {
7234
7340
  return;
7235
7341
  }
7236
- throw new ValidationError({
7237
- message: "Required field is missing",
7238
- fields: [field],
7239
- value: fieldValue
7240
- });
7241
- }
7242
- let value;
7243
- if (field.type?.name === "json") {
7244
- try {
7245
- const text = extractBlock(fieldValue);
7246
- value = JSON.parse(text);
7247
- return value;
7248
- } catch (e) {
7249
- throw new ValidationError({
7250
- message: "Invalid JSON: " + e.message,
7251
- fields: [field],
7252
- value: fieldValue
7342
+ const validTypes = [
7343
+ "array",
7344
+ "integer",
7345
+ "number",
7346
+ "string",
7347
+ "boolean",
7348
+ "null",
7349
+ "object"
7350
+ ];
7351
+ if (schema2.anyOf && Array.isArray(schema2.anyOf)) {
7352
+ if (schema2.anyOf.length === 0) {
7353
+ errors.push({
7354
+ path: path || "root",
7355
+ issue: "anyOf array is empty",
7356
+ fix: "Add at least one schema to the anyOf array",
7357
+ example: 'anyOf: [{ type: "string" }, { type: "null" }]'
7358
+ });
7359
+ }
7360
+ schema2.anyOf.forEach((subSchema, index) => {
7361
+ validateSchemaObject(subSchema, `${path}anyOf[${index}].`);
7253
7362
  });
7363
+ return;
7254
7364
  }
7255
- }
7256
- if (field.type?.isArray) {
7257
- try {
7258
- try {
7259
- value = JSON.parse(fieldValue);
7260
- } catch {
7261
- value = parseMarkdownList(fieldValue);
7365
+ if (schema2.oneOf && Array.isArray(schema2.oneOf)) {
7366
+ if (schema2.oneOf.length === 0) {
7367
+ errors.push({
7368
+ path: path || "root",
7369
+ issue: "oneOf array is empty",
7370
+ fix: "Add at least one schema to the oneOf array",
7371
+ example: 'oneOf: [{ type: "string" }, { type: "number" }]'
7372
+ });
7262
7373
  }
7263
- if (!Array.isArray(value)) {
7264
- throw new Error("Expected an array");
7374
+ schema2.oneOf.forEach((subSchema, index) => {
7375
+ validateSchemaObject(subSchema, `${path}oneOf[${index}].`);
7376
+ });
7377
+ return;
7378
+ }
7379
+ if (schema2.allOf && Array.isArray(schema2.allOf)) {
7380
+ if (schema2.allOf.length === 0) {
7381
+ errors.push({
7382
+ path: path || "root",
7383
+ issue: "allOf array is empty",
7384
+ fix: "Add at least one schema to the allOf array",
7385
+ example: 'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'
7386
+ });
7265
7387
  }
7266
- } catch (e) {
7267
- throw new ValidationError({
7268
- message: "Invalid Array: " + e.message,
7269
- fields: [field],
7270
- value: fieldValue
7388
+ schema2.allOf.forEach((subSchema, index) => {
7389
+ validateSchemaObject(subSchema, `${path}allOf[${index}].`);
7271
7390
  });
7272
- }
7273
- }
7274
- try {
7275
- if (Array.isArray(value)) {
7276
- for (const [index, item] of value.entries()) {
7277
- if (item !== void 0) {
7278
- const v = typeof item === "string" ? item.trim() : item;
7279
- value[index] = convertValueToType(field, v, true);
7280
- }
7281
- }
7282
- } else {
7283
- value = convertValueToType(field, fieldValue);
7284
- }
7285
- } catch (e) {
7286
- throw new ValidationError({
7287
- message: e.message,
7288
- fields: [field],
7289
- value: fieldValue
7290
- });
7291
- }
7292
- if (typeof value === "string" && value === "") {
7293
- return void 0;
7294
- }
7295
- return value;
7296
- }
7297
- var extractBlock = (input) => {
7298
- const markdownBlockPattern = /```([A-Za-z]*)\n([\s\S]*?)\n```/g;
7299
- const match = markdownBlockPattern.exec(input);
7300
- if (!match) {
7301
- return input;
7302
- }
7303
- if (match.length === 3) {
7304
- return match[2];
7305
- }
7306
- if (match.length === 2) {
7307
- return match[1];
7308
- }
7309
- return input;
7310
- };
7311
-
7312
- // dsp/fieldProcessor.ts
7313
- async function processFieldProcessors(fieldProcessors, values, mem, sessionId) {
7314
- for (const processor of fieldProcessors) {
7315
- if (values[processor.field.name] === void 0) {
7316
- continue;
7317
- }
7318
- const processFn = processor.process;
7319
- const result = await processFn(values[processor.field.name], {
7320
- sessionId,
7321
- values,
7322
- done: true
7323
- });
7324
- addToMemory(processor.field, mem, result, sessionId);
7325
- }
7326
- }
7327
- async function processStreamingFieldProcessors(fieldProcessors, content, xstate, mem, values, sessionId, done = false) {
7328
- for (const processor of fieldProcessors) {
7329
- if (xstate.currField?.name !== processor.field.name) {
7330
- continue;
7331
- }
7332
- let value = content.substring(xstate.s);
7333
- if (xstate.currField?.type?.name === "code") {
7334
- value = value.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/, "");
7335
- value = value.replace(/\s*```\s*$/, "");
7336
- }
7337
- const processFn = processor.process;
7338
- const result = await processFn(value, {
7339
- sessionId,
7340
- values,
7341
- done
7342
- });
7343
- addToMemory(xstate.currField, mem, result, sessionId);
7344
- }
7345
- }
7346
- var addToMemory = (field, mem, result, sessionId) => {
7347
- if (result === void 0 || typeof result === "string" && (result === "" || /^(null|undefined)\s*$/i.test(result))) {
7348
- return;
7349
- }
7350
- let resultText = JSON.stringify(
7351
- result,
7352
- (key, value) => typeof value === "bigint" ? Number(value) : value,
7353
- 2
7354
- );
7355
- const text = getFieldProcessingMessage(field, resultText);
7356
- mem.add({ role: "user", content: [{ type: "text", text }] }, sessionId);
7357
- mem.addTag(`processor`, sessionId);
7358
- };
7359
- function getFieldProcessingMessage(field, resultText) {
7360
- const isCodeField = field.type?.name === "code";
7361
- const fieldTitle = field.title;
7362
- if (isCodeField) {
7363
- return `Code in the field "${fieldTitle}" was executed. The code execution produced the following output: ${resultText}`;
7364
- } else {
7365
- return `The field "${fieldTitle}" was processed. The field contents were transformed into the following output: ${resultText}`;
7366
- }
7367
- }
7368
-
7369
- // dsp/jsonschema.ts
7370
- var validateJSONSchema = (schema) => {
7371
- const errors = [];
7372
- const validateSchemaObject = (schema2, path = "") => {
7373
- if (!schema2 || typeof schema2 !== "object") {
7374
- return;
7375
- }
7376
- const validTypes = [
7377
- "array",
7378
- "integer",
7379
- "number",
7380
- "string",
7381
- "boolean",
7382
- "null",
7383
- "object"
7384
- ];
7385
- if (schema2.anyOf && Array.isArray(schema2.anyOf)) {
7386
- if (schema2.anyOf.length === 0) {
7387
- errors.push({
7388
- path: path || "root",
7389
- issue: "anyOf array is empty",
7390
- fix: "Add at least one schema to the anyOf array",
7391
- example: 'anyOf: [{ type: "string" }, { type: "null" }]'
7392
- });
7393
- }
7394
- schema2.anyOf.forEach((subSchema, index) => {
7395
- validateSchemaObject(subSchema, `${path}anyOf[${index}].`);
7396
- });
7397
- return;
7398
- }
7399
- if (schema2.oneOf && Array.isArray(schema2.oneOf)) {
7400
- if (schema2.oneOf.length === 0) {
7401
- errors.push({
7402
- path: path || "root",
7403
- issue: "oneOf array is empty",
7404
- fix: "Add at least one schema to the oneOf array",
7405
- example: 'oneOf: [{ type: "string" }, { type: "number" }]'
7406
- });
7407
- }
7408
- schema2.oneOf.forEach((subSchema, index) => {
7409
- validateSchemaObject(subSchema, `${path}oneOf[${index}].`);
7410
- });
7411
- return;
7412
- }
7413
- if (schema2.allOf && Array.isArray(schema2.allOf)) {
7414
- if (schema2.allOf.length === 0) {
7415
- errors.push({
7416
- path: path || "root",
7417
- issue: "allOf array is empty",
7418
- fix: "Add at least one schema to the allOf array",
7419
- example: 'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'
7420
- });
7421
- }
7422
- schema2.allOf.forEach((subSchema, index) => {
7423
- validateSchemaObject(subSchema, `${path}allOf[${index}].`);
7424
- });
7425
- return;
7391
+ return;
7426
7392
  }
7427
7393
  if (!schema2.type) {
7428
7394
  return;
@@ -7612,10 +7578,10 @@ var AxFunctionProcessor = class {
7612
7578
  } : void 0;
7613
7579
  if (!fnSpec.parameters) {
7614
7580
  const res2 = fnSpec.func.length === 1 ? await fnSpec.func(opt) : await fnSpec.func();
7615
- return typeof res2 === "string" ? res2 : JSON.stringify(res2, null, 2);
7581
+ return typeof res2 === "string" ? res2 : res2 === void 0 || res2 === null ? "" : JSON.stringify(res2, null, 2);
7616
7582
  }
7617
7583
  const res = fnSpec.func.length === 2 ? await fnSpec.func(args, opt) : await fnSpec.func(args);
7618
- return typeof res === "string" ? res : JSON.stringify(res, null, 2);
7584
+ return typeof res === "string" ? res : res === void 0 || res === null ? "" : JSON.stringify(res, null, 2);
7619
7585
  };
7620
7586
  execute = async (func, options) => {
7621
7587
  const fnSpec = this.funcList.find(
@@ -7654,7 +7620,17 @@ var parseFunctions = (newFuncs, existingFuncs) => {
7654
7620
  }
7655
7621
  return [...existingFuncs ?? [], ...functions];
7656
7622
  };
7657
- var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, traceId, span, excludeContentFromTelemetry) => {
7623
+ var processFunctions = async ({
7624
+ ai,
7625
+ functionList,
7626
+ functionCalls,
7627
+ mem,
7628
+ sessionId,
7629
+ traceId,
7630
+ span,
7631
+ excludeContentFromTrace,
7632
+ index
7633
+ }) => {
7658
7634
  const funcProc = new AxFunctionProcessor(functionList);
7659
7635
  const functionsExecuted = /* @__PURE__ */ new Set();
7660
7636
  const promises = functionCalls.map((func) => {
@@ -7667,59 +7643,56 @@ var processFunctions = async (ai, functionList, functionCalls, mem, sessionId, t
7667
7643
  const eventData = {
7668
7644
  name: func.name
7669
7645
  };
7670
- if (!excludeContentFromTelemetry) {
7646
+ if (!excludeContentFromTrace) {
7671
7647
  eventData.args = func.args;
7672
7648
  eventData.result = functionResult ?? "";
7673
7649
  }
7674
7650
  span.addEvent("function.call", eventData);
7675
7651
  }
7676
7652
  return {
7677
- role: "function",
7678
7653
  result: functionResult ?? "",
7679
- functionId: func.id
7654
+ role: "function",
7655
+ functionId: func.id,
7656
+ index
7680
7657
  };
7681
7658
  }).catch((e) => {
7682
- if (e instanceof FunctionError) {
7683
- const result = e.getFixingInstructions();
7684
- if (span) {
7685
- const errorEventData = {
7686
- name: func.name,
7687
- message: e.toString()
7688
- };
7689
- if (!excludeContentFromTelemetry) {
7690
- errorEventData.args = func.args;
7691
- errorEventData.fixing_instructions = result;
7692
- }
7693
- span.addEvent("function.error", errorEventData);
7659
+ if (!(e instanceof FunctionError)) {
7660
+ throw e;
7661
+ }
7662
+ const result = e.getFixingInstructions();
7663
+ if (span) {
7664
+ const errorEventData = {
7665
+ name: func.name,
7666
+ message: e.toString()
7667
+ };
7668
+ if (!excludeContentFromTrace) {
7669
+ errorEventData.args = func.args;
7670
+ errorEventData.fixing_instructions = result;
7694
7671
  }
7695
- mem.add(
7696
- {
7697
- role: "function",
7698
- functionId: func.id,
7699
- isError: true,
7700
- result
7701
- },
7702
- sessionId
7703
- );
7704
- mem.addTag("error");
7705
- if (ai.getOptions().debug) {
7706
- const logger = ai.getLogger();
7707
- logger(`\u274C Function Error Correction:
7672
+ span.addEvent("function.error", errorEventData);
7673
+ }
7674
+ if (ai.getOptions().debug) {
7675
+ const logger = ai.getLogger();
7676
+ logger(`\u274C Function Error Correction:
7708
7677
  ${result}`, {
7709
- tags: ["error"]
7710
- });
7711
- }
7712
- } else {
7713
- throw e;
7678
+ tags: ["error"]
7679
+ });
7714
7680
  }
7681
+ return {
7682
+ functionId: func.id,
7683
+ isError: true,
7684
+ index,
7685
+ result,
7686
+ role: "function"
7687
+ };
7715
7688
  });
7716
7689
  return promise;
7717
7690
  });
7718
7691
  const results = await Promise.all(promises);
7719
- for (const result of results) {
7720
- if (result) {
7721
- mem.add(result, sessionId);
7722
- }
7692
+ const functionResults = results.filter((result) => result !== void 0);
7693
+ mem.addFunctionResults(functionResults, sessionId);
7694
+ if (functionResults.some((result) => result.isError)) {
7695
+ mem.addTag("error", sessionId);
7723
7696
  }
7724
7697
  return functionsExecuted;
7725
7698
  };
@@ -7738,23 +7711,28 @@ function parseFunctionCalls(ai, functionCalls, values, model) {
7738
7711
  return funcs;
7739
7712
  }
7740
7713
 
7741
- // dsp/registry.ts
7742
- var AxInstanceRegistry = class {
7743
- reg;
7744
- // To track keys for iteration
7745
- constructor() {
7746
- this.reg = /* @__PURE__ */ new Set();
7747
- }
7748
- register(instance) {
7749
- this.reg.add(instance);
7750
- }
7751
- *[Symbol.iterator]() {
7752
- const items = Array.from(this.reg);
7753
- for (let i = 0; i < items.length; i++) {
7754
- yield items[i];
7714
+ // dsp/processResponse.ts
7715
+ var import_web5 = require("stream/web");
7716
+
7717
+ // ai/util.ts
7718
+ function mergeFunctionCalls(functionCalls, functionCallDeltas) {
7719
+ for (const _fc of functionCallDeltas) {
7720
+ const fc = functionCalls.find((fc2) => fc2.id === _fc.id);
7721
+ if (fc) {
7722
+ if (typeof _fc.function.name == "string" && _fc.function.name.length > 0) {
7723
+ fc.function.name += _fc.function.name;
7724
+ }
7725
+ if (typeof _fc.function.params == "string" && _fc.function.params.length > 0) {
7726
+ fc.function.params += _fc.function.params;
7727
+ }
7728
+ if (typeof _fc.function.params == "object") {
7729
+ fc.function.params = _fc.function.params;
7730
+ }
7731
+ } else {
7732
+ functionCalls.push(_fc);
7755
7733
  }
7756
7734
  }
7757
- };
7735
+ }
7758
7736
 
7759
7737
  // dsp/sig.ts
7760
7738
  var import_crypto3 = require("crypto");
@@ -8964,32 +8942,828 @@ function validateFieldType(field, context3) {
8964
8942
  );
8965
8943
  }
8966
8944
  }
8967
- const uniqueOptions = new Set(
8968
- type.options.map((opt) => opt.trim().toLowerCase())
8969
- );
8970
- if (uniqueOptions.size !== type.options.length) {
8971
- throw new AxSignatureValidationError(
8972
- "Duplicate class options found",
8973
- field.name,
8974
- "Each class option must be unique (case-insensitive)"
8975
- );
8945
+ const uniqueOptions = new Set(
8946
+ type.options.map((opt) => opt.trim().toLowerCase())
8947
+ );
8948
+ if (uniqueOptions.size !== type.options.length) {
8949
+ throw new AxSignatureValidationError(
8950
+ "Duplicate class options found",
8951
+ field.name,
8952
+ "Each class option must be unique (case-insensitive)"
8953
+ );
8954
+ }
8955
+ }
8956
+ if (type.name === "code" && type.isArray) {
8957
+ throw new AxSignatureValidationError(
8958
+ "Arrays of code are not commonly supported",
8959
+ field.name,
8960
+ "Consider using a single code field or an array of strings instead"
8961
+ );
8962
+ }
8963
+ if (field.isInternal && context3 === "input") {
8964
+ throw new AxSignatureValidationError(
8965
+ "Internal marker (!) is not allowed on input fields",
8966
+ field.name,
8967
+ "Internal markers are only allowed on output fields"
8968
+ );
8969
+ }
8970
+ }
8971
+
8972
+ // dsp/processResponse.ts
8973
+ async function* processStreamingResponse({
8974
+ res,
8975
+ usage,
8976
+ states,
8977
+ ...args
8978
+ }) {
8979
+ const skipEarlyFail = (args.ai.getFeatures().functionCot ?? false) && args.functions !== void 0 && args.functions.length > 0;
8980
+ for await (const v of res) {
8981
+ if (v.modelUsage) {
8982
+ usage.push(v.modelUsage);
8983
+ }
8984
+ for (const result of v.results) {
8985
+ if (result.content === "" && (!result.functionCalls || result.functionCalls.length === 0)) {
8986
+ continue;
8987
+ }
8988
+ const state = states.find((s2) => s2.index === result.index);
8989
+ if (!state) {
8990
+ throw new Error(`No state found for result (index: ${result.index})`);
8991
+ }
8992
+ yield* _processStreamingResponse({
8993
+ ...args,
8994
+ result,
8995
+ skipEarlyFail,
8996
+ state
8997
+ });
8998
+ }
8999
+ }
9000
+ for (const state of states) {
9001
+ yield* finalizeStreamingResponse({
9002
+ ...args,
9003
+ state
9004
+ });
9005
+ }
9006
+ }
9007
+ async function* _processStreamingResponse({
9008
+ result,
9009
+ mem,
9010
+ sessionId,
9011
+ strictMode,
9012
+ skipEarlyFail,
9013
+ state,
9014
+ signature,
9015
+ streamingFieldProcessors,
9016
+ thoughtFieldName,
9017
+ streamingAsserts,
9018
+ asserts
9019
+ }) {
9020
+ if (result.functionCalls && result.functionCalls.length > 0) {
9021
+ mergeFunctionCalls(state.functionCalls, result.functionCalls);
9022
+ mem.updateResult(
9023
+ {
9024
+ name: result.name,
9025
+ content: result.content,
9026
+ functionCalls: state.functionCalls,
9027
+ delta: result.functionCalls?.[0]?.function?.params,
9028
+ index: result.index
9029
+ },
9030
+ sessionId
9031
+ );
9032
+ } else if (result.content && result.content.length > 0) {
9033
+ if (result.thought && result.thought.length > 0) {
9034
+ yield {
9035
+ index: result.index,
9036
+ delta: { [thoughtFieldName]: result.thought }
9037
+ };
9038
+ }
9039
+ state.content += result.content;
9040
+ mem.updateResult(
9041
+ {
9042
+ name: result.name,
9043
+ content: state.content,
9044
+ delta: result.content,
9045
+ index: result.index
9046
+ },
9047
+ sessionId
9048
+ );
9049
+ const skip = streamingExtractValues(
9050
+ signature,
9051
+ state.values,
9052
+ state.xstate,
9053
+ state.content,
9054
+ { strictMode, skipEarlyFail }
9055
+ );
9056
+ if (skip) {
9057
+ return;
9058
+ }
9059
+ if (streamingAsserts.length !== 0) {
9060
+ await assertStreamingAssertions(
9061
+ streamingAsserts,
9062
+ state.xstate,
9063
+ state.content
9064
+ );
9065
+ }
9066
+ if (streamingFieldProcessors.length !== 0) {
9067
+ await processStreamingFieldProcessors(
9068
+ streamingFieldProcessors,
9069
+ state.content,
9070
+ state.xstate,
9071
+ mem,
9072
+ state.values,
9073
+ sessionId
9074
+ );
9075
+ }
9076
+ yield* streamValues(
9077
+ signature,
9078
+ state.content,
9079
+ state.values,
9080
+ state.xstate,
9081
+ result.index
9082
+ );
9083
+ await assertAssertions(asserts, state.values);
9084
+ } else if (result.thought && result.thought.length > 0) {
9085
+ state.values[thoughtFieldName] = (state.values[thoughtFieldName] ?? "") + result.thought;
9086
+ yield {
9087
+ index: result.index,
9088
+ delta: { [thoughtFieldName]: result.thought }
9089
+ };
9090
+ }
9091
+ if (result.finishReason === "length") {
9092
+ throw new Error(
9093
+ `Max tokens reached before completion
9094
+ Content: ${state.content}`
9095
+ );
9096
+ }
9097
+ }
9098
+ async function* finalizeStreamingResponse({
9099
+ state,
9100
+ signature,
9101
+ ai,
9102
+ model,
9103
+ functions,
9104
+ mem,
9105
+ sessionId,
9106
+ traceId,
9107
+ span,
9108
+ excludeContentFromTrace,
9109
+ streamingAsserts,
9110
+ asserts,
9111
+ fieldProcessors,
9112
+ streamingFieldProcessors
9113
+ }) {
9114
+ const funcs = parseFunctionCalls(ai, state.functionCalls, state.values, model);
9115
+ if (funcs) {
9116
+ if (!functions) {
9117
+ throw new Error("Functions are not defined");
9118
+ }
9119
+ const fx = await processFunctions({
9120
+ ai,
9121
+ functionList: functions,
9122
+ functionCalls: funcs,
9123
+ mem,
9124
+ sessionId,
9125
+ traceId,
9126
+ span,
9127
+ index: state.index,
9128
+ excludeContentFromTrace
9129
+ });
9130
+ state.functionsExecuted = /* @__PURE__ */ new Set([...state.functionsExecuted, ...fx]);
9131
+ } else {
9132
+ streamingExtractFinalValue(
9133
+ signature,
9134
+ state.values,
9135
+ state.xstate,
9136
+ state.content
9137
+ );
9138
+ await assertStreamingAssertions(
9139
+ streamingAsserts,
9140
+ state.xstate,
9141
+ state.content,
9142
+ true
9143
+ );
9144
+ await assertAssertions(asserts, state.values);
9145
+ if (fieldProcessors.length) {
9146
+ await processFieldProcessors(
9147
+ fieldProcessors,
9148
+ state.values,
9149
+ mem,
9150
+ sessionId
9151
+ );
9152
+ }
9153
+ if (streamingFieldProcessors.length !== 0) {
9154
+ await processStreamingFieldProcessors(
9155
+ streamingFieldProcessors,
9156
+ state.content,
9157
+ state.xstate,
9158
+ mem,
9159
+ state.values,
9160
+ sessionId,
9161
+ true
9162
+ );
9163
+ }
9164
+ yield* streamValues(
9165
+ signature,
9166
+ state.content,
9167
+ state.values,
9168
+ state.xstate,
9169
+ state.index
9170
+ );
9171
+ }
9172
+ }
9173
+ async function* processResponse({
9174
+ ai,
9175
+ res,
9176
+ mem,
9177
+ sessionId,
9178
+ traceId,
9179
+ functions,
9180
+ span,
9181
+ strictMode,
9182
+ states,
9183
+ usage,
9184
+ excludeContentFromTrace,
9185
+ asserts,
9186
+ fieldProcessors,
9187
+ thoughtFieldName,
9188
+ signature
9189
+ }) {
9190
+ let results = res.results ?? [];
9191
+ mem.addResponse(results, sessionId);
9192
+ for (const result of results) {
9193
+ const state = states[result.index];
9194
+ if (!state) {
9195
+ throw new Error(`No state found for result (index: ${result.index})`);
9196
+ }
9197
+ if (res.modelUsage) {
9198
+ usage.push(res.modelUsage);
9199
+ }
9200
+ if (result.functionCalls?.length) {
9201
+ const funcs = parseFunctionCalls(ai, result.functionCalls, state.values);
9202
+ if (funcs) {
9203
+ if (!functions) {
9204
+ throw new Error("Functions are not defined");
9205
+ }
9206
+ const fx = await processFunctions({
9207
+ ai,
9208
+ functionList: functions,
9209
+ functionCalls: funcs,
9210
+ mem,
9211
+ sessionId,
9212
+ traceId,
9213
+ span,
9214
+ excludeContentFromTrace,
9215
+ index: result.index
9216
+ });
9217
+ state.functionsExecuted = /* @__PURE__ */ new Set([...state.functionsExecuted, ...fx]);
9218
+ }
9219
+ } else if (result.content) {
9220
+ if (result.thought && result.thought.length > 0) {
9221
+ state.values[thoughtFieldName] = result.thought;
9222
+ }
9223
+ extractValues(signature, state.values, result.content, strictMode);
9224
+ await assertAssertions(asserts, state.values);
9225
+ if (fieldProcessors.length) {
9226
+ await processFieldProcessors(
9227
+ fieldProcessors,
9228
+ state.values,
9229
+ mem,
9230
+ sessionId
9231
+ );
9232
+ }
9233
+ }
9234
+ if (result.finishReason === "length") {
9235
+ throw new Error(
9236
+ `Max tokens reached before completion
9237
+ Content: ${result.content}`
9238
+ );
9239
+ }
9240
+ }
9241
+ const values = states.map((s2) => s2.values);
9242
+ for (const v of values) {
9243
+ for (const field of signature.getOutputFields()) {
9244
+ if (field.isInternal) {
9245
+ delete v[field.name];
9246
+ }
9247
+ }
9248
+ }
9249
+ const outputFields = signature.getOutputFields();
9250
+ const deltas = values.map((v, index) => {
9251
+ const delta = {};
9252
+ for (const field of outputFields) {
9253
+ if (field.isInternal) {
9254
+ continue;
9255
+ }
9256
+ delta[field.name] = v[field.name];
9257
+ }
9258
+ if (v[thoughtFieldName] !== void 0) {
9259
+ delta[thoughtFieldName] = v[thoughtFieldName];
9260
+ }
9261
+ return { index, delta };
9262
+ });
9263
+ for (const delta of deltas) {
9264
+ yield delta;
9265
+ }
9266
+ }
9267
+ function shouldContinueSteps(mem, stopFunction, states, sessionId) {
9268
+ const lastMemItem = mem.getLast(sessionId);
9269
+ if (!lastMemItem) {
9270
+ return true;
9271
+ }
9272
+ for (const [index, state] of states.entries()) {
9273
+ const stopFunctionExecuted = stopFunction && state.functionsExecuted.has(stopFunction);
9274
+ const chat = lastMemItem.chat[index];
9275
+ if (!chat) {
9276
+ throw new Error(`No chat message found for result (index: ${index})`);
9277
+ }
9278
+ const isFunction = lastMemItem.role === "function";
9279
+ const isProcessor = lastMemItem.tags ? lastMemItem.tags.some((tag) => tag === "processor") : false;
9280
+ if (isFunction && stopFunction && stopFunctionExecuted) {
9281
+ return false;
9282
+ }
9283
+ if (!(isFunction || isProcessor)) {
9284
+ return false;
9285
+ }
9286
+ }
9287
+ return true;
9288
+ }
9289
+
9290
+ // dsp/prompt.ts
9291
+ var functionCallInstructions = `
9292
+ ## Function Call Instructions
9293
+ - Complete the task, using the functions defined earlier in this prompt.
9294
+ - Output fields should only be generated after all functions have been called.
9295
+ - Use the function results to generate the output fields.`;
9296
+ var formattingRules = `
9297
+ ## Strict Output Formatting Rules
9298
+ - Output must strictly follow the defined plain-text \`field name: value\` field format.
9299
+ - Output field, values must strictly adhere to the specified output field formatting rules.
9300
+ - No formatting rules should override these **Strict Output Formatting Rules**
9301
+ - Do not add any text before or after the output fields, just the field name and value.
9302
+ - Do not use code blocks.`;
9303
+ var AxPromptTemplate = class {
9304
+ sig;
9305
+ fieldTemplates;
9306
+ task;
9307
+ thoughtFieldName;
9308
+ functions;
9309
+ constructor(sig, options, fieldTemplates) {
9310
+ this.sig = sig;
9311
+ this.fieldTemplates = fieldTemplates;
9312
+ this.thoughtFieldName = options?.thoughtFieldName ?? "thought";
9313
+ this.functions = options?.functions;
9314
+ const task = [];
9315
+ const inArgs = renderDescFields(this.sig.getInputFields());
9316
+ const outArgs = renderDescFields(this.sig.getOutputFields());
9317
+ task.push(
9318
+ `You will be provided with the following fields: ${inArgs}. Your task is to generate new fields: ${outArgs}.`
9319
+ );
9320
+ const funcs = this.functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
9321
+ const funcList = funcs?.map((fn) => `- \`${fn.name}\`: ${formatDescription(fn.description)}`).join("\n");
9322
+ if (funcList && funcList.length > 0) {
9323
+ task.push(`## Available Functions
9324
+ ${funcList}`);
9325
+ }
9326
+ const inputFields = renderInputFields(this.sig.getInputFields());
9327
+ task.push(`## Input Fields
9328
+ ${inputFields}`);
9329
+ const outputFields = renderOutputFields(this.sig.getOutputFields());
9330
+ task.push(`## Output Fields
9331
+ ${outputFields}`);
9332
+ if (funcList && funcList.length > 0) {
9333
+ task.push(functionCallInstructions.trim());
9334
+ }
9335
+ task.push(formattingRules.trim());
9336
+ const desc = this.sig.getDescription();
9337
+ if (desc) {
9338
+ const text = formatDescription(desc);
9339
+ task.push(text);
9340
+ }
9341
+ this.task = {
9342
+ type: "text",
9343
+ text: task.join("\n\n")
9344
+ };
9345
+ }
9346
+ renderSingleValueUserContent = (values, renderedExamples, renderedDemos, examplesInSystemPrompt) => {
9347
+ const completion = this.renderInputFields(values);
9348
+ const promptList = examplesInSystemPrompt ? completion : [...renderedExamples, ...renderedDemos, ...completion];
9349
+ const prompt = promptList.filter((v) => v !== void 0);
9350
+ return prompt.every((v) => v.type === "text") ? prompt.map((v) => v.text).join("\n") : prompt.reduce(combineConsecutiveStrings("\n"), []);
9351
+ };
9352
+ render = (values, {
9353
+ examples,
9354
+ demos
9355
+ }) => {
9356
+ const renderedExamples = examples ? [
9357
+ { type: "text", text: "\n\n## Examples\n" },
9358
+ ...this.renderExamples(examples)
9359
+ ] : [];
9360
+ const renderedDemos = demos ? this.renderDemos(demos) : [];
9361
+ const allTextExamples = renderedExamples.every((v) => v.type === "text");
9362
+ const allTextDemos = renderedDemos.every((v) => v.type === "text");
9363
+ const examplesInSystemPrompt = allTextExamples && allTextDemos;
9364
+ let systemContent = this.task.text;
9365
+ if (examplesInSystemPrompt) {
9366
+ const combinedItems = [
9367
+ { type: "text", text: systemContent },
9368
+ ...renderedExamples,
9369
+ ...renderedDemos
9370
+ ];
9371
+ combinedItems.reduce(combineConsecutiveStrings(""), []);
9372
+ if (combinedItems && combinedItems[0]) {
9373
+ systemContent = combinedItems[0].text;
9374
+ }
9375
+ }
9376
+ const systemPrompt = {
9377
+ role: "system",
9378
+ content: systemContent
9379
+ };
9380
+ if (Array.isArray(values)) {
9381
+ let messages = [];
9382
+ const history = values;
9383
+ let firstItem = true;
9384
+ for (const message of history) {
9385
+ let content;
9386
+ if (firstItem) {
9387
+ content = this.renderSingleValueUserContent(
9388
+ message.values,
9389
+ renderedExamples,
9390
+ renderedDemos,
9391
+ examplesInSystemPrompt
9392
+ );
9393
+ firstItem = false;
9394
+ } else {
9395
+ content = this.renderSingleValueUserContent(
9396
+ message.values,
9397
+ [],
9398
+ [],
9399
+ false
9400
+ );
9401
+ }
9402
+ if (message.role === "user") {
9403
+ messages.push({ role: "user", content });
9404
+ continue;
9405
+ }
9406
+ if (message.role !== "assistant") {
9407
+ throw new Error("Invalid message role");
9408
+ }
9409
+ if (typeof content !== "string") {
9410
+ throw new Error(
9411
+ "Assistant message cannot contain non-text content like images, files,etc"
9412
+ );
9413
+ }
9414
+ messages.push({ role: "assistant", content });
9415
+ }
9416
+ return [systemPrompt, ...messages];
9417
+ }
9418
+ const userContent = this.renderSingleValueUserContent(
9419
+ values,
9420
+ renderedExamples,
9421
+ renderedDemos,
9422
+ examplesInSystemPrompt
9423
+ );
9424
+ return [systemPrompt, { role: "user", content: userContent }];
9425
+ };
9426
+ renderExtraFields = (extraFields) => {
9427
+ const prompt = [];
9428
+ if (!extraFields || extraFields.length === 0) {
9429
+ return prompt;
9430
+ }
9431
+ const groupedFields = extraFields.reduce(
9432
+ (acc, field) => {
9433
+ const title = field.title;
9434
+ if (!acc[title]) {
9435
+ acc[title] = [];
9436
+ }
9437
+ acc[title].push(field);
9438
+ return acc;
9439
+ },
9440
+ {}
9441
+ );
9442
+ const formattedGroupedFields = Object.entries(groupedFields).map(([title, fields]) => {
9443
+ if (fields.length === 1) {
9444
+ const field = fields[0];
9445
+ return {
9446
+ title,
9447
+ name: field.name,
9448
+ description: field.description
9449
+ };
9450
+ } else if (fields.length > 1) {
9451
+ const valuesList = fields.map((field) => `- ${field.description}`).join("\n");
9452
+ return {
9453
+ title,
9454
+ name: fields[0].name,
9455
+ description: valuesList
9456
+ };
9457
+ }
9458
+ }).filter(Boolean);
9459
+ formattedGroupedFields.forEach((field) => {
9460
+ const fn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
9461
+ prompt.push(...fn(field, field.description));
9462
+ });
9463
+ return prompt;
9464
+ };
9465
+ renderExamples = (data) => {
9466
+ const list = [];
9467
+ const exampleContext = {
9468
+ isExample: true
9469
+ };
9470
+ for (const [index, item] of data.entries()) {
9471
+ const renderedInputItem = this.sig.getInputFields().map(
9472
+ (field) => this.renderInField(field, item, {
9473
+ ...exampleContext,
9474
+ isInputField: true
9475
+ })
9476
+ ).filter((v) => v !== void 0).flat();
9477
+ const renderedOutputItem = this.sig.getOutputFields().map(
9478
+ (field) => this.renderInField(field, item, {
9479
+ ...exampleContext,
9480
+ isInputField: false
9481
+ })
9482
+ ).filter((v) => v !== void 0).flat();
9483
+ const renderedItem = [...renderedInputItem, ...renderedOutputItem];
9484
+ if (index > 0 && renderedItem.length > 0 && renderedItem[0]?.type === "text") {
9485
+ list.push({ type: "text", text: "---\n\n" });
9486
+ }
9487
+ renderedItem.forEach((v) => {
9488
+ if ("text" in v) {
9489
+ v.text = v.text + "\n";
9490
+ }
9491
+ list.push(v);
9492
+ });
9493
+ }
9494
+ return list;
9495
+ };
9496
+ renderDemos = (data) => {
9497
+ const list = [];
9498
+ const inputFields = this.sig.getInputFields();
9499
+ const outputFields = this.sig.getOutputFields();
9500
+ const demoContext = {
9501
+ isExample: true
9502
+ };
9503
+ for (const item of data) {
9504
+ const inputRenderedItems = inputFields.map(
9505
+ (field) => this.renderInField(field, item, {
9506
+ ...demoContext,
9507
+ isInputField: true
9508
+ })
9509
+ ).filter((v) => v !== void 0).flat();
9510
+ const outputRenderedItems = outputFields.map(
9511
+ (field) => this.renderInField(field, item, {
9512
+ ...demoContext,
9513
+ isInputField: false
9514
+ })
9515
+ ).filter((v) => v !== void 0).flat();
9516
+ const renderedItem = [...inputRenderedItems, ...outputRenderedItems];
9517
+ renderedItem.slice(0, -1).forEach((v) => {
9518
+ if ("text" in v) {
9519
+ v.text = v.text + "\n";
9520
+ }
9521
+ list.push(v);
9522
+ });
9523
+ }
9524
+ return list;
9525
+ };
9526
+ renderInputFields = (values) => {
9527
+ const renderedItems = this.sig.getInputFields().map((field) => this.renderInField(field, values, void 0)).filter((v) => v !== void 0).flat();
9528
+ renderedItems.filter((v) => v.type === "text").forEach((v) => {
9529
+ v.text = v.text + "\n";
9530
+ });
9531
+ return renderedItems;
9532
+ };
9533
+ renderInField = (field, values, context3) => {
9534
+ const value = values[field.name];
9535
+ if (isEmptyValue(field, value, context3)) {
9536
+ return;
9537
+ }
9538
+ if (field.type) {
9539
+ validateValue(field, value);
9540
+ }
9541
+ const processedValue = processValue(field, value);
9542
+ const textFieldFn = this.fieldTemplates?.[field.name] ?? this.defaultRenderInField;
9543
+ return textFieldFn(field, processedValue);
9544
+ };
9545
+ defaultRenderInField = (field, value) => {
9546
+ if (field.type?.name === "image") {
9547
+ const validateImage = (value2) => {
9548
+ if (!value2) {
9549
+ throw new Error("Image field value is required.");
9550
+ }
9551
+ if (typeof value2 !== "object") {
9552
+ throw new Error("Image field value must be an object.");
9553
+ }
9554
+ if (!("mimeType" in value2)) {
9555
+ throw new Error("Image field must have mimeType");
9556
+ }
9557
+ if (!("data" in value2)) {
9558
+ throw new Error("Image field must have data");
9559
+ }
9560
+ return value2;
9561
+ };
9562
+ let result = [
9563
+ { type: "text", text: `${field.title}: ` }
9564
+ ];
9565
+ if (field.type.isArray) {
9566
+ if (!Array.isArray(value)) {
9567
+ throw new Error("Image field value must be an array.");
9568
+ }
9569
+ result = result.concat(
9570
+ value.map((v) => {
9571
+ const validated = validateImage(v);
9572
+ return {
9573
+ type: "image",
9574
+ mimeType: validated.mimeType,
9575
+ image: validated.data
9576
+ };
9577
+ })
9578
+ );
9579
+ } else {
9580
+ const validated = validateImage(value);
9581
+ result.push({
9582
+ type: "image",
9583
+ mimeType: validated.mimeType,
9584
+ image: validated.data
9585
+ });
9586
+ }
9587
+ return result;
9588
+ }
9589
+ if (field.type?.name === "audio") {
9590
+ const validateAudio = (value2) => {
9591
+ if (!value2) {
9592
+ throw new Error("Audio field value is required.");
9593
+ }
9594
+ if (typeof value2 !== "object") {
9595
+ throw new Error("Audio field value must be an object.");
9596
+ }
9597
+ if (!("data" in value2)) {
9598
+ throw new Error("Audio field must have data");
9599
+ }
9600
+ return value2;
9601
+ };
9602
+ let result = [
9603
+ { type: "text", text: `${field.title}: ` }
9604
+ ];
9605
+ if (field.type.isArray) {
9606
+ if (!Array.isArray(value)) {
9607
+ throw new Error("Audio field value must be an array.");
9608
+ }
9609
+ result = result.concat(
9610
+ value.map((v) => {
9611
+ const validated = validateAudio(v);
9612
+ return {
9613
+ type: "audio",
9614
+ format: validated.format ?? "wav",
9615
+ data: validated.data
9616
+ };
9617
+ })
9618
+ );
9619
+ } else {
9620
+ const validated = validateAudio(value);
9621
+ result.push({
9622
+ type: "audio",
9623
+ format: validated.format ?? "wav",
9624
+ data: validated.data
9625
+ });
9626
+ }
9627
+ return result;
9628
+ }
9629
+ const text = [field.title, ": "];
9630
+ if (Array.isArray(value)) {
9631
+ text.push("\n");
9632
+ text.push(value.map((v) => `- ${v}`).join("\n"));
9633
+ } else {
9634
+ text.push(value);
9635
+ }
9636
+ return [{ type: "text", text: text.join("") }];
9637
+ };
9638
+ };
9639
+ var renderDescFields = (list) => list.map((v) => `\`${v.title}\``).join(", ");
9640
+ var renderInputFields = (fields) => {
9641
+ const rows = fields.map((field) => {
9642
+ const name = field.title;
9643
+ const type = field.type?.name ? toFieldType(field.type) : "string";
9644
+ const requiredMsg = field.isOptional ? `This optional ${type} field may be omitted` : `A ${type} field`;
9645
+ const description = field.description ? ` ${formatDescription(field.description)}` : "";
9646
+ return `${name}: (${requiredMsg})${description}`.trim();
9647
+ });
9648
+ return rows.join("\n");
9649
+ };
9650
+ var renderOutputFields = (fields) => {
9651
+ const rows = fields.map((field) => {
9652
+ const name = field.title;
9653
+ const type = field.type?.name ? toFieldType(field.type) : "string";
9654
+ const requiredMsg = field.isOptional ? `Only include this ${type} field if its value is available` : `This ${type} field must be included`;
9655
+ let description = "";
9656
+ if (field.description && field.description.length > 0) {
9657
+ const value = field.type?.name === "class" ? field.description : formatDescription(field.description);
9658
+ description = ` ${value}`;
9659
+ }
9660
+ if (field.type?.options && field.type.options.length > 0) {
9661
+ if (description.length > 0) {
9662
+ description += `. `;
9663
+ }
9664
+ description += `Allowed values: ${field.type.options.join(", ")}`;
9665
+ }
9666
+ return `${name}: (${requiredMsg})${description}`.trim();
9667
+ });
9668
+ return rows.join("\n");
9669
+ };
9670
+ var processValue = (field, value) => {
9671
+ if (field.type?.name === "date" && value instanceof Date) {
9672
+ const v = value.toISOString();
9673
+ return v.slice(0, v.indexOf("T"));
9674
+ }
9675
+ if (field.type?.name === "datetime" && value instanceof Date) {
9676
+ return formatDateWithTimezone(value);
9677
+ }
9678
+ if (field.type?.name === "image" && typeof value === "object") {
9679
+ return value;
9680
+ }
9681
+ if (field.type?.name === "audio" && typeof value === "object") {
9682
+ return value;
9683
+ }
9684
+ if (typeof value === "string") {
9685
+ return value;
9686
+ }
9687
+ return JSON.stringify(value, null, 2);
9688
+ };
9689
+ var toFieldType = (type) => {
9690
+ const baseType = (() => {
9691
+ switch (type?.name) {
9692
+ case "string":
9693
+ return "string";
9694
+ case "number":
9695
+ return "number";
9696
+ case "boolean":
9697
+ return "boolean";
9698
+ case "date":
9699
+ return 'date ("YYYY-MM-DD" format)';
9700
+ case "datetime":
9701
+ return 'date time ("YYYY-MM-DD HH:mm Timezone" format)';
9702
+ case "json":
9703
+ return "JSON object";
9704
+ case "class":
9705
+ return "classification class";
9706
+ case "code":
9707
+ return "code";
9708
+ default:
9709
+ return "string";
9710
+ }
9711
+ })();
9712
+ return type?.isArray ? `json array of ${baseType} items` : baseType;
9713
+ };
9714
+ function combineConsecutiveStrings(separator) {
9715
+ return (acc, current) => {
9716
+ if (current.type === "text") {
9717
+ const previous = acc.length > 0 ? acc[acc.length - 1] : null;
9718
+ if (previous && previous.type === "text") {
9719
+ previous.text += separator + current.text;
9720
+ } else {
9721
+ acc.push(current);
9722
+ }
9723
+ } else {
9724
+ acc.push(current);
9725
+ }
9726
+ return acc;
9727
+ };
9728
+ }
9729
+ var isEmptyValue = (field, value, context3) => {
9730
+ if (typeof value === "boolean") {
9731
+ return false;
9732
+ }
9733
+ if (!value || (Array.isArray(value) || typeof value === "string") && value.length === 0) {
9734
+ if (context3?.isExample) {
9735
+ return true;
8976
9736
  }
9737
+ if (field.isOptional || field.isInternal) {
9738
+ return true;
9739
+ }
9740
+ const fieldType = context3?.isInputField !== false ? "input" : "output";
9741
+ throw new Error(`Value for ${fieldType} field '${field.name}' is required.`);
8977
9742
  }
8978
- if (type.name === "code" && type.isArray) {
8979
- throw new AxSignatureValidationError(
8980
- "Arrays of code are not commonly supported",
8981
- field.name,
8982
- "Consider using a single code field or an array of strings instead"
8983
- );
9743
+ return false;
9744
+ };
9745
+ function formatDescription(str) {
9746
+ const value = str.trim();
9747
+ return value.length > 0 ? `${value.charAt(0).toUpperCase()}${value.slice(1)}${value.endsWith(".") ? "" : "."}` : "";
9748
+ }
9749
+
9750
+ // dsp/registry.ts
9751
+ var AxInstanceRegistry = class {
9752
+ reg;
9753
+ // To track keys for iteration
9754
+ constructor() {
9755
+ this.reg = /* @__PURE__ */ new Set();
8984
9756
  }
8985
- if (field.isInternal && context3 === "input") {
8986
- throw new AxSignatureValidationError(
8987
- "Internal marker (!) is not allowed on input fields",
8988
- field.name,
8989
- "Internal markers are only allowed on output fields"
8990
- );
9757
+ register(instance) {
9758
+ this.reg.add(instance);
8991
9759
  }
8992
- }
9760
+ *[Symbol.iterator]() {
9761
+ const items = Array.from(this.reg);
9762
+ for (let i = 0; i < items.length; i++) {
9763
+ yield items[i];
9764
+ }
9765
+ }
9766
+ };
8993
9767
 
8994
9768
  // dsp/program.ts
8995
9769
  var AxProgramWithSignature = class {
@@ -9192,6 +9966,118 @@ var AxProgram = class {
9192
9966
  }
9193
9967
  };
9194
9968
 
9969
+ // dsp/samples.ts
9970
+ function checkForFunctionCalls(mem, sessionId) {
9971
+ const history = mem.history(0, sessionId);
9972
+ const hasFunctionResults = history.some((msg) => msg.role === "function");
9973
+ const hasFunctionCalls = history.some(
9974
+ (msg) => msg.role === "assistant" && "functionCalls" in msg && Array.isArray(msg.functionCalls) && msg.functionCalls.length > 0
9975
+ );
9976
+ return hasFunctionCalls && hasFunctionResults;
9977
+ }
9978
+ function extractFunctionResults(mem, sessionId) {
9979
+ const history = mem.history(0, sessionId);
9980
+ const results = [];
9981
+ const assistantMessages = history.filter(
9982
+ (msg) => msg.role === "assistant" && "functionCalls" in msg && Array.isArray(msg.functionCalls) && msg.functionCalls.length > 0
9983
+ );
9984
+ const functionMessages = history.filter((msg) => msg.role === "function");
9985
+ for (const assistantMsg of assistantMessages) {
9986
+ if ("functionCalls" in assistantMsg && assistantMsg.functionCalls) {
9987
+ for (const funcCall of assistantMsg.functionCalls) {
9988
+ const funcResult = functionMessages.find(
9989
+ (msg) => "functionId" in msg && msg.functionId === funcCall.id
9990
+ );
9991
+ if (funcResult && "result" in funcResult && "functionId" in funcResult) {
9992
+ results.push({
9993
+ index: results.length,
9994
+ // Use sequential index for function results
9995
+ functionName: funcCall.function.name,
9996
+ functionId: funcCall.id,
9997
+ args: funcCall.function.params || "",
9998
+ result: String(funcResult.result),
9999
+ isError: "isError" in funcResult ? Boolean(funcResult.isError) : false
10000
+ });
10001
+ }
10002
+ }
10003
+ }
10004
+ }
10005
+ return results;
10006
+ }
10007
+ async function selectFromSamples(buffer, options, mem, sessionId) {
10008
+ if (!options?.resultPicker || buffer.length <= 1) {
10009
+ return 0;
10010
+ }
10011
+ const resultPicker = options.resultPicker;
10012
+ const hasFunctionCalls = mem ? checkForFunctionCalls(mem, sessionId) : false;
10013
+ if (hasFunctionCalls && mem) {
10014
+ const functionResults = extractFunctionResults(mem, sessionId);
10015
+ const selectedIndex = await resultPicker({
10016
+ type: "function",
10017
+ results: functionResults
10018
+ });
10019
+ if (selectedIndex < 0 || selectedIndex >= functionResults.length) {
10020
+ throw new Error(
10021
+ `Result picker returned invalid index: ${selectedIndex}. Must be between 0 and ${functionResults.length - 1}`
10022
+ );
10023
+ }
10024
+ return selectedIndex;
10025
+ } else {
10026
+ const fieldResults = buffer.map((b, index) => ({
10027
+ index,
10028
+ sample: b.delta
10029
+ }));
10030
+ const selectedIndex = await resultPicker({
10031
+ type: "fields",
10032
+ results: fieldResults
10033
+ });
10034
+ if (selectedIndex < 0 || selectedIndex >= buffer.length) {
10035
+ throw new Error(
10036
+ `Result picker returned invalid index: ${selectedIndex}. Must be between 0 and ${buffer.length - 1}`
10037
+ );
10038
+ }
10039
+ return selectedIndex;
10040
+ }
10041
+ }
10042
+ async function selectFromSamplesInMemory(mem, sessionId, options) {
10043
+ const lastMemory = mem?.getLast(sessionId);
10044
+ if (!lastMemory || lastMemory.role !== "assistant") {
10045
+ return 0;
10046
+ }
10047
+ if (lastMemory.chat.length <= 1) {
10048
+ return 0;
10049
+ }
10050
+ const buffer = lastMemory.chat.map((chat) => ({
10051
+ version: 0,
10052
+ index: chat.index,
10053
+ delta: chat.value
10054
+ }));
10055
+ const selectedIndex = await selectFromSamples(buffer, options, mem, sessionId);
10056
+ return selectedIndex;
10057
+ }
10058
+
10059
+ // dsp/validate.ts
10060
+ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId) {
10061
+ mem.addRequest(
10062
+ [
10063
+ {
10064
+ role: "user",
10065
+ content: promptTemplate.renderExtraFields(errorFields)
10066
+ }
10067
+ ],
10068
+ sessionId
10069
+ );
10070
+ mem.addTag("error", sessionId);
10071
+ if (ai.getOptions().debug) {
10072
+ const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
10073
+ const logger = ai.getLogger();
10074
+ logger(`\u274C Error Correction:
10075
+ ${errors}`, {
10076
+ tags: ["error"]
10077
+ });
10078
+ }
10079
+ }
10080
+
9195
10081
  // dsp/generate.ts
9196
10082
  var AxGen = class extends AxProgramWithSignature {
9197
10083
  promptTemplate;
@@ -9199,10 +10085,8 @@ var AxGen = class extends AxProgramWithSignature {
9199
10085
  streamingAsserts;
9200
10086
  options;
9201
10087
  functions;
9202
- functionsExecuted = /* @__PURE__ */ new Set();
9203
10088
  fieldProcessors = [];
9204
10089
  streamingFieldProcessors = [];
9205
- values = {};
9206
10090
  excludeContentFromTrace = false;
9207
10091
  thoughtFieldName;
9208
10092
  constructor(signature, options) {
@@ -9225,6 +10109,20 @@ var AxGen = class extends AxProgramWithSignature {
9225
10109
  this.functions = parseFunctions(options.functions);
9226
10110
  }
9227
10111
  }
10112
+ createStates(n) {
10113
+ return Array.from({ length: n }, (_, index) => ({
10114
+ index,
10115
+ functionCalls: [],
10116
+ values: {},
10117
+ content: "",
10118
+ functionsExecuted: /* @__PURE__ */ new Set(),
10119
+ xstate: {
10120
+ extractedFields: [],
10121
+ streamedIndex: {},
10122
+ s: -1
10123
+ }
10124
+ }));
10125
+ }
9228
10126
  addAssert = (fn, message) => {
9229
10127
  this.asserts.push({ fn, message });
9230
10128
  };
@@ -9265,7 +10163,6 @@ var AxGen = class extends AxProgramWithSignature {
9265
10163
  const {
9266
10164
  sessionId,
9267
10165
  traceId,
9268
- modelConfig,
9269
10166
  model,
9270
10167
  rateLimiter,
9271
10168
  stream,
@@ -9274,7 +10171,10 @@ var AxGen = class extends AxProgramWithSignature {
9274
10171
  thinkingTokenBudget,
9275
10172
  showThoughts
9276
10173
  } = options ?? {};
9277
- const chatPrompt = mem?.history(sessionId) ?? [];
10174
+ const selectedIndex = await selectFromSamplesInMemory(mem, sessionId, {
10175
+ resultPicker: options?.resultPicker
10176
+ });
10177
+ const chatPrompt = mem?.history(selectedIndex, sessionId) ?? [];
9278
10178
  if (chatPrompt.length === 0) {
9279
10179
  throw new Error("No chat prompt found");
9280
10180
  }
@@ -9283,6 +10183,11 @@ var AxGen = class extends AxProgramWithSignature {
9283
10183
  if (!firstStep && (functionCall === "required" || typeof functionCall === "function")) {
9284
10184
  functionCall = void 0;
9285
10185
  }
10186
+ const modelConfig = {
10187
+ ...options?.modelConfig,
10188
+ ...options?.sampleCount ? { n: options.sampleCount } : {},
10189
+ ...options?.sampleCount && options?.modelConfig?.temperature == 1 ? { temperature: 0.8 } : {}
10190
+ };
9286
10191
  const res = await ai.chat(
9287
10192
  {
9288
10193
  chatPrompt,
@@ -9317,7 +10222,9 @@ var AxGen = class extends AxProgramWithSignature {
9317
10222
  const { sessionId, traceId, functions: _functions } = options ?? {};
9318
10223
  const strictMode = options?.strictMode ?? false;
9319
10224
  const model = options.model;
9320
- const functions = _functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat();
10225
+ const states = this.createStates(options.sampleCount ?? 1);
10226
+ const usage = this.usage;
10227
+ const functions = _functions?.map((f2) => "toFunction" in f2 ? f2.toFunction() : f2)?.flat() ?? [];
9321
10228
  const res = await this.forwardSendRequest({
9322
10229
  ai,
9323
10230
  mem,
@@ -9325,8 +10232,8 @@ var AxGen = class extends AxProgramWithSignature {
9325
10232
  traceContext,
9326
10233
  firstStep
9327
10234
  });
9328
- if (res instanceof import_web5.ReadableStream) {
9329
- yield* this.processStreamingResponse({
10235
+ if (res instanceof import_web6.ReadableStream) {
10236
+ yield* processStreamingResponse({
9330
10237
  ai,
9331
10238
  model,
9332
10239
  res,
@@ -9335,11 +10242,20 @@ var AxGen = class extends AxProgramWithSignature {
9335
10242
  sessionId,
9336
10243
  functions,
9337
10244
  strictMode,
9338
- span
10245
+ span,
10246
+ states,
10247
+ usage,
10248
+ asserts: this.asserts,
10249
+ streamingAsserts: this.streamingAsserts,
10250
+ fieldProcessors: this.fieldProcessors,
10251
+ streamingFieldProcessors: this.streamingFieldProcessors,
10252
+ thoughtFieldName: this.thoughtFieldName,
10253
+ excludeContentFromTrace: this.excludeContentFromTrace,
10254
+ signature: this.signature
9339
10255
  });
9340
10256
  this.getLogger(ai, options)?.("", { tags: ["responseEnd"] });
9341
10257
  } else {
9342
- yield await this.processResponse({
10258
+ yield* processResponse({
9343
10259
  ai,
9344
10260
  model,
9345
10261
  res,
@@ -9348,233 +10264,18 @@ var AxGen = class extends AxProgramWithSignature {
9348
10264
  sessionId,
9349
10265
  functions,
9350
10266
  span,
9351
- strictMode
10267
+ strictMode,
10268
+ states,
10269
+ usage,
10270
+ asserts: this.asserts,
10271
+ fieldProcessors: this.fieldProcessors,
10272
+ thoughtFieldName: this.thoughtFieldName,
10273
+ excludeContentFromTrace: this.excludeContentFromTrace,
10274
+ signature: this.signature
9352
10275
  });
9353
10276
  }
9354
10277
  }
9355
- async *processStreamingResponse({
9356
- ai,
9357
- model,
9358
- res,
9359
- mem,
9360
- sessionId,
9361
- traceId,
9362
- functions,
9363
- strictMode,
9364
- span
9365
- }) {
9366
- const functionCalls = [];
9367
- this.values = {};
9368
- const xstate = {
9369
- extractedFields: [],
9370
- streamedIndex: {},
9371
- s: -1
9372
- };
9373
- let content = "";
9374
- mem.addResult(
9375
- {
9376
- content: "",
9377
- functionCalls: []
9378
- },
9379
- sessionId
9380
- );
9381
- for await (const v of res) {
9382
- const result = v.results[0];
9383
- if (!result) {
9384
- continue;
9385
- }
9386
- if (v.modelUsage) {
9387
- this.usage.push(v.modelUsage);
9388
- }
9389
- if (result.functionCalls && result.functionCalls.length > 0) {
9390
- mergeFunctionCalls(functionCalls, result.functionCalls);
9391
- mem.updateResult(
9392
- {
9393
- name: result.name,
9394
- content,
9395
- functionCalls,
9396
- delta: result.functionCalls?.[0]?.function?.params
9397
- },
9398
- sessionId
9399
- );
9400
- } else if (result.content && result.content.length > 0) {
9401
- if (result.thought && result.thought.length > 0) {
9402
- yield {
9403
- [this.thoughtFieldName]: result.thought
9404
- };
9405
- }
9406
- content += result.content;
9407
- mem.updateResult(
9408
- { name: result.name, content, delta: result.content },
9409
- sessionId
9410
- );
9411
- const skip = streamingExtractValues(
9412
- this.signature,
9413
- this.values,
9414
- xstate,
9415
- content,
9416
- strictMode
9417
- );
9418
- if (skip) {
9419
- continue;
9420
- }
9421
- if (this.streamingAsserts.length !== 0) {
9422
- await assertStreamingAssertions(
9423
- this.streamingAsserts,
9424
- xstate,
9425
- content
9426
- );
9427
- }
9428
- if (this.streamingFieldProcessors.length !== 0) {
9429
- await processStreamingFieldProcessors(
9430
- this.streamingFieldProcessors,
9431
- content,
9432
- xstate,
9433
- mem,
9434
- this.values,
9435
- sessionId
9436
- );
9437
- }
9438
- yield* streamValues(
9439
- this.signature,
9440
- content,
9441
- this.values,
9442
- xstate
9443
- );
9444
- await assertAssertions(this.asserts, this.values);
9445
- } else if (result.thought && result.thought.length > 0) {
9446
- this.values[this.thoughtFieldName] = (this.values[this.thoughtFieldName] ?? "") + result.thought;
9447
- yield {
9448
- [this.thoughtFieldName]: result.thought
9449
- };
9450
- }
9451
- if (result.finishReason === "length") {
9452
- throw new Error(
9453
- `Max tokens reached before completion
9454
- Content: ${content}`
9455
- );
9456
- }
9457
- }
9458
- const funcs = parseFunctionCalls(ai, functionCalls, this.values, model);
9459
- if (funcs) {
9460
- if (!functions) {
9461
- throw new Error("Functions are not defined");
9462
- }
9463
- const fx = await processFunctions(
9464
- ai,
9465
- functions,
9466
- funcs,
9467
- mem,
9468
- sessionId,
9469
- traceId,
9470
- span,
9471
- this.excludeContentFromTrace
9472
- );
9473
- this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
9474
- } else {
9475
- streamingExtractFinalValue(this.signature, this.values, xstate, content);
9476
- await assertStreamingAssertions(
9477
- this.streamingAsserts,
9478
- xstate,
9479
- content,
9480
- true
9481
- );
9482
- await assertAssertions(this.asserts, this.values);
9483
- if (this.fieldProcessors.length) {
9484
- await processFieldProcessors(
9485
- this.fieldProcessors,
9486
- this.values,
9487
- mem,
9488
- sessionId
9489
- );
9490
- }
9491
- if (this.streamingFieldProcessors.length !== 0) {
9492
- await processStreamingFieldProcessors(
9493
- this.streamingFieldProcessors,
9494
- content,
9495
- xstate,
9496
- mem,
9497
- this.values,
9498
- sessionId,
9499
- true
9500
- );
9501
- }
9502
- yield* streamValues(
9503
- this.signature,
9504
- content,
9505
- this.values,
9506
- xstate
9507
- );
9508
- }
9509
- }
9510
- async processResponse({
9511
- ai,
9512
- res,
9513
- mem,
9514
- sessionId,
9515
- traceId,
9516
- functions,
9517
- span,
9518
- strictMode
9519
- }) {
9520
- this.values = {};
9521
- let results = res.results ?? [];
9522
- if (results.length > 1) {
9523
- results = results.filter((r) => r.functionCalls);
9524
- }
9525
- for (const result of results) {
9526
- if (res.modelUsage) {
9527
- this.usage.push(res.modelUsage);
9528
- }
9529
- mem.addResult(result, sessionId);
9530
- if (result.functionCalls?.length) {
9531
- const funcs = parseFunctionCalls(ai, result.functionCalls, this.values);
9532
- if (funcs) {
9533
- if (!functions) {
9534
- throw new Error("Functions are not defined");
9535
- }
9536
- const fx = await processFunctions(
9537
- ai,
9538
- functions,
9539
- funcs,
9540
- mem,
9541
- sessionId,
9542
- traceId,
9543
- span,
9544
- this.excludeContentFromTrace
9545
- );
9546
- this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
9547
- }
9548
- } else if (result.content) {
9549
- if (result.thought && result.thought.length > 0) {
9550
- this.values[this.thoughtFieldName] = result.thought;
9551
- }
9552
- extractValues(this.signature, this.values, result.content, strictMode);
9553
- await assertAssertions(this.asserts, this.values);
9554
- if (this.fieldProcessors.length) {
9555
- await processFieldProcessors(
9556
- this.fieldProcessors,
9557
- this.values,
9558
- mem,
9559
- sessionId
9560
- );
9561
- }
9562
- }
9563
- if (result.finishReason === "length") {
9564
- throw new Error(
9565
- `Max tokens reached before completion
9566
- Content: ${result.content}`
9567
- );
9568
- }
9569
- }
9570
- for (const field of this.signature.getOutputFields()) {
9571
- if (field.isInternal) {
9572
- delete this.values[field.name];
9573
- }
9574
- }
9575
- return { ...this.values };
9576
- }
9577
- async *_forward2(ai, values, options, span, traceContext) {
10278
+ async *_forward2(ai, values, states, options, span, traceContext) {
9578
10279
  const stopFunction = (options?.stopFunction ?? this.options?.stopFunction)?.toLowerCase();
9579
10280
  const maxRetries = options.maxRetries ?? this.options?.maxRetries ?? 10;
9580
10281
  const maxSteps = options.maxSteps ?? this.options?.maxSteps ?? 10;
@@ -9583,7 +10284,7 @@ Content: ${result.content}`
9583
10284
  debug: this.isDebug(ai, options),
9584
10285
  debugHideSystemPrompt
9585
10286
  };
9586
- const mem = options.mem ?? this.options?.mem ?? new AxMemory(1e4, memOptions);
10287
+ const mem = options.mem ?? this.options?.mem ?? new AxMemory(memOptions);
9587
10288
  let err;
9588
10289
  if (options?.functions && options.functions.length > 0) {
9589
10290
  const promptTemplateClass = this.options?.promptTemplate ?? AxPromptTemplate;
@@ -9610,7 +10311,7 @@ Content: ${result.content}`
9610
10311
  demos: this.demos
9611
10312
  });
9612
10313
  }
9613
- mem.add(prompt, options?.sessionId);
10314
+ mem.addRequest(prompt, options.sessionId);
9614
10315
  multiStepLoop: for (let n = 0; n < maxSteps; n++) {
9615
10316
  const firstStep = n === 0;
9616
10317
  for (let errCount = 0; errCount < maxRetries; errCount++) {
@@ -9623,15 +10324,20 @@ Content: ${result.content}`
9623
10324
  span,
9624
10325
  traceContext
9625
10326
  });
9626
- for await (const delta of generator) {
9627
- if (delta !== void 0) {
9628
- yield { version: errCount, delta };
10327
+ for await (const result of generator) {
10328
+ if (result !== void 0) {
10329
+ yield {
10330
+ version: errCount,
10331
+ index: result.index,
10332
+ delta: result.delta
10333
+ };
9629
10334
  }
9630
10335
  }
9631
- const lastMemItem = mem.getLast(options?.sessionId);
9632
- const shouldContinue = this.shouldContinueSteps(
9633
- lastMemItem,
9634
- stopFunction
10336
+ const shouldContinue = shouldContinueSteps(
10337
+ mem,
10338
+ stopFunction,
10339
+ states,
10340
+ options?.sessionId
9635
10341
  );
9636
10342
  if (shouldContinue) {
9637
10343
  continue multiStepLoop;
@@ -9687,26 +10393,15 @@ Content: ${result.content}`
9687
10393
  this.signature
9688
10394
  );
9689
10395
  }
9690
- shouldContinueSteps(lastMemItem, stopFunction) {
9691
- const stopFunctionExecuted = stopFunction && this.functionsExecuted.has(stopFunction);
9692
- const isFunction = lastMemItem?.chat?.role === "function";
9693
- const isProcessor = lastMemItem?.tags ? lastMemItem.tags.some((tag) => tag === "processor") : false;
9694
- if (isFunction && stopFunction && stopFunctionExecuted) {
9695
- return false;
9696
- }
9697
- if (isFunction || isProcessor) {
9698
- return true;
9699
- }
9700
- return false;
9701
- }
9702
10396
  async *_forward1(ai, values, options) {
10397
+ const states = this.createStates(options.sampleCount ?? 1);
9703
10398
  const tracer = options?.tracer ?? this.options?.tracer ?? ai.getOptions().tracer;
9704
10399
  let functions = this.functions;
9705
10400
  if (options?.functions) {
9706
10401
  functions = parseFunctions(options.functions, this.functions);
9707
10402
  }
9708
10403
  if (!tracer) {
9709
- yield* this._forward2(ai, values, {
10404
+ yield* this._forward2(ai, values, states, {
9710
10405
  ...options,
9711
10406
  functions
9712
10407
  });
@@ -9738,6 +10433,7 @@ Content: ${result.content}`
9738
10433
  yield* this._forward2(
9739
10434
  ai,
9740
10435
  values,
10436
+ states,
9741
10437
  {
9742
10438
  ...options,
9743
10439
  functions
@@ -9746,8 +10442,10 @@ Content: ${result.content}`
9746
10442
  traceContext
9747
10443
  );
9748
10444
  if (!this.excludeContentFromTrace) {
10445
+ const valuesList = states.map((s2) => s2.values);
10446
+ const values2 = valuesList.length === 1 ? valuesList[0] : valuesList;
9749
10447
  span.addEvent("output", {
9750
- content: JSON.stringify(this.values, null, 2)
10448
+ content: JSON.stringify(values2, null, 2)
9751
10449
  });
9752
10450
  }
9753
10451
  } finally {
@@ -9756,23 +10454,67 @@ Content: ${result.content}`
9756
10454
  }
9757
10455
  async forward(ai, values, options) {
9758
10456
  const generator = this._forward1(ai, values, options ?? {});
9759
- let buffer = {};
10457
+ let buffer = [];
9760
10458
  let currentVersion = 0;
9761
- for await (const item of generator) {
9762
- if (item.version !== currentVersion) {
9763
- buffer = {};
10459
+ for await (const delta of generator) {
10460
+ if (delta.version !== currentVersion) {
10461
+ buffer = [];
9764
10462
  }
9765
- currentVersion = item.version;
9766
- buffer = mergeDeltas(buffer, item.delta);
10463
+ currentVersion = delta.version;
10464
+ buffer = mergeDeltas(buffer, delta);
9767
10465
  }
9768
- this.trace = { ...values, ...buffer };
9769
- return buffer;
10466
+ const selectedIndex = await selectFromSamples(
10467
+ buffer,
10468
+ {
10469
+ resultPicker: options?.resultPicker
10470
+ },
10471
+ // Pass memory to enable function result selection
10472
+ options?.mem,
10473
+ options?.sessionId
10474
+ );
10475
+ const selectedResult = buffer[selectedIndex];
10476
+ const result = selectedResult?.delta ?? {};
10477
+ this.trace = { ...values, ...result };
10478
+ return result;
9770
10479
  }
9771
10480
  async *streamingForward(ai, values, options) {
9772
- yield* this._forward1(ai, values, {
10481
+ if (!options?.resultPicker) {
10482
+ yield* this._forward1(ai, values, {
10483
+ ...options,
10484
+ stream: true
10485
+ });
10486
+ return;
10487
+ }
10488
+ const generator = this._forward1(ai, values, {
9773
10489
  ...options,
9774
10490
  stream: true
9775
10491
  });
10492
+ let buffer = [];
10493
+ let currentVersion = 0;
10494
+ for await (const delta of generator) {
10495
+ if (delta.version !== currentVersion) {
10496
+ buffer = [];
10497
+ }
10498
+ currentVersion = delta.version;
10499
+ buffer = mergeDeltas(buffer, delta);
10500
+ }
10501
+ const selectedIndex = await selectFromSamples(
10502
+ buffer,
10503
+ {
10504
+ resultPicker: options?.resultPicker
10505
+ },
10506
+ // Pass memory to enable function result selection
10507
+ options?.mem,
10508
+ options?.sessionId
10509
+ );
10510
+ const selectedResult = buffer[selectedIndex];
10511
+ if (selectedResult) {
10512
+ yield {
10513
+ version: currentVersion,
10514
+ index: selectedIndex,
10515
+ delta: selectedResult.delta
10516
+ };
10517
+ }
9776
10518
  }
9777
10519
  setExamples(examples, options) {
9778
10520
  super.setExamples(examples, options);
@@ -9787,9 +10529,13 @@ Content: ${result.content}`
9787
10529
  var AxGenerateError = class extends Error {
9788
10530
  details;
9789
10531
  constructor(message, details, options) {
9790
- super(message, options);
10532
+ super(message);
9791
10533
  this.name = "AxGenerateError";
9792
10534
  this.details = details;
10535
+ if (options?.cause) {
10536
+ ;
10537
+ this.cause = options.cause;
10538
+ }
9793
10539
  }
9794
10540
  };
9795
10541
  function enhanceError(e, ai, signature) {
@@ -11864,23 +12610,6 @@ var getTopInPercent = (entries, percent = 0.1) => {
11864
12610
  return sortedEntries.slice(0, topTenPercentCount);
11865
12611
  };
11866
12612
 
11867
- // docs/rewriter.ts
11868
- var AxDefaultQueryRewriter = class extends AxGen {
11869
- constructor(options) {
11870
- 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."
11871
- query: string -> rewrittenQuery: string`;
11872
- super(signature, options);
11873
- }
11874
- };
11875
- var AxRewriter = class extends AxGen {
11876
- constructor(options) {
11877
- super(
11878
- '"Rewrite a given text to be clear and concise" original -> rewritten "improved text"',
11879
- options
11880
- );
11881
- }
11882
- };
11883
-
11884
12613
  // funcs/docker.ts
11885
12614
  var AxDockerSession = class {
11886
12615
  apiUrl;
@@ -13471,6 +14200,7 @@ var AxMockAIService = class {
13471
14200
  return this.config.chatResponse ?? {
13472
14201
  results: [
13473
14202
  {
14203
+ index: 0,
13474
14204
  content: "Mock response",
13475
14205
  finishReason: "stop"
13476
14206
  }
@@ -15772,7 +16502,6 @@ var AxRAG = class extends AxChainOfThought {
15772
16502
  AxDBPinecone,
15773
16503
  AxDBWeaviate,
15774
16504
  AxDefaultCostTracker,
15775
- AxDefaultQueryRewriter,
15776
16505
  AxDefaultResultReranker,
15777
16506
  AxDockerSession,
15778
16507
  AxEmbeddingAdapter,
@@ -15799,7 +16528,6 @@ var AxRAG = class extends AxChainOfThought {
15799
16528
  AxPromptTemplate,
15800
16529
  AxRAG,
15801
16530
  AxRateLimiterTokenUsage,
15802
- AxRewriter,
15803
16531
  AxSignature,
15804
16532
  AxSimpleClassifier,
15805
16533
  AxSimpleClassifierClass,
@@ -15859,6 +16587,8 @@ var AxRAG = class extends AxChainOfThought {
15859
16587
  axModelInfoTogether,
15860
16588
  axSpanAttributes,
15861
16589
  axSpanEvents,
16590
+ axValidateChatRequestMessage,
16591
+ axValidateChatResponseResult,
15862
16592
  f,
15863
16593
  s
15864
16594
  });