@ai-sdk/xai 0.0.0-1c33ba03-20260114162300

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.js ADDED
@@ -0,0 +1,2281 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ VERSION: () => VERSION,
24
+ codeExecution: () => codeExecution,
25
+ createXai: () => createXai,
26
+ viewImage: () => viewImage,
27
+ viewXVideo: () => viewXVideo,
28
+ webSearch: () => webSearch,
29
+ xSearch: () => xSearch,
30
+ xai: () => xai,
31
+ xaiTools: () => xaiTools
32
+ });
33
+ module.exports = __toCommonJS(src_exports);
34
+
35
+ // src/xai-provider.ts
36
+ var import_openai_compatible = require("@ai-sdk/openai-compatible");
37
+ var import_provider6 = require("@ai-sdk/provider");
38
+ var import_provider_utils12 = require("@ai-sdk/provider-utils");
39
+
40
+ // src/xai-chat-language-model.ts
41
+ var import_provider3 = require("@ai-sdk/provider");
42
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
43
+ var import_v43 = require("zod/v4");
44
+
45
+ // src/convert-to-xai-chat-messages.ts
46
+ var import_provider = require("@ai-sdk/provider");
47
+ var import_provider_utils = require("@ai-sdk/provider-utils");
48
+ function convertToXaiChatMessages(prompt) {
49
+ var _a;
50
+ const messages = [];
51
+ const warnings = [];
52
+ for (const { role, content } of prompt) {
53
+ switch (role) {
54
+ case "system": {
55
+ messages.push({ role: "system", content });
56
+ break;
57
+ }
58
+ case "user": {
59
+ if (content.length === 1 && content[0].type === "text") {
60
+ messages.push({ role: "user", content: content[0].text });
61
+ break;
62
+ }
63
+ messages.push({
64
+ role: "user",
65
+ content: content.map((part) => {
66
+ switch (part.type) {
67
+ case "text": {
68
+ return { type: "text", text: part.text };
69
+ }
70
+ case "file": {
71
+ if (part.mediaType.startsWith("image/")) {
72
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
73
+ return {
74
+ type: "image_url",
75
+ image_url: {
76
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${(0, import_provider_utils.convertToBase64)(part.data)}`
77
+ }
78
+ };
79
+ } else {
80
+ throw new import_provider.UnsupportedFunctionalityError({
81
+ functionality: `file part media type ${part.mediaType}`
82
+ });
83
+ }
84
+ }
85
+ }
86
+ })
87
+ });
88
+ break;
89
+ }
90
+ case "assistant": {
91
+ let text = "";
92
+ const toolCalls = [];
93
+ for (const part of content) {
94
+ switch (part.type) {
95
+ case "text": {
96
+ text += part.text;
97
+ break;
98
+ }
99
+ case "tool-call": {
100
+ toolCalls.push({
101
+ id: part.toolCallId,
102
+ type: "function",
103
+ function: {
104
+ name: part.toolName,
105
+ arguments: JSON.stringify(part.input)
106
+ }
107
+ });
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ messages.push({
113
+ role: "assistant",
114
+ content: text,
115
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
116
+ });
117
+ break;
118
+ }
119
+ case "tool": {
120
+ for (const toolResponse of content) {
121
+ if (toolResponse.type === "tool-approval-response") {
122
+ continue;
123
+ }
124
+ const output = toolResponse.output;
125
+ let contentValue;
126
+ switch (output.type) {
127
+ case "text":
128
+ case "error-text":
129
+ contentValue = output.value;
130
+ break;
131
+ case "execution-denied":
132
+ contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
133
+ break;
134
+ case "content":
135
+ case "json":
136
+ case "error-json":
137
+ contentValue = JSON.stringify(output.value);
138
+ break;
139
+ }
140
+ messages.push({
141
+ role: "tool",
142
+ tool_call_id: toolResponse.toolCallId,
143
+ content: contentValue
144
+ });
145
+ }
146
+ break;
147
+ }
148
+ default: {
149
+ const _exhaustiveCheck = role;
150
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
151
+ }
152
+ }
153
+ }
154
+ return { messages, warnings };
155
+ }
156
+
157
+ // src/convert-xai-chat-usage.ts
158
+ function convertXaiChatUsage(usage) {
159
+ var _a, _b, _c, _d;
160
+ const cacheReadTokens = (_b = (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
161
+ const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
162
+ return {
163
+ inputTokens: {
164
+ total: usage.prompt_tokens,
165
+ noCache: usage.prompt_tokens - cacheReadTokens,
166
+ cacheRead: cacheReadTokens,
167
+ cacheWrite: void 0
168
+ },
169
+ outputTokens: {
170
+ total: usage.completion_tokens,
171
+ text: usage.completion_tokens - reasoningTokens,
172
+ reasoning: reasoningTokens
173
+ },
174
+ raw: usage
175
+ };
176
+ }
177
+
178
+ // src/get-response-metadata.ts
179
+ function getResponseMetadata({
180
+ id,
181
+ model,
182
+ created,
183
+ created_at
184
+ }) {
185
+ const unixTime = created != null ? created : created_at;
186
+ return {
187
+ id: id != null ? id : void 0,
188
+ modelId: model != null ? model : void 0,
189
+ timestamp: unixTime != null ? new Date(unixTime * 1e3) : void 0
190
+ };
191
+ }
192
+
193
+ // src/map-xai-finish-reason.ts
194
+ function mapXaiFinishReason(finishReason) {
195
+ switch (finishReason) {
196
+ case "stop":
197
+ return "stop";
198
+ case "length":
199
+ return "length";
200
+ case "tool_calls":
201
+ case "function_call":
202
+ return "tool-calls";
203
+ case "content_filter":
204
+ return "content-filter";
205
+ default:
206
+ return "other";
207
+ }
208
+ }
209
+
210
+ // src/xai-chat-options.ts
211
+ var import_v4 = require("zod/v4");
212
+ var webSourceSchema = import_v4.z.object({
213
+ type: import_v4.z.literal("web"),
214
+ country: import_v4.z.string().length(2).optional(),
215
+ excludedWebsites: import_v4.z.array(import_v4.z.string()).max(5).optional(),
216
+ allowedWebsites: import_v4.z.array(import_v4.z.string()).max(5).optional(),
217
+ safeSearch: import_v4.z.boolean().optional()
218
+ });
219
+ var xSourceSchema = import_v4.z.object({
220
+ type: import_v4.z.literal("x"),
221
+ excludedXHandles: import_v4.z.array(import_v4.z.string()).optional(),
222
+ includedXHandles: import_v4.z.array(import_v4.z.string()).optional(),
223
+ postFavoriteCount: import_v4.z.number().int().optional(),
224
+ postViewCount: import_v4.z.number().int().optional(),
225
+ /**
226
+ * @deprecated use `includedXHandles` instead
227
+ */
228
+ xHandles: import_v4.z.array(import_v4.z.string()).optional()
229
+ });
230
+ var newsSourceSchema = import_v4.z.object({
231
+ type: import_v4.z.literal("news"),
232
+ country: import_v4.z.string().length(2).optional(),
233
+ excludedWebsites: import_v4.z.array(import_v4.z.string()).max(5).optional(),
234
+ safeSearch: import_v4.z.boolean().optional()
235
+ });
236
+ var rssSourceSchema = import_v4.z.object({
237
+ type: import_v4.z.literal("rss"),
238
+ links: import_v4.z.array(import_v4.z.string().url()).max(1)
239
+ // currently only supports one RSS link
240
+ });
241
+ var searchSourceSchema = import_v4.z.discriminatedUnion("type", [
242
+ webSourceSchema,
243
+ xSourceSchema,
244
+ newsSourceSchema,
245
+ rssSourceSchema
246
+ ]);
247
+ var xaiProviderOptions = import_v4.z.object({
248
+ reasoningEffort: import_v4.z.enum(["low", "high"]).optional(),
249
+ /**
250
+ * Whether to enable parallel function calling during tool use.
251
+ * When true, the model can call multiple functions in parallel.
252
+ * When false, the model will call functions sequentially.
253
+ * Defaults to true.
254
+ */
255
+ parallel_function_calling: import_v4.z.boolean().optional(),
256
+ searchParameters: import_v4.z.object({
257
+ /**
258
+ * search mode preference
259
+ * - "off": disables search completely
260
+ * - "auto": model decides whether to search (default)
261
+ * - "on": always enables search
262
+ */
263
+ mode: import_v4.z.enum(["off", "auto", "on"]),
264
+ /**
265
+ * whether to return citations in the response
266
+ * defaults to true
267
+ */
268
+ returnCitations: import_v4.z.boolean().optional(),
269
+ /**
270
+ * start date for search data (ISO8601 format: YYYY-MM-DD)
271
+ */
272
+ fromDate: import_v4.z.string().optional(),
273
+ /**
274
+ * end date for search data (ISO8601 format: YYYY-MM-DD)
275
+ */
276
+ toDate: import_v4.z.string().optional(),
277
+ /**
278
+ * maximum number of search results to consider
279
+ * defaults to 20
280
+ */
281
+ maxSearchResults: import_v4.z.number().min(1).max(50).optional(),
282
+ /**
283
+ * data sources to search from.
284
+ * defaults to [{ type: 'web' }, { type: 'x' }] if not specified.
285
+ *
286
+ * @example
287
+ * sources: [{ type: 'web', country: 'US' }, { type: 'x' }]
288
+ */
289
+ sources: import_v4.z.array(searchSourceSchema).optional()
290
+ }).optional()
291
+ });
292
+
293
+ // src/xai-error.ts
294
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
295
+ var import_v42 = require("zod/v4");
296
+ var xaiErrorDataSchema = import_v42.z.object({
297
+ error: import_v42.z.object({
298
+ message: import_v42.z.string(),
299
+ type: import_v42.z.string().nullish(),
300
+ param: import_v42.z.any().nullish(),
301
+ code: import_v42.z.union([import_v42.z.string(), import_v42.z.number()]).nullish()
302
+ })
303
+ });
304
+ var xaiFailedResponseHandler = (0, import_provider_utils2.createJsonErrorResponseHandler)({
305
+ errorSchema: xaiErrorDataSchema,
306
+ errorToMessage: (data) => data.error.message
307
+ });
308
+
309
+ // src/xai-prepare-tools.ts
310
+ var import_provider2 = require("@ai-sdk/provider");
311
+ function prepareTools({
312
+ tools,
313
+ toolChoice
314
+ }) {
315
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
316
+ const toolWarnings = [];
317
+ if (tools == null) {
318
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
319
+ }
320
+ const xaiTools2 = [];
321
+ for (const tool of tools) {
322
+ if (tool.type === "provider") {
323
+ toolWarnings.push({
324
+ type: "unsupported",
325
+ feature: `provider-defined tool ${tool.name}`
326
+ });
327
+ } else {
328
+ xaiTools2.push({
329
+ type: "function",
330
+ function: {
331
+ name: tool.name,
332
+ description: tool.description,
333
+ parameters: tool.inputSchema
334
+ }
335
+ });
336
+ }
337
+ }
338
+ if (toolChoice == null) {
339
+ return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
340
+ }
341
+ const type = toolChoice.type;
342
+ switch (type) {
343
+ case "auto":
344
+ case "none":
345
+ return { tools: xaiTools2, toolChoice: type, toolWarnings };
346
+ case "required":
347
+ return { tools: xaiTools2, toolChoice: "required", toolWarnings };
348
+ case "tool":
349
+ return {
350
+ tools: xaiTools2,
351
+ toolChoice: {
352
+ type: "function",
353
+ function: { name: toolChoice.toolName }
354
+ },
355
+ toolWarnings
356
+ };
357
+ default: {
358
+ const _exhaustiveCheck = type;
359
+ throw new import_provider2.UnsupportedFunctionalityError({
360
+ functionality: `tool choice type: ${_exhaustiveCheck}`
361
+ });
362
+ }
363
+ }
364
+ }
365
+
366
+ // src/xai-chat-language-model.ts
367
+ var XaiChatLanguageModel = class {
368
+ constructor(modelId, config) {
369
+ this.specificationVersion = "v3";
370
+ this.supportedUrls = {
371
+ "image/*": [/^https?:\/\/.*$/]
372
+ };
373
+ this.modelId = modelId;
374
+ this.config = config;
375
+ }
376
+ get provider() {
377
+ return this.config.provider;
378
+ }
379
+ async getArgs({
380
+ prompt,
381
+ maxOutputTokens,
382
+ temperature,
383
+ topP,
384
+ topK,
385
+ frequencyPenalty,
386
+ presencePenalty,
387
+ stopSequences,
388
+ seed,
389
+ responseFormat,
390
+ providerOptions,
391
+ tools,
392
+ toolChoice
393
+ }) {
394
+ var _a, _b, _c;
395
+ const warnings = [];
396
+ const options = (_a = await (0, import_provider_utils3.parseProviderOptions)({
397
+ provider: "xai",
398
+ providerOptions,
399
+ schema: xaiProviderOptions
400
+ })) != null ? _a : {};
401
+ if (topK != null) {
402
+ warnings.push({ type: "unsupported", feature: "topK" });
403
+ }
404
+ if (frequencyPenalty != null) {
405
+ warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
406
+ }
407
+ if (presencePenalty != null) {
408
+ warnings.push({ type: "unsupported", feature: "presencePenalty" });
409
+ }
410
+ if (stopSequences != null) {
411
+ warnings.push({ type: "unsupported", feature: "stopSequences" });
412
+ }
413
+ const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
414
+ warnings.push(...messageWarnings);
415
+ const {
416
+ tools: xaiTools2,
417
+ toolChoice: xaiToolChoice,
418
+ toolWarnings
419
+ } = prepareTools({
420
+ tools,
421
+ toolChoice
422
+ });
423
+ warnings.push(...toolWarnings);
424
+ const baseArgs = {
425
+ // model id
426
+ model: this.modelId,
427
+ // standard generation settings
428
+ max_completion_tokens: maxOutputTokens,
429
+ temperature,
430
+ top_p: topP,
431
+ seed,
432
+ reasoning_effort: options.reasoningEffort,
433
+ // parallel function calling
434
+ parallel_function_calling: options.parallel_function_calling,
435
+ // response format
436
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
437
+ type: "json_schema",
438
+ json_schema: {
439
+ name: (_b = responseFormat.name) != null ? _b : "response",
440
+ schema: responseFormat.schema,
441
+ strict: true
442
+ }
443
+ } : { type: "json_object" } : void 0,
444
+ // search parameters
445
+ search_parameters: options.searchParameters ? {
446
+ mode: options.searchParameters.mode,
447
+ return_citations: options.searchParameters.returnCitations,
448
+ from_date: options.searchParameters.fromDate,
449
+ to_date: options.searchParameters.toDate,
450
+ max_search_results: options.searchParameters.maxSearchResults,
451
+ sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
452
+ var _a2;
453
+ return {
454
+ type: source.type,
455
+ ...source.type === "web" && {
456
+ country: source.country,
457
+ excluded_websites: source.excludedWebsites,
458
+ allowed_websites: source.allowedWebsites,
459
+ safe_search: source.safeSearch
460
+ },
461
+ ...source.type === "x" && {
462
+ excluded_x_handles: source.excludedXHandles,
463
+ included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
464
+ post_favorite_count: source.postFavoriteCount,
465
+ post_view_count: source.postViewCount
466
+ },
467
+ ...source.type === "news" && {
468
+ country: source.country,
469
+ excluded_websites: source.excludedWebsites,
470
+ safe_search: source.safeSearch
471
+ },
472
+ ...source.type === "rss" && {
473
+ links: source.links
474
+ }
475
+ };
476
+ })
477
+ } : void 0,
478
+ // messages in xai format
479
+ messages,
480
+ // tools in xai format
481
+ tools: xaiTools2,
482
+ tool_choice: xaiToolChoice
483
+ };
484
+ return {
485
+ args: baseArgs,
486
+ warnings
487
+ };
488
+ }
489
+ async doGenerate(options) {
490
+ var _a, _b;
491
+ const { args: body, warnings } = await this.getArgs(options);
492
+ const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
493
+ const {
494
+ responseHeaders,
495
+ value: response,
496
+ rawValue: rawResponse
497
+ } = await (0, import_provider_utils3.postJsonToApi)({
498
+ url,
499
+ headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
500
+ body,
501
+ failedResponseHandler: xaiFailedResponseHandler,
502
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
503
+ xaiChatResponseSchema
504
+ ),
505
+ abortSignal: options.abortSignal,
506
+ fetch: this.config.fetch
507
+ });
508
+ if (response.error != null) {
509
+ throw new import_provider3.APICallError({
510
+ message: response.error,
511
+ url,
512
+ requestBodyValues: body,
513
+ statusCode: 200,
514
+ responseHeaders,
515
+ responseBody: JSON.stringify(rawResponse),
516
+ isRetryable: response.code === "The service is currently unavailable"
517
+ });
518
+ }
519
+ const choice = response.choices[0];
520
+ const content = [];
521
+ if (choice.message.content != null && choice.message.content.length > 0) {
522
+ let text = choice.message.content;
523
+ const lastMessage = body.messages[body.messages.length - 1];
524
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
525
+ text = "";
526
+ }
527
+ if (text.length > 0) {
528
+ content.push({ type: "text", text });
529
+ }
530
+ }
531
+ if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
532
+ content.push({
533
+ type: "reasoning",
534
+ text: choice.message.reasoning_content
535
+ });
536
+ }
537
+ if (choice.message.tool_calls != null) {
538
+ for (const toolCall of choice.message.tool_calls) {
539
+ content.push({
540
+ type: "tool-call",
541
+ toolCallId: toolCall.id,
542
+ toolName: toolCall.function.name,
543
+ input: toolCall.function.arguments
544
+ });
545
+ }
546
+ }
547
+ if (response.citations != null) {
548
+ for (const url2 of response.citations) {
549
+ content.push({
550
+ type: "source",
551
+ sourceType: "url",
552
+ id: this.config.generateId(),
553
+ url: url2
554
+ });
555
+ }
556
+ }
557
+ return {
558
+ content,
559
+ finishReason: {
560
+ unified: mapXaiFinishReason(choice.finish_reason),
561
+ raw: (_b = choice.finish_reason) != null ? _b : void 0
562
+ },
563
+ usage: convertXaiChatUsage(response.usage),
564
+ // defined when there is no error
565
+ request: { body },
566
+ response: {
567
+ ...getResponseMetadata(response),
568
+ headers: responseHeaders,
569
+ body: rawResponse
570
+ },
571
+ warnings
572
+ };
573
+ }
574
+ async doStream(options) {
575
+ var _a;
576
+ const { args, warnings } = await this.getArgs(options);
577
+ const body = {
578
+ ...args,
579
+ stream: true,
580
+ stream_options: {
581
+ include_usage: true
582
+ }
583
+ };
584
+ const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
585
+ const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
586
+ url,
587
+ headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
588
+ body,
589
+ failedResponseHandler: xaiFailedResponseHandler,
590
+ successfulResponseHandler: async ({ response: response2 }) => {
591
+ const responseHeaders2 = (0, import_provider_utils3.extractResponseHeaders)(response2);
592
+ const contentType = response2.headers.get("content-type");
593
+ if (contentType == null ? void 0 : contentType.includes("application/json")) {
594
+ const responseBody = await response2.text();
595
+ const parsedError = await (0, import_provider_utils3.safeParseJSON)({
596
+ text: responseBody,
597
+ schema: xaiStreamErrorSchema
598
+ });
599
+ if (parsedError.success) {
600
+ throw new import_provider3.APICallError({
601
+ message: parsedError.value.error,
602
+ url,
603
+ requestBodyValues: body,
604
+ statusCode: 200,
605
+ responseHeaders: responseHeaders2,
606
+ responseBody,
607
+ isRetryable: parsedError.value.code === "The service is currently unavailable"
608
+ });
609
+ }
610
+ throw new import_provider3.APICallError({
611
+ message: "Invalid JSON response",
612
+ url,
613
+ requestBodyValues: body,
614
+ statusCode: 200,
615
+ responseHeaders: responseHeaders2,
616
+ responseBody
617
+ });
618
+ }
619
+ return (0, import_provider_utils3.createEventSourceResponseHandler)(xaiChatChunkSchema)({
620
+ response: response2,
621
+ url,
622
+ requestBodyValues: body
623
+ });
624
+ },
625
+ abortSignal: options.abortSignal,
626
+ fetch: this.config.fetch
627
+ });
628
+ let finishReason = {
629
+ unified: "other",
630
+ raw: void 0
631
+ };
632
+ let usage = void 0;
633
+ let isFirstChunk = true;
634
+ const contentBlocks = {};
635
+ const lastReasoningDeltas = {};
636
+ let activeReasoningBlockId = void 0;
637
+ const self = this;
638
+ return {
639
+ stream: response.pipeThrough(
640
+ new TransformStream({
641
+ start(controller) {
642
+ controller.enqueue({ type: "stream-start", warnings });
643
+ },
644
+ transform(chunk, controller) {
645
+ if (options.includeRawChunks) {
646
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
647
+ }
648
+ if (!chunk.success) {
649
+ controller.enqueue({ type: "error", error: chunk.error });
650
+ return;
651
+ }
652
+ const value = chunk.value;
653
+ if (isFirstChunk) {
654
+ controller.enqueue({
655
+ type: "response-metadata",
656
+ ...getResponseMetadata(value)
657
+ });
658
+ isFirstChunk = false;
659
+ }
660
+ if (value.citations != null) {
661
+ for (const url2 of value.citations) {
662
+ controller.enqueue({
663
+ type: "source",
664
+ sourceType: "url",
665
+ id: self.config.generateId(),
666
+ url: url2
667
+ });
668
+ }
669
+ }
670
+ if (value.usage != null) {
671
+ usage = convertXaiChatUsage(value.usage);
672
+ }
673
+ const choice = value.choices[0];
674
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
675
+ finishReason = {
676
+ unified: mapXaiFinishReason(choice.finish_reason),
677
+ raw: choice.finish_reason
678
+ };
679
+ }
680
+ if ((choice == null ? void 0 : choice.delta) == null) {
681
+ return;
682
+ }
683
+ const delta = choice.delta;
684
+ const choiceIndex = choice.index;
685
+ if (delta.content != null && delta.content.length > 0) {
686
+ const textContent = delta.content;
687
+ if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
688
+ controller.enqueue({
689
+ type: "reasoning-end",
690
+ id: activeReasoningBlockId
691
+ });
692
+ contentBlocks[activeReasoningBlockId].ended = true;
693
+ activeReasoningBlockId = void 0;
694
+ }
695
+ const lastMessage = body.messages[body.messages.length - 1];
696
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
697
+ return;
698
+ }
699
+ const blockId = `text-${value.id || choiceIndex}`;
700
+ if (contentBlocks[blockId] == null) {
701
+ contentBlocks[blockId] = { type: "text", ended: false };
702
+ controller.enqueue({
703
+ type: "text-start",
704
+ id: blockId
705
+ });
706
+ }
707
+ controller.enqueue({
708
+ type: "text-delta",
709
+ id: blockId,
710
+ delta: textContent
711
+ });
712
+ }
713
+ if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
714
+ const blockId = `reasoning-${value.id || choiceIndex}`;
715
+ if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
716
+ return;
717
+ }
718
+ lastReasoningDeltas[blockId] = delta.reasoning_content;
719
+ if (contentBlocks[blockId] == null) {
720
+ contentBlocks[blockId] = { type: "reasoning", ended: false };
721
+ activeReasoningBlockId = blockId;
722
+ controller.enqueue({
723
+ type: "reasoning-start",
724
+ id: blockId
725
+ });
726
+ }
727
+ controller.enqueue({
728
+ type: "reasoning-delta",
729
+ id: blockId,
730
+ delta: delta.reasoning_content
731
+ });
732
+ }
733
+ if (delta.tool_calls != null) {
734
+ if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
735
+ controller.enqueue({
736
+ type: "reasoning-end",
737
+ id: activeReasoningBlockId
738
+ });
739
+ contentBlocks[activeReasoningBlockId].ended = true;
740
+ activeReasoningBlockId = void 0;
741
+ }
742
+ for (const toolCall of delta.tool_calls) {
743
+ const toolCallId = toolCall.id;
744
+ controller.enqueue({
745
+ type: "tool-input-start",
746
+ id: toolCallId,
747
+ toolName: toolCall.function.name
748
+ });
749
+ controller.enqueue({
750
+ type: "tool-input-delta",
751
+ id: toolCallId,
752
+ delta: toolCall.function.arguments
753
+ });
754
+ controller.enqueue({
755
+ type: "tool-input-end",
756
+ id: toolCallId
757
+ });
758
+ controller.enqueue({
759
+ type: "tool-call",
760
+ toolCallId,
761
+ toolName: toolCall.function.name,
762
+ input: toolCall.function.arguments
763
+ });
764
+ }
765
+ }
766
+ },
767
+ flush(controller) {
768
+ for (const [blockId, block] of Object.entries(contentBlocks)) {
769
+ if (!block.ended) {
770
+ controller.enqueue({
771
+ type: block.type === "text" ? "text-end" : "reasoning-end",
772
+ id: blockId
773
+ });
774
+ }
775
+ }
776
+ controller.enqueue({ type: "finish", finishReason, usage });
777
+ }
778
+ })
779
+ ),
780
+ request: { body },
781
+ response: { headers: responseHeaders }
782
+ };
783
+ }
784
+ };
785
+ var xaiUsageSchema = import_v43.z.object({
786
+ prompt_tokens: import_v43.z.number(),
787
+ completion_tokens: import_v43.z.number(),
788
+ total_tokens: import_v43.z.number(),
789
+ prompt_tokens_details: import_v43.z.object({
790
+ text_tokens: import_v43.z.number().nullish(),
791
+ audio_tokens: import_v43.z.number().nullish(),
792
+ image_tokens: import_v43.z.number().nullish(),
793
+ cached_tokens: import_v43.z.number().nullish()
794
+ }).nullish(),
795
+ completion_tokens_details: import_v43.z.object({
796
+ reasoning_tokens: import_v43.z.number().nullish(),
797
+ audio_tokens: import_v43.z.number().nullish(),
798
+ accepted_prediction_tokens: import_v43.z.number().nullish(),
799
+ rejected_prediction_tokens: import_v43.z.number().nullish()
800
+ }).nullish()
801
+ });
802
+ var xaiChatResponseSchema = import_v43.z.object({
803
+ id: import_v43.z.string().nullish(),
804
+ created: import_v43.z.number().nullish(),
805
+ model: import_v43.z.string().nullish(),
806
+ choices: import_v43.z.array(
807
+ import_v43.z.object({
808
+ message: import_v43.z.object({
809
+ role: import_v43.z.literal("assistant"),
810
+ content: import_v43.z.string().nullish(),
811
+ reasoning_content: import_v43.z.string().nullish(),
812
+ tool_calls: import_v43.z.array(
813
+ import_v43.z.object({
814
+ id: import_v43.z.string(),
815
+ type: import_v43.z.literal("function"),
816
+ function: import_v43.z.object({
817
+ name: import_v43.z.string(),
818
+ arguments: import_v43.z.string()
819
+ })
820
+ })
821
+ ).nullish()
822
+ }),
823
+ index: import_v43.z.number(),
824
+ finish_reason: import_v43.z.string().nullish()
825
+ })
826
+ ).nullish(),
827
+ object: import_v43.z.literal("chat.completion").nullish(),
828
+ usage: xaiUsageSchema.nullish(),
829
+ citations: import_v43.z.array(import_v43.z.string().url()).nullish(),
830
+ code: import_v43.z.string().nullish(),
831
+ error: import_v43.z.string().nullish()
832
+ });
833
+ var xaiChatChunkSchema = import_v43.z.object({
834
+ id: import_v43.z.string().nullish(),
835
+ created: import_v43.z.number().nullish(),
836
+ model: import_v43.z.string().nullish(),
837
+ choices: import_v43.z.array(
838
+ import_v43.z.object({
839
+ delta: import_v43.z.object({
840
+ role: import_v43.z.enum(["assistant"]).optional(),
841
+ content: import_v43.z.string().nullish(),
842
+ reasoning_content: import_v43.z.string().nullish(),
843
+ tool_calls: import_v43.z.array(
844
+ import_v43.z.object({
845
+ id: import_v43.z.string(),
846
+ type: import_v43.z.literal("function"),
847
+ function: import_v43.z.object({
848
+ name: import_v43.z.string(),
849
+ arguments: import_v43.z.string()
850
+ })
851
+ })
852
+ ).nullish()
853
+ }),
854
+ finish_reason: import_v43.z.string().nullish(),
855
+ index: import_v43.z.number()
856
+ })
857
+ ),
858
+ usage: xaiUsageSchema.nullish(),
859
+ citations: import_v43.z.array(import_v43.z.string().url()).nullish()
860
+ });
861
+ var xaiStreamErrorSchema = import_v43.z.object({
862
+ code: import_v43.z.string(),
863
+ error: import_v43.z.string()
864
+ });
865
+
866
+ // src/responses/xai-responses-language-model.ts
867
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
868
+
869
+ // src/responses/convert-to-xai-responses-input.ts
870
+ var import_provider4 = require("@ai-sdk/provider");
871
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
872
+ async function convertToXaiResponsesInput({
873
+ prompt
874
+ }) {
875
+ var _a, _b, _c, _d, _e;
876
+ const input = [];
877
+ const inputWarnings = [];
878
+ for (const message of prompt) {
879
+ switch (message.role) {
880
+ case "system": {
881
+ input.push({
882
+ role: "system",
883
+ content: message.content
884
+ });
885
+ break;
886
+ }
887
+ case "user": {
888
+ const contentParts = [];
889
+ for (const block of message.content) {
890
+ switch (block.type) {
891
+ case "text": {
892
+ contentParts.push({ type: "input_text", text: block.text });
893
+ break;
894
+ }
895
+ case "file": {
896
+ if (block.mediaType.startsWith("image/")) {
897
+ const mediaType = block.mediaType === "image/*" ? "image/jpeg" : block.mediaType;
898
+ const imageUrl = block.data instanceof URL ? block.data.toString() : `data:${mediaType};base64,${(0, import_provider_utils4.convertToBase64)(block.data)}`;
899
+ contentParts.push({ type: "input_image", image_url: imageUrl });
900
+ } else {
901
+ throw new import_provider4.UnsupportedFunctionalityError({
902
+ functionality: `file part media type ${block.mediaType}`
903
+ });
904
+ }
905
+ break;
906
+ }
907
+ default: {
908
+ const _exhaustiveCheck = block;
909
+ inputWarnings.push({
910
+ type: "other",
911
+ message: "xAI Responses API does not support this content type in user messages"
912
+ });
913
+ }
914
+ }
915
+ }
916
+ input.push({
917
+ role: "user",
918
+ content: contentParts
919
+ });
920
+ break;
921
+ }
922
+ case "assistant": {
923
+ for (const part of message.content) {
924
+ switch (part.type) {
925
+ case "text": {
926
+ const id = typeof ((_b = (_a = part.providerOptions) == null ? void 0 : _a.xai) == null ? void 0 : _b.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
927
+ input.push({
928
+ role: "assistant",
929
+ content: part.text,
930
+ id
931
+ });
932
+ break;
933
+ }
934
+ case "tool-call": {
935
+ if (part.providerExecuted) {
936
+ break;
937
+ }
938
+ const id = typeof ((_d = (_c = part.providerOptions) == null ? void 0 : _c.xai) == null ? void 0 : _d.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
939
+ input.push({
940
+ type: "function_call",
941
+ id: id != null ? id : part.toolCallId,
942
+ call_id: part.toolCallId,
943
+ name: part.toolName,
944
+ arguments: JSON.stringify(part.input),
945
+ status: "completed"
946
+ });
947
+ break;
948
+ }
949
+ case "tool-result": {
950
+ break;
951
+ }
952
+ case "reasoning":
953
+ case "file": {
954
+ inputWarnings.push({
955
+ type: "other",
956
+ message: `xAI Responses API does not support ${part.type} in assistant messages`
957
+ });
958
+ break;
959
+ }
960
+ default: {
961
+ const _exhaustiveCheck = part;
962
+ inputWarnings.push({
963
+ type: "other",
964
+ message: "xAI Responses API does not support this content type in assistant messages"
965
+ });
966
+ }
967
+ }
968
+ }
969
+ break;
970
+ }
971
+ case "tool": {
972
+ for (const part of message.content) {
973
+ if (part.type === "tool-approval-response") {
974
+ continue;
975
+ }
976
+ const output = part.output;
977
+ let outputValue;
978
+ switch (output.type) {
979
+ case "text":
980
+ case "error-text":
981
+ outputValue = output.value;
982
+ break;
983
+ case "execution-denied":
984
+ outputValue = (_e = output.reason) != null ? _e : "tool execution denied";
985
+ break;
986
+ case "json":
987
+ case "error-json":
988
+ outputValue = JSON.stringify(output.value);
989
+ break;
990
+ case "content":
991
+ outputValue = output.value.map((item) => {
992
+ if (item.type === "text") {
993
+ return item.text;
994
+ }
995
+ return "";
996
+ }).join("");
997
+ break;
998
+ default: {
999
+ const _exhaustiveCheck = output;
1000
+ outputValue = "";
1001
+ }
1002
+ }
1003
+ input.push({
1004
+ type: "function_call_output",
1005
+ call_id: part.toolCallId,
1006
+ output: outputValue
1007
+ });
1008
+ }
1009
+ break;
1010
+ }
1011
+ default: {
1012
+ const _exhaustiveCheck = message;
1013
+ inputWarnings.push({
1014
+ type: "other",
1015
+ message: "unsupported message role"
1016
+ });
1017
+ }
1018
+ }
1019
+ }
1020
+ return { input, inputWarnings };
1021
+ }
1022
+
1023
+ // src/responses/convert-xai-responses-usage.ts
1024
+ function convertXaiResponsesUsage(usage) {
1025
+ var _a, _b, _c, _d;
1026
+ const cacheReadTokens = (_b = (_a = usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
1027
+ const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
1028
+ return {
1029
+ inputTokens: {
1030
+ total: usage.input_tokens,
1031
+ noCache: usage.input_tokens - cacheReadTokens,
1032
+ cacheRead: cacheReadTokens,
1033
+ cacheWrite: void 0
1034
+ },
1035
+ outputTokens: {
1036
+ total: usage.output_tokens,
1037
+ text: usage.output_tokens - reasoningTokens,
1038
+ reasoning: reasoningTokens
1039
+ },
1040
+ raw: usage
1041
+ };
1042
+ }
1043
+
1044
+ // src/responses/map-xai-responses-finish-reason.ts
1045
+ function mapXaiResponsesFinishReason(finishReason) {
1046
+ switch (finishReason) {
1047
+ case "stop":
1048
+ case "completed":
1049
+ return "stop";
1050
+ case "length":
1051
+ return "length";
1052
+ case "tool_calls":
1053
+ case "function_call":
1054
+ return "tool-calls";
1055
+ case "content_filter":
1056
+ return "content-filter";
1057
+ default:
1058
+ return "other";
1059
+ }
1060
+ }
1061
+
1062
+ // src/responses/xai-responses-api.ts
1063
+ var import_v44 = require("zod/v4");
1064
+ var annotationSchema = import_v44.z.union([
1065
+ import_v44.z.object({
1066
+ type: import_v44.z.literal("url_citation"),
1067
+ url: import_v44.z.string(),
1068
+ title: import_v44.z.string().optional()
1069
+ }),
1070
+ import_v44.z.object({
1071
+ type: import_v44.z.string()
1072
+ })
1073
+ ]);
1074
+ var messageContentPartSchema = import_v44.z.object({
1075
+ type: import_v44.z.string(),
1076
+ text: import_v44.z.string().optional(),
1077
+ logprobs: import_v44.z.array(import_v44.z.any()).optional(),
1078
+ annotations: import_v44.z.array(annotationSchema).optional()
1079
+ });
1080
+ var reasoningSummaryPartSchema = import_v44.z.object({
1081
+ type: import_v44.z.string(),
1082
+ text: import_v44.z.string()
1083
+ });
1084
+ var toolCallSchema = import_v44.z.object({
1085
+ name: import_v44.z.string().optional(),
1086
+ arguments: import_v44.z.string().optional(),
1087
+ input: import_v44.z.string().optional(),
1088
+ call_id: import_v44.z.string().optional(),
1089
+ id: import_v44.z.string(),
1090
+ status: import_v44.z.string(),
1091
+ action: import_v44.z.any().optional()
1092
+ });
1093
+ var outputItemSchema = import_v44.z.discriminatedUnion("type", [
1094
+ import_v44.z.object({
1095
+ type: import_v44.z.literal("web_search_call"),
1096
+ ...toolCallSchema.shape
1097
+ }),
1098
+ import_v44.z.object({
1099
+ type: import_v44.z.literal("x_search_call"),
1100
+ ...toolCallSchema.shape
1101
+ }),
1102
+ import_v44.z.object({
1103
+ type: import_v44.z.literal("code_interpreter_call"),
1104
+ ...toolCallSchema.shape
1105
+ }),
1106
+ import_v44.z.object({
1107
+ type: import_v44.z.literal("code_execution_call"),
1108
+ ...toolCallSchema.shape
1109
+ }),
1110
+ import_v44.z.object({
1111
+ type: import_v44.z.literal("view_image_call"),
1112
+ ...toolCallSchema.shape
1113
+ }),
1114
+ import_v44.z.object({
1115
+ type: import_v44.z.literal("view_x_video_call"),
1116
+ ...toolCallSchema.shape
1117
+ }),
1118
+ import_v44.z.object({
1119
+ type: import_v44.z.literal("custom_tool_call"),
1120
+ ...toolCallSchema.shape
1121
+ }),
1122
+ import_v44.z.object({
1123
+ type: import_v44.z.literal("message"),
1124
+ role: import_v44.z.string(),
1125
+ content: import_v44.z.array(messageContentPartSchema),
1126
+ id: import_v44.z.string(),
1127
+ status: import_v44.z.string()
1128
+ }),
1129
+ import_v44.z.object({
1130
+ type: import_v44.z.literal("function_call"),
1131
+ name: import_v44.z.string(),
1132
+ arguments: import_v44.z.string(),
1133
+ call_id: import_v44.z.string(),
1134
+ id: import_v44.z.string()
1135
+ }),
1136
+ import_v44.z.object({
1137
+ type: import_v44.z.literal("reasoning"),
1138
+ id: import_v44.z.string(),
1139
+ summary: import_v44.z.array(reasoningSummaryPartSchema),
1140
+ status: import_v44.z.string(),
1141
+ encrypted_content: import_v44.z.string().nullish()
1142
+ })
1143
+ ]);
1144
+ var xaiResponsesUsageSchema = import_v44.z.object({
1145
+ input_tokens: import_v44.z.number(),
1146
+ output_tokens: import_v44.z.number(),
1147
+ total_tokens: import_v44.z.number().optional(),
1148
+ input_tokens_details: import_v44.z.object({
1149
+ cached_tokens: import_v44.z.number().optional()
1150
+ }).optional(),
1151
+ output_tokens_details: import_v44.z.object({
1152
+ reasoning_tokens: import_v44.z.number().optional()
1153
+ }).optional(),
1154
+ num_sources_used: import_v44.z.number().optional(),
1155
+ num_server_side_tools_used: import_v44.z.number().optional()
1156
+ });
1157
+ var xaiResponsesResponseSchema = import_v44.z.object({
1158
+ id: import_v44.z.string().nullish(),
1159
+ created_at: import_v44.z.number().nullish(),
1160
+ model: import_v44.z.string().nullish(),
1161
+ object: import_v44.z.literal("response"),
1162
+ output: import_v44.z.array(outputItemSchema),
1163
+ usage: xaiResponsesUsageSchema,
1164
+ status: import_v44.z.string()
1165
+ });
1166
+ var xaiResponsesChunkSchema = import_v44.z.union([
1167
+ import_v44.z.object({
1168
+ type: import_v44.z.literal("response.created"),
1169
+ response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
1170
+ }),
1171
+ import_v44.z.object({
1172
+ type: import_v44.z.literal("response.in_progress"),
1173
+ response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
1174
+ }),
1175
+ import_v44.z.object({
1176
+ type: import_v44.z.literal("response.output_item.added"),
1177
+ item: outputItemSchema,
1178
+ output_index: import_v44.z.number()
1179
+ }),
1180
+ import_v44.z.object({
1181
+ type: import_v44.z.literal("response.output_item.done"),
1182
+ item: outputItemSchema,
1183
+ output_index: import_v44.z.number()
1184
+ }),
1185
+ import_v44.z.object({
1186
+ type: import_v44.z.literal("response.content_part.added"),
1187
+ item_id: import_v44.z.string(),
1188
+ output_index: import_v44.z.number(),
1189
+ content_index: import_v44.z.number(),
1190
+ part: messageContentPartSchema
1191
+ }),
1192
+ import_v44.z.object({
1193
+ type: import_v44.z.literal("response.content_part.done"),
1194
+ item_id: import_v44.z.string(),
1195
+ output_index: import_v44.z.number(),
1196
+ content_index: import_v44.z.number(),
1197
+ part: messageContentPartSchema
1198
+ }),
1199
+ import_v44.z.object({
1200
+ type: import_v44.z.literal("response.output_text.delta"),
1201
+ item_id: import_v44.z.string(),
1202
+ output_index: import_v44.z.number(),
1203
+ content_index: import_v44.z.number(),
1204
+ delta: import_v44.z.string(),
1205
+ logprobs: import_v44.z.array(import_v44.z.any()).optional()
1206
+ }),
1207
+ import_v44.z.object({
1208
+ type: import_v44.z.literal("response.output_text.done"),
1209
+ item_id: import_v44.z.string(),
1210
+ output_index: import_v44.z.number(),
1211
+ content_index: import_v44.z.number(),
1212
+ text: import_v44.z.string(),
1213
+ logprobs: import_v44.z.array(import_v44.z.any()).optional(),
1214
+ annotations: import_v44.z.array(annotationSchema).optional()
1215
+ }),
1216
+ import_v44.z.object({
1217
+ type: import_v44.z.literal("response.output_text.annotation.added"),
1218
+ item_id: import_v44.z.string(),
1219
+ output_index: import_v44.z.number(),
1220
+ content_index: import_v44.z.number(),
1221
+ annotation_index: import_v44.z.number(),
1222
+ annotation: annotationSchema
1223
+ }),
1224
+ import_v44.z.object({
1225
+ type: import_v44.z.literal("response.reasoning_summary_part.added"),
1226
+ item_id: import_v44.z.string(),
1227
+ output_index: import_v44.z.number(),
1228
+ summary_index: import_v44.z.number(),
1229
+ part: reasoningSummaryPartSchema
1230
+ }),
1231
+ import_v44.z.object({
1232
+ type: import_v44.z.literal("response.reasoning_summary_part.done"),
1233
+ item_id: import_v44.z.string(),
1234
+ output_index: import_v44.z.number(),
1235
+ summary_index: import_v44.z.number(),
1236
+ part: reasoningSummaryPartSchema
1237
+ }),
1238
+ import_v44.z.object({
1239
+ type: import_v44.z.literal("response.reasoning_summary_text.delta"),
1240
+ item_id: import_v44.z.string(),
1241
+ output_index: import_v44.z.number(),
1242
+ summary_index: import_v44.z.number(),
1243
+ delta: import_v44.z.string()
1244
+ }),
1245
+ import_v44.z.object({
1246
+ type: import_v44.z.literal("response.reasoning_summary_text.done"),
1247
+ item_id: import_v44.z.string(),
1248
+ output_index: import_v44.z.number(),
1249
+ summary_index: import_v44.z.number(),
1250
+ text: import_v44.z.string()
1251
+ }),
1252
+ import_v44.z.object({
1253
+ type: import_v44.z.literal("response.web_search_call.in_progress"),
1254
+ item_id: import_v44.z.string(),
1255
+ output_index: import_v44.z.number()
1256
+ }),
1257
+ import_v44.z.object({
1258
+ type: import_v44.z.literal("response.web_search_call.searching"),
1259
+ item_id: import_v44.z.string(),
1260
+ output_index: import_v44.z.number()
1261
+ }),
1262
+ import_v44.z.object({
1263
+ type: import_v44.z.literal("response.web_search_call.completed"),
1264
+ item_id: import_v44.z.string(),
1265
+ output_index: import_v44.z.number()
1266
+ }),
1267
+ import_v44.z.object({
1268
+ type: import_v44.z.literal("response.x_search_call.in_progress"),
1269
+ item_id: import_v44.z.string(),
1270
+ output_index: import_v44.z.number()
1271
+ }),
1272
+ import_v44.z.object({
1273
+ type: import_v44.z.literal("response.x_search_call.searching"),
1274
+ item_id: import_v44.z.string(),
1275
+ output_index: import_v44.z.number()
1276
+ }),
1277
+ import_v44.z.object({
1278
+ type: import_v44.z.literal("response.x_search_call.completed"),
1279
+ item_id: import_v44.z.string(),
1280
+ output_index: import_v44.z.number()
1281
+ }),
1282
+ import_v44.z.object({
1283
+ type: import_v44.z.literal("response.custom_tool_call_input.done"),
1284
+ item_id: import_v44.z.string(),
1285
+ output_index: import_v44.z.number()
1286
+ }),
1287
+ import_v44.z.object({
1288
+ type: import_v44.z.literal("response.custom_tool_call_input.delta"),
1289
+ item_id: import_v44.z.string(),
1290
+ output_index: import_v44.z.number()
1291
+ }),
1292
+ import_v44.z.object({
1293
+ type: import_v44.z.literal("response.code_execution_call.in_progress"),
1294
+ item_id: import_v44.z.string(),
1295
+ output_index: import_v44.z.number()
1296
+ }),
1297
+ import_v44.z.object({
1298
+ type: import_v44.z.literal("response.code_execution_call.executing"),
1299
+ item_id: import_v44.z.string(),
1300
+ output_index: import_v44.z.number()
1301
+ }),
1302
+ import_v44.z.object({
1303
+ type: import_v44.z.literal("response.code_execution_call.completed"),
1304
+ item_id: import_v44.z.string(),
1305
+ output_index: import_v44.z.number()
1306
+ }),
1307
+ import_v44.z.object({
1308
+ type: import_v44.z.literal("response.code_interpreter_call.in_progress"),
1309
+ item_id: import_v44.z.string(),
1310
+ output_index: import_v44.z.number()
1311
+ }),
1312
+ import_v44.z.object({
1313
+ type: import_v44.z.literal("response.code_interpreter_call.executing"),
1314
+ item_id: import_v44.z.string(),
1315
+ output_index: import_v44.z.number()
1316
+ }),
1317
+ import_v44.z.object({
1318
+ type: import_v44.z.literal("response.code_interpreter_call.interpreting"),
1319
+ item_id: import_v44.z.string(),
1320
+ output_index: import_v44.z.number()
1321
+ }),
1322
+ import_v44.z.object({
1323
+ type: import_v44.z.literal("response.code_interpreter_call.completed"),
1324
+ item_id: import_v44.z.string(),
1325
+ output_index: import_v44.z.number()
1326
+ }),
1327
+ // Code interpreter code streaming events
1328
+ import_v44.z.object({
1329
+ type: import_v44.z.literal("response.code_interpreter_call_code.delta"),
1330
+ item_id: import_v44.z.string(),
1331
+ output_index: import_v44.z.number(),
1332
+ delta: import_v44.z.string()
1333
+ }),
1334
+ import_v44.z.object({
1335
+ type: import_v44.z.literal("response.code_interpreter_call_code.done"),
1336
+ item_id: import_v44.z.string(),
1337
+ output_index: import_v44.z.number(),
1338
+ code: import_v44.z.string()
1339
+ }),
1340
+ import_v44.z.object({
1341
+ type: import_v44.z.literal("response.done"),
1342
+ response: xaiResponsesResponseSchema
1343
+ }),
1344
+ import_v44.z.object({
1345
+ type: import_v44.z.literal("response.completed"),
1346
+ response: xaiResponsesResponseSchema
1347
+ })
1348
+ ]);
1349
+
1350
+ // src/responses/xai-responses-options.ts
1351
+ var import_v45 = require("zod/v4");
1352
+ var xaiResponsesProviderOptions = import_v45.z.object({
1353
+ /**
1354
+ * Constrains how hard a reasoning model thinks before responding.
1355
+ * Possible values are `low` (uses fewer reasoning tokens), `medium` and `high` (uses more reasoning tokens).
1356
+ */
1357
+ reasoningEffort: import_v45.z.enum(["low", "medium", "high"]).optional(),
1358
+ /**
1359
+ * Whether to store the input message(s) and model response for later retrieval.
1360
+ * @default true
1361
+ */
1362
+ store: import_v45.z.boolean().optional(),
1363
+ /**
1364
+ * The ID of the previous response from the model.
1365
+ */
1366
+ previousResponseId: import_v45.z.string().optional()
1367
+ });
1368
+
1369
+ // src/responses/xai-responses-prepare-tools.ts
1370
+ var import_provider5 = require("@ai-sdk/provider");
1371
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1372
+
1373
+ // src/tool/web-search.ts
1374
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
1375
+ var import_v46 = require("zod/v4");
1376
+ var webSearchArgsSchema = (0, import_provider_utils5.lazySchema)(
1377
+ () => (0, import_provider_utils5.zodSchema)(
1378
+ import_v46.z.object({
1379
+ allowedDomains: import_v46.z.array(import_v46.z.string()).max(5).optional(),
1380
+ excludedDomains: import_v46.z.array(import_v46.z.string()).max(5).optional(),
1381
+ enableImageUnderstanding: import_v46.z.boolean().optional()
1382
+ })
1383
+ )
1384
+ );
1385
+ var webSearchOutputSchema = (0, import_provider_utils5.lazySchema)(
1386
+ () => (0, import_provider_utils5.zodSchema)(
1387
+ import_v46.z.object({
1388
+ query: import_v46.z.string(),
1389
+ sources: import_v46.z.array(
1390
+ import_v46.z.object({
1391
+ title: import_v46.z.string(),
1392
+ url: import_v46.z.string(),
1393
+ snippet: import_v46.z.string()
1394
+ })
1395
+ )
1396
+ })
1397
+ )
1398
+ );
1399
+ var webSearchToolFactory = (0, import_provider_utils5.createProviderToolFactoryWithOutputSchema)({
1400
+ id: "xai.web_search",
1401
+ inputSchema: (0, import_provider_utils5.lazySchema)(() => (0, import_provider_utils5.zodSchema)(import_v46.z.object({}))),
1402
+ outputSchema: webSearchOutputSchema
1403
+ });
1404
+ var webSearch = (args = {}) => webSearchToolFactory(args);
1405
+
1406
+ // src/tool/x-search.ts
1407
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
1408
+ var import_v47 = require("zod/v4");
1409
+ var xSearchArgsSchema = (0, import_provider_utils6.lazySchema)(
1410
+ () => (0, import_provider_utils6.zodSchema)(
1411
+ import_v47.z.object({
1412
+ allowedXHandles: import_v47.z.array(import_v47.z.string()).max(10).optional(),
1413
+ excludedXHandles: import_v47.z.array(import_v47.z.string()).max(10).optional(),
1414
+ fromDate: import_v47.z.string().optional(),
1415
+ toDate: import_v47.z.string().optional(),
1416
+ enableImageUnderstanding: import_v47.z.boolean().optional(),
1417
+ enableVideoUnderstanding: import_v47.z.boolean().optional()
1418
+ })
1419
+ )
1420
+ );
1421
+ var xSearchOutputSchema = (0, import_provider_utils6.lazySchema)(
1422
+ () => (0, import_provider_utils6.zodSchema)(
1423
+ import_v47.z.object({
1424
+ query: import_v47.z.string(),
1425
+ posts: import_v47.z.array(
1426
+ import_v47.z.object({
1427
+ author: import_v47.z.string(),
1428
+ text: import_v47.z.string(),
1429
+ url: import_v47.z.string(),
1430
+ likes: import_v47.z.number()
1431
+ })
1432
+ )
1433
+ })
1434
+ )
1435
+ );
1436
+ var xSearchToolFactory = (0, import_provider_utils6.createProviderToolFactoryWithOutputSchema)({
1437
+ id: "xai.x_search",
1438
+ inputSchema: (0, import_provider_utils6.lazySchema)(() => (0, import_provider_utils6.zodSchema)(import_v47.z.object({}))),
1439
+ outputSchema: xSearchOutputSchema
1440
+ });
1441
+ var xSearch = (args = {}) => xSearchToolFactory(args);
1442
+
1443
+ // src/responses/xai-responses-prepare-tools.ts
1444
+ async function prepareResponsesTools({
1445
+ tools,
1446
+ toolChoice
1447
+ }) {
1448
+ const normalizedTools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1449
+ const toolWarnings = [];
1450
+ if (normalizedTools == null) {
1451
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
1452
+ }
1453
+ const xaiTools2 = [];
1454
+ const toolByName = /* @__PURE__ */ new Map();
1455
+ for (const tool of normalizedTools) {
1456
+ toolByName.set(tool.name, tool);
1457
+ if (tool.type === "provider") {
1458
+ switch (tool.id) {
1459
+ case "xai.web_search": {
1460
+ const args = await (0, import_provider_utils7.validateTypes)({
1461
+ value: tool.args,
1462
+ schema: webSearchArgsSchema
1463
+ });
1464
+ xaiTools2.push({
1465
+ type: "web_search",
1466
+ allowed_domains: args.allowedDomains,
1467
+ excluded_domains: args.excludedDomains,
1468
+ enable_image_understanding: args.enableImageUnderstanding
1469
+ });
1470
+ break;
1471
+ }
1472
+ case "xai.x_search": {
1473
+ const args = await (0, import_provider_utils7.validateTypes)({
1474
+ value: tool.args,
1475
+ schema: xSearchArgsSchema
1476
+ });
1477
+ xaiTools2.push({
1478
+ type: "x_search",
1479
+ allowed_x_handles: args.allowedXHandles,
1480
+ excluded_x_handles: args.excludedXHandles,
1481
+ from_date: args.fromDate,
1482
+ to_date: args.toDate,
1483
+ enable_image_understanding: args.enableImageUnderstanding,
1484
+ enable_video_understanding: args.enableVideoUnderstanding
1485
+ });
1486
+ break;
1487
+ }
1488
+ case "xai.code_execution": {
1489
+ xaiTools2.push({
1490
+ type: "code_interpreter"
1491
+ });
1492
+ break;
1493
+ }
1494
+ case "xai.view_image": {
1495
+ xaiTools2.push({
1496
+ type: "view_image"
1497
+ });
1498
+ break;
1499
+ }
1500
+ case "xai.view_x_video": {
1501
+ xaiTools2.push({
1502
+ type: "view_x_video"
1503
+ });
1504
+ break;
1505
+ }
1506
+ case "xai.file_search": {
1507
+ xaiTools2.push({
1508
+ type: "file_search"
1509
+ });
1510
+ break;
1511
+ }
1512
+ case "xai.mcp": {
1513
+ xaiTools2.push({
1514
+ type: "mcp"
1515
+ });
1516
+ break;
1517
+ }
1518
+ default: {
1519
+ toolWarnings.push({
1520
+ type: "unsupported",
1521
+ feature: `provider-defined tool ${tool.name}`
1522
+ });
1523
+ break;
1524
+ }
1525
+ }
1526
+ } else {
1527
+ xaiTools2.push({
1528
+ type: "function",
1529
+ name: tool.name,
1530
+ description: tool.description,
1531
+ parameters: tool.inputSchema
1532
+ });
1533
+ }
1534
+ }
1535
+ if (toolChoice == null) {
1536
+ return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
1537
+ }
1538
+ const type = toolChoice.type;
1539
+ switch (type) {
1540
+ case "auto":
1541
+ case "none":
1542
+ return { tools: xaiTools2, toolChoice: type, toolWarnings };
1543
+ case "required":
1544
+ return { tools: xaiTools2, toolChoice: "required", toolWarnings };
1545
+ case "tool": {
1546
+ const selectedTool = toolByName.get(toolChoice.toolName);
1547
+ if (selectedTool == null) {
1548
+ return {
1549
+ tools: xaiTools2,
1550
+ toolChoice: void 0,
1551
+ toolWarnings
1552
+ };
1553
+ }
1554
+ if (selectedTool.type === "provider") {
1555
+ switch (selectedTool.id) {
1556
+ case "xai.web_search":
1557
+ return {
1558
+ tools: xaiTools2,
1559
+ toolChoice: { type: "web_search" },
1560
+ toolWarnings
1561
+ };
1562
+ case "xai.x_search":
1563
+ return {
1564
+ tools: xaiTools2,
1565
+ toolChoice: { type: "x_search" },
1566
+ toolWarnings
1567
+ };
1568
+ case "xai.code_execution":
1569
+ return {
1570
+ tools: xaiTools2,
1571
+ toolChoice: { type: "code_interpreter" },
1572
+ toolWarnings
1573
+ };
1574
+ case "xai.view_image":
1575
+ return {
1576
+ tools: xaiTools2,
1577
+ toolChoice: { type: "view_image" },
1578
+ toolWarnings
1579
+ };
1580
+ case "xai.view_x_video":
1581
+ return {
1582
+ tools: xaiTools2,
1583
+ toolChoice: { type: "view_x_video" },
1584
+ toolWarnings
1585
+ };
1586
+ case "xai.file_search":
1587
+ return {
1588
+ tools: xaiTools2,
1589
+ toolChoice: { type: "file_search" },
1590
+ toolWarnings
1591
+ };
1592
+ case "xai.mcp":
1593
+ return {
1594
+ tools: xaiTools2,
1595
+ toolChoice: { type: "mcp" },
1596
+ toolWarnings
1597
+ };
1598
+ default:
1599
+ toolWarnings.push({
1600
+ type: "unsupported",
1601
+ feature: `provider-defined tool ${selectedTool.name}`
1602
+ });
1603
+ return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
1604
+ }
1605
+ }
1606
+ return {
1607
+ tools: xaiTools2,
1608
+ toolChoice: { type: "function", name: selectedTool.name },
1609
+ toolWarnings
1610
+ };
1611
+ }
1612
+ default: {
1613
+ const _exhaustiveCheck = type;
1614
+ throw new import_provider5.UnsupportedFunctionalityError({
1615
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1616
+ });
1617
+ }
1618
+ }
1619
+ }
1620
+
1621
+ // src/responses/xai-responses-language-model.ts
1622
+ var XaiResponsesLanguageModel = class {
1623
+ constructor(modelId, config) {
1624
+ this.specificationVersion = "v3";
1625
+ this.supportedUrls = {
1626
+ "image/*": [/^https?:\/\/.*$/]
1627
+ };
1628
+ this.modelId = modelId;
1629
+ this.config = config;
1630
+ }
1631
+ get provider() {
1632
+ return this.config.provider;
1633
+ }
1634
+ async getArgs({
1635
+ prompt,
1636
+ maxOutputTokens,
1637
+ temperature,
1638
+ topP,
1639
+ stopSequences,
1640
+ seed,
1641
+ responseFormat,
1642
+ providerOptions,
1643
+ tools,
1644
+ toolChoice
1645
+ }) {
1646
+ var _a, _b, _c, _d, _e;
1647
+ const warnings = [];
1648
+ const options = (_a = await (0, import_provider_utils8.parseProviderOptions)({
1649
+ provider: "xai",
1650
+ providerOptions,
1651
+ schema: xaiResponsesProviderOptions
1652
+ })) != null ? _a : {};
1653
+ if (stopSequences != null) {
1654
+ warnings.push({ type: "unsupported", feature: "stopSequences" });
1655
+ }
1656
+ const webSearchToolName = (_b = tools == null ? void 0 : tools.find(
1657
+ (tool) => tool.type === "provider" && tool.id === "xai.web_search"
1658
+ )) == null ? void 0 : _b.name;
1659
+ const xSearchToolName = (_c = tools == null ? void 0 : tools.find(
1660
+ (tool) => tool.type === "provider" && tool.id === "xai.x_search"
1661
+ )) == null ? void 0 : _c.name;
1662
+ const codeExecutionToolName = (_d = tools == null ? void 0 : tools.find(
1663
+ (tool) => tool.type === "provider" && tool.id === "xai.code_execution"
1664
+ )) == null ? void 0 : _d.name;
1665
+ const { input, inputWarnings } = await convertToXaiResponsesInput({
1666
+ prompt,
1667
+ store: true
1668
+ });
1669
+ warnings.push(...inputWarnings);
1670
+ const {
1671
+ tools: xaiTools2,
1672
+ toolChoice: xaiToolChoice,
1673
+ toolWarnings
1674
+ } = await prepareResponsesTools({
1675
+ tools,
1676
+ toolChoice
1677
+ });
1678
+ warnings.push(...toolWarnings);
1679
+ const baseArgs = {
1680
+ model: this.modelId,
1681
+ input,
1682
+ max_output_tokens: maxOutputTokens,
1683
+ temperature,
1684
+ top_p: topP,
1685
+ seed,
1686
+ ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && {
1687
+ text: {
1688
+ format: responseFormat.schema != null ? {
1689
+ type: "json_schema",
1690
+ strict: true,
1691
+ name: (_e = responseFormat.name) != null ? _e : "response",
1692
+ description: responseFormat.description,
1693
+ schema: responseFormat.schema
1694
+ } : { type: "json_object" }
1695
+ }
1696
+ },
1697
+ ...options.reasoningEffort != null && {
1698
+ reasoning: { effort: options.reasoningEffort }
1699
+ },
1700
+ ...options.store === false && {
1701
+ store: options.store,
1702
+ include: ["reasoning.encrypted_content"]
1703
+ },
1704
+ ...options.previousResponseId != null && {
1705
+ previous_response_id: options.previousResponseId
1706
+ }
1707
+ };
1708
+ if (xaiTools2 && xaiTools2.length > 0) {
1709
+ baseArgs.tools = xaiTools2;
1710
+ }
1711
+ if (xaiToolChoice != null) {
1712
+ baseArgs.tool_choice = xaiToolChoice;
1713
+ }
1714
+ return {
1715
+ args: baseArgs,
1716
+ warnings,
1717
+ webSearchToolName,
1718
+ xSearchToolName,
1719
+ codeExecutionToolName
1720
+ };
1721
+ }
1722
+ async doGenerate(options) {
1723
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1724
+ const {
1725
+ args: body,
1726
+ warnings,
1727
+ webSearchToolName,
1728
+ xSearchToolName,
1729
+ codeExecutionToolName
1730
+ } = await this.getArgs(options);
1731
+ const {
1732
+ responseHeaders,
1733
+ value: response,
1734
+ rawValue: rawResponse
1735
+ } = await (0, import_provider_utils8.postJsonToApi)({
1736
+ url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
1737
+ headers: (0, import_provider_utils8.combineHeaders)(this.config.headers(), options.headers),
1738
+ body,
1739
+ failedResponseHandler: xaiFailedResponseHandler,
1740
+ successfulResponseHandler: (0, import_provider_utils8.createJsonResponseHandler)(
1741
+ xaiResponsesResponseSchema
1742
+ ),
1743
+ abortSignal: options.abortSignal,
1744
+ fetch: this.config.fetch
1745
+ });
1746
+ const content = [];
1747
+ const webSearchSubTools = [
1748
+ "web_search",
1749
+ "web_search_with_snippets",
1750
+ "browse_page"
1751
+ ];
1752
+ const xSearchSubTools = [
1753
+ "x_user_search",
1754
+ "x_keyword_search",
1755
+ "x_semantic_search",
1756
+ "x_thread_fetch"
1757
+ ];
1758
+ for (const part of response.output) {
1759
+ if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call") {
1760
+ let toolName = (_b = part.name) != null ? _b : "";
1761
+ if (webSearchSubTools.includes((_c = part.name) != null ? _c : "") || part.type === "web_search_call") {
1762
+ toolName = webSearchToolName != null ? webSearchToolName : "web_search";
1763
+ } else if (xSearchSubTools.includes((_d = part.name) != null ? _d : "") || part.type === "x_search_call") {
1764
+ toolName = xSearchToolName != null ? xSearchToolName : "x_search";
1765
+ } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
1766
+ toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
1767
+ }
1768
+ const toolInput = part.type === "custom_tool_call" ? (_e = part.input) != null ? _e : "" : (_f = part.arguments) != null ? _f : "";
1769
+ content.push({
1770
+ type: "tool-call",
1771
+ toolCallId: part.id,
1772
+ toolName,
1773
+ input: toolInput,
1774
+ providerExecuted: true
1775
+ });
1776
+ continue;
1777
+ }
1778
+ switch (part.type) {
1779
+ case "message": {
1780
+ for (const contentPart of part.content) {
1781
+ if (contentPart.text) {
1782
+ content.push({
1783
+ type: "text",
1784
+ text: contentPart.text
1785
+ });
1786
+ }
1787
+ if (contentPart.annotations) {
1788
+ for (const annotation of contentPart.annotations) {
1789
+ if (annotation.type === "url_citation" && "url" in annotation) {
1790
+ content.push({
1791
+ type: "source",
1792
+ sourceType: "url",
1793
+ id: this.config.generateId(),
1794
+ url: annotation.url,
1795
+ title: (_g = annotation.title) != null ? _g : annotation.url
1796
+ });
1797
+ }
1798
+ }
1799
+ }
1800
+ }
1801
+ break;
1802
+ }
1803
+ case "function_call": {
1804
+ content.push({
1805
+ type: "tool-call",
1806
+ toolCallId: part.call_id,
1807
+ toolName: part.name,
1808
+ input: part.arguments
1809
+ });
1810
+ break;
1811
+ }
1812
+ case "reasoning": {
1813
+ const summaryTexts = part.summary.map((s) => s.text).filter((text) => text && text.length > 0);
1814
+ if (summaryTexts.length > 0) {
1815
+ const reasoningText = summaryTexts.join("");
1816
+ if (part.encrypted_content || part.id) {
1817
+ content.push({
1818
+ type: "reasoning",
1819
+ text: reasoningText,
1820
+ providerMetadata: {
1821
+ xai: {
1822
+ ...part.encrypted_content && {
1823
+ reasoningEncryptedContent: part.encrypted_content
1824
+ },
1825
+ ...part.id && { itemId: part.id }
1826
+ }
1827
+ }
1828
+ });
1829
+ } else {
1830
+ content.push({
1831
+ type: "reasoning",
1832
+ text: reasoningText
1833
+ });
1834
+ }
1835
+ }
1836
+ break;
1837
+ }
1838
+ default: {
1839
+ break;
1840
+ }
1841
+ }
1842
+ }
1843
+ return {
1844
+ content,
1845
+ finishReason: {
1846
+ unified: mapXaiResponsesFinishReason(response.status),
1847
+ raw: (_h = response.status) != null ? _h : void 0
1848
+ },
1849
+ usage: convertXaiResponsesUsage(response.usage),
1850
+ request: { body },
1851
+ response: {
1852
+ ...getResponseMetadata(response),
1853
+ headers: responseHeaders,
1854
+ body: rawResponse
1855
+ },
1856
+ warnings
1857
+ };
1858
+ }
1859
+ async doStream(options) {
1860
+ var _a;
1861
+ const {
1862
+ args,
1863
+ warnings,
1864
+ webSearchToolName,
1865
+ xSearchToolName,
1866
+ codeExecutionToolName
1867
+ } = await this.getArgs(options);
1868
+ const body = {
1869
+ ...args,
1870
+ stream: true
1871
+ };
1872
+ const { responseHeaders, value: response } = await (0, import_provider_utils8.postJsonToApi)({
1873
+ url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
1874
+ headers: (0, import_provider_utils8.combineHeaders)(this.config.headers(), options.headers),
1875
+ body,
1876
+ failedResponseHandler: xaiFailedResponseHandler,
1877
+ successfulResponseHandler: (0, import_provider_utils8.createEventSourceResponseHandler)(
1878
+ xaiResponsesChunkSchema
1879
+ ),
1880
+ abortSignal: options.abortSignal,
1881
+ fetch: this.config.fetch
1882
+ });
1883
+ let finishReason = {
1884
+ unified: "other",
1885
+ raw: void 0
1886
+ };
1887
+ let usage = void 0;
1888
+ let isFirstChunk = true;
1889
+ const contentBlocks = {};
1890
+ const seenToolCalls = /* @__PURE__ */ new Set();
1891
+ const activeReasoning = {};
1892
+ const self = this;
1893
+ return {
1894
+ stream: response.pipeThrough(
1895
+ new TransformStream({
1896
+ start(controller) {
1897
+ controller.enqueue({ type: "stream-start", warnings });
1898
+ },
1899
+ transform(chunk, controller) {
1900
+ var _a2, _b, _c, _d, _e, _f, _g, _h;
1901
+ if (options.includeRawChunks) {
1902
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1903
+ }
1904
+ if (!chunk.success) {
1905
+ controller.enqueue({ type: "error", error: chunk.error });
1906
+ return;
1907
+ }
1908
+ const event = chunk.value;
1909
+ if (event.type === "response.created" || event.type === "response.in_progress") {
1910
+ if (isFirstChunk) {
1911
+ controller.enqueue({
1912
+ type: "response-metadata",
1913
+ ...getResponseMetadata(event.response)
1914
+ });
1915
+ isFirstChunk = false;
1916
+ }
1917
+ return;
1918
+ }
1919
+ if (event.type === "response.reasoning_summary_part.added") {
1920
+ const blockId = `reasoning-${event.item_id}`;
1921
+ controller.enqueue({
1922
+ type: "reasoning-start",
1923
+ id: blockId,
1924
+ providerMetadata: {
1925
+ xai: {
1926
+ itemId: event.item_id
1927
+ }
1928
+ }
1929
+ });
1930
+ }
1931
+ if (event.type === "response.reasoning_summary_text.delta") {
1932
+ const blockId = `reasoning-${event.item_id}`;
1933
+ controller.enqueue({
1934
+ type: "reasoning-delta",
1935
+ id: blockId,
1936
+ delta: event.delta,
1937
+ providerMetadata: {
1938
+ xai: {
1939
+ itemId: event.item_id
1940
+ }
1941
+ }
1942
+ });
1943
+ return;
1944
+ }
1945
+ if (event.type === "response.reasoning_summary_text.done") {
1946
+ return;
1947
+ }
1948
+ if (event.type === "response.output_text.delta") {
1949
+ const blockId = `text-${event.item_id}`;
1950
+ if (contentBlocks[blockId] == null) {
1951
+ contentBlocks[blockId] = { type: "text" };
1952
+ controller.enqueue({
1953
+ type: "text-start",
1954
+ id: blockId
1955
+ });
1956
+ }
1957
+ controller.enqueue({
1958
+ type: "text-delta",
1959
+ id: blockId,
1960
+ delta: event.delta
1961
+ });
1962
+ return;
1963
+ }
1964
+ if (event.type === "response.output_text.done") {
1965
+ if (event.annotations) {
1966
+ for (const annotation of event.annotations) {
1967
+ if (annotation.type === "url_citation" && "url" in annotation) {
1968
+ controller.enqueue({
1969
+ type: "source",
1970
+ sourceType: "url",
1971
+ id: self.config.generateId(),
1972
+ url: annotation.url,
1973
+ title: (_a2 = annotation.title) != null ? _a2 : annotation.url
1974
+ });
1975
+ }
1976
+ }
1977
+ }
1978
+ return;
1979
+ }
1980
+ if (event.type === "response.output_text.annotation.added") {
1981
+ const annotation = event.annotation;
1982
+ if (annotation.type === "url_citation" && "url" in annotation) {
1983
+ controller.enqueue({
1984
+ type: "source",
1985
+ sourceType: "url",
1986
+ id: self.config.generateId(),
1987
+ url: annotation.url,
1988
+ title: (_b = annotation.title) != null ? _b : annotation.url
1989
+ });
1990
+ }
1991
+ return;
1992
+ }
1993
+ if (event.type === "response.done" || event.type === "response.completed") {
1994
+ const response2 = event.response;
1995
+ if (response2.usage) {
1996
+ usage = convertXaiResponsesUsage(response2.usage);
1997
+ }
1998
+ if (response2.status) {
1999
+ finishReason = {
2000
+ unified: mapXaiResponsesFinishReason(response2.status),
2001
+ raw: response2.status
2002
+ };
2003
+ }
2004
+ return;
2005
+ }
2006
+ if (event.type === "response.output_item.added" || event.type === "response.output_item.done") {
2007
+ const part = event.item;
2008
+ if (part.type === "reasoning") {
2009
+ if (event.type === "response.output_item.done") {
2010
+ controller.enqueue({
2011
+ type: "reasoning-end",
2012
+ id: `reasoning-${part.id}`,
2013
+ providerMetadata: {
2014
+ xai: {
2015
+ ...part.encrypted_content && {
2016
+ reasoningEncryptedContent: part.encrypted_content
2017
+ },
2018
+ ...part.id && { itemId: part.id }
2019
+ }
2020
+ }
2021
+ });
2022
+ delete activeReasoning[part.id];
2023
+ }
2024
+ return;
2025
+ }
2026
+ if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call") {
2027
+ const webSearchSubTools = [
2028
+ "web_search",
2029
+ "web_search_with_snippets",
2030
+ "browse_page"
2031
+ ];
2032
+ const xSearchSubTools = [
2033
+ "x_user_search",
2034
+ "x_keyword_search",
2035
+ "x_semantic_search",
2036
+ "x_thread_fetch"
2037
+ ];
2038
+ let toolName = (_c = part.name) != null ? _c : "";
2039
+ if (webSearchSubTools.includes((_d = part.name) != null ? _d : "") || part.type === "web_search_call") {
2040
+ toolName = webSearchToolName != null ? webSearchToolName : "web_search";
2041
+ } else if (xSearchSubTools.includes((_e = part.name) != null ? _e : "") || part.type === "x_search_call") {
2042
+ toolName = xSearchToolName != null ? xSearchToolName : "x_search";
2043
+ } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
2044
+ toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
2045
+ }
2046
+ const toolInput = part.type === "custom_tool_call" ? (_f = part.input) != null ? _f : "" : (_g = part.arguments) != null ? _g : "";
2047
+ const shouldEmit = part.type === "custom_tool_call" ? event.type === "response.output_item.done" : !seenToolCalls.has(part.id);
2048
+ if (shouldEmit && !seenToolCalls.has(part.id)) {
2049
+ seenToolCalls.add(part.id);
2050
+ controller.enqueue({
2051
+ type: "tool-input-start",
2052
+ id: part.id,
2053
+ toolName
2054
+ });
2055
+ controller.enqueue({
2056
+ type: "tool-input-delta",
2057
+ id: part.id,
2058
+ delta: toolInput
2059
+ });
2060
+ controller.enqueue({
2061
+ type: "tool-input-end",
2062
+ id: part.id
2063
+ });
2064
+ controller.enqueue({
2065
+ type: "tool-call",
2066
+ toolCallId: part.id,
2067
+ toolName,
2068
+ input: toolInput,
2069
+ providerExecuted: true
2070
+ });
2071
+ }
2072
+ return;
2073
+ }
2074
+ if (part.type === "message") {
2075
+ for (const contentPart of part.content) {
2076
+ if (contentPart.text && contentPart.text.length > 0) {
2077
+ const blockId = `text-${part.id}`;
2078
+ if (contentBlocks[blockId] == null) {
2079
+ contentBlocks[blockId] = { type: "text" };
2080
+ controller.enqueue({
2081
+ type: "text-start",
2082
+ id: blockId
2083
+ });
2084
+ controller.enqueue({
2085
+ type: "text-delta",
2086
+ id: blockId,
2087
+ delta: contentPart.text
2088
+ });
2089
+ }
2090
+ }
2091
+ if (contentPart.annotations) {
2092
+ for (const annotation of contentPart.annotations) {
2093
+ if (annotation.type === "url_citation" && "url" in annotation) {
2094
+ controller.enqueue({
2095
+ type: "source",
2096
+ sourceType: "url",
2097
+ id: self.config.generateId(),
2098
+ url: annotation.url,
2099
+ title: (_h = annotation.title) != null ? _h : annotation.url
2100
+ });
2101
+ }
2102
+ }
2103
+ }
2104
+ }
2105
+ } else if (part.type === "function_call") {
2106
+ if (!seenToolCalls.has(part.call_id)) {
2107
+ seenToolCalls.add(part.call_id);
2108
+ controller.enqueue({
2109
+ type: "tool-input-start",
2110
+ id: part.call_id,
2111
+ toolName: part.name
2112
+ });
2113
+ controller.enqueue({
2114
+ type: "tool-input-delta",
2115
+ id: part.call_id,
2116
+ delta: part.arguments
2117
+ });
2118
+ controller.enqueue({
2119
+ type: "tool-input-end",
2120
+ id: part.call_id
2121
+ });
2122
+ controller.enqueue({
2123
+ type: "tool-call",
2124
+ toolCallId: part.call_id,
2125
+ toolName: part.name,
2126
+ input: part.arguments
2127
+ });
2128
+ }
2129
+ }
2130
+ }
2131
+ },
2132
+ flush(controller) {
2133
+ for (const [blockId, block] of Object.entries(contentBlocks)) {
2134
+ if (block.type === "text") {
2135
+ controller.enqueue({
2136
+ type: "text-end",
2137
+ id: blockId
2138
+ });
2139
+ }
2140
+ }
2141
+ controller.enqueue({ type: "finish", finishReason, usage });
2142
+ }
2143
+ })
2144
+ ),
2145
+ request: { body },
2146
+ response: { headers: responseHeaders }
2147
+ };
2148
+ }
2149
+ };
2150
+
2151
+ // src/tool/code-execution.ts
2152
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
2153
+ var import_v48 = require("zod/v4");
2154
+ var codeExecutionOutputSchema = import_v48.z.object({
2155
+ output: import_v48.z.string().describe("the output of the code execution"),
2156
+ error: import_v48.z.string().optional().describe("any error that occurred")
2157
+ });
2158
+ var codeExecutionToolFactory = (0, import_provider_utils9.createProviderToolFactoryWithOutputSchema)({
2159
+ id: "xai.code_execution",
2160
+ inputSchema: import_v48.z.object({}).describe("no input parameters"),
2161
+ outputSchema: codeExecutionOutputSchema
2162
+ });
2163
+ var codeExecution = (args = {}) => codeExecutionToolFactory(args);
2164
+
2165
+ // src/tool/view-image.ts
2166
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
2167
+ var import_v49 = require("zod/v4");
2168
+ var viewImageOutputSchema = import_v49.z.object({
2169
+ description: import_v49.z.string().describe("description of the image"),
2170
+ objects: import_v49.z.array(import_v49.z.string()).optional().describe("objects detected in the image")
2171
+ });
2172
+ var viewImageToolFactory = (0, import_provider_utils10.createProviderToolFactoryWithOutputSchema)({
2173
+ id: "xai.view_image",
2174
+ inputSchema: import_v49.z.object({}).describe("no input parameters"),
2175
+ outputSchema: viewImageOutputSchema
2176
+ });
2177
+ var viewImage = (args = {}) => viewImageToolFactory(args);
2178
+
2179
+ // src/tool/view-x-video.ts
2180
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
2181
+ var import_v410 = require("zod/v4");
2182
+ var viewXVideoOutputSchema = import_v410.z.object({
2183
+ transcript: import_v410.z.string().optional().describe("transcript of the video"),
2184
+ description: import_v410.z.string().describe("description of the video content"),
2185
+ duration: import_v410.z.number().optional().describe("duration in seconds")
2186
+ });
2187
+ var viewXVideoToolFactory = (0, import_provider_utils11.createProviderToolFactoryWithOutputSchema)({
2188
+ id: "xai.view_x_video",
2189
+ inputSchema: import_v410.z.object({}).describe("no input parameters"),
2190
+ outputSchema: viewXVideoOutputSchema
2191
+ });
2192
+ var viewXVideo = (args = {}) => viewXVideoToolFactory(args);
2193
+
2194
+ // src/tool/index.ts
2195
+ var xaiTools = {
2196
+ codeExecution,
2197
+ viewImage,
2198
+ viewXVideo,
2199
+ webSearch,
2200
+ xSearch
2201
+ };
2202
+
2203
+ // src/version.ts
2204
+ var VERSION = true ? "0.0.0-1c33ba03-20260114162300" : "0.0.0-test";
2205
+
2206
+ // src/xai-provider.ts
2207
+ var xaiErrorStructure = {
2208
+ errorSchema: xaiErrorDataSchema,
2209
+ errorToMessage: (data) => data.error.message
2210
+ };
2211
+ function createXai(options = {}) {
2212
+ var _a;
2213
+ const baseURL = (0, import_provider_utils12.withoutTrailingSlash)(
2214
+ (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
2215
+ );
2216
+ const getHeaders = () => (0, import_provider_utils12.withUserAgentSuffix)(
2217
+ {
2218
+ Authorization: `Bearer ${(0, import_provider_utils12.loadApiKey)({
2219
+ apiKey: options.apiKey,
2220
+ environmentVariableName: "XAI_API_KEY",
2221
+ description: "xAI API key"
2222
+ })}`,
2223
+ ...options.headers
2224
+ },
2225
+ `ai-sdk/xai/${VERSION}`
2226
+ );
2227
+ const createChatLanguageModel = (modelId) => {
2228
+ return new XaiChatLanguageModel(modelId, {
2229
+ provider: "xai.chat",
2230
+ baseURL,
2231
+ headers: getHeaders,
2232
+ generateId: import_provider_utils12.generateId,
2233
+ fetch: options.fetch
2234
+ });
2235
+ };
2236
+ const createResponsesLanguageModel = (modelId) => {
2237
+ return new XaiResponsesLanguageModel(modelId, {
2238
+ provider: "xai.responses",
2239
+ baseURL,
2240
+ headers: getHeaders,
2241
+ generateId: import_provider_utils12.generateId,
2242
+ fetch: options.fetch
2243
+ });
2244
+ };
2245
+ const createImageModel = (modelId) => {
2246
+ return new import_openai_compatible.OpenAICompatibleImageModel(modelId, {
2247
+ provider: "xai.image",
2248
+ url: ({ path }) => `${baseURL}${path}`,
2249
+ headers: getHeaders,
2250
+ fetch: options.fetch,
2251
+ errorStructure: xaiErrorStructure
2252
+ });
2253
+ };
2254
+ const provider = (modelId) => createChatLanguageModel(modelId);
2255
+ provider.specificationVersion = "v3";
2256
+ provider.languageModel = createChatLanguageModel;
2257
+ provider.chat = createChatLanguageModel;
2258
+ provider.responses = createResponsesLanguageModel;
2259
+ provider.embeddingModel = (modelId) => {
2260
+ throw new import_provider6.NoSuchModelError({ modelId, modelType: "embeddingModel" });
2261
+ };
2262
+ provider.textEmbeddingModel = provider.embeddingModel;
2263
+ provider.imageModel = createImageModel;
2264
+ provider.image = createImageModel;
2265
+ provider.tools = xaiTools;
2266
+ return provider;
2267
+ }
2268
+ var xai = createXai();
2269
+ // Annotate the CommonJS export names for ESM import in node:
2270
+ 0 && (module.exports = {
2271
+ VERSION,
2272
+ codeExecution,
2273
+ createXai,
2274
+ viewImage,
2275
+ viewXVideo,
2276
+ webSearch,
2277
+ xSearch,
2278
+ xai,
2279
+ xaiTools
2280
+ });
2281
+ //# sourceMappingURL=index.js.map