@ai-sdk/xai 4.0.0-beta.34 → 4.0.0-beta.35

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 DELETED
@@ -1,3390 +0,0 @@
1
- // src/xai-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- generateId,
7
- loadApiKey,
8
- withoutTrailingSlash,
9
- withUserAgentSuffix
10
- } from "@ai-sdk/provider-utils";
11
-
12
- // src/xai-chat-language-model.ts
13
- import {
14
- APICallError
15
- } from "@ai-sdk/provider";
16
- import {
17
- combineHeaders,
18
- createEventSourceResponseHandler,
19
- createJsonResponseHandler,
20
- extractResponseHeaders,
21
- isCustomReasoning,
22
- mapReasoningToProviderEffort,
23
- parseProviderOptions,
24
- postJsonToApi,
25
- safeParseJSON
26
- } from "@ai-sdk/provider-utils";
27
- import { z as z3 } from "zod/v4";
28
-
29
- // src/convert-to-xai-chat-messages.ts
30
- import {
31
- UnsupportedFunctionalityError
32
- } from "@ai-sdk/provider";
33
- import {
34
- convertToBase64,
35
- isProviderReference,
36
- resolveProviderReference
37
- } from "@ai-sdk/provider-utils";
38
- function convertToXaiChatMessages(prompt) {
39
- var _a;
40
- const messages = [];
41
- const warnings = [];
42
- for (const { role, content } of prompt) {
43
- switch (role) {
44
- case "system": {
45
- messages.push({ role: "system", content });
46
- break;
47
- }
48
- case "user": {
49
- if (content.length === 1 && content[0].type === "text") {
50
- messages.push({ role: "user", content: content[0].text });
51
- break;
52
- }
53
- messages.push({
54
- role: "user",
55
- content: content.map((part) => {
56
- switch (part.type) {
57
- case "text": {
58
- return { type: "text", text: part.text };
59
- }
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
- }
72
- if (part.mediaType.startsWith("image/")) {
73
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
74
- return {
75
- type: "image_url",
76
- image_url: {
77
- url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
78
- }
79
- };
80
- } else {
81
- throw new UnsupportedFunctionalityError({
82
- functionality: `file part media type ${part.mediaType}`
83
- });
84
- }
85
- }
86
- }
87
- })
88
- });
89
- break;
90
- }
91
- case "assistant": {
92
- let text = "";
93
- const toolCalls = [];
94
- for (const part of content) {
95
- switch (part.type) {
96
- case "text": {
97
- text += part.text;
98
- break;
99
- }
100
- case "tool-call": {
101
- toolCalls.push({
102
- id: part.toolCallId,
103
- type: "function",
104
- function: {
105
- name: part.toolName,
106
- arguments: JSON.stringify(part.input)
107
- }
108
- });
109
- break;
110
- }
111
- }
112
- }
113
- messages.push({
114
- role: "assistant",
115
- content: text,
116
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
117
- });
118
- break;
119
- }
120
- case "tool": {
121
- for (const toolResponse of content) {
122
- if (toolResponse.type === "tool-approval-response") {
123
- continue;
124
- }
125
- const output = toolResponse.output;
126
- let contentValue;
127
- switch (output.type) {
128
- case "text":
129
- case "error-text":
130
- contentValue = output.value;
131
- break;
132
- case "execution-denied":
133
- contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
134
- break;
135
- case "content":
136
- case "json":
137
- case "error-json":
138
- contentValue = JSON.stringify(output.value);
139
- break;
140
- }
141
- messages.push({
142
- role: "tool",
143
- tool_call_id: toolResponse.toolCallId,
144
- content: contentValue
145
- });
146
- }
147
- break;
148
- }
149
- default: {
150
- const _exhaustiveCheck = role;
151
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
152
- }
153
- }
154
- }
155
- return { messages, warnings };
156
- }
157
-
158
- // src/convert-xai-chat-usage.ts
159
- function convertXaiChatUsage(usage) {
160
- var _a, _b, _c, _d;
161
- const cacheReadTokens = (_b = (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
162
- const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
163
- const promptTokensIncludesCached = cacheReadTokens <= usage.prompt_tokens;
164
- return {
165
- inputTokens: {
166
- total: promptTokensIncludesCached ? usage.prompt_tokens : usage.prompt_tokens + cacheReadTokens,
167
- noCache: promptTokensIncludesCached ? usage.prompt_tokens - cacheReadTokens : usage.prompt_tokens,
168
- cacheRead: cacheReadTokens,
169
- cacheWrite: void 0
170
- },
171
- outputTokens: {
172
- total: usage.completion_tokens + reasoningTokens,
173
- text: usage.completion_tokens,
174
- reasoning: reasoningTokens
175
- },
176
- raw: usage
177
- };
178
- }
179
-
180
- // src/get-response-metadata.ts
181
- function getResponseMetadata({
182
- id,
183
- model,
184
- created,
185
- created_at
186
- }) {
187
- const unixTime = created != null ? created : created_at;
188
- return {
189
- id: id != null ? id : void 0,
190
- modelId: model != null ? model : void 0,
191
- timestamp: unixTime != null ? new Date(unixTime * 1e3) : void 0
192
- };
193
- }
194
-
195
- // src/map-xai-finish-reason.ts
196
- function mapXaiFinishReason(finishReason) {
197
- switch (finishReason) {
198
- case "stop":
199
- return "stop";
200
- case "length":
201
- return "length";
202
- case "tool_calls":
203
- case "function_call":
204
- return "tool-calls";
205
- case "content_filter":
206
- return "content-filter";
207
- default:
208
- return "other";
209
- }
210
- }
211
-
212
- // src/xai-chat-options.ts
213
- import { z } from "zod/v4";
214
- var webSourceSchema = z.object({
215
- type: z.literal("web"),
216
- country: z.string().length(2).optional(),
217
- excludedWebsites: z.array(z.string()).max(5).optional(),
218
- allowedWebsites: z.array(z.string()).max(5).optional(),
219
- safeSearch: z.boolean().optional()
220
- });
221
- var xSourceSchema = z.object({
222
- type: z.literal("x"),
223
- excludedXHandles: z.array(z.string()).optional(),
224
- includedXHandles: z.array(z.string()).optional(),
225
- postFavoriteCount: z.number().int().optional(),
226
- postViewCount: z.number().int().optional(),
227
- /**
228
- * @deprecated use `includedXHandles` instead
229
- */
230
- xHandles: z.array(z.string()).optional()
231
- });
232
- var newsSourceSchema = z.object({
233
- type: z.literal("news"),
234
- country: z.string().length(2).optional(),
235
- excludedWebsites: z.array(z.string()).max(5).optional(),
236
- safeSearch: z.boolean().optional()
237
- });
238
- var rssSourceSchema = z.object({
239
- type: z.literal("rss"),
240
- links: z.array(z.string().url()).max(1)
241
- // currently only supports one RSS link
242
- });
243
- var searchSourceSchema = z.discriminatedUnion("type", [
244
- webSourceSchema,
245
- xSourceSchema,
246
- newsSourceSchema,
247
- rssSourceSchema
248
- ]);
249
- var xaiLanguageModelChatOptions = z.object({
250
- reasoningEffort: z.enum(["low", "high"]).optional(),
251
- logprobs: z.boolean().optional(),
252
- topLogprobs: z.number().int().min(0).max(8).optional(),
253
- /**
254
- * Whether to enable parallel function calling during tool use.
255
- * When true, the model can call multiple functions in parallel.
256
- * When false, the model will call functions sequentially.
257
- * Defaults to true.
258
- */
259
- parallel_function_calling: z.boolean().optional(),
260
- searchParameters: z.object({
261
- /**
262
- * search mode preference
263
- * - "off": disables search completely
264
- * - "auto": model decides whether to search (default)
265
- * - "on": always enables search
266
- */
267
- mode: z.enum(["off", "auto", "on"]),
268
- /**
269
- * whether to return citations in the response
270
- * defaults to true
271
- */
272
- returnCitations: z.boolean().optional(),
273
- /**
274
- * start date for search data (ISO8601 format: YYYY-MM-DD)
275
- */
276
- fromDate: z.string().optional(),
277
- /**
278
- * end date for search data (ISO8601 format: YYYY-MM-DD)
279
- */
280
- toDate: z.string().optional(),
281
- /**
282
- * maximum number of search results to consider
283
- * defaults to 20
284
- */
285
- maxSearchResults: z.number().min(1).max(50).optional(),
286
- /**
287
- * data sources to search from.
288
- * defaults to [{ type: 'web' }, { type: 'x' }] if not specified.
289
- *
290
- * @example
291
- * sources: [{ type: 'web', country: 'US' }, { type: 'x' }]
292
- */
293
- sources: z.array(searchSourceSchema).optional()
294
- }).optional()
295
- });
296
-
297
- // src/xai-error.ts
298
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
299
- import { z as z2 } from "zod/v4";
300
- var xaiErrorDataSchema = z2.object({
301
- error: z2.object({
302
- message: z2.string(),
303
- type: z2.string().nullish(),
304
- param: z2.any().nullish(),
305
- code: z2.union([z2.string(), z2.number()]).nullish()
306
- })
307
- });
308
- var xaiFailedResponseHandler = createJsonErrorResponseHandler({
309
- errorSchema: xaiErrorDataSchema,
310
- errorToMessage: (data) => data.error.message
311
- });
312
-
313
- // src/xai-prepare-tools.ts
314
- import {
315
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
316
- } from "@ai-sdk/provider";
317
- function prepareTools({
318
- tools,
319
- toolChoice
320
- }) {
321
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
322
- const toolWarnings = [];
323
- if (tools == null) {
324
- return { tools: void 0, toolChoice: void 0, toolWarnings };
325
- }
326
- const xaiTools2 = [];
327
- for (const tool of tools) {
328
- if (tool.type === "provider") {
329
- toolWarnings.push({
330
- type: "unsupported",
331
- feature: `provider-defined tool ${tool.name}`
332
- });
333
- } else {
334
- xaiTools2.push({
335
- type: "function",
336
- function: {
337
- name: tool.name,
338
- description: tool.description,
339
- parameters: tool.inputSchema,
340
- ...tool.strict != null ? { strict: tool.strict } : {}
341
- }
342
- });
343
- }
344
- }
345
- if (toolChoice == null) {
346
- return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
347
- }
348
- const type = toolChoice.type;
349
- switch (type) {
350
- case "auto":
351
- case "none":
352
- return { tools: xaiTools2, toolChoice: type, toolWarnings };
353
- case "required":
354
- return { tools: xaiTools2, toolChoice: "required", toolWarnings };
355
- case "tool":
356
- return {
357
- tools: xaiTools2,
358
- toolChoice: {
359
- type: "function",
360
- function: { name: toolChoice.toolName }
361
- },
362
- toolWarnings
363
- };
364
- default: {
365
- const _exhaustiveCheck = type;
366
- throw new UnsupportedFunctionalityError2({
367
- functionality: `tool choice type: ${_exhaustiveCheck}`
368
- });
369
- }
370
- }
371
- }
372
-
373
- // src/xai-chat-language-model.ts
374
- var XaiChatLanguageModel = class {
375
- constructor(modelId, config) {
376
- this.specificationVersion = "v4";
377
- this.supportedUrls = {
378
- "image/*": [/^https?:\/\/.*$/]
379
- };
380
- this.modelId = modelId;
381
- this.config = config;
382
- }
383
- get provider() {
384
- return this.config.provider;
385
- }
386
- async getArgs({
387
- prompt,
388
- maxOutputTokens,
389
- temperature,
390
- topP,
391
- topK,
392
- frequencyPenalty,
393
- presencePenalty,
394
- stopSequences,
395
- seed,
396
- reasoning,
397
- responseFormat,
398
- providerOptions,
399
- tools,
400
- toolChoice
401
- }) {
402
- var _a, _b, _c, _d;
403
- const warnings = [];
404
- const options = (_a = await parseProviderOptions({
405
- provider: "xai",
406
- providerOptions,
407
- schema: xaiLanguageModelChatOptions
408
- })) != null ? _a : {};
409
- if (topK != null) {
410
- warnings.push({ type: "unsupported", feature: "topK" });
411
- }
412
- if (frequencyPenalty != null) {
413
- warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
414
- }
415
- if (presencePenalty != null) {
416
- warnings.push({ type: "unsupported", feature: "presencePenalty" });
417
- }
418
- if (stopSequences != null) {
419
- warnings.push({ type: "unsupported", feature: "stopSequences" });
420
- }
421
- const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
422
- warnings.push(...messageWarnings);
423
- const {
424
- tools: xaiTools2,
425
- toolChoice: xaiToolChoice,
426
- toolWarnings
427
- } = prepareTools({
428
- tools,
429
- toolChoice
430
- });
431
- warnings.push(...toolWarnings);
432
- const baseArgs = {
433
- // model id
434
- model: this.modelId,
435
- // standard generation settings
436
- logprobs: options.logprobs === true || options.topLogprobs != null ? true : void 0,
437
- top_logprobs: options.topLogprobs,
438
- max_completion_tokens: maxOutputTokens,
439
- temperature,
440
- top_p: topP,
441
- seed,
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,
453
- // parallel function calling
454
- parallel_function_calling: options.parallel_function_calling,
455
- // response format
456
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
457
- type: "json_schema",
458
- json_schema: {
459
- name: (_c = responseFormat.name) != null ? _c : "response",
460
- schema: responseFormat.schema,
461
- strict: true
462
- }
463
- } : { type: "json_object" } : void 0,
464
- // search parameters
465
- search_parameters: options.searchParameters ? {
466
- mode: options.searchParameters.mode,
467
- return_citations: options.searchParameters.returnCitations,
468
- from_date: options.searchParameters.fromDate,
469
- to_date: options.searchParameters.toDate,
470
- max_search_results: options.searchParameters.maxSearchResults,
471
- sources: (_d = options.searchParameters.sources) == null ? void 0 : _d.map((source) => {
472
- var _a2;
473
- return {
474
- type: source.type,
475
- ...source.type === "web" && {
476
- country: source.country,
477
- excluded_websites: source.excludedWebsites,
478
- allowed_websites: source.allowedWebsites,
479
- safe_search: source.safeSearch
480
- },
481
- ...source.type === "x" && {
482
- excluded_x_handles: source.excludedXHandles,
483
- included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
484
- post_favorite_count: source.postFavoriteCount,
485
- post_view_count: source.postViewCount
486
- },
487
- ...source.type === "news" && {
488
- country: source.country,
489
- excluded_websites: source.excludedWebsites,
490
- safe_search: source.safeSearch
491
- },
492
- ...source.type === "rss" && {
493
- links: source.links
494
- }
495
- };
496
- })
497
- } : void 0,
498
- // messages in xai format
499
- messages,
500
- // tools in xai format
501
- tools: xaiTools2,
502
- tool_choice: xaiToolChoice
503
- };
504
- return {
505
- args: baseArgs,
506
- warnings
507
- };
508
- }
509
- async doGenerate(options) {
510
- var _a, _b;
511
- const { args: body, warnings } = await this.getArgs(options);
512
- const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
513
- const {
514
- responseHeaders,
515
- value: response,
516
- rawValue: rawResponse
517
- } = await postJsonToApi({
518
- url,
519
- headers: combineHeaders(this.config.headers(), options.headers),
520
- body,
521
- failedResponseHandler: xaiFailedResponseHandler,
522
- successfulResponseHandler: createJsonResponseHandler(
523
- xaiChatResponseSchema
524
- ),
525
- abortSignal: options.abortSignal,
526
- fetch: this.config.fetch
527
- });
528
- if (response.error != null) {
529
- throw new APICallError({
530
- message: response.error,
531
- url,
532
- requestBodyValues: body,
533
- statusCode: 200,
534
- responseHeaders,
535
- responseBody: JSON.stringify(rawResponse),
536
- isRetryable: response.code === "The service is currently unavailable"
537
- });
538
- }
539
- const choice = response.choices[0];
540
- const content = [];
541
- if (choice.message.content != null && choice.message.content.length > 0) {
542
- let text = choice.message.content;
543
- const lastMessage = body.messages[body.messages.length - 1];
544
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
545
- text = "";
546
- }
547
- if (text.length > 0) {
548
- content.push({ type: "text", text });
549
- }
550
- }
551
- if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
552
- content.push({
553
- type: "reasoning",
554
- text: choice.message.reasoning_content
555
- });
556
- }
557
- if (choice.message.tool_calls != null) {
558
- for (const toolCall of choice.message.tool_calls) {
559
- content.push({
560
- type: "tool-call",
561
- toolCallId: toolCall.id,
562
- toolName: toolCall.function.name,
563
- input: toolCall.function.arguments
564
- });
565
- }
566
- }
567
- if (response.citations != null) {
568
- for (const url2 of response.citations) {
569
- content.push({
570
- type: "source",
571
- sourceType: "url",
572
- id: this.config.generateId(),
573
- url: url2
574
- });
575
- }
576
- }
577
- return {
578
- content,
579
- finishReason: {
580
- unified: mapXaiFinishReason(choice.finish_reason),
581
- raw: (_b = choice.finish_reason) != null ? _b : void 0
582
- },
583
- usage: response.usage ? convertXaiChatUsage(response.usage) : {
584
- inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
585
- outputTokens: { total: 0, text: 0, reasoning: 0 }
586
- },
587
- request: { body },
588
- response: {
589
- ...getResponseMetadata(response),
590
- headers: responseHeaders,
591
- body: rawResponse
592
- },
593
- warnings
594
- };
595
- }
596
- async doStream(options) {
597
- var _a;
598
- const { args, warnings } = await this.getArgs(options);
599
- const body = {
600
- ...args,
601
- stream: true,
602
- stream_options: {
603
- include_usage: true
604
- }
605
- };
606
- const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
607
- const { responseHeaders, value: response } = await postJsonToApi({
608
- url,
609
- headers: combineHeaders(this.config.headers(), options.headers),
610
- body,
611
- failedResponseHandler: xaiFailedResponseHandler,
612
- successfulResponseHandler: async ({ response: response2 }) => {
613
- const responseHeaders2 = extractResponseHeaders(response2);
614
- const contentType = response2.headers.get("content-type");
615
- if (contentType == null ? void 0 : contentType.includes("application/json")) {
616
- const responseBody = await response2.text();
617
- const parsedError = await safeParseJSON({
618
- text: responseBody,
619
- schema: xaiStreamErrorSchema
620
- });
621
- if (parsedError.success) {
622
- throw new APICallError({
623
- message: parsedError.value.error,
624
- url,
625
- requestBodyValues: body,
626
- statusCode: 200,
627
- responseHeaders: responseHeaders2,
628
- responseBody,
629
- isRetryable: parsedError.value.code === "The service is currently unavailable"
630
- });
631
- }
632
- throw new APICallError({
633
- message: "Invalid JSON response",
634
- url,
635
- requestBodyValues: body,
636
- statusCode: 200,
637
- responseHeaders: responseHeaders2,
638
- responseBody
639
- });
640
- }
641
- return createEventSourceResponseHandler(xaiChatChunkSchema)({
642
- response: response2,
643
- url,
644
- requestBodyValues: body
645
- });
646
- },
647
- abortSignal: options.abortSignal,
648
- fetch: this.config.fetch
649
- });
650
- let finishReason = {
651
- unified: "other",
652
- raw: void 0
653
- };
654
- let usage = void 0;
655
- let isFirstChunk = true;
656
- const contentBlocks = {};
657
- const lastReasoningDeltas = {};
658
- let activeReasoningBlockId = void 0;
659
- const self = this;
660
- return {
661
- stream: response.pipeThrough(
662
- new TransformStream({
663
- start(controller) {
664
- controller.enqueue({ type: "stream-start", warnings });
665
- },
666
- transform(chunk, controller) {
667
- if (options.includeRawChunks) {
668
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
669
- }
670
- if (!chunk.success) {
671
- controller.enqueue({ type: "error", error: chunk.error });
672
- return;
673
- }
674
- const value = chunk.value;
675
- if (isFirstChunk) {
676
- controller.enqueue({
677
- type: "response-metadata",
678
- ...getResponseMetadata(value)
679
- });
680
- isFirstChunk = false;
681
- }
682
- if (value.citations != null) {
683
- for (const url2 of value.citations) {
684
- controller.enqueue({
685
- type: "source",
686
- sourceType: "url",
687
- id: self.config.generateId(),
688
- url: url2
689
- });
690
- }
691
- }
692
- if (value.usage != null) {
693
- usage = convertXaiChatUsage(value.usage);
694
- }
695
- const choice = value.choices[0];
696
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
697
- finishReason = {
698
- unified: mapXaiFinishReason(choice.finish_reason),
699
- raw: choice.finish_reason
700
- };
701
- }
702
- if ((choice == null ? void 0 : choice.delta) == null) {
703
- return;
704
- }
705
- const delta = choice.delta;
706
- const choiceIndex = choice.index;
707
- if (delta.content != null && delta.content.length > 0) {
708
- const textContent = delta.content;
709
- if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
710
- controller.enqueue({
711
- type: "reasoning-end",
712
- id: activeReasoningBlockId
713
- });
714
- contentBlocks[activeReasoningBlockId].ended = true;
715
- activeReasoningBlockId = void 0;
716
- }
717
- const lastMessage = body.messages[body.messages.length - 1];
718
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
719
- return;
720
- }
721
- const blockId = `text-${value.id || choiceIndex}`;
722
- if (contentBlocks[blockId] == null) {
723
- contentBlocks[blockId] = { type: "text", ended: false };
724
- controller.enqueue({
725
- type: "text-start",
726
- id: blockId
727
- });
728
- }
729
- controller.enqueue({
730
- type: "text-delta",
731
- id: blockId,
732
- delta: textContent
733
- });
734
- }
735
- if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
736
- const blockId = `reasoning-${value.id || choiceIndex}`;
737
- if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
738
- return;
739
- }
740
- lastReasoningDeltas[blockId] = delta.reasoning_content;
741
- if (contentBlocks[blockId] == null) {
742
- contentBlocks[blockId] = { type: "reasoning", ended: false };
743
- activeReasoningBlockId = blockId;
744
- controller.enqueue({
745
- type: "reasoning-start",
746
- id: blockId
747
- });
748
- }
749
- controller.enqueue({
750
- type: "reasoning-delta",
751
- id: blockId,
752
- delta: delta.reasoning_content
753
- });
754
- }
755
- if (delta.tool_calls != null) {
756
- if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
757
- controller.enqueue({
758
- type: "reasoning-end",
759
- id: activeReasoningBlockId
760
- });
761
- contentBlocks[activeReasoningBlockId].ended = true;
762
- activeReasoningBlockId = void 0;
763
- }
764
- for (const toolCall of delta.tool_calls) {
765
- const toolCallId = toolCall.id;
766
- controller.enqueue({
767
- type: "tool-input-start",
768
- id: toolCallId,
769
- toolName: toolCall.function.name
770
- });
771
- controller.enqueue({
772
- type: "tool-input-delta",
773
- id: toolCallId,
774
- delta: toolCall.function.arguments
775
- });
776
- controller.enqueue({
777
- type: "tool-input-end",
778
- id: toolCallId
779
- });
780
- controller.enqueue({
781
- type: "tool-call",
782
- toolCallId,
783
- toolName: toolCall.function.name,
784
- input: toolCall.function.arguments
785
- });
786
- }
787
- }
788
- },
789
- flush(controller) {
790
- for (const [blockId, block] of Object.entries(contentBlocks)) {
791
- if (!block.ended) {
792
- controller.enqueue({
793
- type: block.type === "text" ? "text-end" : "reasoning-end",
794
- id: blockId
795
- });
796
- }
797
- }
798
- controller.enqueue({
799
- type: "finish",
800
- finishReason,
801
- usage: usage != null ? usage : {
802
- inputTokens: {
803
- total: 0,
804
- noCache: 0,
805
- cacheRead: 0,
806
- cacheWrite: 0
807
- },
808
- outputTokens: { total: 0, text: 0, reasoning: 0 }
809
- }
810
- });
811
- }
812
- })
813
- ),
814
- request: { body },
815
- response: { headers: responseHeaders }
816
- };
817
- }
818
- };
819
- var xaiUsageSchema = z3.object({
820
- prompt_tokens: z3.number(),
821
- completion_tokens: z3.number(),
822
- total_tokens: z3.number(),
823
- prompt_tokens_details: z3.object({
824
- text_tokens: z3.number().nullish(),
825
- audio_tokens: z3.number().nullish(),
826
- image_tokens: z3.number().nullish(),
827
- cached_tokens: z3.number().nullish()
828
- }).nullish(),
829
- completion_tokens_details: z3.object({
830
- reasoning_tokens: z3.number().nullish(),
831
- audio_tokens: z3.number().nullish(),
832
- accepted_prediction_tokens: z3.number().nullish(),
833
- rejected_prediction_tokens: z3.number().nullish()
834
- }).nullish()
835
- });
836
- var xaiChatResponseSchema = z3.object({
837
- id: z3.string().nullish(),
838
- created: z3.number().nullish(),
839
- model: z3.string().nullish(),
840
- choices: z3.array(
841
- z3.object({
842
- message: z3.object({
843
- role: z3.literal("assistant"),
844
- content: z3.string().nullish(),
845
- reasoning_content: z3.string().nullish(),
846
- tool_calls: z3.array(
847
- z3.object({
848
- id: z3.string(),
849
- type: z3.literal("function"),
850
- function: z3.object({
851
- name: z3.string(),
852
- arguments: z3.string()
853
- })
854
- })
855
- ).nullish()
856
- }),
857
- index: z3.number(),
858
- finish_reason: z3.string().nullish()
859
- })
860
- ).nullish(),
861
- object: z3.literal("chat.completion").nullish(),
862
- usage: xaiUsageSchema.nullish(),
863
- citations: z3.array(z3.string().url()).nullish(),
864
- code: z3.string().nullish(),
865
- error: z3.string().nullish()
866
- });
867
- var xaiChatChunkSchema = z3.object({
868
- id: z3.string().nullish(),
869
- created: z3.number().nullish(),
870
- model: z3.string().nullish(),
871
- choices: z3.array(
872
- z3.object({
873
- delta: z3.object({
874
- role: z3.enum(["assistant"]).optional(),
875
- content: z3.string().nullish(),
876
- reasoning_content: z3.string().nullish(),
877
- tool_calls: z3.array(
878
- z3.object({
879
- id: z3.string(),
880
- type: z3.literal("function"),
881
- function: z3.object({
882
- name: z3.string(),
883
- arguments: z3.string()
884
- })
885
- })
886
- ).nullish()
887
- }),
888
- finish_reason: z3.string().nullish(),
889
- index: z3.number()
890
- })
891
- ),
892
- usage: xaiUsageSchema.nullish(),
893
- citations: z3.array(z3.string().url()).nullish()
894
- });
895
- var xaiStreamErrorSchema = z3.object({
896
- code: z3.string(),
897
- error: z3.string()
898
- });
899
-
900
- // src/xai-image-model.ts
901
- import {
902
- combineHeaders as combineHeaders2,
903
- convertImageModelFileToDataUri,
904
- createBinaryResponseHandler,
905
- createJsonResponseHandler as createJsonResponseHandler2,
906
- createStatusCodeErrorResponseHandler,
907
- getFromApi,
908
- parseProviderOptions as parseProviderOptions2,
909
- postJsonToApi as postJsonToApi2
910
- } from "@ai-sdk/provider-utils";
911
- import { z as z5 } from "zod/v4";
912
-
913
- // src/xai-image-options.ts
914
- import { z as z4 } from "zod/v4";
915
- var xaiImageModelOptions = z4.object({
916
- aspect_ratio: z4.string().optional(),
917
- output_format: z4.string().optional(),
918
- sync_mode: z4.boolean().optional(),
919
- resolution: z4.enum(["1k", "2k"]).optional(),
920
- quality: z4.enum(["low", "medium", "high"]).optional(),
921
- user: z4.string().optional()
922
- });
923
-
924
- // src/xai-image-model.ts
925
- var XaiImageModel = class {
926
- constructor(modelId, config) {
927
- this.modelId = modelId;
928
- this.config = config;
929
- this.specificationVersion = "v4";
930
- this.maxImagesPerCall = 3;
931
- }
932
- get provider() {
933
- return this.config.provider;
934
- }
935
- async doGenerate({
936
- prompt,
937
- n,
938
- size,
939
- aspectRatio,
940
- seed,
941
- providerOptions,
942
- headers,
943
- abortSignal,
944
- files,
945
- mask
946
- }) {
947
- var _a, _b, _c, _d, _e;
948
- const warnings = [];
949
- if (size != null) {
950
- warnings.push({
951
- type: "unsupported",
952
- feature: "size",
953
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
954
- });
955
- }
956
- if (seed != null) {
957
- warnings.push({
958
- type: "unsupported",
959
- feature: "seed"
960
- });
961
- }
962
- if (mask != null) {
963
- warnings.push({
964
- type: "unsupported",
965
- feature: "mask"
966
- });
967
- }
968
- const xaiOptions = await parseProviderOptions2({
969
- provider: "xai",
970
- providerOptions,
971
- schema: xaiImageModelOptions
972
- });
973
- const hasFiles = files != null && files.length > 0;
974
- const imageUrls = hasFiles ? files.map((file) => convertImageModelFileToDataUri(file)) : [];
975
- const endpoint = hasFiles ? "/images/edits" : "/images/generations";
976
- const body = {
977
- model: this.modelId,
978
- prompt,
979
- n,
980
- response_format: "b64_json"
981
- };
982
- if (aspectRatio != null) {
983
- body.aspect_ratio = aspectRatio;
984
- }
985
- if ((xaiOptions == null ? void 0 : xaiOptions.output_format) != null) {
986
- body.output_format = xaiOptions.output_format;
987
- }
988
- if ((xaiOptions == null ? void 0 : xaiOptions.sync_mode) != null) {
989
- body.sync_mode = xaiOptions.sync_mode;
990
- }
991
- if ((xaiOptions == null ? void 0 : xaiOptions.aspect_ratio) != null && aspectRatio == null) {
992
- body.aspect_ratio = xaiOptions.aspect_ratio;
993
- }
994
- if ((xaiOptions == null ? void 0 : xaiOptions.resolution) != null) {
995
- body.resolution = xaiOptions.resolution;
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
- }
1003
- if (imageUrls.length === 1) {
1004
- body.image = { url: imageUrls[0], type: "image_url" };
1005
- } else if (imageUrls.length > 1) {
1006
- body.images = imageUrls.map((url) => ({ url, type: "image_url" }));
1007
- }
1008
- const baseURL = (_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1";
1009
- const currentDate = (_d = (_c = (_b = this.config._internal) == null ? void 0 : _b.currentDate) == null ? void 0 : _c.call(_b)) != null ? _d : /* @__PURE__ */ new Date();
1010
- const { value: response, responseHeaders } = await postJsonToApi2({
1011
- url: `${baseURL}${endpoint}`,
1012
- headers: combineHeaders2(this.config.headers(), headers),
1013
- body,
1014
- failedResponseHandler: xaiFailedResponseHandler,
1015
- successfulResponseHandler: createJsonResponseHandler2(
1016
- xaiImageResponseSchema
1017
- ),
1018
- abortSignal,
1019
- fetch: this.config.fetch
1020
- });
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
- )
1026
- );
1027
- return {
1028
- images,
1029
- warnings,
1030
- response: {
1031
- timestamp: currentDate,
1032
- modelId: this.modelId,
1033
- headers: responseHeaders
1034
- },
1035
- providerMetadata: {
1036
- xai: {
1037
- images: response.data.map((item) => ({
1038
- ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}
1039
- })),
1040
- ...((_e = response.usage) == null ? void 0 : _e.cost_in_usd_ticks) != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {}
1041
- }
1042
- }
1043
- };
1044
- }
1045
- async downloadImage(url, abortSignal) {
1046
- const { value } = await getFromApi({
1047
- url,
1048
- abortSignal,
1049
- failedResponseHandler: createStatusCodeErrorResponseHandler(),
1050
- successfulResponseHandler: createBinaryResponseHandler(),
1051
- fetch: this.config.fetch
1052
- });
1053
- return value;
1054
- }
1055
- };
1056
- var xaiImageResponseSchema = z5.object({
1057
- data: z5.array(
1058
- z5.object({
1059
- url: z5.string().nullish(),
1060
- b64_json: z5.string().nullish(),
1061
- revised_prompt: z5.string().nullish()
1062
- })
1063
- ),
1064
- usage: z5.object({
1065
- cost_in_usd_ticks: z5.number().nullish()
1066
- }).nullish()
1067
- });
1068
-
1069
- // src/responses/xai-responses-language-model.ts
1070
- import {
1071
- combineHeaders as combineHeaders3,
1072
- createEventSourceResponseHandler as createEventSourceResponseHandler2,
1073
- createJsonResponseHandler as createJsonResponseHandler3,
1074
- isCustomReasoning as isCustomReasoning2,
1075
- mapReasoningToProviderEffort as mapReasoningToProviderEffort2,
1076
- parseProviderOptions as parseProviderOptions3,
1077
- postJsonToApi as postJsonToApi3
1078
- } from "@ai-sdk/provider-utils";
1079
-
1080
- // src/responses/convert-to-xai-responses-input.ts
1081
- import {
1082
- UnsupportedFunctionalityError as UnsupportedFunctionalityError3
1083
- } from "@ai-sdk/provider";
1084
- import {
1085
- convertToBase64 as convertToBase642,
1086
- isProviderReference as isProviderReference2,
1087
- resolveProviderReference as resolveProviderReference2
1088
- } from "@ai-sdk/provider-utils";
1089
- async function convertToXaiResponsesInput({
1090
- prompt
1091
- }) {
1092
- var _a, _b, _c, _d, _e;
1093
- const input = [];
1094
- const inputWarnings = [];
1095
- for (const message of prompt) {
1096
- switch (message.role) {
1097
- case "system": {
1098
- input.push({
1099
- role: "system",
1100
- content: message.content
1101
- });
1102
- break;
1103
- }
1104
- case "user": {
1105
- const contentParts = [];
1106
- for (const block of message.content) {
1107
- switch (block.type) {
1108
- case "text": {
1109
- contentParts.push({ type: "input_text", text: block.text });
1110
- break;
1111
- }
1112
- case "file": {
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/")) {
1122
- const mediaType = block.mediaType === "image/*" ? "image/jpeg" : block.mediaType;
1123
- const imageUrl = block.data instanceof URL ? block.data.toString() : `data:${mediaType};base64,${convertToBase642(block.data)}`;
1124
- contentParts.push({ type: "input_image", image_url: imageUrl });
1125
- } else {
1126
- throw new UnsupportedFunctionalityError3({
1127
- functionality: `file part media type ${block.mediaType}`
1128
- });
1129
- }
1130
- break;
1131
- }
1132
- default: {
1133
- const _exhaustiveCheck = block;
1134
- inputWarnings.push({
1135
- type: "other",
1136
- message: "xAI Responses API does not support this content type in user messages"
1137
- });
1138
- }
1139
- }
1140
- }
1141
- input.push({
1142
- role: "user",
1143
- content: contentParts
1144
- });
1145
- break;
1146
- }
1147
- case "assistant": {
1148
- for (const part of message.content) {
1149
- switch (part.type) {
1150
- case "text": {
1151
- const id = typeof ((_b = (_a = part.providerOptions) == null ? void 0 : _a.xai) == null ? void 0 : _b.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
1152
- input.push({
1153
- role: "assistant",
1154
- content: part.text,
1155
- id
1156
- });
1157
- break;
1158
- }
1159
- case "tool-call": {
1160
- if (part.providerExecuted) {
1161
- break;
1162
- }
1163
- const id = typeof ((_d = (_c = part.providerOptions) == null ? void 0 : _c.xai) == null ? void 0 : _d.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
1164
- input.push({
1165
- type: "function_call",
1166
- id: id != null ? id : part.toolCallId,
1167
- call_id: part.toolCallId,
1168
- name: part.toolName,
1169
- arguments: JSON.stringify(part.input),
1170
- status: "completed"
1171
- });
1172
- break;
1173
- }
1174
- case "tool-result": {
1175
- break;
1176
- }
1177
- case "reasoning":
1178
- case "reasoning-file":
1179
- case "custom":
1180
- case "file": {
1181
- inputWarnings.push({
1182
- type: "other",
1183
- message: `xAI Responses API does not support ${part.type} in assistant messages`
1184
- });
1185
- break;
1186
- }
1187
- default: {
1188
- const _exhaustiveCheck = part;
1189
- inputWarnings.push({
1190
- type: "other",
1191
- message: "xAI Responses API does not support this content type in assistant messages"
1192
- });
1193
- }
1194
- }
1195
- }
1196
- break;
1197
- }
1198
- case "tool": {
1199
- for (const part of message.content) {
1200
- if (part.type === "tool-approval-response") {
1201
- continue;
1202
- }
1203
- const output = part.output;
1204
- let outputValue;
1205
- switch (output.type) {
1206
- case "text":
1207
- case "error-text":
1208
- outputValue = output.value;
1209
- break;
1210
- case "execution-denied":
1211
- outputValue = (_e = output.reason) != null ? _e : "tool execution denied";
1212
- break;
1213
- case "json":
1214
- case "error-json":
1215
- outputValue = JSON.stringify(output.value);
1216
- break;
1217
- case "content":
1218
- outputValue = output.value.map((item) => {
1219
- if (item.type === "text") {
1220
- return item.text;
1221
- }
1222
- return "";
1223
- }).join("");
1224
- break;
1225
- default: {
1226
- const _exhaustiveCheck = output;
1227
- outputValue = "";
1228
- }
1229
- }
1230
- input.push({
1231
- type: "function_call_output",
1232
- call_id: part.toolCallId,
1233
- output: outputValue
1234
- });
1235
- }
1236
- break;
1237
- }
1238
- default: {
1239
- const _exhaustiveCheck = message;
1240
- inputWarnings.push({
1241
- type: "other",
1242
- message: "unsupported message role"
1243
- });
1244
- }
1245
- }
1246
- }
1247
- return { input, inputWarnings };
1248
- }
1249
-
1250
- // src/responses/convert-xai-responses-usage.ts
1251
- function convertXaiResponsesUsage(usage) {
1252
- var _a, _b, _c, _d;
1253
- const cacheReadTokens = (_b = (_a = usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
1254
- const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
1255
- const inputTokensIncludesCached = cacheReadTokens <= usage.input_tokens;
1256
- return {
1257
- inputTokens: {
1258
- total: inputTokensIncludesCached ? usage.input_tokens : usage.input_tokens + cacheReadTokens,
1259
- noCache: inputTokensIncludesCached ? usage.input_tokens - cacheReadTokens : usage.input_tokens,
1260
- cacheRead: cacheReadTokens,
1261
- cacheWrite: void 0
1262
- },
1263
- outputTokens: {
1264
- total: usage.output_tokens,
1265
- text: usage.output_tokens - reasoningTokens,
1266
- reasoning: reasoningTokens
1267
- },
1268
- raw: usage
1269
- };
1270
- }
1271
-
1272
- // src/responses/map-xai-responses-finish-reason.ts
1273
- function mapXaiResponsesFinishReason(finishReason) {
1274
- switch (finishReason) {
1275
- case "stop":
1276
- case "completed":
1277
- return "stop";
1278
- case "length":
1279
- case "max_output_tokens":
1280
- return "length";
1281
- case "tool_calls":
1282
- case "function_call":
1283
- return "tool-calls";
1284
- case "content_filter":
1285
- return "content-filter";
1286
- default:
1287
- return "other";
1288
- }
1289
- }
1290
-
1291
- // src/responses/xai-responses-api.ts
1292
- import { z as z6 } from "zod/v4";
1293
- var annotationSchema = z6.union([
1294
- z6.object({
1295
- type: z6.literal("url_citation"),
1296
- url: z6.string(),
1297
- title: z6.string().optional()
1298
- }),
1299
- z6.object({
1300
- type: z6.string()
1301
- })
1302
- ]);
1303
- var messageContentPartSchema = z6.object({
1304
- type: z6.string(),
1305
- text: z6.string().optional(),
1306
- logprobs: z6.array(z6.any()).optional(),
1307
- annotations: z6.array(annotationSchema).optional()
1308
- });
1309
- var reasoningSummaryPartSchema = z6.object({
1310
- type: z6.string(),
1311
- text: z6.string()
1312
- });
1313
- var toolCallSchema = z6.object({
1314
- name: z6.string().optional(),
1315
- arguments: z6.string().optional(),
1316
- input: z6.string().optional(),
1317
- call_id: z6.string().optional(),
1318
- id: z6.string(),
1319
- status: z6.string(),
1320
- action: z6.any().optional()
1321
- });
1322
- var mcpCallSchema = z6.object({
1323
- name: z6.string().optional(),
1324
- arguments: z6.string().optional(),
1325
- output: z6.string().optional(),
1326
- error: z6.string().optional(),
1327
- id: z6.string(),
1328
- status: z6.string(),
1329
- server_label: z6.string().optional()
1330
- });
1331
- var outputItemSchema = z6.discriminatedUnion("type", [
1332
- z6.object({
1333
- type: z6.literal("web_search_call"),
1334
- ...toolCallSchema.shape
1335
- }),
1336
- z6.object({
1337
- type: z6.literal("x_search_call"),
1338
- ...toolCallSchema.shape
1339
- }),
1340
- z6.object({
1341
- type: z6.literal("code_interpreter_call"),
1342
- ...toolCallSchema.shape
1343
- }),
1344
- z6.object({
1345
- type: z6.literal("code_execution_call"),
1346
- ...toolCallSchema.shape
1347
- }),
1348
- z6.object({
1349
- type: z6.literal("view_image_call"),
1350
- ...toolCallSchema.shape
1351
- }),
1352
- z6.object({
1353
- type: z6.literal("view_x_video_call"),
1354
- ...toolCallSchema.shape
1355
- }),
1356
- z6.object({
1357
- type: z6.literal("file_search_call"),
1358
- id: z6.string(),
1359
- status: z6.string(),
1360
- queries: z6.array(z6.string()).optional(),
1361
- results: z6.array(
1362
- z6.object({
1363
- file_id: z6.string(),
1364
- filename: z6.string(),
1365
- score: z6.number(),
1366
- text: z6.string()
1367
- })
1368
- ).nullish()
1369
- }),
1370
- z6.object({
1371
- type: z6.literal("custom_tool_call"),
1372
- ...toolCallSchema.shape
1373
- }),
1374
- z6.object({
1375
- type: z6.literal("mcp_call"),
1376
- ...mcpCallSchema.shape
1377
- }),
1378
- z6.object({
1379
- type: z6.literal("message"),
1380
- role: z6.string(),
1381
- content: z6.array(messageContentPartSchema),
1382
- id: z6.string(),
1383
- status: z6.string()
1384
- }),
1385
- z6.object({
1386
- type: z6.literal("function_call"),
1387
- name: z6.string(),
1388
- arguments: z6.string(),
1389
- call_id: z6.string(),
1390
- id: z6.string()
1391
- }),
1392
- z6.object({
1393
- type: z6.literal("reasoning"),
1394
- id: z6.string(),
1395
- summary: z6.array(reasoningSummaryPartSchema),
1396
- content: z6.array(z6.object({ type: z6.string(), text: z6.string() })).nullish(),
1397
- status: z6.string(),
1398
- encrypted_content: z6.string().nullish()
1399
- })
1400
- ]);
1401
- var xaiResponsesUsageSchema = z6.object({
1402
- input_tokens: z6.number(),
1403
- output_tokens: z6.number(),
1404
- total_tokens: z6.number().optional(),
1405
- input_tokens_details: z6.object({
1406
- cached_tokens: z6.number().optional()
1407
- }).optional(),
1408
- output_tokens_details: z6.object({
1409
- reasoning_tokens: z6.number().optional()
1410
- }).optional(),
1411
- num_sources_used: z6.number().optional(),
1412
- num_server_side_tools_used: z6.number().optional()
1413
- });
1414
- var xaiResponsesResponseSchema = z6.object({
1415
- id: z6.string().nullish(),
1416
- created_at: z6.number().nullish(),
1417
- model: z6.string().nullish(),
1418
- object: z6.literal("response"),
1419
- output: z6.array(outputItemSchema),
1420
- usage: xaiResponsesUsageSchema.nullish(),
1421
- status: z6.string()
1422
- });
1423
- var xaiResponsesChunkSchema = z6.union([
1424
- z6.object({
1425
- type: z6.literal("response.created"),
1426
- response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
1427
- }),
1428
- z6.object({
1429
- type: z6.literal("response.in_progress"),
1430
- response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
1431
- }),
1432
- z6.object({
1433
- type: z6.literal("response.output_item.added"),
1434
- item: outputItemSchema,
1435
- output_index: z6.number()
1436
- }),
1437
- z6.object({
1438
- type: z6.literal("response.output_item.done"),
1439
- item: outputItemSchema,
1440
- output_index: z6.number()
1441
- }),
1442
- z6.object({
1443
- type: z6.literal("response.content_part.added"),
1444
- item_id: z6.string(),
1445
- output_index: z6.number(),
1446
- content_index: z6.number(),
1447
- part: messageContentPartSchema
1448
- }),
1449
- z6.object({
1450
- type: z6.literal("response.content_part.done"),
1451
- item_id: z6.string(),
1452
- output_index: z6.number(),
1453
- content_index: z6.number(),
1454
- part: messageContentPartSchema
1455
- }),
1456
- z6.object({
1457
- type: z6.literal("response.output_text.delta"),
1458
- item_id: z6.string(),
1459
- output_index: z6.number(),
1460
- content_index: z6.number(),
1461
- delta: z6.string(),
1462
- logprobs: z6.array(z6.any()).optional()
1463
- }),
1464
- z6.object({
1465
- type: z6.literal("response.output_text.done"),
1466
- item_id: z6.string(),
1467
- output_index: z6.number(),
1468
- content_index: z6.number(),
1469
- text: z6.string(),
1470
- logprobs: z6.array(z6.any()).optional(),
1471
- annotations: z6.array(annotationSchema).optional()
1472
- }),
1473
- z6.object({
1474
- type: z6.literal("response.output_text.annotation.added"),
1475
- item_id: z6.string(),
1476
- output_index: z6.number(),
1477
- content_index: z6.number(),
1478
- annotation_index: z6.number(),
1479
- annotation: annotationSchema
1480
- }),
1481
- z6.object({
1482
- type: z6.literal("response.reasoning_summary_part.added"),
1483
- item_id: z6.string(),
1484
- output_index: z6.number(),
1485
- summary_index: z6.number(),
1486
- part: reasoningSummaryPartSchema
1487
- }),
1488
- z6.object({
1489
- type: z6.literal("response.reasoning_summary_part.done"),
1490
- item_id: z6.string(),
1491
- output_index: z6.number(),
1492
- summary_index: z6.number(),
1493
- part: reasoningSummaryPartSchema
1494
- }),
1495
- z6.object({
1496
- type: z6.literal("response.reasoning_summary_text.delta"),
1497
- item_id: z6.string(),
1498
- output_index: z6.number(),
1499
- summary_index: z6.number(),
1500
- delta: z6.string()
1501
- }),
1502
- z6.object({
1503
- type: z6.literal("response.reasoning_summary_text.done"),
1504
- item_id: z6.string(),
1505
- output_index: z6.number(),
1506
- summary_index: z6.number(),
1507
- text: z6.string()
1508
- }),
1509
- z6.object({
1510
- type: z6.literal("response.reasoning_text.delta"),
1511
- item_id: z6.string(),
1512
- output_index: z6.number(),
1513
- content_index: z6.number(),
1514
- delta: z6.string()
1515
- }),
1516
- z6.object({
1517
- type: z6.literal("response.reasoning_text.done"),
1518
- item_id: z6.string(),
1519
- output_index: z6.number(),
1520
- content_index: z6.number(),
1521
- text: z6.string()
1522
- }),
1523
- z6.object({
1524
- type: z6.literal("response.web_search_call.in_progress"),
1525
- item_id: z6.string(),
1526
- output_index: z6.number()
1527
- }),
1528
- z6.object({
1529
- type: z6.literal("response.web_search_call.searching"),
1530
- item_id: z6.string(),
1531
- output_index: z6.number()
1532
- }),
1533
- z6.object({
1534
- type: z6.literal("response.web_search_call.completed"),
1535
- item_id: z6.string(),
1536
- output_index: z6.number()
1537
- }),
1538
- z6.object({
1539
- type: z6.literal("response.x_search_call.in_progress"),
1540
- item_id: z6.string(),
1541
- output_index: z6.number()
1542
- }),
1543
- z6.object({
1544
- type: z6.literal("response.x_search_call.searching"),
1545
- item_id: z6.string(),
1546
- output_index: z6.number()
1547
- }),
1548
- z6.object({
1549
- type: z6.literal("response.x_search_call.completed"),
1550
- item_id: z6.string(),
1551
- output_index: z6.number()
1552
- }),
1553
- z6.object({
1554
- type: z6.literal("response.file_search_call.in_progress"),
1555
- item_id: z6.string(),
1556
- output_index: z6.number()
1557
- }),
1558
- z6.object({
1559
- type: z6.literal("response.file_search_call.searching"),
1560
- item_id: z6.string(),
1561
- output_index: z6.number()
1562
- }),
1563
- z6.object({
1564
- type: z6.literal("response.file_search_call.completed"),
1565
- item_id: z6.string(),
1566
- output_index: z6.number()
1567
- }),
1568
- z6.object({
1569
- type: z6.literal("response.code_execution_call.in_progress"),
1570
- item_id: z6.string(),
1571
- output_index: z6.number()
1572
- }),
1573
- z6.object({
1574
- type: z6.literal("response.code_execution_call.executing"),
1575
- item_id: z6.string(),
1576
- output_index: z6.number()
1577
- }),
1578
- z6.object({
1579
- type: z6.literal("response.code_execution_call.completed"),
1580
- item_id: z6.string(),
1581
- output_index: z6.number()
1582
- }),
1583
- z6.object({
1584
- type: z6.literal("response.code_interpreter_call.in_progress"),
1585
- item_id: z6.string(),
1586
- output_index: z6.number()
1587
- }),
1588
- z6.object({
1589
- type: z6.literal("response.code_interpreter_call.executing"),
1590
- item_id: z6.string(),
1591
- output_index: z6.number()
1592
- }),
1593
- z6.object({
1594
- type: z6.literal("response.code_interpreter_call.interpreting"),
1595
- item_id: z6.string(),
1596
- output_index: z6.number()
1597
- }),
1598
- z6.object({
1599
- type: z6.literal("response.code_interpreter_call.completed"),
1600
- item_id: z6.string(),
1601
- output_index: z6.number()
1602
- }),
1603
- // Code interpreter code streaming events
1604
- z6.object({
1605
- type: z6.literal("response.code_interpreter_call_code.delta"),
1606
- item_id: z6.string(),
1607
- output_index: z6.number(),
1608
- delta: z6.string()
1609
- }),
1610
- z6.object({
1611
- type: z6.literal("response.code_interpreter_call_code.done"),
1612
- item_id: z6.string(),
1613
- output_index: z6.number(),
1614
- code: z6.string()
1615
- }),
1616
- z6.object({
1617
- type: z6.literal("response.custom_tool_call_input.delta"),
1618
- item_id: z6.string(),
1619
- output_index: z6.number(),
1620
- delta: z6.string()
1621
- }),
1622
- z6.object({
1623
- type: z6.literal("response.custom_tool_call_input.done"),
1624
- item_id: z6.string(),
1625
- output_index: z6.number(),
1626
- input: z6.string()
1627
- }),
1628
- // Function call arguments streaming events (standard function tools)
1629
- z6.object({
1630
- type: z6.literal("response.function_call_arguments.delta"),
1631
- item_id: z6.string(),
1632
- output_index: z6.number(),
1633
- delta: z6.string()
1634
- }),
1635
- z6.object({
1636
- type: z6.literal("response.function_call_arguments.done"),
1637
- item_id: z6.string(),
1638
- output_index: z6.number(),
1639
- arguments: z6.string()
1640
- }),
1641
- z6.object({
1642
- type: z6.literal("response.mcp_call.in_progress"),
1643
- item_id: z6.string(),
1644
- output_index: z6.number()
1645
- }),
1646
- z6.object({
1647
- type: z6.literal("response.mcp_call.executing"),
1648
- item_id: z6.string(),
1649
- output_index: z6.number()
1650
- }),
1651
- z6.object({
1652
- type: z6.literal("response.mcp_call.completed"),
1653
- item_id: z6.string(),
1654
- output_index: z6.number()
1655
- }),
1656
- z6.object({
1657
- type: z6.literal("response.mcp_call.failed"),
1658
- item_id: z6.string(),
1659
- output_index: z6.number()
1660
- }),
1661
- z6.object({
1662
- type: z6.literal("response.mcp_call_arguments.delta"),
1663
- item_id: z6.string(),
1664
- output_index: z6.number(),
1665
- delta: z6.string()
1666
- }),
1667
- z6.object({
1668
- type: z6.literal("response.mcp_call_arguments.done"),
1669
- item_id: z6.string(),
1670
- output_index: z6.number(),
1671
- arguments: z6.string().optional()
1672
- }),
1673
- z6.object({
1674
- type: z6.literal("response.mcp_call_output.delta"),
1675
- item_id: z6.string(),
1676
- output_index: z6.number(),
1677
- delta: z6.string()
1678
- }),
1679
- z6.object({
1680
- type: z6.literal("response.mcp_call_output.done"),
1681
- item_id: z6.string(),
1682
- output_index: z6.number(),
1683
- output: z6.string().optional()
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
- }),
1709
- z6.object({
1710
- type: z6.literal("response.done"),
1711
- response: xaiResponsesResponseSchema
1712
- }),
1713
- z6.object({
1714
- type: z6.literal("response.completed"),
1715
- response: xaiResponsesResponseSchema
1716
- })
1717
- ]);
1718
-
1719
- // src/responses/xai-responses-options.ts
1720
- import { z as z7 } from "zod/v4";
1721
- var xaiLanguageModelResponsesOptions = z7.object({
1722
- /**
1723
- * Constrains how hard a reasoning model thinks before responding.
1724
- * Possible values are `low` (uses fewer reasoning tokens), `medium` and `high` (uses more reasoning tokens).
1725
- */
1726
- reasoningEffort: z7.enum(["low", "medium", "high"]).optional(),
1727
- reasoningSummary: z7.enum(["auto", "concise", "detailed"]).optional(),
1728
- logprobs: z7.boolean().optional(),
1729
- topLogprobs: z7.number().int().min(0).max(8).optional(),
1730
- /**
1731
- * Whether to store the input message(s) and model response for later retrieval.
1732
- * @default true
1733
- */
1734
- store: z7.boolean().optional(),
1735
- /**
1736
- * The ID of the previous response from the model.
1737
- */
1738
- previousResponseId: z7.string().optional(),
1739
- /**
1740
- * Specify additional output data to include in the model response.
1741
- * Example values: 'file_search_call.results'.
1742
- */
1743
- include: z7.array(z7.enum(["file_search_call.results"])).nullish()
1744
- });
1745
-
1746
- // src/responses/xai-responses-prepare-tools.ts
1747
- import {
1748
- UnsupportedFunctionalityError as UnsupportedFunctionalityError4
1749
- } from "@ai-sdk/provider";
1750
- import { validateTypes } from "@ai-sdk/provider-utils";
1751
-
1752
- // src/tool/file-search.ts
1753
- import {
1754
- createProviderToolFactoryWithOutputSchema,
1755
- lazySchema,
1756
- zodSchema
1757
- } from "@ai-sdk/provider-utils";
1758
- import { z as z8 } from "zod/v4";
1759
- var fileSearchArgsSchema = lazySchema(
1760
- () => zodSchema(
1761
- z8.object({
1762
- vectorStoreIds: z8.array(z8.string()),
1763
- maxNumResults: z8.number().optional()
1764
- })
1765
- )
1766
- );
1767
- var fileSearchOutputSchema = lazySchema(
1768
- () => zodSchema(
1769
- z8.object({
1770
- queries: z8.array(z8.string()),
1771
- results: z8.array(
1772
- z8.object({
1773
- fileId: z8.string(),
1774
- filename: z8.string(),
1775
- score: z8.number().min(0).max(1),
1776
- text: z8.string()
1777
- })
1778
- ).nullable()
1779
- })
1780
- )
1781
- );
1782
- var fileSearchToolFactory = createProviderToolFactoryWithOutputSchema({
1783
- id: "xai.file_search",
1784
- inputSchema: lazySchema(() => zodSchema(z8.object({}))),
1785
- outputSchema: fileSearchOutputSchema
1786
- });
1787
- var fileSearch = (args) => fileSearchToolFactory(args);
1788
-
1789
- // src/tool/mcp-server.ts
1790
- import {
1791
- createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema2,
1792
- lazySchema as lazySchema2,
1793
- zodSchema as zodSchema2
1794
- } from "@ai-sdk/provider-utils";
1795
- import { z as z9 } from "zod/v4";
1796
- var mcpServerArgsSchema = lazySchema2(
1797
- () => zodSchema2(
1798
- z9.object({
1799
- serverUrl: z9.string().describe("The URL of the MCP server"),
1800
- serverLabel: z9.string().optional().describe("A label for the MCP server"),
1801
- serverDescription: z9.string().optional().describe("Description of the MCP server"),
1802
- allowedTools: z9.array(z9.string()).optional().describe("List of allowed tool names"),
1803
- headers: z9.record(z9.string(), z9.string()).optional().describe("Custom headers to send"),
1804
- authorization: z9.string().optional().describe("Authorization header value")
1805
- })
1806
- )
1807
- );
1808
- var mcpServerOutputSchema = lazySchema2(
1809
- () => zodSchema2(
1810
- z9.object({
1811
- name: z9.string(),
1812
- arguments: z9.string(),
1813
- result: z9.unknown()
1814
- })
1815
- )
1816
- );
1817
- var mcpServerToolFactory = createProviderToolFactoryWithOutputSchema2({
1818
- id: "xai.mcp",
1819
- inputSchema: lazySchema2(() => zodSchema2(z9.object({}))),
1820
- outputSchema: mcpServerOutputSchema
1821
- });
1822
- var mcpServer = (args) => mcpServerToolFactory(args);
1823
-
1824
- // src/tool/web-search.ts
1825
- import {
1826
- createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema3,
1827
- lazySchema as lazySchema3,
1828
- zodSchema as zodSchema3
1829
- } from "@ai-sdk/provider-utils";
1830
- import { z as z10 } from "zod/v4";
1831
- var webSearchArgsSchema = lazySchema3(
1832
- () => zodSchema3(
1833
- z10.object({
1834
- allowedDomains: z10.array(z10.string()).max(5).optional(),
1835
- excludedDomains: z10.array(z10.string()).max(5).optional(),
1836
- enableImageUnderstanding: z10.boolean().optional()
1837
- })
1838
- )
1839
- );
1840
- var webSearchOutputSchema = lazySchema3(
1841
- () => zodSchema3(
1842
- z10.object({
1843
- query: z10.string(),
1844
- sources: z10.array(
1845
- z10.object({
1846
- title: z10.string(),
1847
- url: z10.string(),
1848
- snippet: z10.string()
1849
- })
1850
- )
1851
- })
1852
- )
1853
- );
1854
- var webSearchToolFactory = createProviderToolFactoryWithOutputSchema3({
1855
- id: "xai.web_search",
1856
- inputSchema: lazySchema3(() => zodSchema3(z10.object({}))),
1857
- outputSchema: webSearchOutputSchema
1858
- });
1859
- var webSearch = (args = {}) => webSearchToolFactory(args);
1860
-
1861
- // src/tool/x-search.ts
1862
- import {
1863
- createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema4,
1864
- lazySchema as lazySchema4,
1865
- zodSchema as zodSchema4
1866
- } from "@ai-sdk/provider-utils";
1867
- import { z as z11 } from "zod/v4";
1868
- var xSearchArgsSchema = lazySchema4(
1869
- () => zodSchema4(
1870
- z11.object({
1871
- allowedXHandles: z11.array(z11.string()).max(10).optional(),
1872
- excludedXHandles: z11.array(z11.string()).max(10).optional(),
1873
- fromDate: z11.string().optional(),
1874
- toDate: z11.string().optional(),
1875
- enableImageUnderstanding: z11.boolean().optional(),
1876
- enableVideoUnderstanding: z11.boolean().optional()
1877
- })
1878
- )
1879
- );
1880
- var xSearchOutputSchema = lazySchema4(
1881
- () => zodSchema4(
1882
- z11.object({
1883
- query: z11.string(),
1884
- posts: z11.array(
1885
- z11.object({
1886
- author: z11.string(),
1887
- text: z11.string(),
1888
- url: z11.string(),
1889
- likes: z11.number()
1890
- })
1891
- )
1892
- })
1893
- )
1894
- );
1895
- var xSearchToolFactory = createProviderToolFactoryWithOutputSchema4({
1896
- id: "xai.x_search",
1897
- inputSchema: lazySchema4(() => zodSchema4(z11.object({}))),
1898
- outputSchema: xSearchOutputSchema
1899
- });
1900
- var xSearch = (args = {}) => xSearchToolFactory(args);
1901
-
1902
- // src/responses/xai-responses-prepare-tools.ts
1903
- async function prepareResponsesTools({
1904
- tools,
1905
- toolChoice
1906
- }) {
1907
- const normalizedTools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1908
- const toolWarnings = [];
1909
- if (normalizedTools == null) {
1910
- return { tools: void 0, toolChoice: void 0, toolWarnings };
1911
- }
1912
- const xaiTools2 = [];
1913
- const toolByName = /* @__PURE__ */ new Map();
1914
- for (const tool of normalizedTools) {
1915
- toolByName.set(tool.name, tool);
1916
- if (tool.type === "provider") {
1917
- switch (tool.id) {
1918
- case "xai.web_search": {
1919
- const args = await validateTypes({
1920
- value: tool.args,
1921
- schema: webSearchArgsSchema
1922
- });
1923
- xaiTools2.push({
1924
- type: "web_search",
1925
- allowed_domains: args.allowedDomains,
1926
- excluded_domains: args.excludedDomains,
1927
- enable_image_understanding: args.enableImageUnderstanding
1928
- });
1929
- break;
1930
- }
1931
- case "xai.x_search": {
1932
- const args = await validateTypes({
1933
- value: tool.args,
1934
- schema: xSearchArgsSchema
1935
- });
1936
- xaiTools2.push({
1937
- type: "x_search",
1938
- allowed_x_handles: args.allowedXHandles,
1939
- excluded_x_handles: args.excludedXHandles,
1940
- from_date: args.fromDate,
1941
- to_date: args.toDate,
1942
- enable_image_understanding: args.enableImageUnderstanding,
1943
- enable_video_understanding: args.enableVideoUnderstanding
1944
- });
1945
- break;
1946
- }
1947
- case "xai.code_execution": {
1948
- xaiTools2.push({
1949
- type: "code_interpreter"
1950
- });
1951
- break;
1952
- }
1953
- case "xai.view_image": {
1954
- xaiTools2.push({
1955
- type: "view_image"
1956
- });
1957
- break;
1958
- }
1959
- case "xai.view_x_video": {
1960
- xaiTools2.push({
1961
- type: "view_x_video"
1962
- });
1963
- break;
1964
- }
1965
- case "xai.file_search": {
1966
- const args = await validateTypes({
1967
- value: tool.args,
1968
- schema: fileSearchArgsSchema
1969
- });
1970
- xaiTools2.push({
1971
- type: "file_search",
1972
- vector_store_ids: args.vectorStoreIds,
1973
- max_num_results: args.maxNumResults
1974
- });
1975
- break;
1976
- }
1977
- case "xai.mcp": {
1978
- const args = await validateTypes({
1979
- value: tool.args,
1980
- schema: mcpServerArgsSchema
1981
- });
1982
- xaiTools2.push({
1983
- type: "mcp",
1984
- server_url: args.serverUrl,
1985
- server_label: args.serverLabel,
1986
- server_description: args.serverDescription,
1987
- allowed_tools: args.allowedTools,
1988
- headers: args.headers,
1989
- authorization: args.authorization
1990
- });
1991
- break;
1992
- }
1993
- default: {
1994
- toolWarnings.push({
1995
- type: "unsupported",
1996
- feature: `provider-defined tool ${tool.name}`
1997
- });
1998
- break;
1999
- }
2000
- }
2001
- } else {
2002
- xaiTools2.push({
2003
- type: "function",
2004
- name: tool.name,
2005
- description: tool.description,
2006
- parameters: tool.inputSchema,
2007
- ...tool.strict != null ? { strict: tool.strict } : {}
2008
- });
2009
- }
2010
- }
2011
- if (toolChoice == null) {
2012
- return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
2013
- }
2014
- const type = toolChoice.type;
2015
- switch (type) {
2016
- case "auto":
2017
- case "none":
2018
- return { tools: xaiTools2, toolChoice: type, toolWarnings };
2019
- case "required":
2020
- return { tools: xaiTools2, toolChoice: "required", toolWarnings };
2021
- case "tool": {
2022
- const selectedTool = toolByName.get(toolChoice.toolName);
2023
- if (selectedTool == null) {
2024
- return {
2025
- tools: xaiTools2,
2026
- toolChoice: void 0,
2027
- toolWarnings
2028
- };
2029
- }
2030
- if (selectedTool.type === "provider") {
2031
- toolWarnings.push({
2032
- type: "unsupported",
2033
- feature: `toolChoice for server-side tool "${selectedTool.name}"`
2034
- });
2035
- return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
2036
- }
2037
- return {
2038
- tools: xaiTools2,
2039
- toolChoice: { type: "function", name: selectedTool.name },
2040
- toolWarnings
2041
- };
2042
- }
2043
- default: {
2044
- const _exhaustiveCheck = type;
2045
- throw new UnsupportedFunctionalityError4({
2046
- functionality: `tool choice type: ${_exhaustiveCheck}`
2047
- });
2048
- }
2049
- }
2050
- }
2051
-
2052
- // src/responses/xai-responses-language-model.ts
2053
- var XaiResponsesLanguageModel = class {
2054
- constructor(modelId, config) {
2055
- this.specificationVersion = "v4";
2056
- this.supportedUrls = {
2057
- "image/*": [/^https?:\/\/.*$/]
2058
- };
2059
- this.modelId = modelId;
2060
- this.config = config;
2061
- }
2062
- get provider() {
2063
- return this.config.provider;
2064
- }
2065
- async getArgs({
2066
- prompt,
2067
- maxOutputTokens,
2068
- temperature,
2069
- topP,
2070
- stopSequences,
2071
- seed,
2072
- responseFormat,
2073
- providerOptions,
2074
- tools,
2075
- toolChoice,
2076
- reasoning
2077
- }) {
2078
- var _a, _b, _c, _d, _e, _f, _g, _h;
2079
- const warnings = [];
2080
- const options = (_a = await parseProviderOptions3({
2081
- provider: "xai",
2082
- providerOptions,
2083
- schema: xaiLanguageModelResponsesOptions
2084
- })) != null ? _a : {};
2085
- if (stopSequences != null) {
2086
- warnings.push({ type: "unsupported", feature: "stopSequences" });
2087
- }
2088
- const webSearchToolName = (_b = tools == null ? void 0 : tools.find(
2089
- (tool) => tool.type === "provider" && tool.id === "xai.web_search"
2090
- )) == null ? void 0 : _b.name;
2091
- const xSearchToolName = (_c = tools == null ? void 0 : tools.find(
2092
- (tool) => tool.type === "provider" && tool.id === "xai.x_search"
2093
- )) == null ? void 0 : _c.name;
2094
- const codeExecutionToolName = (_d = tools == null ? void 0 : tools.find(
2095
- (tool) => tool.type === "provider" && tool.id === "xai.code_execution"
2096
- )) == null ? void 0 : _d.name;
2097
- const mcpToolName = (_e = tools == null ? void 0 : tools.find(
2098
- (tool) => tool.type === "provider" && tool.id === "xai.mcp"
2099
- )) == null ? void 0 : _e.name;
2100
- const fileSearchToolName = (_f = tools == null ? void 0 : tools.find(
2101
- (tool) => tool.type === "provider" && tool.id === "xai.file_search"
2102
- )) == null ? void 0 : _f.name;
2103
- const { input, inputWarnings } = await convertToXaiResponsesInput({
2104
- prompt,
2105
- store: true
2106
- });
2107
- warnings.push(...inputWarnings);
2108
- const {
2109
- tools: xaiTools2,
2110
- toolChoice: xaiToolChoice,
2111
- toolWarnings
2112
- } = await prepareResponsesTools({
2113
- tools,
2114
- toolChoice
2115
- });
2116
- warnings.push(...toolWarnings);
2117
- let include = options.include ? [...options.include] : void 0;
2118
- if (options.store === false) {
2119
- if (include == null) {
2120
- include = ["reasoning.encrypted_content"];
2121
- } else {
2122
- include = [...include, "reasoning.encrypted_content"];
2123
- }
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;
2136
- const baseArgs = {
2137
- model: this.modelId,
2138
- input,
2139
- logprobs: options.logprobs === true || options.topLogprobs != null ? true : void 0,
2140
- top_logprobs: options.topLogprobs,
2141
- max_output_tokens: maxOutputTokens,
2142
- temperature,
2143
- top_p: topP,
2144
- seed,
2145
- ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && {
2146
- text: {
2147
- format: responseFormat.schema != null ? {
2148
- type: "json_schema",
2149
- strict: true,
2150
- name: (_h = responseFormat.name) != null ? _h : "response",
2151
- description: responseFormat.description,
2152
- schema: responseFormat.schema
2153
- } : { type: "json_object" }
2154
- }
2155
- },
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
- }
2165
- },
2166
- ...options.store === false && {
2167
- store: options.store
2168
- },
2169
- ...include != null && {
2170
- include
2171
- },
2172
- ...options.previousResponseId != null && {
2173
- previous_response_id: options.previousResponseId
2174
- }
2175
- };
2176
- if (xaiTools2 && xaiTools2.length > 0) {
2177
- baseArgs.tools = xaiTools2;
2178
- }
2179
- if (xaiToolChoice != null) {
2180
- baseArgs.tool_choice = xaiToolChoice;
2181
- }
2182
- return {
2183
- args: baseArgs,
2184
- warnings,
2185
- webSearchToolName,
2186
- xSearchToolName,
2187
- codeExecutionToolName,
2188
- mcpToolName,
2189
- fileSearchToolName
2190
- };
2191
- }
2192
- async doGenerate(options) {
2193
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2194
- const {
2195
- args: body,
2196
- warnings,
2197
- webSearchToolName,
2198
- xSearchToolName,
2199
- codeExecutionToolName,
2200
- mcpToolName,
2201
- fileSearchToolName
2202
- } = await this.getArgs(options);
2203
- const {
2204
- responseHeaders,
2205
- value: response,
2206
- rawValue: rawResponse
2207
- } = await postJsonToApi3({
2208
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
2209
- headers: combineHeaders3(this.config.headers(), options.headers),
2210
- body,
2211
- failedResponseHandler: xaiFailedResponseHandler,
2212
- successfulResponseHandler: createJsonResponseHandler3(
2213
- xaiResponsesResponseSchema
2214
- ),
2215
- abortSignal: options.abortSignal,
2216
- fetch: this.config.fetch
2217
- });
2218
- const content = [];
2219
- let hasFunctionCall = false;
2220
- const webSearchSubTools = [
2221
- "web_search",
2222
- "web_search_with_snippets",
2223
- "browse_page"
2224
- ];
2225
- const xSearchSubTools = [
2226
- "x_user_search",
2227
- "x_keyword_search",
2228
- "x_semantic_search",
2229
- "x_thread_fetch"
2230
- ];
2231
- for (const part of response.output) {
2232
- if (part.type === "file_search_call") {
2233
- const toolName = fileSearchToolName != null ? fileSearchToolName : "file_search";
2234
- content.push({
2235
- type: "tool-call",
2236
- toolCallId: part.id,
2237
- toolName,
2238
- input: "",
2239
- providerExecuted: true
2240
- });
2241
- content.push({
2242
- type: "tool-result",
2243
- toolCallId: part.id,
2244
- toolName,
2245
- result: {
2246
- queries: (_b = part.queries) != null ? _b : [],
2247
- results: (_d = (_c = part.results) == null ? void 0 : _c.map((result) => ({
2248
- fileId: result.file_id,
2249
- filename: result.filename,
2250
- score: result.score,
2251
- text: result.text
2252
- }))) != null ? _d : null
2253
- }
2254
- });
2255
- continue;
2256
- }
2257
- 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" || part.type === "mcp_call") {
2258
- let toolName = (_e = part.name) != null ? _e : "";
2259
- if (webSearchSubTools.includes((_f = part.name) != null ? _f : "") || part.type === "web_search_call") {
2260
- toolName = webSearchToolName != null ? webSearchToolName : "web_search";
2261
- } else if (xSearchSubTools.includes((_g = part.name) != null ? _g : "") || part.type === "x_search_call") {
2262
- toolName = xSearchToolName != null ? xSearchToolName : "x_search";
2263
- } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
2264
- toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
2265
- } else if (part.type === "mcp_call") {
2266
- toolName = (_h = mcpToolName != null ? mcpToolName : part.name) != null ? _h : "mcp";
2267
- }
2268
- const toolInput = part.type === "custom_tool_call" ? (_i = part.input) != null ? _i : "" : part.type === "mcp_call" ? (_j = part.arguments) != null ? _j : "" : (_k = part.arguments) != null ? _k : "";
2269
- content.push({
2270
- type: "tool-call",
2271
- toolCallId: part.id,
2272
- toolName,
2273
- input: toolInput,
2274
- providerExecuted: true
2275
- });
2276
- continue;
2277
- }
2278
- switch (part.type) {
2279
- case "message": {
2280
- for (const contentPart of part.content) {
2281
- if (contentPart.text) {
2282
- content.push({
2283
- type: "text",
2284
- text: contentPart.text
2285
- });
2286
- }
2287
- if (contentPart.annotations) {
2288
- for (const annotation of contentPart.annotations) {
2289
- if (annotation.type === "url_citation" && "url" in annotation) {
2290
- content.push({
2291
- type: "source",
2292
- sourceType: "url",
2293
- id: this.config.generateId(),
2294
- url: annotation.url,
2295
- title: (_l = annotation.title) != null ? _l : annotation.url
2296
- });
2297
- }
2298
- }
2299
- }
2300
- }
2301
- break;
2302
- }
2303
- case "function_call": {
2304
- hasFunctionCall = true;
2305
- content.push({
2306
- type: "tool-call",
2307
- toolCallId: part.call_id,
2308
- toolName: part.name,
2309
- input: part.arguments
2310
- });
2311
- break;
2312
- }
2313
- case "reasoning": {
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) {
2317
- if (part.encrypted_content || part.id) {
2318
- content.push({
2319
- type: "reasoning",
2320
- text: reasoningText,
2321
- providerMetadata: {
2322
- xai: {
2323
- ...part.encrypted_content && {
2324
- reasoningEncryptedContent: part.encrypted_content
2325
- },
2326
- ...part.id && { itemId: part.id }
2327
- }
2328
- }
2329
- });
2330
- } else {
2331
- content.push({
2332
- type: "reasoning",
2333
- text: reasoningText
2334
- });
2335
- }
2336
- }
2337
- break;
2338
- }
2339
- default: {
2340
- break;
2341
- }
2342
- }
2343
- }
2344
- return {
2345
- content,
2346
- finishReason: {
2347
- unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response.status),
2348
- raw: (_n = response.status) != null ? _n : void 0
2349
- },
2350
- usage: response.usage ? convertXaiResponsesUsage(response.usage) : {
2351
- inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
2352
- outputTokens: { total: 0, text: 0, reasoning: 0 }
2353
- },
2354
- request: { body },
2355
- response: {
2356
- ...getResponseMetadata(response),
2357
- headers: responseHeaders,
2358
- body: rawResponse
2359
- },
2360
- warnings
2361
- };
2362
- }
2363
- async doStream(options) {
2364
- var _a;
2365
- const {
2366
- args,
2367
- warnings,
2368
- webSearchToolName,
2369
- xSearchToolName,
2370
- codeExecutionToolName,
2371
- mcpToolName,
2372
- fileSearchToolName
2373
- } = await this.getArgs(options);
2374
- const body = {
2375
- ...args,
2376
- stream: true
2377
- };
2378
- const { responseHeaders, value: response } = await postJsonToApi3({
2379
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
2380
- headers: combineHeaders3(this.config.headers(), options.headers),
2381
- body,
2382
- failedResponseHandler: xaiFailedResponseHandler,
2383
- successfulResponseHandler: createEventSourceResponseHandler2(
2384
- xaiResponsesChunkSchema
2385
- ),
2386
- abortSignal: options.abortSignal,
2387
- fetch: this.config.fetch
2388
- });
2389
- let finishReason = {
2390
- unified: "other",
2391
- raw: void 0
2392
- };
2393
- let hasFunctionCall = false;
2394
- let usage = void 0;
2395
- let isFirstChunk = true;
2396
- const contentBlocks = {};
2397
- const seenToolCalls = /* @__PURE__ */ new Set();
2398
- const ongoingToolCalls = {};
2399
- const activeReasoning = {};
2400
- const self = this;
2401
- return {
2402
- stream: response.pipeThrough(
2403
- new TransformStream({
2404
- start(controller) {
2405
- controller.enqueue({ type: "stream-start", warnings });
2406
- },
2407
- transform(chunk, controller) {
2408
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
2409
- if (options.includeRawChunks) {
2410
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2411
- }
2412
- if (!chunk.success) {
2413
- controller.enqueue({ type: "error", error: chunk.error });
2414
- return;
2415
- }
2416
- const event = chunk.value;
2417
- if (event.type === "response.created" || event.type === "response.in_progress") {
2418
- if (isFirstChunk) {
2419
- controller.enqueue({
2420
- type: "response-metadata",
2421
- ...getResponseMetadata(event.response)
2422
- });
2423
- isFirstChunk = false;
2424
- }
2425
- return;
2426
- }
2427
- if (event.type === "response.reasoning_summary_part.added") {
2428
- const blockId = `reasoning-${event.item_id}`;
2429
- activeReasoning[event.item_id] = {};
2430
- controller.enqueue({
2431
- type: "reasoning-start",
2432
- id: blockId,
2433
- providerMetadata: {
2434
- xai: {
2435
- itemId: event.item_id
2436
- }
2437
- }
2438
- });
2439
- }
2440
- if (event.type === "response.reasoning_summary_text.delta") {
2441
- const blockId = `reasoning-${event.item_id}`;
2442
- controller.enqueue({
2443
- type: "reasoning-delta",
2444
- id: blockId,
2445
- delta: event.delta,
2446
- providerMetadata: {
2447
- xai: {
2448
- itemId: event.item_id
2449
- }
2450
- }
2451
- });
2452
- return;
2453
- }
2454
- if (event.type === "response.reasoning_summary_text.done") {
2455
- return;
2456
- }
2457
- if (event.type === "response.reasoning_text.delta") {
2458
- const blockId = `reasoning-${event.item_id}`;
2459
- if (activeReasoning[event.item_id] == null) {
2460
- activeReasoning[event.item_id] = {};
2461
- controller.enqueue({
2462
- type: "reasoning-start",
2463
- id: blockId,
2464
- providerMetadata: {
2465
- xai: {
2466
- itemId: event.item_id
2467
- }
2468
- }
2469
- });
2470
- }
2471
- controller.enqueue({
2472
- type: "reasoning-delta",
2473
- id: blockId,
2474
- delta: event.delta,
2475
- providerMetadata: {
2476
- xai: {
2477
- itemId: event.item_id
2478
- }
2479
- }
2480
- });
2481
- return;
2482
- }
2483
- if (event.type === "response.reasoning_text.done") {
2484
- return;
2485
- }
2486
- if (event.type === "response.output_text.delta") {
2487
- const blockId = `text-${event.item_id}`;
2488
- if (contentBlocks[blockId] == null) {
2489
- contentBlocks[blockId] = { type: "text" };
2490
- controller.enqueue({
2491
- type: "text-start",
2492
- id: blockId
2493
- });
2494
- }
2495
- controller.enqueue({
2496
- type: "text-delta",
2497
- id: blockId,
2498
- delta: event.delta
2499
- });
2500
- return;
2501
- }
2502
- if (event.type === "response.output_text.done") {
2503
- if (event.annotations) {
2504
- for (const annotation of event.annotations) {
2505
- if (annotation.type === "url_citation" && "url" in annotation) {
2506
- controller.enqueue({
2507
- type: "source",
2508
- sourceType: "url",
2509
- id: self.config.generateId(),
2510
- url: annotation.url,
2511
- title: (_a2 = annotation.title) != null ? _a2 : annotation.url
2512
- });
2513
- }
2514
- }
2515
- }
2516
- return;
2517
- }
2518
- if (event.type === "response.output_text.annotation.added") {
2519
- const annotation = event.annotation;
2520
- if (annotation.type === "url_citation" && "url" in annotation) {
2521
- controller.enqueue({
2522
- type: "source",
2523
- sourceType: "url",
2524
- id: self.config.generateId(),
2525
- url: annotation.url,
2526
- title: (_b = annotation.title) != null ? _b : annotation.url
2527
- });
2528
- }
2529
- return;
2530
- }
2531
- if (event.type === "response.done" || event.type === "response.completed" || event.type === "response.incomplete") {
2532
- const response2 = event.response;
2533
- if (response2.usage) {
2534
- usage = convertXaiResponsesUsage(response2.usage);
2535
- }
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) {
2543
- finishReason = {
2544
- unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response2.status),
2545
- raw: response2.status
2546
- };
2547
- }
2548
- return;
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
- }
2565
- if (event.type === "response.custom_tool_call_input.delta" || event.type === "response.custom_tool_call_input.done") {
2566
- return;
2567
- }
2568
- if (event.type === "response.function_call_arguments.delta") {
2569
- const toolCall = ongoingToolCalls[event.output_index];
2570
- if (toolCall != null) {
2571
- controller.enqueue({
2572
- type: "tool-input-delta",
2573
- id: toolCall.toolCallId,
2574
- delta: event.delta
2575
- });
2576
- }
2577
- return;
2578
- }
2579
- if (event.type === "response.function_call_arguments.done") {
2580
- return;
2581
- }
2582
- if (event.type === "response.output_item.added" || event.type === "response.output_item.done") {
2583
- const part = event.item;
2584
- if (part.type === "reasoning") {
2585
- if (event.type === "response.output_item.done") {
2586
- const blockId = `reasoning-${part.id}`;
2587
- if (!(part.id in activeReasoning)) {
2588
- activeReasoning[part.id] = {};
2589
- controller.enqueue({
2590
- type: "reasoning-start",
2591
- id: blockId,
2592
- providerMetadata: {
2593
- xai: {
2594
- ...part.id && { itemId: part.id }
2595
- }
2596
- }
2597
- });
2598
- }
2599
- controller.enqueue({
2600
- type: "reasoning-end",
2601
- id: blockId,
2602
- providerMetadata: {
2603
- xai: {
2604
- ...part.encrypted_content && {
2605
- reasoningEncryptedContent: part.encrypted_content
2606
- },
2607
- ...part.id && { itemId: part.id }
2608
- }
2609
- }
2610
- });
2611
- delete activeReasoning[part.id];
2612
- }
2613
- return;
2614
- }
2615
- if (part.type === "file_search_call") {
2616
- const toolName = fileSearchToolName != null ? fileSearchToolName : "file_search";
2617
- if (!seenToolCalls.has(part.id)) {
2618
- seenToolCalls.add(part.id);
2619
- controller.enqueue({
2620
- type: "tool-input-start",
2621
- id: part.id,
2622
- toolName
2623
- });
2624
- controller.enqueue({
2625
- type: "tool-input-delta",
2626
- id: part.id,
2627
- delta: ""
2628
- });
2629
- controller.enqueue({
2630
- type: "tool-input-end",
2631
- id: part.id
2632
- });
2633
- controller.enqueue({
2634
- type: "tool-call",
2635
- toolCallId: part.id,
2636
- toolName,
2637
- input: "",
2638
- providerExecuted: true
2639
- });
2640
- }
2641
- if (event.type === "response.output_item.done") {
2642
- controller.enqueue({
2643
- type: "tool-result",
2644
- toolCallId: part.id,
2645
- toolName,
2646
- result: {
2647
- queries: (_e = part.queries) != null ? _e : [],
2648
- results: (_g = (_f = part.results) == null ? void 0 : _f.map((result) => ({
2649
- fileId: result.file_id,
2650
- filename: result.filename,
2651
- score: result.score,
2652
- text: result.text
2653
- }))) != null ? _g : null
2654
- }
2655
- });
2656
- }
2657
- return;
2658
- }
2659
- 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" || part.type === "mcp_call") {
2660
- const webSearchSubTools = [
2661
- "web_search",
2662
- "web_search_with_snippets",
2663
- "browse_page"
2664
- ];
2665
- const xSearchSubTools = [
2666
- "x_user_search",
2667
- "x_keyword_search",
2668
- "x_semantic_search",
2669
- "x_thread_fetch"
2670
- ];
2671
- let toolName = (_h = part.name) != null ? _h : "";
2672
- if (webSearchSubTools.includes((_i = part.name) != null ? _i : "") || part.type === "web_search_call") {
2673
- toolName = webSearchToolName != null ? webSearchToolName : "web_search";
2674
- } else if (xSearchSubTools.includes((_j = part.name) != null ? _j : "") || part.type === "x_search_call") {
2675
- toolName = xSearchToolName != null ? xSearchToolName : "x_search";
2676
- } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
2677
- toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
2678
- } else if (part.type === "mcp_call") {
2679
- toolName = (_k = mcpToolName != null ? mcpToolName : part.name) != null ? _k : "mcp";
2680
- }
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 : "";
2682
- const shouldEmit = part.type === "custom_tool_call" ? event.type === "response.output_item.done" : !seenToolCalls.has(part.id);
2683
- if (shouldEmit && !seenToolCalls.has(part.id)) {
2684
- seenToolCalls.add(part.id);
2685
- controller.enqueue({
2686
- type: "tool-input-start",
2687
- id: part.id,
2688
- toolName
2689
- });
2690
- controller.enqueue({
2691
- type: "tool-input-delta",
2692
- id: part.id,
2693
- delta: toolInput
2694
- });
2695
- controller.enqueue({
2696
- type: "tool-input-end",
2697
- id: part.id
2698
- });
2699
- controller.enqueue({
2700
- type: "tool-call",
2701
- toolCallId: part.id,
2702
- toolName,
2703
- input: toolInput,
2704
- providerExecuted: true
2705
- });
2706
- }
2707
- return;
2708
- }
2709
- if (part.type === "message") {
2710
- for (const contentPart of part.content) {
2711
- if (contentPart.text && contentPart.text.length > 0) {
2712
- const blockId = `text-${part.id}`;
2713
- if (contentBlocks[blockId] == null) {
2714
- contentBlocks[blockId] = { type: "text" };
2715
- controller.enqueue({
2716
- type: "text-start",
2717
- id: blockId
2718
- });
2719
- controller.enqueue({
2720
- type: "text-delta",
2721
- id: blockId,
2722
- delta: contentPart.text
2723
- });
2724
- }
2725
- }
2726
- if (contentPart.annotations) {
2727
- for (const annotation of contentPart.annotations) {
2728
- if (annotation.type === "url_citation" && "url" in annotation) {
2729
- controller.enqueue({
2730
- type: "source",
2731
- sourceType: "url",
2732
- id: self.config.generateId(),
2733
- url: annotation.url,
2734
- title: (_o = annotation.title) != null ? _o : annotation.url
2735
- });
2736
- }
2737
- }
2738
- }
2739
- }
2740
- } else if (part.type === "function_call") {
2741
- if (event.type === "response.output_item.added") {
2742
- ongoingToolCalls[event.output_index] = {
2743
- toolName: part.name,
2744
- toolCallId: part.call_id
2745
- };
2746
- controller.enqueue({
2747
- type: "tool-input-start",
2748
- id: part.call_id,
2749
- toolName: part.name
2750
- });
2751
- } else if (event.type === "response.output_item.done") {
2752
- hasFunctionCall = true;
2753
- ongoingToolCalls[event.output_index] = void 0;
2754
- controller.enqueue({
2755
- type: "tool-input-end",
2756
- id: part.call_id
2757
- });
2758
- controller.enqueue({
2759
- type: "tool-call",
2760
- toolCallId: part.call_id,
2761
- toolName: part.name,
2762
- input: part.arguments
2763
- });
2764
- }
2765
- }
2766
- }
2767
- },
2768
- flush(controller) {
2769
- for (const [blockId, block] of Object.entries(contentBlocks)) {
2770
- if (block.type === "text") {
2771
- controller.enqueue({
2772
- type: "text-end",
2773
- id: blockId
2774
- });
2775
- }
2776
- }
2777
- controller.enqueue({
2778
- type: "finish",
2779
- finishReason,
2780
- usage: usage != null ? usage : {
2781
- inputTokens: {
2782
- total: 0,
2783
- noCache: 0,
2784
- cacheRead: 0,
2785
- cacheWrite: 0
2786
- },
2787
- outputTokens: { total: 0, text: 0, reasoning: 0 }
2788
- }
2789
- });
2790
- }
2791
- })
2792
- ),
2793
- request: { body },
2794
- response: { headers: responseHeaders }
2795
- };
2796
- }
2797
- };
2798
-
2799
- // src/tool/code-execution.ts
2800
- import { createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema5 } from "@ai-sdk/provider-utils";
2801
- import { z as z12 } from "zod/v4";
2802
- var codeExecutionOutputSchema = z12.object({
2803
- output: z12.string().describe("the output of the code execution"),
2804
- error: z12.string().optional().describe("any error that occurred")
2805
- });
2806
- var codeExecutionToolFactory = createProviderToolFactoryWithOutputSchema5({
2807
- id: "xai.code_execution",
2808
- inputSchema: z12.object({}).describe("no input parameters"),
2809
- outputSchema: codeExecutionOutputSchema
2810
- });
2811
- var codeExecution = (args = {}) => codeExecutionToolFactory(args);
2812
-
2813
- // src/tool/view-image.ts
2814
- import { createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema6 } from "@ai-sdk/provider-utils";
2815
- import { z as z13 } from "zod/v4";
2816
- var viewImageOutputSchema = z13.object({
2817
- description: z13.string().describe("description of the image"),
2818
- objects: z13.array(z13.string()).optional().describe("objects detected in the image")
2819
- });
2820
- var viewImageToolFactory = createProviderToolFactoryWithOutputSchema6({
2821
- id: "xai.view_image",
2822
- inputSchema: z13.object({}).describe("no input parameters"),
2823
- outputSchema: viewImageOutputSchema
2824
- });
2825
- var viewImage = (args = {}) => viewImageToolFactory(args);
2826
-
2827
- // src/tool/view-x-video.ts
2828
- import { createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema7 } from "@ai-sdk/provider-utils";
2829
- import { z as z14 } from "zod/v4";
2830
- var viewXVideoOutputSchema = z14.object({
2831
- transcript: z14.string().optional().describe("transcript of the video"),
2832
- description: z14.string().describe("description of the video content"),
2833
- duration: z14.number().optional().describe("duration in seconds")
2834
- });
2835
- var viewXVideoToolFactory = createProviderToolFactoryWithOutputSchema7({
2836
- id: "xai.view_x_video",
2837
- inputSchema: z14.object({}).describe("no input parameters"),
2838
- outputSchema: viewXVideoOutputSchema
2839
- });
2840
- var viewXVideo = (args = {}) => viewXVideoToolFactory(args);
2841
-
2842
- // src/tool/index.ts
2843
- var xaiTools = {
2844
- codeExecution,
2845
- fileSearch,
2846
- mcpServer,
2847
- viewImage,
2848
- viewXVideo,
2849
- webSearch,
2850
- xSearch
2851
- };
2852
-
2853
- // src/version.ts
2854
- var VERSION = true ? "4.0.0-beta.34" : "0.0.0-test";
2855
-
2856
- // src/files/xai-files.ts
2857
- import {
2858
- combineHeaders as combineHeaders4,
2859
- convertBase64ToUint8Array,
2860
- createJsonResponseHandler as createJsonResponseHandler4,
2861
- parseProviderOptions as parseProviderOptions4,
2862
- postFormDataToApi
2863
- } from "@ai-sdk/provider-utils";
2864
-
2865
- // src/files/xai-files-api.ts
2866
- import { lazySchema as lazySchema5, zodSchema as zodSchema5 } from "@ai-sdk/provider-utils";
2867
- import { z as z15 } from "zod/v4";
2868
- var xaiFilesResponseSchema = lazySchema5(
2869
- () => zodSchema5(
2870
- z15.object({
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()
2890
- }).passthrough()
2891
- )
2892
- );
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
-
3020
- // src/xai-video-model.ts
3021
- var RESOLUTION_MAP = {
3022
- "1280x720": "720p",
3023
- "854x480": "480p",
3024
- "640x480": "480p"
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
- }
3038
- var XaiVideoModel = class {
3039
- constructor(modelId, config) {
3040
- this.modelId = modelId;
3041
- this.config = config;
3042
- this.specificationVersion = "v4";
3043
- this.maxVideosPerCall = 1;
3044
- }
3045
- get provider() {
3046
- return this.config.provider;
3047
- }
3048
- async doGenerate(options) {
3049
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
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();
3051
- const warnings = [];
3052
- const xaiOptions = await parseProviderOptions5({
3053
- provider: "xai",
3054
- providerOptions: options.providerOptions,
3055
- schema: xaiVideoModelOptionsSchema
3056
- });
3057
- const effectiveMode = resolveVideoMode(xaiOptions);
3058
- const isEdit = effectiveMode === "edit-video";
3059
- const isExtension = effectiveMode === "extend-video";
3060
- const hasReferenceImages = effectiveMode === "reference-to-video";
3061
- if (options.fps != null) {
3062
- warnings.push({
3063
- type: "unsupported",
3064
- feature: "fps",
3065
- details: "xAI video models do not support custom FPS."
3066
- });
3067
- }
3068
- if (options.seed != null) {
3069
- warnings.push({
3070
- type: "unsupported",
3071
- feature: "seed",
3072
- details: "xAI video models do not support seed."
3073
- });
3074
- }
3075
- if (options.n != null && options.n > 1) {
3076
- warnings.push({
3077
- type: "unsupported",
3078
- feature: "n",
3079
- details: "xAI video models do not support generating multiple videos per call. Only 1 video will be generated."
3080
- });
3081
- }
3082
- if (isEdit && options.duration != null) {
3083
- warnings.push({
3084
- type: "unsupported",
3085
- feature: "duration",
3086
- details: "xAI video editing does not support custom duration."
3087
- });
3088
- }
3089
- if (isEdit && options.aspectRatio != null) {
3090
- warnings.push({
3091
- type: "unsupported",
3092
- feature: "aspectRatio",
3093
- details: "xAI video editing does not support custom aspect ratio."
3094
- });
3095
- }
3096
- if (isEdit && ((xaiOptions == null ? void 0 : xaiOptions.resolution) != null || options.resolution != null)) {
3097
- warnings.push({
3098
- type: "unsupported",
3099
- feature: "resolution",
3100
- details: "xAI video editing does not support custom resolution."
3101
- });
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
- }
3117
- const body = {
3118
- model: this.modelId,
3119
- prompt: options.prompt
3120
- };
3121
- const allowDuration = !isEdit;
3122
- const allowAspectRatio = !isEdit && !isExtension;
3123
- const allowResolution = !isEdit && !isExtension;
3124
- if (allowDuration && options.duration != null) {
3125
- body.duration = options.duration;
3126
- }
3127
- if (allowAspectRatio && options.aspectRatio != null) {
3128
- body.aspect_ratio = options.aspectRatio;
3129
- }
3130
- if (allowResolution && (xaiOptions == null ? void 0 : xaiOptions.resolution) != null) {
3131
- body.resolution = xaiOptions.resolution;
3132
- } else if (allowResolution && options.resolution != null) {
3133
- const mapped = RESOLUTION_MAP[options.resolution];
3134
- if (mapped != null) {
3135
- body.resolution = mapped;
3136
- } else {
3137
- warnings.push({
3138
- type: "unsupported",
3139
- feature: "resolution",
3140
- details: `Unrecognized resolution "${options.resolution}". Use providerOptions.xai.resolution with "480p" or "720p" instead.`
3141
- });
3142
- }
3143
- }
3144
- if (isEdit) {
3145
- body.video = { url: xaiOptions.videoUrl };
3146
- }
3147
- if (isExtension) {
3148
- body.video = { url: xaiOptions.videoUrl };
3149
- }
3150
- if (options.image != null) {
3151
- if (options.image.type === "url") {
3152
- body.image = { url: options.image.url };
3153
- } else {
3154
- const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase64(options.image.data);
3155
- body.image = {
3156
- url: `data:${options.image.mediaType};base64,${base64Data}`
3157
- };
3158
- }
3159
- }
3160
- if (hasReferenceImages) {
3161
- body.reference_images = xaiOptions.referenceImageUrls.map((url) => ({
3162
- url
3163
- }));
3164
- }
3165
- if (xaiOptions != null) {
3166
- for (const [key, value] of Object.entries(xaiOptions)) {
3167
- if (![
3168
- "mode",
3169
- "pollIntervalMs",
3170
- "pollTimeoutMs",
3171
- "resolution",
3172
- "videoUrl",
3173
- "referenceImageUrls"
3174
- ].includes(key)) {
3175
- body[key] = value;
3176
- }
3177
- }
3178
- }
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
- }
3188
- const { value: createResponse } = await postJsonToApi4({
3189
- url: endpoint,
3190
- headers: combineHeaders5(this.config.headers(), options.headers),
3191
- body,
3192
- failedResponseHandler: xaiFailedResponseHandler,
3193
- successfulResponseHandler: createJsonResponseHandler5(
3194
- xaiCreateVideoResponseSchema
3195
- ),
3196
- abortSignal: options.abortSignal,
3197
- fetch: this.config.fetch
3198
- });
3199
- const requestId = createResponse.request_id;
3200
- if (!requestId) {
3201
- throw new AISDKError({
3202
- name: "XAI_VIDEO_GENERATION_ERROR",
3203
- message: `No request_id returned from xAI API. Response: ${JSON.stringify(createResponse)}`
3204
- });
3205
- }
3206
- const pollIntervalMs = (_e = xaiOptions == null ? void 0 : xaiOptions.pollIntervalMs) != null ? _e : 5e3;
3207
- const pollTimeoutMs = (_f = xaiOptions == null ? void 0 : xaiOptions.pollTimeoutMs) != null ? _f : 6e5;
3208
- const startTime = Date.now();
3209
- let responseHeaders;
3210
- while (true) {
3211
- await delay(pollIntervalMs, { abortSignal: options.abortSignal });
3212
- if (Date.now() - startTime > pollTimeoutMs) {
3213
- throw new AISDKError({
3214
- name: "XAI_VIDEO_GENERATION_TIMEOUT",
3215
- message: `Video generation timed out after ${pollTimeoutMs}ms`
3216
- });
3217
- }
3218
- const { value: statusResponse, responseHeaders: pollHeaders } = await getFromApi2({
3219
- url: `${baseURL}/videos/${requestId}`,
3220
- headers: combineHeaders5(this.config.headers(), options.headers),
3221
- successfulResponseHandler: createJsonResponseHandler5(
3222
- xaiVideoStatusResponseSchema
3223
- ),
3224
- failedResponseHandler: xaiFailedResponseHandler,
3225
- abortSignal: options.abortSignal,
3226
- fetch: this.config.fetch
3227
- });
3228
- responseHeaders = pollHeaders;
3229
- if (statusResponse.status === "done" || statusResponse.status == null && ((_g = statusResponse.video) == null ? void 0 : _g.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)) {
3237
- throw new AISDKError({
3238
- name: "XAI_VIDEO_GENERATION_ERROR",
3239
- message: "Video generation completed but no video URL was returned."
3240
- });
3241
- }
3242
- return {
3243
- videos: [
3244
- {
3245
- type: "url",
3246
- url: statusResponse.video.url,
3247
- mediaType: "video/mp4"
3248
- }
3249
- ],
3250
- warnings,
3251
- response: {
3252
- timestamp: currentDate,
3253
- modelId: this.modelId,
3254
- headers: responseHeaders
3255
- },
3256
- providerMetadata: {
3257
- xai: {
3258
- requestId,
3259
- videoUrl: statusResponse.video.url,
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 } : {}
3263
- }
3264
- }
3265
- };
3266
- }
3267
- if (statusResponse.status === "expired") {
3268
- throw new AISDKError({
3269
- name: "XAI_VIDEO_GENERATION_EXPIRED",
3270
- message: "Video generation request expired."
3271
- });
3272
- }
3273
- if (statusResponse.status === "failed") {
3274
- throw new AISDKError({
3275
- name: "XAI_VIDEO_GENERATION_FAILED",
3276
- message: "Video generation failed."
3277
- });
3278
- }
3279
- }
3280
- }
3281
- };
3282
- var xaiCreateVideoResponseSchema = z18.object({
3283
- request_id: z18.string().nullish()
3284
- });
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()
3291
- }).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()
3301
- });
3302
-
3303
- // src/xai-provider.ts
3304
- function createXai(options = {}) {
3305
- var _a;
3306
- const baseURL = withoutTrailingSlash(
3307
- (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
3308
- );
3309
- const getHeaders = () => withUserAgentSuffix(
3310
- {
3311
- Authorization: `Bearer ${loadApiKey({
3312
- apiKey: options.apiKey,
3313
- environmentVariableName: "XAI_API_KEY",
3314
- description: "xAI API key"
3315
- })}`,
3316
- ...options.headers
3317
- },
3318
- `ai-sdk/xai/${VERSION}`
3319
- );
3320
- const createChatLanguageModel = (modelId) => {
3321
- return new XaiChatLanguageModel(modelId, {
3322
- provider: "xai.chat",
3323
- baseURL,
3324
- headers: getHeaders,
3325
- generateId,
3326
- fetch: options.fetch
3327
- });
3328
- };
3329
- const createResponsesLanguageModel = (modelId) => {
3330
- return new XaiResponsesLanguageModel(modelId, {
3331
- provider: "xai.responses",
3332
- baseURL,
3333
- headers: getHeaders,
3334
- generateId,
3335
- fetch: options.fetch
3336
- });
3337
- };
3338
- const createImageModel = (modelId) => {
3339
- return new XaiImageModel(modelId, {
3340
- provider: "xai.image",
3341
- baseURL,
3342
- headers: getHeaders,
3343
- fetch: options.fetch
3344
- });
3345
- };
3346
- const createVideoModel = (modelId) => {
3347
- return new XaiVideoModel(modelId, {
3348
- provider: "xai.video",
3349
- baseURL,
3350
- headers: getHeaders,
3351
- fetch: options.fetch
3352
- });
3353
- };
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;
3363
- provider.chat = createChatLanguageModel;
3364
- provider.responses = createResponsesLanguageModel;
3365
- provider.embeddingModel = (modelId) => {
3366
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
3367
- };
3368
- provider.textEmbeddingModel = provider.embeddingModel;
3369
- provider.imageModel = createImageModel;
3370
- provider.image = createImageModel;
3371
- provider.videoModel = createVideoModel;
3372
- provider.video = createVideoModel;
3373
- provider.files = createFiles;
3374
- provider.tools = xaiTools;
3375
- return provider;
3376
- }
3377
- var xai = createXai();
3378
- export {
3379
- VERSION,
3380
- codeExecution,
3381
- createXai,
3382
- mcpServer,
3383
- viewImage,
3384
- viewXVideo,
3385
- webSearch,
3386
- xSearch,
3387
- xai,
3388
- xaiTools
3389
- };
3390
- //# sourceMappingURL=index.mjs.map