@ax-llm/ax 10.0.40 → 10.0.42

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
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  AxAI: () => AxAI,
34
34
  AxAIAnthropic: () => AxAIAnthropic,
35
35
  AxAIAnthropicModel: () => AxAIAnthropicModel,
36
+ AxAIAnthropicVertexModel: () => AxAIAnthropicVertexModel,
36
37
  AxAIAzureOpenAI: () => AxAIAzureOpenAI,
37
38
  AxAICohere: () => AxAICohere,
38
39
  AxAICohereEmbedModel: () => AxAICohereEmbedModel,
@@ -883,6 +884,61 @@ var setResponseAttr = (res, span) => {
883
884
  }
884
885
  };
885
886
 
887
+ // ai/google-vertex/auth.ts
888
+ var import_google_auth_library = require("google-auth-library");
889
+ var GoogleVertexAuth = class {
890
+ auth;
891
+ client;
892
+ currentToken;
893
+ tokenExpiry;
894
+ constructor(config = {}) {
895
+ this.auth = new import_google_auth_library.GoogleAuth({
896
+ scopes: ["https://www.googleapis.com/auth/cloud-platform"],
897
+ ...config
898
+ });
899
+ }
900
+ async getAuthenticatedClient() {
901
+ if (!this.client) {
902
+ this.client = await this.auth.getClient();
903
+ }
904
+ return this.client;
905
+ }
906
+ async getAccessToken() {
907
+ if (this.currentToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
908
+ return this.currentToken;
909
+ }
910
+ const client = await this.getAuthenticatedClient();
911
+ const tokenResponse = await client.getAccessToken();
912
+ this.currentToken = tokenResponse.token ?? void 0;
913
+ const expiry = this.getExpiry(tokenResponse);
914
+ const fiveMinutes = 5 * 60 * 1e3;
915
+ this.tokenExpiry = expiry - fiveMinutes;
916
+ return this.currentToken;
917
+ }
918
+ /**
919
+ * Get the expiry date from the token response.
920
+ */
921
+ getExpiry(tokenResponse) {
922
+ const oneHour = 3600 * 1e3;
923
+ let expiry = Date.now() + oneHour;
924
+ let responseExpiry = tokenResponse.res?.data?.expiry_date;
925
+ if (responseExpiry) {
926
+ if (typeof responseExpiry === "number") {
927
+ expiry = responseExpiry;
928
+ } else if (responseExpiry instanceof Date) {
929
+ expiry = responseExpiry.getTime();
930
+ } else if (typeof responseExpiry === "string") {
931
+ expiry = new Date(responseExpiry).getTime();
932
+ } else {
933
+ console.warn("Unknown expiry type", responseExpiry);
934
+ }
935
+ } else {
936
+ console.warn("No expiry date found in response", tokenResponse.res?.data);
937
+ }
938
+ return expiry;
939
+ }
940
+ };
941
+
886
942
  // ai/anthropic/types.ts
887
943
  var AxAIAnthropicModel = /* @__PURE__ */ ((AxAIAnthropicModel2) => {
888
944
  AxAIAnthropicModel2["Claude35Sonnet"] = "claude-3-5-sonnet-latest";
@@ -894,6 +950,14 @@ var AxAIAnthropicModel = /* @__PURE__ */ ((AxAIAnthropicModel2) => {
894
950
  AxAIAnthropicModel2["ClaudeInstant12"] = "claude-instant-1.2";
895
951
  return AxAIAnthropicModel2;
896
952
  })(AxAIAnthropicModel || {});
953
+ var AxAIAnthropicVertexModel = /* @__PURE__ */ ((AxAIAnthropicVertexModel2) => {
954
+ AxAIAnthropicVertexModel2["Claude35Haiku"] = "claude-3-5-haiku";
955
+ AxAIAnthropicVertexModel2["Claude35Sonnet"] = "claude-3-5-sonnet";
956
+ AxAIAnthropicVertexModel2["Claude35SonnetV2"] = "claude-3-5-sonnet-v2";
957
+ AxAIAnthropicVertexModel2["Claude3Haiku"] = "claude-3-haiku";
958
+ AxAIAnthropicVertexModel2["Claude3Opus"] = "claude-3-opus";
959
+ return AxAIAnthropicVertexModel2;
960
+ })(AxAIAnthropicVertexModel || {});
897
961
 
898
962
  // ai/anthropic/info.ts
899
963
  var axModelInfoAnthropic = [
@@ -950,8 +1014,9 @@ var axAIAnthropicDefaultConfig = () => structuredClone({
950
1014
  ...axBaseAIDefaultConfig()
951
1015
  });
952
1016
  var AxAIAnthropicImpl = class {
953
- constructor(config) {
1017
+ constructor(config, isVertex) {
954
1018
  this.config = config;
1019
+ this.isVertex = isVertex;
955
1020
  }
956
1021
  getModelConfig() {
957
1022
  const { config } = this;
@@ -970,9 +1035,17 @@ var AxAIAnthropicImpl = class {
970
1035
  }
971
1036
  createChatReq = (req) => {
972
1037
  const model = req.model;
973
- const apiConfig = {
974
- name: "/messages"
975
- };
1038
+ const stream = req.modelConfig?.stream ?? this.config.stream;
1039
+ let apiConfig;
1040
+ if (this.isVertex) {
1041
+ apiConfig = {
1042
+ name: stream ? `/models/${model}:streamRawPredict?alt=sse` : `/models/${model}:rawPredict`
1043
+ };
1044
+ } else {
1045
+ apiConfig = {
1046
+ name: "/messages"
1047
+ };
1048
+ }
976
1049
  let toolsChoice;
977
1050
  if (req.functionCall && req.functions && req.functions.length > 0) {
978
1051
  if (typeof req.functionCall === "string") {
@@ -1011,9 +1084,8 @@ var AxAIAnthropicImpl = class {
1011
1084
  input_schema: v.parameters
1012
1085
  })
1013
1086
  );
1014
- const stream = req.modelConfig?.stream ?? this.config.stream;
1015
1087
  const reqValue = {
1016
- model,
1088
+ ...this.isVertex ? { anthropic_version: "vertex-2023-10-16" } : { model },
1017
1089
  max_tokens: req.modelConfig?.maxTokens ?? this.config.maxTokens,
1018
1090
  stop_sequences: req.modelConfig?.stopSequences ?? this.config.stopSequences,
1019
1091
  temperature: req.modelConfig?.temperature ?? this.config.temperature,
@@ -1168,26 +1240,45 @@ var AxAIAnthropicImpl = class {
1168
1240
  var AxAIAnthropic = class extends AxBaseAI {
1169
1241
  constructor({
1170
1242
  apiKey,
1243
+ projectId,
1244
+ region,
1171
1245
  config,
1172
1246
  options,
1173
1247
  modelMap
1174
1248
  }) {
1175
- if (!apiKey || apiKey === "") {
1176
- throw new Error("Anthropic API key not set");
1249
+ const isVertex = projectId !== void 0 && region !== void 0;
1250
+ let apiURL;
1251
+ let headers;
1252
+ if (isVertex) {
1253
+ apiURL = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/anthropic/`;
1254
+ if (apiKey) {
1255
+ headers = async () => ({ Authorization: `Bearer ${apiKey}` });
1256
+ } else {
1257
+ const vertexAuth = new GoogleVertexAuth();
1258
+ headers = async () => ({
1259
+ Authorization: `Bearer ${await vertexAuth.getAccessToken()}`
1260
+ });
1261
+ }
1262
+ } else {
1263
+ if (!apiKey) {
1264
+ throw new Error("Anthropic API key not set");
1265
+ }
1266
+ apiURL = "https://api.anthropic.com/v1";
1267
+ headers = async () => ({
1268
+ "anthropic-version": "2023-06-01",
1269
+ "anthropic-beta": "prompt-caching-2024-07-31",
1270
+ "x-api-key": apiKey
1271
+ });
1177
1272
  }
1178
1273
  const _config = {
1179
1274
  ...axAIAnthropicDefaultConfig(),
1180
1275
  ...config
1181
1276
  };
1182
- const aiImpl = new AxAIAnthropicImpl(_config);
1277
+ const aiImpl = new AxAIAnthropicImpl(_config, isVertex);
1183
1278
  super(aiImpl, {
1184
1279
  name: "Anthropic",
1185
- apiURL: "https://api.anthropic.com/v1",
1186
- headers: async () => ({
1187
- "anthropic-version": "2023-06-01",
1188
- "anthropic-beta": "prompt-caching-2024-07-31",
1189
- "x-api-key": apiKey
1190
- }),
1280
+ apiURL,
1281
+ headers,
1191
1282
  modelInfo: axModelInfoAnthropic,
1192
1283
  models: { model: _config.model },
1193
1284
  options,
@@ -2124,61 +2215,6 @@ var AxAIDeepSeek = class extends AxAIOpenAI {
2124
2215
  }
2125
2216
  };
2126
2217
 
2127
- // ai/google-gemini/auth.ts
2128
- var import_google_auth_library = require("google-auth-library");
2129
- var GoogleVertexAuth = class {
2130
- auth;
2131
- client;
2132
- currentToken;
2133
- tokenExpiry;
2134
- constructor(config = {}) {
2135
- this.auth = new import_google_auth_library.GoogleAuth({
2136
- scopes: ["https://www.googleapis.com/auth/cloud-platform"],
2137
- ...config
2138
- });
2139
- }
2140
- async getAuthenticatedClient() {
2141
- if (!this.client) {
2142
- this.client = await this.auth.getClient();
2143
- }
2144
- return this.client;
2145
- }
2146
- async getAccessToken() {
2147
- if (this.currentToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
2148
- return this.currentToken;
2149
- }
2150
- const client = await this.getAuthenticatedClient();
2151
- const tokenResponse = await client.getAccessToken();
2152
- this.currentToken = tokenResponse.token ?? void 0;
2153
- const expiry = this.getExpiry(tokenResponse);
2154
- const fiveMinutes = 5 * 60 * 1e3;
2155
- this.tokenExpiry = expiry - fiveMinutes;
2156
- return this.currentToken;
2157
- }
2158
- /**
2159
- * Get the expiry date from the token response.
2160
- */
2161
- getExpiry(tokenResponse) {
2162
- const oneHour = 3600 * 1e3;
2163
- let expiry = Date.now() + oneHour;
2164
- let responseExpiry = tokenResponse.res?.data?.expiry_date;
2165
- if (responseExpiry) {
2166
- if (typeof responseExpiry === "number") {
2167
- expiry = responseExpiry;
2168
- } else if (responseExpiry instanceof Date) {
2169
- expiry = responseExpiry.getTime();
2170
- } else if (typeof responseExpiry === "string") {
2171
- expiry = new Date(responseExpiry).getTime();
2172
- } else {
2173
- console.warn("Unknown expiry type", responseExpiry);
2174
- }
2175
- } else {
2176
- console.warn("No expiry date found in response", tokenResponse.res?.data);
2177
- }
2178
- return expiry;
2179
- }
2180
- };
2181
-
2182
2218
  // ai/google-gemini/types.ts
2183
2219
  var AxAIGoogleGeminiModel = /* @__PURE__ */ ((AxAIGoogleGeminiModel2) => {
2184
2220
  AxAIGoogleGeminiModel2["Gemini1Pro"] = "gemini-1.0-pro";
@@ -2268,11 +2304,10 @@ var axAIGoogleGeminiDefaultConfig = () => structuredClone({
2268
2304
  ...axBaseAIDefaultConfig()
2269
2305
  });
2270
2306
  var AxAIGoogleGeminiImpl = class {
2271
- constructor(config, isVertex, apiKey, keyFile, options) {
2307
+ constructor(config, isVertex, apiKey, options) {
2272
2308
  this.config = config;
2273
2309
  this.isVertex = isVertex;
2274
2310
  this.apiKey = apiKey;
2275
- this.keyFile = keyFile;
2276
2311
  this.options = options;
2277
2312
  }
2278
2313
  getModelConfig() {
@@ -2549,7 +2584,6 @@ var AxAIGoogleGemini = class extends AxBaseAI {
2549
2584
  apiKey,
2550
2585
  projectId,
2551
2586
  region,
2552
- keyFile,
2553
2587
  config,
2554
2588
  options,
2555
2589
  modelMap
@@ -2562,9 +2596,7 @@ var AxAIGoogleGemini = class extends AxBaseAI {
2562
2596
  if (apiKey) {
2563
2597
  headers = async () => ({ Authorization: `Bearer ${apiKey}` });
2564
2598
  } else {
2565
- const vertexAuth = new GoogleVertexAuth({
2566
- keyFile
2567
- });
2599
+ const vertexAuth = new GoogleVertexAuth();
2568
2600
  headers = async () => ({
2569
2601
  Authorization: `Bearer ${await vertexAuth.getAccessToken()}`
2570
2602
  });
@@ -2580,13 +2612,7 @@ var AxAIGoogleGemini = class extends AxBaseAI {
2580
2612
  ...axAIGoogleGeminiDefaultConfig(),
2581
2613
  ...config
2582
2614
  };
2583
- const aiImpl = new AxAIGoogleGeminiImpl(
2584
- _config,
2585
- isVertex,
2586
- apiKey,
2587
- keyFile,
2588
- options
2589
- );
2615
+ const aiImpl = new AxAIGoogleGeminiImpl(_config, isVertex, apiKey, options);
2590
2616
  super(aiImpl, {
2591
2617
  name: "GoogleGeminiAI",
2592
2618
  apiURL,
@@ -4104,19 +4130,65 @@ var parseMarkdownList = (input) => {
4104
4130
  return list;
4105
4131
  };
4106
4132
  function mergeDeltas(base, delta) {
4107
- const merged = { ...base };
4108
- for (const key in delta) {
4133
+ for (const key of Object.keys(delta)) {
4109
4134
  const baseValue = base[key];
4110
4135
  const deltaValue = delta[key];
4111
- if (Array.isArray(baseValue) && Array.isArray(deltaValue)) {
4112
- merged[key] = [...baseValue, ...deltaValue];
4113
- } else if (typeof baseValue === "string" && typeof deltaValue === "string") {
4114
- merged[key] = baseValue + deltaValue;
4136
+ if ((baseValue === void 0 || Array.isArray(baseValue)) && Array.isArray(deltaValue)) {
4137
+ base[key] = [...baseValue ?? [], ...deltaValue];
4138
+ } else if ((baseValue === void 0 || typeof baseValue === "string") && typeof deltaValue === "string") {
4139
+ base[key] = (baseValue ?? "") + deltaValue;
4115
4140
  } else {
4116
- merged[key] = deltaValue;
4141
+ base[key] = deltaValue;
4142
+ }
4143
+ }
4144
+ return base;
4145
+ }
4146
+ var LRUCache = class {
4147
+ cache = /* @__PURE__ */ new Map();
4148
+ maxSize;
4149
+ constructor(maxSize) {
4150
+ this.maxSize = maxSize;
4151
+ }
4152
+ get(key) {
4153
+ const value = this.cache.get(key);
4154
+ if (value) {
4155
+ this.cache.delete(key);
4156
+ this.cache.set(key, value);
4157
+ }
4158
+ return value;
4159
+ }
4160
+ set(key, value) {
4161
+ if (this.cache.has(key)) {
4162
+ this.cache.delete(key);
4163
+ } else if (this.cache.size >= this.maxSize) {
4164
+ const firstKey = this.cache.keys().next().value;
4165
+ if (firstKey) {
4166
+ this.cache.delete(firstKey);
4167
+ }
4117
4168
  }
4169
+ this.cache.set(key, value);
4118
4170
  }
4119
- return merged;
4171
+ };
4172
+ var globalPrefixCache = new LRUCache(500);
4173
+ function matchesContent(content, prefix, startIndex = 0, prefixCache = globalPrefixCache) {
4174
+ const exactMatchIndex = content.indexOf(prefix, startIndex);
4175
+ if (exactMatchIndex !== -1) {
4176
+ return exactMatchIndex;
4177
+ }
4178
+ const prefixes = prefixCache.get(prefix) ?? Array.from({ length: prefix.length }, (_, i) => prefix.slice(0, i + 1));
4179
+ if (!prefixCache.get(prefix)) {
4180
+ prefixCache.set(prefix, prefixes);
4181
+ }
4182
+ const contentEnd = content.slice(
4183
+ Math.max(startIndex, content.length - prefix.length)
4184
+ );
4185
+ for (let i = 0; i < prefixes.length - 1; i++) {
4186
+ const partialPrefix = prefixes[i];
4187
+ if (contentEnd.endsWith(partialPrefix)) {
4188
+ return -2;
4189
+ }
4190
+ }
4191
+ return -1;
4120
4192
  }
4121
4193
 
4122
4194
  // dsp/program.ts
@@ -4713,14 +4785,11 @@ function handleValidationError(mem, errorFields, ai, promptTemplate, sessionId)
4713
4785
  );
4714
4786
  mem.addTag("error");
4715
4787
  if (ai.getOptions().debug) {
4716
- process.stdout.write(
4717
- colorLog4.red(
4718
- `
4788
+ const errors = errorFields.map((field) => `- ${field.title}: ${field.description}`).join("\n");
4789
+ process.stdout.write(colorLog4.red(`
4719
4790
  Error Correction:
4720
- ${JSON.stringify(errorFields, null, 2)}
4721
- `
4722
- )
4723
- );
4791
+ ${errors}
4792
+ `));
4724
4793
  }
4725
4794
  }
4726
4795
 
@@ -4815,19 +4884,24 @@ var streamingExtractValues = (sig, values, xstate, content) => {
4815
4884
  continue;
4816
4885
  }
4817
4886
  const prefix = field.title + ":";
4818
- const e = content.indexOf(prefix, xstate.s + 1);
4819
- if (e === -1) {
4820
- continue;
4887
+ let e = matchesContent(content, prefix, xstate.s + 1);
4888
+ switch (e) {
4889
+ case -1:
4890
+ continue;
4891
+ // Field is not found, continue to the next field
4892
+ case -2:
4893
+ return true;
4821
4894
  }
4895
+ let prefixLen = prefix.length;
4822
4896
  if (xstate.currField) {
4823
- const val = content.substring(xstate.s, e);
4897
+ const val = content.substring(xstate.s, e).trim();
4824
4898
  const parsedValue = validateAndParseFieldValue(xstate.currField, val);
4825
4899
  if (parsedValue !== void 0) {
4826
4900
  values[xstate.currField.name] = parsedValue;
4827
4901
  }
4828
4902
  }
4829
4903
  checkMissingRequiredFields(xstate, values, index);
4830
- xstate.s = e + prefix.length;
4904
+ xstate.s = e + prefixLen;
4831
4905
  xstate.currField = field;
4832
4906
  if (!xstate.extractedFields.includes(field)) {
4833
4907
  xstate.extractedFields.push(field);
@@ -4836,7 +4910,7 @@ var streamingExtractValues = (sig, values, xstate, content) => {
4836
4910
  };
4837
4911
  var streamingExtractFinalValue = (sig, values, xstate, content) => {
4838
4912
  if (xstate.currField) {
4839
- const val = content.substring(xstate.s);
4913
+ const val = content.substring(xstate.s).trim();
4840
4914
  const parsedValue = validateAndParseFieldValue(xstate.currField, val);
4841
4915
  if (parsedValue !== void 0) {
4842
4916
  values[xstate.currField.name] = parsedValue;
@@ -4857,6 +4931,9 @@ var convertValueToType = (field, val) => {
4857
4931
  return v;
4858
4932
  }
4859
4933
  case "boolean": {
4934
+ if (typeof val === "boolean") {
4935
+ return val;
4936
+ }
4860
4937
  const v = val.toLowerCase();
4861
4938
  if (v === "true") {
4862
4939
  return true;
@@ -4871,17 +4948,18 @@ var convertValueToType = (field, val) => {
4871
4948
  case "datetime":
4872
4949
  return parseLLMFriendlyDateTime(field, val);
4873
4950
  case "class":
4874
- if (field.type.classes && !field.type.classes.includes(val)) {
4951
+ const className = val;
4952
+ if (field.type.classes && !field.type.classes.includes(className)) {
4875
4953
  throw new Error(
4876
4954
  `Invalid class '${val}', expected one of the following: ${field.type.classes.join(", ")}`
4877
4955
  );
4878
4956
  }
4879
- return val;
4957
+ return className;
4880
4958
  default:
4881
4959
  return val;
4882
4960
  }
4883
4961
  };
4884
- function* streamingValues(sig, values, xstate, content) {
4962
+ function* streamValues(sig, values, xstate, content, final = false) {
4885
4963
  if (!xstate.currField) {
4886
4964
  return;
4887
4965
  }
@@ -4889,81 +4967,88 @@ function* streamingValues(sig, values, xstate, content) {
4889
4967
  if (!xstate.streamedIndex) {
4890
4968
  xstate.streamedIndex = { [fieldName]: 0 };
4891
4969
  }
4892
- if (!xstate.currField.type || !xstate.currField.type.isArray && xstate.currField.type.name === "string") {
4893
- const s = xstate.s + (xstate.streamedIndex[fieldName] ?? 0);
4894
- const v = content.substring(s);
4895
- yield { [fieldName]: v };
4896
- xstate.streamedIndex[fieldName] = v.length;
4897
- return;
4970
+ if (!final) {
4971
+ if (!xstate.currField.type || !xstate.currField.type.isArray && xstate.currField.type.name === "string") {
4972
+ const pos = xstate.streamedIndex[fieldName] ?? 0;
4973
+ const s = xstate.s + pos;
4974
+ const v = content.substring(s);
4975
+ const v1 = v.replace(/[\s\n\t]+$/, "");
4976
+ const v2 = pos === 0 ? v1.trimStart() : v1;
4977
+ yield { [fieldName]: v2 };
4978
+ xstate.streamedIndex[fieldName] = pos + v1.length;
4979
+ return;
4980
+ }
4898
4981
  }
4899
4982
  for (const key of Object.keys(values)) {
4900
4983
  const value = values[key];
4901
4984
  if (Array.isArray(value)) {
4902
- const s = xstate.streamedIndex[fieldName] ?? 0;
4985
+ const s = xstate.streamedIndex[key] ?? 0;
4903
4986
  const v = value.slice(s);
4904
4987
  if (v) {
4905
- yield { [fieldName]: v };
4906
- xstate.streamedIndex[fieldName] = s + 1;
4988
+ yield { [key]: v };
4989
+ xstate.streamedIndex[key] = s + 1;
4907
4990
  }
4908
4991
  continue;
4909
4992
  }
4910
- if (!xstate.streamedIndex[fieldName]) {
4911
- yield { [fieldName]: value };
4912
- xstate.streamedIndex[fieldName] = 1;
4993
+ if (!xstate.streamedIndex[key]) {
4994
+ yield { [key]: value };
4995
+ xstate.streamedIndex[key] = 1;
4913
4996
  }
4914
4997
  }
4915
4998
  }
4916
4999
  function validateAndParseFieldValue(field, fieldValue) {
4917
- const fv = fieldValue?.trim();
4918
- if (!fv || !fv || fv === "" || fv === "null" || fv === "NULL" || fv === "undefined") {
5000
+ if (!fieldValue || fieldValue === "" || fieldValue === "null" || fieldValue === "NULL" || fieldValue === "undefined") {
4919
5001
  if (field.isOptional) {
4920
5002
  return;
4921
5003
  }
4922
5004
  throw new ValidationError({
4923
5005
  message: "Required field is missing",
4924
5006
  fields: [field],
4925
- value: fv
5007
+ value: fieldValue
4926
5008
  });
4927
5009
  }
4928
5010
  let value;
4929
5011
  if (field.type?.name === "json") {
4930
5012
  try {
4931
- const text = extractBlock(fv);
5013
+ const text = extractBlock(fieldValue);
4932
5014
  value = import_json5.default.parse(text);
4933
5015
  return value;
4934
5016
  } catch (e) {
4935
5017
  throw new ValidationError({
4936
5018
  message: "Invalid JSON: " + e.message,
4937
5019
  fields: [field],
4938
- value: fv
5020
+ value: fieldValue
4939
5021
  });
4940
5022
  }
4941
5023
  }
4942
5024
  if (field.type?.isArray) {
4943
5025
  try {
4944
5026
  try {
4945
- value = import_json5.default.parse(fv);
5027
+ value = import_json5.default.parse(fieldValue);
4946
5028
  } catch {
4947
- value = parseMarkdownList(fv);
5029
+ value = parseMarkdownList(fieldValue);
4948
5030
  }
4949
5031
  if (!Array.isArray(value)) {
4950
5032
  throw new Error("Expected an array");
4951
5033
  }
4952
5034
  } catch (e) {
4953
5035
  throw new ValidationError({
4954
- message: "Invalid array: " + e.message,
5036
+ message: "Invalid Array: " + e.message,
4955
5037
  fields: [field],
4956
- value: fv
5038
+ value: fieldValue
4957
5039
  });
4958
5040
  }
4959
5041
  }
4960
5042
  try {
4961
5043
  if (Array.isArray(value)) {
4962
5044
  for (const [index, item] of value.entries()) {
4963
- value[index] = convertValueToType(field, item);
5045
+ if (item !== void 0) {
5046
+ const v = typeof item === "string" ? item.trim() : item;
5047
+ value[index] = convertValueToType(field, v);
5048
+ }
4964
5049
  }
4965
5050
  } else {
4966
- value = convertValueToType(field, fv);
5051
+ value = convertValueToType(field, fieldValue);
4967
5052
  }
4968
5053
  } catch (e) {
4969
5054
  throw new ValidationError({
@@ -4972,7 +5057,10 @@ function validateAndParseFieldValue(field, fieldValue) {
4972
5057
  value: fieldValue
4973
5058
  });
4974
5059
  }
4975
- return value ?? fv;
5060
+ if (typeof value === "string" && value === "") {
5061
+ return void 0;
5062
+ }
5063
+ return value;
4976
5064
  }
4977
5065
  var extractBlock = (input) => {
4978
5066
  const jsonBlockPattern = /```([A-Za-z]+)?\s*([\s\S]*?)\s*```/g;
@@ -5254,7 +5342,10 @@ var AxGen = class extends AxProgramWithSignature {
5254
5342
  }) {
5255
5343
  const functionCalls = [];
5256
5344
  const values = {};
5257
- const xstate = { extractedFields: [], s: -1 };
5345
+ const xstate = {
5346
+ extractedFields: [],
5347
+ s: -1
5348
+ };
5258
5349
  let content = "";
5259
5350
  for await (const v of res) {
5260
5351
  const result = v.results[0];
@@ -5267,6 +5358,15 @@ var AxGen = class extends AxProgramWithSignature {
5267
5358
  if (result.content) {
5268
5359
  content += result.content;
5269
5360
  mem.updateResult({ name: result.name, content }, sessionId);
5361
+ const skip = streamingExtractValues(
5362
+ this.signature,
5363
+ values,
5364
+ xstate,
5365
+ content
5366
+ );
5367
+ if (skip) {
5368
+ continue;
5369
+ }
5270
5370
  assertStreamingAssertions(
5271
5371
  this.streamingAsserts,
5272
5372
  values,
@@ -5274,9 +5374,8 @@ var AxGen = class extends AxProgramWithSignature {
5274
5374
  content,
5275
5375
  false
5276
5376
  );
5277
- streamingExtractValues(this.signature, values, xstate, content);
5278
5377
  assertAssertions(this.asserts, values);
5279
- yield* streamingValues(this.signature, values, xstate, content);
5378
+ yield* streamValues(this.signature, values, xstate, content);
5280
5379
  }
5281
5380
  if (result.functionCalls) {
5282
5381
  mergeFunctionCalls(functionCalls, result.functionCalls);
@@ -5304,6 +5403,7 @@ var AxGen = class extends AxProgramWithSignature {
5304
5403
  );
5305
5404
  this.functionsExecuted = /* @__PURE__ */ new Set([...this.functionsExecuted, ...fx]);
5306
5405
  }
5406
+ streamingExtractFinalValue(this.signature, values, xstate, content);
5307
5407
  assertStreamingAssertions(
5308
5408
  this.streamingAsserts,
5309
5409
  values,
@@ -5311,9 +5411,8 @@ var AxGen = class extends AxProgramWithSignature {
5311
5411
  content,
5312
5412
  true
5313
5413
  );
5314
- streamingExtractFinalValue(this.signature, values, xstate, content);
5315
5414
  assertAssertions(this.asserts, values);
5316
- return values;
5415
+ yield* streamValues(this.signature, values, xstate, content, true);
5317
5416
  }
5318
5417
  async processResponse({
5319
5418
  ai,
@@ -5382,10 +5481,9 @@ var AxGen = class extends AxProgramWithSignature {
5382
5481
  try {
5383
5482
  const generator = this.forwardCore({ options, ai, mem });
5384
5483
  for await (const delta of generator) {
5385
- yield {
5386
- version: errCount,
5387
- delta
5388
- };
5484
+ if (delta !== void 0) {
5485
+ yield { version: errCount, delta };
5486
+ }
5389
5487
  }
5390
5488
  const lastMemItem = mem.getLast(options?.sessionId);
5391
5489
  const shouldContinue = this.shouldContinueSteps(
@@ -5478,8 +5576,13 @@ var AxGen = class extends AxProgramWithSignature {
5478
5576
  ...options
5479
5577
  });
5480
5578
  let buffer = {};
5481
- for await (const delta of generator) {
5482
- buffer = mergeDeltas(buffer, delta.delta);
5579
+ let currentVersion = 0;
5580
+ for await (const item of generator) {
5581
+ if (item.version !== currentVersion) {
5582
+ buffer = {};
5583
+ }
5584
+ currentVersion = item.version;
5585
+ buffer = mergeDeltas(buffer, item.delta);
5483
5586
  }
5484
5587
  this.trace = { ...values, ...buffer };
5485
5588
  return buffer;
@@ -7392,6 +7495,7 @@ var AxRAG = class extends AxChainOfThought {
7392
7495
  AxAI,
7393
7496
  AxAIAnthropic,
7394
7497
  AxAIAnthropicModel,
7498
+ AxAIAnthropicVertexModel,
7395
7499
  AxAIAzureOpenAI,
7396
7500
  AxAICohere,
7397
7501
  AxAICohereEmbedModel,