@ai-sdk/xai 4.0.0-beta.3 → 4.0.0-beta.31

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/dist/index.mjs CHANGED
@@ -18,6 +18,8 @@ import {
18
18
  createEventSourceResponseHandler,
19
19
  createJsonResponseHandler,
20
20
  extractResponseHeaders,
21
+ isCustomReasoning,
22
+ mapReasoningToProviderEffort,
21
23
  parseProviderOptions,
22
24
  postJsonToApi,
23
25
  safeParseJSON
@@ -28,7 +30,11 @@ import { z as z3 } from "zod/v4";
28
30
  import {
29
31
  UnsupportedFunctionalityError
30
32
  } from "@ai-sdk/provider";
31
- import { convertToBase64 } from "@ai-sdk/provider-utils";
33
+ import {
34
+ convertToBase64,
35
+ isProviderReference,
36
+ resolveProviderReference
37
+ } from "@ai-sdk/provider-utils";
32
38
  function convertToXaiChatMessages(prompt) {
33
39
  var _a;
34
40
  const messages = [];
@@ -52,6 +58,17 @@ function convertToXaiChatMessages(prompt) {
52
58
  return { type: "text", text: part.text };
53
59
  }
54
60
  case "file": {
61
+ if (isProviderReference(part.data)) {
62
+ return {
63
+ type: "file",
64
+ file: {
65
+ file_id: resolveProviderReference({
66
+ reference: part.data,
67
+ provider: "xai"
68
+ })
69
+ }
70
+ };
71
+ }
55
72
  if (part.mediaType.startsWith("image/")) {
56
73
  const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
57
74
  return {
@@ -356,7 +373,7 @@ function prepareTools({
356
373
  // src/xai-chat-language-model.ts
357
374
  var XaiChatLanguageModel = class {
358
375
  constructor(modelId, config) {
359
- this.specificationVersion = "v3";
376
+ this.specificationVersion = "v4";
360
377
  this.supportedUrls = {
361
378
  "image/*": [/^https?:\/\/.*$/]
362
379
  };
@@ -376,12 +393,13 @@ var XaiChatLanguageModel = class {
376
393
  presencePenalty,
377
394
  stopSequences,
378
395
  seed,
396
+ reasoning,
379
397
  responseFormat,
380
398
  providerOptions,
381
399
  tools,
382
400
  toolChoice
383
401
  }) {
384
- var _a, _b, _c;
402
+ var _a, _b, _c, _d;
385
403
  const warnings = [];
386
404
  const options = (_a = await parseProviderOptions({
387
405
  provider: "xai",
@@ -421,14 +439,24 @@ var XaiChatLanguageModel = class {
421
439
  temperature,
422
440
  top_p: topP,
423
441
  seed,
424
- reasoning_effort: options.reasoningEffort,
442
+ reasoning_effort: (_b = options.reasoningEffort) != null ? _b : isCustomReasoning(reasoning) ? reasoning === "none" ? void 0 : mapReasoningToProviderEffort({
443
+ reasoning,
444
+ effortMap: {
445
+ minimal: "low",
446
+ low: "low",
447
+ medium: "low",
448
+ high: "high",
449
+ xhigh: "high"
450
+ },
451
+ warnings
452
+ }) : void 0,
425
453
  // parallel function calling
426
454
  parallel_function_calling: options.parallel_function_calling,
427
455
  // response format
428
456
  response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
429
457
  type: "json_schema",
430
458
  json_schema: {
431
- name: (_b = responseFormat.name) != null ? _b : "response",
459
+ name: (_c = responseFormat.name) != null ? _c : "response",
432
460
  schema: responseFormat.schema,
433
461
  strict: true
434
462
  }
@@ -440,7 +468,7 @@ var XaiChatLanguageModel = class {
440
468
  from_date: options.searchParameters.fromDate,
441
469
  to_date: options.searchParameters.toDate,
442
470
  max_search_results: options.searchParameters.maxSearchResults,
443
- sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
471
+ sources: (_d = options.searchParameters.sources) == null ? void 0 : _d.map((source) => {
444
472
  var _a2;
445
473
  return {
446
474
  type: source.type,
@@ -888,7 +916,9 @@ var xaiImageModelOptions = z4.object({
888
916
  aspect_ratio: z4.string().optional(),
889
917
  output_format: z4.string().optional(),
890
918
  sync_mode: z4.boolean().optional(),
891
- resolution: z4.enum(["1k", "2k"]).optional()
919
+ resolution: z4.enum(["1k", "2k"]).optional(),
920
+ quality: z4.enum(["low", "medium", "high"]).optional(),
921
+ user: z4.string().optional()
892
922
  });
893
923
 
894
924
  // src/xai-image-model.ts
@@ -896,7 +926,7 @@ var XaiImageModel = class {
896
926
  constructor(modelId, config) {
897
927
  this.modelId = modelId;
898
928
  this.config = config;
899
- this.specificationVersion = "v3";
929
+ this.specificationVersion = "v4";
900
930
  this.maxImagesPerCall = 3;
901
931
  }
902
932
  get provider() {
@@ -914,7 +944,7 @@ var XaiImageModel = class {
914
944
  files,
915
945
  mask
916
946
  }) {
917
- var _a, _b, _c, _d;
947
+ var _a, _b, _c, _d, _e;
918
948
  const warnings = [];
919
949
  if (size != null) {
920
950
  warnings.push({
@@ -947,7 +977,7 @@ var XaiImageModel = class {
947
977
  model: this.modelId,
948
978
  prompt,
949
979
  n,
950
- response_format: "url"
980
+ response_format: "b64_json"
951
981
  };
952
982
  if (aspectRatio != null) {
953
983
  body.aspect_ratio = aspectRatio;
@@ -964,6 +994,12 @@ var XaiImageModel = class {
964
994
  if ((xaiOptions == null ? void 0 : xaiOptions.resolution) != null) {
965
995
  body.resolution = xaiOptions.resolution;
966
996
  }
997
+ if ((xaiOptions == null ? void 0 : xaiOptions.quality) != null) {
998
+ body.quality = xaiOptions.quality;
999
+ }
1000
+ if ((xaiOptions == null ? void 0 : xaiOptions.user) != null) {
1001
+ body.user = xaiOptions.user;
1002
+ }
967
1003
  if (imageUrls.length === 1) {
968
1004
  body.image = { url: imageUrls[0], type: "image_url" };
969
1005
  } else if (imageUrls.length > 1) {
@@ -982,11 +1018,14 @@ var XaiImageModel = class {
982
1018
  abortSignal,
983
1019
  fetch: this.config.fetch
984
1020
  });
985
- const downloadedImages = await Promise.all(
986
- response.data.map((image) => this.downloadImage(image.url, abortSignal))
1021
+ const hasAllBase64 = response.data.every((image) => image.b64_json != null);
1022
+ const images = hasAllBase64 ? response.data.map((image) => image.b64_json) : await Promise.all(
1023
+ response.data.map(
1024
+ (image) => this.downloadImage(image.url, abortSignal)
1025
+ )
987
1026
  );
988
1027
  return {
989
- images: downloadedImages,
1028
+ images,
990
1029
  warnings,
991
1030
  response: {
992
1031
  timestamp: currentDate,
@@ -997,7 +1036,8 @@ var XaiImageModel = class {
997
1036
  xai: {
998
1037
  images: response.data.map((item) => ({
999
1038
  ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}
1000
- }))
1039
+ })),
1040
+ ...((_e = response.usage) == null ? void 0 : _e.cost_in_usd_ticks) != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {}
1001
1041
  }
1002
1042
  }
1003
1043
  };
@@ -1016,10 +1056,14 @@ var XaiImageModel = class {
1016
1056
  var xaiImageResponseSchema = z5.object({
1017
1057
  data: z5.array(
1018
1058
  z5.object({
1019
- url: z5.string(),
1059
+ url: z5.string().nullish(),
1060
+ b64_json: z5.string().nullish(),
1020
1061
  revised_prompt: z5.string().nullish()
1021
1062
  })
1022
- )
1063
+ ),
1064
+ usage: z5.object({
1065
+ cost_in_usd_ticks: z5.number().nullish()
1066
+ }).nullish()
1023
1067
  });
1024
1068
 
1025
1069
  // src/responses/xai-responses-language-model.ts
@@ -1027,6 +1071,8 @@ import {
1027
1071
  combineHeaders as combineHeaders3,
1028
1072
  createEventSourceResponseHandler as createEventSourceResponseHandler2,
1029
1073
  createJsonResponseHandler as createJsonResponseHandler3,
1074
+ isCustomReasoning as isCustomReasoning2,
1075
+ mapReasoningToProviderEffort as mapReasoningToProviderEffort2,
1030
1076
  parseProviderOptions as parseProviderOptions3,
1031
1077
  postJsonToApi as postJsonToApi3
1032
1078
  } from "@ai-sdk/provider-utils";
@@ -1035,7 +1081,11 @@ import {
1035
1081
  import {
1036
1082
  UnsupportedFunctionalityError as UnsupportedFunctionalityError3
1037
1083
  } from "@ai-sdk/provider";
1038
- import { convertToBase64 as convertToBase642 } from "@ai-sdk/provider-utils";
1084
+ import {
1085
+ convertToBase64 as convertToBase642,
1086
+ isProviderReference as isProviderReference2,
1087
+ resolveProviderReference as resolveProviderReference2
1088
+ } from "@ai-sdk/provider-utils";
1039
1089
  async function convertToXaiResponsesInput({
1040
1090
  prompt
1041
1091
  }) {
@@ -1060,7 +1110,15 @@ async function convertToXaiResponsesInput({
1060
1110
  break;
1061
1111
  }
1062
1112
  case "file": {
1063
- if (block.mediaType.startsWith("image/")) {
1113
+ if (isProviderReference2(block.data)) {
1114
+ contentParts.push({
1115
+ type: "input_file",
1116
+ file_id: resolveProviderReference2({
1117
+ reference: block.data,
1118
+ provider: "xai"
1119
+ })
1120
+ });
1121
+ } else if (block.mediaType.startsWith("image/")) {
1064
1122
  const mediaType = block.mediaType === "image/*" ? "image/jpeg" : block.mediaType;
1065
1123
  const imageUrl = block.data instanceof URL ? block.data.toString() : `data:${mediaType};base64,${convertToBase642(block.data)}`;
1066
1124
  contentParts.push({ type: "input_image", image_url: imageUrl });
@@ -1117,6 +1175,8 @@ async function convertToXaiResponsesInput({
1117
1175
  break;
1118
1176
  }
1119
1177
  case "reasoning":
1178
+ case "reasoning-file":
1179
+ case "custom":
1120
1180
  case "file": {
1121
1181
  inputWarnings.push({
1122
1182
  type: "other",
@@ -1216,6 +1276,7 @@ function mapXaiResponsesFinishReason(finishReason) {
1216
1276
  case "completed":
1217
1277
  return "stop";
1218
1278
  case "length":
1279
+ case "max_output_tokens":
1219
1280
  return "length";
1220
1281
  case "tool_calls":
1221
1282
  case "function_call":
@@ -1332,6 +1393,7 @@ var outputItemSchema = z6.discriminatedUnion("type", [
1332
1393
  type: z6.literal("reasoning"),
1333
1394
  id: z6.string(),
1334
1395
  summary: z6.array(reasoningSummaryPartSchema),
1396
+ content: z6.array(z6.object({ type: z6.string(), text: z6.string() })).nullish(),
1335
1397
  status: z6.string(),
1336
1398
  encrypted_content: z6.string().nullish()
1337
1399
  })
@@ -1620,6 +1682,30 @@ var xaiResponsesChunkSchema = z6.union([
1620
1682
  output_index: z6.number(),
1621
1683
  output: z6.string().optional()
1622
1684
  }),
1685
+ z6.object({
1686
+ type: z6.literal("response.incomplete"),
1687
+ response: z6.object({
1688
+ incomplete_details: z6.object({ reason: z6.string() }).nullish(),
1689
+ usage: xaiResponsesUsageSchema.nullish()
1690
+ })
1691
+ }),
1692
+ z6.object({
1693
+ type: z6.literal("response.failed"),
1694
+ response: z6.object({
1695
+ error: z6.object({
1696
+ code: z6.string().nullish(),
1697
+ message: z6.string()
1698
+ }).nullish(),
1699
+ incomplete_details: z6.object({ reason: z6.string() }).nullish(),
1700
+ usage: xaiResponsesUsageSchema.nullish()
1701
+ })
1702
+ }),
1703
+ z6.object({
1704
+ type: z6.literal("error"),
1705
+ code: z6.string().nullish(),
1706
+ message: z6.string(),
1707
+ param: z6.string().nullish()
1708
+ }),
1623
1709
  z6.object({
1624
1710
  type: z6.literal("response.done"),
1625
1711
  response: xaiResponsesResponseSchema
@@ -1638,6 +1724,7 @@ var xaiLanguageModelResponsesOptions = z7.object({
1638
1724
  * Possible values are `low` (uses fewer reasoning tokens), `medium` and `high` (uses more reasoning tokens).
1639
1725
  */
1640
1726
  reasoningEffort: z7.enum(["low", "medium", "high"]).optional(),
1727
+ reasoningSummary: z7.enum(["auto", "concise", "detailed"]).optional(),
1641
1728
  logprobs: z7.boolean().optional(),
1642
1729
  topLogprobs: z7.number().int().min(0).max(8).optional(),
1643
1730
  /**
@@ -1965,7 +2052,7 @@ async function prepareResponsesTools({
1965
2052
  // src/responses/xai-responses-language-model.ts
1966
2053
  var XaiResponsesLanguageModel = class {
1967
2054
  constructor(modelId, config) {
1968
- this.specificationVersion = "v3";
2055
+ this.specificationVersion = "v4";
1969
2056
  this.supportedUrls = {
1970
2057
  "image/*": [/^https?:\/\/.*$/]
1971
2058
  };
@@ -1985,9 +2072,10 @@ var XaiResponsesLanguageModel = class {
1985
2072
  responseFormat,
1986
2073
  providerOptions,
1987
2074
  tools,
1988
- toolChoice
2075
+ toolChoice,
2076
+ reasoning
1989
2077
  }) {
1990
- var _a, _b, _c, _d, _e, _f, _g;
2078
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1991
2079
  const warnings = [];
1992
2080
  const options = (_a = await parseProviderOptions3({
1993
2081
  provider: "xai",
@@ -2034,6 +2122,17 @@ var XaiResponsesLanguageModel = class {
2034
2122
  include = [...include, "reasoning.encrypted_content"];
2035
2123
  }
2036
2124
  }
2125
+ const resolvedReasoningEffort = (_g = options.reasoningEffort) != null ? _g : isCustomReasoning2(reasoning) ? reasoning === "none" ? void 0 : mapReasoningToProviderEffort2({
2126
+ reasoning,
2127
+ effortMap: {
2128
+ minimal: "low",
2129
+ low: "low",
2130
+ medium: "medium",
2131
+ high: "high",
2132
+ xhigh: "high"
2133
+ },
2134
+ warnings
2135
+ }) : void 0;
2037
2136
  const baseArgs = {
2038
2137
  model: this.modelId,
2039
2138
  input,
@@ -2048,14 +2147,21 @@ var XaiResponsesLanguageModel = class {
2048
2147
  format: responseFormat.schema != null ? {
2049
2148
  type: "json_schema",
2050
2149
  strict: true,
2051
- name: (_g = responseFormat.name) != null ? _g : "response",
2150
+ name: (_h = responseFormat.name) != null ? _h : "response",
2052
2151
  description: responseFormat.description,
2053
2152
  schema: responseFormat.schema
2054
2153
  } : { type: "json_object" }
2055
2154
  }
2056
2155
  },
2057
- ...options.reasoningEffort != null && {
2058
- reasoning: { effort: options.reasoningEffort }
2156
+ ...(resolvedReasoningEffort != null || options.reasoningSummary != null) && {
2157
+ reasoning: {
2158
+ ...resolvedReasoningEffort != null && {
2159
+ effort: resolvedReasoningEffort
2160
+ },
2161
+ ...options.reasoningSummary != null && {
2162
+ summary: options.reasoningSummary
2163
+ }
2164
+ }
2059
2165
  },
2060
2166
  ...options.store === false && {
2061
2167
  store: options.store
@@ -2084,7 +2190,7 @@ var XaiResponsesLanguageModel = class {
2084
2190
  };
2085
2191
  }
2086
2192
  async doGenerate(options) {
2087
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
2193
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2088
2194
  const {
2089
2195
  args: body,
2090
2196
  warnings,
@@ -2110,6 +2216,7 @@ var XaiResponsesLanguageModel = class {
2110
2216
  fetch: this.config.fetch
2111
2217
  });
2112
2218
  const content = [];
2219
+ let hasFunctionCall = false;
2113
2220
  const webSearchSubTools = [
2114
2221
  "web_search",
2115
2222
  "web_search_with_snippets",
@@ -2194,6 +2301,7 @@ var XaiResponsesLanguageModel = class {
2194
2301
  break;
2195
2302
  }
2196
2303
  case "function_call": {
2304
+ hasFunctionCall = true;
2197
2305
  content.push({
2198
2306
  type: "tool-call",
2199
2307
  toolCallId: part.call_id,
@@ -2203,9 +2311,9 @@ var XaiResponsesLanguageModel = class {
2203
2311
  break;
2204
2312
  }
2205
2313
  case "reasoning": {
2206
- const summaryTexts = part.summary.map((s) => s.text).filter((text) => text && text.length > 0);
2207
- if (summaryTexts.length > 0) {
2208
- const reasoningText = summaryTexts.join("");
2314
+ const texts = part.summary.length > 0 ? part.summary.map((s) => s.text) : ((_m = part.content) != null ? _m : []).map((c) => c.text);
2315
+ const reasoningText = texts.filter((text) => text && text.length > 0).join("");
2316
+ if (reasoningText) {
2209
2317
  if (part.encrypted_content || part.id) {
2210
2318
  content.push({
2211
2319
  type: "reasoning",
@@ -2236,8 +2344,8 @@ var XaiResponsesLanguageModel = class {
2236
2344
  return {
2237
2345
  content,
2238
2346
  finishReason: {
2239
- unified: mapXaiResponsesFinishReason(response.status),
2240
- raw: (_m = response.status) != null ? _m : void 0
2347
+ unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response.status),
2348
+ raw: (_n = response.status) != null ? _n : void 0
2241
2349
  },
2242
2350
  usage: response.usage ? convertXaiResponsesUsage(response.usage) : {
2243
2351
  inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
@@ -2282,6 +2390,7 @@ var XaiResponsesLanguageModel = class {
2282
2390
  unified: "other",
2283
2391
  raw: void 0
2284
2392
  };
2393
+ let hasFunctionCall = false;
2285
2394
  let usage = void 0;
2286
2395
  let isFirstChunk = true;
2287
2396
  const contentBlocks = {};
@@ -2296,7 +2405,7 @@ var XaiResponsesLanguageModel = class {
2296
2405
  controller.enqueue({ type: "stream-start", warnings });
2297
2406
  },
2298
2407
  transform(chunk, controller) {
2299
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
2408
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
2300
2409
  if (options.includeRawChunks) {
2301
2410
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2302
2411
  }
@@ -2419,19 +2528,40 @@ var XaiResponsesLanguageModel = class {
2419
2528
  }
2420
2529
  return;
2421
2530
  }
2422
- if (event.type === "response.done" || event.type === "response.completed") {
2531
+ if (event.type === "response.done" || event.type === "response.completed" || event.type === "response.incomplete") {
2423
2532
  const response2 = event.response;
2424
2533
  if (response2.usage) {
2425
2534
  usage = convertXaiResponsesUsage(response2.usage);
2426
2535
  }
2427
- if (response2.status) {
2536
+ if (event.type === "response.incomplete") {
2537
+ const reason = "incomplete_details" in response2 ? (_c = response2.incomplete_details) == null ? void 0 : _c.reason : void 0;
2538
+ finishReason = {
2539
+ unified: reason ? mapXaiResponsesFinishReason(reason) : "other",
2540
+ raw: reason != null ? reason : "incomplete"
2541
+ };
2542
+ } else if ("status" in response2 && response2.status) {
2428
2543
  finishReason = {
2429
- unified: mapXaiResponsesFinishReason(response2.status),
2544
+ unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response2.status),
2430
2545
  raw: response2.status
2431
2546
  };
2432
2547
  }
2433
2548
  return;
2434
2549
  }
2550
+ if (event.type === "response.failed") {
2551
+ const reason = (_d = event.response.incomplete_details) == null ? void 0 : _d.reason;
2552
+ finishReason = {
2553
+ unified: reason ? mapXaiResponsesFinishReason(reason) : "error",
2554
+ raw: reason != null ? reason : "error"
2555
+ };
2556
+ if (event.response.usage) {
2557
+ usage = convertXaiResponsesUsage(event.response.usage);
2558
+ }
2559
+ return;
2560
+ }
2561
+ if (event.type === "error") {
2562
+ controller.enqueue({ type: "error", error: event });
2563
+ return;
2564
+ }
2435
2565
  if (event.type === "response.custom_tool_call_input.delta" || event.type === "response.custom_tool_call_input.done") {
2436
2566
  return;
2437
2567
  }
@@ -2514,13 +2644,13 @@ var XaiResponsesLanguageModel = class {
2514
2644
  toolCallId: part.id,
2515
2645
  toolName,
2516
2646
  result: {
2517
- queries: (_c = part.queries) != null ? _c : [],
2518
- results: (_e = (_d = part.results) == null ? void 0 : _d.map((result) => ({
2647
+ queries: (_e = part.queries) != null ? _e : [],
2648
+ results: (_g = (_f = part.results) == null ? void 0 : _f.map((result) => ({
2519
2649
  fileId: result.file_id,
2520
2650
  filename: result.filename,
2521
2651
  score: result.score,
2522
2652
  text: result.text
2523
- }))) != null ? _e : null
2653
+ }))) != null ? _g : null
2524
2654
  }
2525
2655
  });
2526
2656
  }
@@ -2538,17 +2668,17 @@ var XaiResponsesLanguageModel = class {
2538
2668
  "x_semantic_search",
2539
2669
  "x_thread_fetch"
2540
2670
  ];
2541
- let toolName = (_f = part.name) != null ? _f : "";
2542
- if (webSearchSubTools.includes((_g = part.name) != null ? _g : "") || part.type === "web_search_call") {
2671
+ let toolName = (_h = part.name) != null ? _h : "";
2672
+ if (webSearchSubTools.includes((_i = part.name) != null ? _i : "") || part.type === "web_search_call") {
2543
2673
  toolName = webSearchToolName != null ? webSearchToolName : "web_search";
2544
- } else if (xSearchSubTools.includes((_h = part.name) != null ? _h : "") || part.type === "x_search_call") {
2674
+ } else if (xSearchSubTools.includes((_j = part.name) != null ? _j : "") || part.type === "x_search_call") {
2545
2675
  toolName = xSearchToolName != null ? xSearchToolName : "x_search";
2546
2676
  } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
2547
2677
  toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
2548
2678
  } else if (part.type === "mcp_call") {
2549
- toolName = (_i = mcpToolName != null ? mcpToolName : part.name) != null ? _i : "mcp";
2679
+ toolName = (_k = mcpToolName != null ? mcpToolName : part.name) != null ? _k : "mcp";
2550
2680
  }
2551
- const toolInput = part.type === "custom_tool_call" ? (_j = part.input) != null ? _j : "" : part.type === "mcp_call" ? (_k = part.arguments) != null ? _k : "" : (_l = part.arguments) != null ? _l : "";
2681
+ const toolInput = part.type === "custom_tool_call" ? (_l = part.input) != null ? _l : "" : part.type === "mcp_call" ? (_m = part.arguments) != null ? _m : "" : (_n = part.arguments) != null ? _n : "";
2552
2682
  const shouldEmit = part.type === "custom_tool_call" ? event.type === "response.output_item.done" : !seenToolCalls.has(part.id);
2553
2683
  if (shouldEmit && !seenToolCalls.has(part.id)) {
2554
2684
  seenToolCalls.add(part.id);
@@ -2601,7 +2731,7 @@ var XaiResponsesLanguageModel = class {
2601
2731
  sourceType: "url",
2602
2732
  id: self.config.generateId(),
2603
2733
  url: annotation.url,
2604
- title: (_m = annotation.title) != null ? _m : annotation.url
2734
+ title: (_o = annotation.title) != null ? _o : annotation.url
2605
2735
  });
2606
2736
  }
2607
2737
  }
@@ -2619,6 +2749,7 @@ var XaiResponsesLanguageModel = class {
2619
2749
  toolName: part.name
2620
2750
  });
2621
2751
  } else if (event.type === "response.output_item.done") {
2752
+ hasFunctionCall = true;
2622
2753
  ongoingToolCalls[event.output_index] = void 0;
2623
2754
  controller.enqueue({
2624
2755
  type: "tool-input-end",
@@ -2720,63 +2851,213 @@ var xaiTools = {
2720
2851
  };
2721
2852
 
2722
2853
  // src/version.ts
2723
- var VERSION = true ? "4.0.0-beta.3" : "0.0.0-test";
2854
+ var VERSION = true ? "4.0.0-beta.31" : "0.0.0-test";
2724
2855
 
2725
- // src/xai-video-model.ts
2726
- import {
2727
- AISDKError
2728
- } from "@ai-sdk/provider";
2856
+ // src/files/xai-files.ts
2729
2857
  import {
2730
2858
  combineHeaders as combineHeaders4,
2731
- convertUint8ArrayToBase64,
2859
+ convertBase64ToUint8Array,
2732
2860
  createJsonResponseHandler as createJsonResponseHandler4,
2733
- delay,
2734
- getFromApi as getFromApi2,
2735
2861
  parseProviderOptions as parseProviderOptions4,
2736
- postJsonToApi as postJsonToApi4
2862
+ postFormDataToApi
2737
2863
  } from "@ai-sdk/provider-utils";
2738
- import { z as z16 } from "zod/v4";
2739
2864
 
2740
- // src/xai-video-options.ts
2865
+ // src/files/xai-files-api.ts
2741
2866
  import { lazySchema as lazySchema5, zodSchema as zodSchema5 } from "@ai-sdk/provider-utils";
2742
2867
  import { z as z15 } from "zod/v4";
2743
- var xaiVideoModelOptionsSchema = lazySchema5(
2868
+ var xaiFilesResponseSchema = lazySchema5(
2744
2869
  () => zodSchema5(
2745
2870
  z15.object({
2746
- pollIntervalMs: z15.number().positive().nullish(),
2747
- pollTimeoutMs: z15.number().positive().nullish(),
2748
- resolution: z15.enum(["480p", "720p"]).nullish(),
2749
- videoUrl: z15.string().nullish()
2871
+ id: z15.string(),
2872
+ object: z15.string().nullish(),
2873
+ bytes: z15.number().nullish(),
2874
+ created_at: z15.number().nullish(),
2875
+ filename: z15.string().nullish(),
2876
+ purpose: z15.string().nullish(),
2877
+ status: z15.string().nullish()
2878
+ })
2879
+ )
2880
+ );
2881
+
2882
+ // src/files/xai-files-options.ts
2883
+ import { lazySchema as lazySchema6, zodSchema as zodSchema6 } from "@ai-sdk/provider-utils";
2884
+ import { z as z16 } from "zod/v4";
2885
+ var xaiFilesOptionsSchema = lazySchema6(
2886
+ () => zodSchema6(
2887
+ z16.object({
2888
+ teamId: z16.string().optional(),
2889
+ filePath: z16.string().optional()
2750
2890
  }).passthrough()
2751
2891
  )
2752
2892
  );
2753
2893
 
2894
+ // src/files/xai-files.ts
2895
+ var XaiFiles = class {
2896
+ constructor(config) {
2897
+ this.config = config;
2898
+ this.specificationVersion = "v4";
2899
+ }
2900
+ get provider() {
2901
+ return this.config.provider;
2902
+ }
2903
+ async uploadFile({
2904
+ data,
2905
+ mediaType,
2906
+ filename,
2907
+ providerOptions
2908
+ }) {
2909
+ var _a, _b;
2910
+ const xaiOptions = await parseProviderOptions4({
2911
+ provider: "xai",
2912
+ providerOptions,
2913
+ schema: xaiFilesOptionsSchema
2914
+ });
2915
+ const fileBytes = data instanceof Uint8Array ? data : convertBase64ToUint8Array(data);
2916
+ const blob = new Blob([fileBytes], {
2917
+ type: mediaType
2918
+ });
2919
+ const formData = new FormData();
2920
+ if (filename != null) {
2921
+ formData.append("file", blob, filename);
2922
+ } else {
2923
+ formData.append("file", blob);
2924
+ }
2925
+ if ((xaiOptions == null ? void 0 : xaiOptions.teamId) != null) {
2926
+ formData.append("team_id", xaiOptions.teamId);
2927
+ }
2928
+ const { value: response } = await postFormDataToApi({
2929
+ url: `${this.config.baseURL}/files`,
2930
+ headers: combineHeaders4(this.config.headers()),
2931
+ formData,
2932
+ failedResponseHandler: xaiFailedResponseHandler,
2933
+ successfulResponseHandler: createJsonResponseHandler4(
2934
+ xaiFilesResponseSchema
2935
+ ),
2936
+ fetch: this.config.fetch
2937
+ });
2938
+ return {
2939
+ warnings: [],
2940
+ providerReference: { xai: response.id },
2941
+ ...((_a = response.filename) != null ? _a : filename) ? { filename: (_b = response.filename) != null ? _b : filename } : {},
2942
+ ...mediaType != null ? { mediaType } : {},
2943
+ providerMetadata: {
2944
+ xai: {
2945
+ ...response.filename != null ? { filename: response.filename } : {},
2946
+ ...response.bytes != null ? { bytes: response.bytes } : {},
2947
+ ...response.created_at != null ? { createdAt: response.created_at } : {}
2948
+ }
2949
+ }
2950
+ };
2951
+ }
2952
+ };
2953
+
2954
+ // src/xai-video-model.ts
2955
+ import {
2956
+ AISDKError
2957
+ } from "@ai-sdk/provider";
2958
+ import {
2959
+ combineHeaders as combineHeaders5,
2960
+ convertUint8ArrayToBase64,
2961
+ createJsonResponseHandler as createJsonResponseHandler5,
2962
+ delay,
2963
+ getFromApi as getFromApi2,
2964
+ parseProviderOptions as parseProviderOptions5,
2965
+ postJsonToApi as postJsonToApi4
2966
+ } from "@ai-sdk/provider-utils";
2967
+ import { z as z18 } from "zod/v4";
2968
+
2969
+ // src/xai-video-options.ts
2970
+ import { lazySchema as lazySchema7, zodSchema as zodSchema7 } from "@ai-sdk/provider-utils";
2971
+ import { z as z17 } from "zod/v4";
2972
+ var nonEmptyStringSchema = z17.string().min(1);
2973
+ var resolutionSchema = z17.enum(["480p", "720p"]);
2974
+ var modeSchema = z17.enum(["edit-video", "extend-video", "reference-to-video"]);
2975
+ var baseFields = {
2976
+ pollIntervalMs: z17.number().positive().nullish(),
2977
+ pollTimeoutMs: z17.number().positive().nullish(),
2978
+ resolution: resolutionSchema.nullish()
2979
+ };
2980
+ var editVideoSchema = z17.object({
2981
+ ...baseFields,
2982
+ mode: z17.literal("edit-video"),
2983
+ videoUrl: nonEmptyStringSchema,
2984
+ referenceImageUrls: z17.undefined().optional()
2985
+ });
2986
+ var extendVideoSchema = z17.object({
2987
+ ...baseFields,
2988
+ mode: z17.literal("extend-video"),
2989
+ videoUrl: nonEmptyStringSchema,
2990
+ referenceImageUrls: z17.undefined().optional()
2991
+ });
2992
+ var referenceToVideoSchema = z17.object({
2993
+ ...baseFields,
2994
+ mode: z17.literal("reference-to-video"),
2995
+ referenceImageUrls: z17.array(nonEmptyStringSchema).min(1).max(7),
2996
+ videoUrl: z17.undefined().optional()
2997
+ });
2998
+ var autoDetectSchema = z17.object({
2999
+ ...baseFields,
3000
+ mode: z17.undefined().optional(),
3001
+ videoUrl: nonEmptyStringSchema.optional(),
3002
+ referenceImageUrls: z17.array(nonEmptyStringSchema).min(1).max(7).optional()
3003
+ });
3004
+ var xaiVideoModelOptions = z17.union([
3005
+ editVideoSchema,
3006
+ extendVideoSchema,
3007
+ referenceToVideoSchema,
3008
+ autoDetectSchema
3009
+ ]);
3010
+ var runtimeSchema = z17.object({
3011
+ mode: modeSchema.optional(),
3012
+ videoUrl: nonEmptyStringSchema.optional(),
3013
+ referenceImageUrls: z17.array(nonEmptyStringSchema).min(1).max(7).optional(),
3014
+ ...baseFields
3015
+ }).passthrough();
3016
+ var xaiVideoModelOptionsSchema = lazySchema7(
3017
+ () => zodSchema7(runtimeSchema)
3018
+ );
3019
+
2754
3020
  // src/xai-video-model.ts
2755
3021
  var RESOLUTION_MAP = {
2756
3022
  "1280x720": "720p",
2757
3023
  "854x480": "480p",
2758
3024
  "640x480": "480p"
2759
3025
  };
3026
+ function resolveVideoMode(options) {
3027
+ if ((options == null ? void 0 : options.mode) != null) {
3028
+ return options.mode;
3029
+ }
3030
+ if ((options == null ? void 0 : options.videoUrl) != null) {
3031
+ return "edit-video";
3032
+ }
3033
+ if ((options == null ? void 0 : options.referenceImageUrls) != null && options.referenceImageUrls.length > 0) {
3034
+ return "reference-to-video";
3035
+ }
3036
+ return void 0;
3037
+ }
2760
3038
  var XaiVideoModel = class {
2761
3039
  constructor(modelId, config) {
2762
3040
  this.modelId = modelId;
2763
3041
  this.config = config;
2764
- this.specificationVersion = "v3";
3042
+ this.specificationVersion = "v4";
2765
3043
  this.maxVideosPerCall = 1;
2766
3044
  }
2767
3045
  get provider() {
2768
3046
  return this.config.provider;
2769
3047
  }
2770
3048
  async doGenerate(options) {
2771
- var _a, _b, _c, _d, _e, _f, _g, _h;
3049
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2772
3050
  const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
2773
3051
  const warnings = [];
2774
- const xaiOptions = await parseProviderOptions4({
3052
+ const xaiOptions = await parseProviderOptions5({
2775
3053
  provider: "xai",
2776
3054
  providerOptions: options.providerOptions,
2777
3055
  schema: xaiVideoModelOptionsSchema
2778
3056
  });
2779
- const isEdit = (xaiOptions == null ? void 0 : xaiOptions.videoUrl) != null;
3057
+ const effectiveMode = resolveVideoMode(xaiOptions);
3058
+ const isEdit = effectiveMode === "edit-video";
3059
+ const isExtension = effectiveMode === "extend-video";
3060
+ const hasReferenceImages = effectiveMode === "reference-to-video";
2780
3061
  if (options.fps != null) {
2781
3062
  warnings.push({
2782
3063
  type: "unsupported",
@@ -2819,19 +3100,36 @@ var XaiVideoModel = class {
2819
3100
  details: "xAI video editing does not support custom resolution."
2820
3101
  });
2821
3102
  }
3103
+ if (isExtension && options.aspectRatio != null) {
3104
+ warnings.push({
3105
+ type: "unsupported",
3106
+ feature: "aspectRatio",
3107
+ details: "xAI video extension does not support custom aspect ratio."
3108
+ });
3109
+ }
3110
+ if (isExtension && ((xaiOptions == null ? void 0 : xaiOptions.resolution) != null || options.resolution != null)) {
3111
+ warnings.push({
3112
+ type: "unsupported",
3113
+ feature: "resolution",
3114
+ details: "xAI video extension does not support custom resolution."
3115
+ });
3116
+ }
2822
3117
  const body = {
2823
3118
  model: this.modelId,
2824
3119
  prompt: options.prompt
2825
3120
  };
2826
- if (!isEdit && options.duration != null) {
3121
+ const allowDuration = !isEdit;
3122
+ const allowAspectRatio = !isEdit && !isExtension;
3123
+ const allowResolution = !isEdit && !isExtension;
3124
+ if (allowDuration && options.duration != null) {
2827
3125
  body.duration = options.duration;
2828
3126
  }
2829
- if (!isEdit && options.aspectRatio != null) {
3127
+ if (allowAspectRatio && options.aspectRatio != null) {
2830
3128
  body.aspect_ratio = options.aspectRatio;
2831
3129
  }
2832
- if (!isEdit && (xaiOptions == null ? void 0 : xaiOptions.resolution) != null) {
3130
+ if (allowResolution && (xaiOptions == null ? void 0 : xaiOptions.resolution) != null) {
2833
3131
  body.resolution = xaiOptions.resolution;
2834
- } else if (!isEdit && options.resolution != null) {
3132
+ } else if (allowResolution && options.resolution != null) {
2835
3133
  const mapped = RESOLUTION_MAP[options.resolution];
2836
3134
  if (mapped != null) {
2837
3135
  body.resolution = mapped;
@@ -2843,7 +3141,10 @@ var XaiVideoModel = class {
2843
3141
  });
2844
3142
  }
2845
3143
  }
2846
- if ((xaiOptions == null ? void 0 : xaiOptions.videoUrl) != null) {
3144
+ if (isEdit) {
3145
+ body.video = { url: xaiOptions.videoUrl };
3146
+ }
3147
+ if (isExtension) {
2847
3148
  body.video = { url: xaiOptions.videoUrl };
2848
3149
  }
2849
3150
  if (options.image != null) {
@@ -2856,25 +3157,40 @@ var XaiVideoModel = class {
2856
3157
  };
2857
3158
  }
2858
3159
  }
3160
+ if (hasReferenceImages) {
3161
+ body.reference_images = xaiOptions.referenceImageUrls.map((url) => ({
3162
+ url
3163
+ }));
3164
+ }
2859
3165
  if (xaiOptions != null) {
2860
3166
  for (const [key, value] of Object.entries(xaiOptions)) {
2861
3167
  if (![
3168
+ "mode",
2862
3169
  "pollIntervalMs",
2863
3170
  "pollTimeoutMs",
2864
3171
  "resolution",
2865
- "videoUrl"
3172
+ "videoUrl",
3173
+ "referenceImageUrls"
2866
3174
  ].includes(key)) {
2867
3175
  body[key] = value;
2868
3176
  }
2869
3177
  }
2870
3178
  }
2871
3179
  const baseURL = (_d = this.config.baseURL) != null ? _d : "https://api.x.ai/v1";
3180
+ let endpoint;
3181
+ if (isEdit) {
3182
+ endpoint = `${baseURL}/videos/edits`;
3183
+ } else if (isExtension) {
3184
+ endpoint = `${baseURL}/videos/extensions`;
3185
+ } else {
3186
+ endpoint = `${baseURL}/videos/generations`;
3187
+ }
2872
3188
  const { value: createResponse } = await postJsonToApi4({
2873
- url: `${baseURL}/videos/${isEdit ? "edits" : "generations"}`,
2874
- headers: combineHeaders4(this.config.headers(), options.headers),
3189
+ url: endpoint,
3190
+ headers: combineHeaders5(this.config.headers(), options.headers),
2875
3191
  body,
2876
3192
  failedResponseHandler: xaiFailedResponseHandler,
2877
- successfulResponseHandler: createJsonResponseHandler4(
3193
+ successfulResponseHandler: createJsonResponseHandler5(
2878
3194
  xaiCreateVideoResponseSchema
2879
3195
  ),
2880
3196
  abortSignal: options.abortSignal,
@@ -2901,8 +3217,8 @@ var XaiVideoModel = class {
2901
3217
  }
2902
3218
  const { value: statusResponse, responseHeaders: pollHeaders } = await getFromApi2({
2903
3219
  url: `${baseURL}/videos/${requestId}`,
2904
- headers: combineHeaders4(this.config.headers(), options.headers),
2905
- successfulResponseHandler: createJsonResponseHandler4(
3220
+ headers: combineHeaders5(this.config.headers(), options.headers),
3221
+ successfulResponseHandler: createJsonResponseHandler5(
2906
3222
  xaiVideoStatusResponseSchema
2907
3223
  ),
2908
3224
  failedResponseHandler: xaiFailedResponseHandler,
@@ -2911,7 +3227,13 @@ var XaiVideoModel = class {
2911
3227
  });
2912
3228
  responseHeaders = pollHeaders;
2913
3229
  if (statusResponse.status === "done" || statusResponse.status == null && ((_g = statusResponse.video) == null ? void 0 : _g.url)) {
2914
- if (!((_h = statusResponse.video) == null ? void 0 : _h.url)) {
3230
+ if (((_h = statusResponse.video) == null ? void 0 : _h.respect_moderation) === false) {
3231
+ throw new AISDKError({
3232
+ name: "XAI_VIDEO_MODERATION_ERROR",
3233
+ message: "Video generation was blocked due to a content policy violation."
3234
+ });
3235
+ }
3236
+ if (!((_i = statusResponse.video) == null ? void 0 : _i.url)) {
2915
3237
  throw new AISDKError({
2916
3238
  name: "XAI_VIDEO_GENERATION_ERROR",
2917
3239
  message: "Video generation completed but no video URL was returned."
@@ -2935,7 +3257,9 @@ var XaiVideoModel = class {
2935
3257
  xai: {
2936
3258
  requestId,
2937
3259
  videoUrl: statusResponse.video.url,
2938
- ...statusResponse.video.duration != null ? { duration: statusResponse.video.duration } : {}
3260
+ ...statusResponse.video.duration != null ? { duration: statusResponse.video.duration } : {},
3261
+ ...((_j = statusResponse.usage) == null ? void 0 : _j.cost_in_usd_ticks) != null ? { costInUsdTicks: statusResponse.usage.cost_in_usd_ticks } : {},
3262
+ ...statusResponse.progress != null ? { progress: statusResponse.progress } : {}
2939
3263
  }
2940
3264
  }
2941
3265
  };
@@ -2946,20 +3270,34 @@ var XaiVideoModel = class {
2946
3270
  message: "Video generation request expired."
2947
3271
  });
2948
3272
  }
3273
+ if (statusResponse.status === "failed") {
3274
+ throw new AISDKError({
3275
+ name: "XAI_VIDEO_GENERATION_FAILED",
3276
+ message: "Video generation failed."
3277
+ });
3278
+ }
2949
3279
  }
2950
3280
  }
2951
3281
  };
2952
- var xaiCreateVideoResponseSchema = z16.object({
2953
- request_id: z16.string().nullish()
3282
+ var xaiCreateVideoResponseSchema = z18.object({
3283
+ request_id: z18.string().nullish()
2954
3284
  });
2955
- var xaiVideoStatusResponseSchema = z16.object({
2956
- status: z16.string().nullish(),
2957
- video: z16.object({
2958
- url: z16.string(),
2959
- duration: z16.number().nullish(),
2960
- respect_moderation: z16.boolean().nullish()
3285
+ var xaiVideoStatusResponseSchema = z18.object({
3286
+ status: z18.string().nullish(),
3287
+ video: z18.object({
3288
+ url: z18.string(),
3289
+ duration: z18.number().nullish(),
3290
+ respect_moderation: z18.boolean().nullish()
2961
3291
  }).nullish(),
2962
- model: z16.string().nullish()
3292
+ model: z18.string().nullish(),
3293
+ usage: z18.object({
3294
+ cost_in_usd_ticks: z18.number().nullish()
3295
+ }).nullish(),
3296
+ progress: z18.number().nullish(),
3297
+ error: z18.object({
3298
+ code: z18.string().nullish(),
3299
+ message: z18.string().nullish()
3300
+ }).nullish()
2963
3301
  });
2964
3302
 
2965
3303
  // src/xai-provider.ts
@@ -3013,9 +3351,15 @@ function createXai(options = {}) {
3013
3351
  fetch: options.fetch
3014
3352
  });
3015
3353
  };
3016
- const provider = (modelId) => createChatLanguageModel(modelId);
3017
- provider.specificationVersion = "v3";
3018
- provider.languageModel = createChatLanguageModel;
3354
+ const createFiles = () => new XaiFiles({
3355
+ provider: "xai.files",
3356
+ baseURL,
3357
+ headers: getHeaders,
3358
+ fetch: options.fetch
3359
+ });
3360
+ const provider = (modelId) => createResponsesLanguageModel(modelId);
3361
+ provider.specificationVersion = "v4";
3362
+ provider.languageModel = createResponsesLanguageModel;
3019
3363
  provider.chat = createChatLanguageModel;
3020
3364
  provider.responses = createResponsesLanguageModel;
3021
3365
  provider.embeddingModel = (modelId) => {
@@ -3026,6 +3370,7 @@ function createXai(options = {}) {
3026
3370
  provider.image = createImageModel;
3027
3371
  provider.videoModel = createVideoModel;
3028
3372
  provider.video = createVideoModel;
3373
+ provider.files = createFiles;
3029
3374
  provider.tools = xaiTools;
3030
3375
  return provider;
3031
3376
  }