@ai-sdk/xai 1.0.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,647 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ createXai: () => createXai,
24
+ xai: () => xai
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // src/xai-provider.ts
29
+ var import_provider4 = require("@ai-sdk/provider");
30
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
31
+
32
+ // src/xai-chat-language-model.ts
33
+ var import_provider3 = require("@ai-sdk/provider");
34
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
35
+ var import_zod2 = require("zod");
36
+
37
+ // src/convert-to-xai-chat-messages.ts
38
+ var import_provider = require("@ai-sdk/provider");
39
+ function convertToXaiChatMessages(prompt) {
40
+ const messages = [];
41
+ for (const { role, content } of prompt) {
42
+ switch (role) {
43
+ case "system": {
44
+ messages.push({ role: "system", content });
45
+ break;
46
+ }
47
+ case "user": {
48
+ if (content.length === 1 && content[0].type === "text") {
49
+ messages.push({ role: "user", content: content[0].text });
50
+ break;
51
+ }
52
+ messages.push({
53
+ role: "user",
54
+ content: content.map((part) => {
55
+ switch (part.type) {
56
+ case "text": {
57
+ return { type: "text", text: part.text };
58
+ }
59
+ case "image": {
60
+ throw new import_provider.UnsupportedFunctionalityError({
61
+ functionality: "Image content parts in user messages"
62
+ });
63
+ }
64
+ case "file": {
65
+ throw new import_provider.UnsupportedFunctionalityError({
66
+ functionality: "File content parts in user messages"
67
+ });
68
+ }
69
+ }
70
+ })
71
+ });
72
+ break;
73
+ }
74
+ case "assistant": {
75
+ let text = "";
76
+ const toolCalls = [];
77
+ for (const part of content) {
78
+ switch (part.type) {
79
+ case "text": {
80
+ text += part.text;
81
+ break;
82
+ }
83
+ case "tool-call": {
84
+ toolCalls.push({
85
+ id: part.toolCallId,
86
+ type: "function",
87
+ function: {
88
+ name: part.toolName,
89
+ arguments: JSON.stringify(part.args)
90
+ }
91
+ });
92
+ break;
93
+ }
94
+ default: {
95
+ const _exhaustiveCheck = part;
96
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
97
+ }
98
+ }
99
+ }
100
+ messages.push({
101
+ role: "assistant",
102
+ content: text,
103
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
104
+ });
105
+ break;
106
+ }
107
+ case "tool": {
108
+ for (const toolResponse of content) {
109
+ messages.push({
110
+ role: "tool",
111
+ tool_call_id: toolResponse.toolCallId,
112
+ content: JSON.stringify(toolResponse.result)
113
+ });
114
+ }
115
+ break;
116
+ }
117
+ default: {
118
+ const _exhaustiveCheck = role;
119
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
120
+ }
121
+ }
122
+ }
123
+ return messages;
124
+ }
125
+
126
+ // src/get-response-metadata.ts
127
+ function getResponseMetadata({
128
+ id,
129
+ model,
130
+ created
131
+ }) {
132
+ return {
133
+ id: id != null ? id : void 0,
134
+ modelId: model != null ? model : void 0,
135
+ timestamp: created != null ? new Date(created * 1e3) : void 0
136
+ };
137
+ }
138
+
139
+ // src/xai-error.ts
140
+ var import_zod = require("zod");
141
+ var import_provider_utils = require("@ai-sdk/provider-utils");
142
+ var xaiErrorDataSchema = import_zod.z.object({
143
+ code: import_zod.z.string(),
144
+ error: import_zod.z.string()
145
+ });
146
+ var xaiFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
147
+ errorSchema: xaiErrorDataSchema,
148
+ errorToMessage: (data) => data.error
149
+ });
150
+
151
+ // src/xai-prepare-tools.ts
152
+ var import_provider2 = require("@ai-sdk/provider");
153
+ function prepareTools({
154
+ mode
155
+ }) {
156
+ var _a;
157
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
158
+ const toolWarnings = [];
159
+ if (tools == null) {
160
+ return { tools: void 0, tool_choice: void 0, toolWarnings };
161
+ }
162
+ const toolChoice = mode.toolChoice;
163
+ const xaiTools = [];
164
+ for (const tool of tools) {
165
+ if (tool.type === "provider-defined") {
166
+ toolWarnings.push({ type: "unsupported-tool", tool });
167
+ } else {
168
+ xaiTools.push({
169
+ type: "function",
170
+ function: {
171
+ name: tool.name,
172
+ description: tool.description,
173
+ parameters: tool.parameters
174
+ }
175
+ });
176
+ }
177
+ }
178
+ if (toolChoice == null) {
179
+ return { tools: xaiTools, tool_choice: void 0, toolWarnings };
180
+ }
181
+ const type = toolChoice.type;
182
+ switch (type) {
183
+ case "auto":
184
+ case "none":
185
+ case "required":
186
+ return { tools: xaiTools, tool_choice: type, toolWarnings };
187
+ case "tool":
188
+ return {
189
+ tools: xaiTools,
190
+ tool_choice: {
191
+ type: "function",
192
+ function: {
193
+ name: toolChoice.toolName
194
+ }
195
+ },
196
+ toolWarnings
197
+ };
198
+ default: {
199
+ const _exhaustiveCheck = type;
200
+ throw new import_provider2.UnsupportedFunctionalityError({
201
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
202
+ });
203
+ }
204
+ }
205
+ }
206
+
207
+ // src/map-xai-finish-reason.ts
208
+ function mapXaiFinishReason(finishReason) {
209
+ switch (finishReason) {
210
+ case "stop":
211
+ return "stop";
212
+ case "length":
213
+ return "length";
214
+ case "content_filter":
215
+ return "content-filter";
216
+ case "function_call":
217
+ case "tool_calls":
218
+ return "tool-calls";
219
+ default:
220
+ return "unknown";
221
+ }
222
+ }
223
+
224
+ // src/xai-chat-language-model.ts
225
+ var XaiChatLanguageModel = class {
226
+ constructor(modelId, settings, config) {
227
+ this.specificationVersion = "v1";
228
+ this.supportsStructuredOutputs = false;
229
+ this.defaultObjectGenerationMode = "tool";
230
+ this.modelId = modelId;
231
+ this.settings = settings;
232
+ this.config = config;
233
+ }
234
+ get provider() {
235
+ return this.config.provider;
236
+ }
237
+ getArgs({
238
+ mode,
239
+ prompt,
240
+ maxTokens,
241
+ temperature,
242
+ topP,
243
+ topK,
244
+ frequencyPenalty,
245
+ presencePenalty,
246
+ stopSequences,
247
+ responseFormat,
248
+ seed,
249
+ stream
250
+ }) {
251
+ const type = mode.type;
252
+ const warnings = [];
253
+ if (topK != null) {
254
+ warnings.push({
255
+ type: "unsupported-setting",
256
+ setting: "topK"
257
+ });
258
+ }
259
+ if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
260
+ warnings.push({
261
+ type: "unsupported-setting",
262
+ setting: "responseFormat",
263
+ details: "JSON response format schema is not supported"
264
+ });
265
+ }
266
+ const baseArgs = {
267
+ // model id:
268
+ model: this.modelId,
269
+ // model specific settings:
270
+ user: this.settings.user,
271
+ // standardized settings:
272
+ max_tokens: maxTokens,
273
+ temperature,
274
+ top_p: topP,
275
+ frequency_penalty: frequencyPenalty,
276
+ presence_penalty: presencePenalty,
277
+ stop: stopSequences,
278
+ seed,
279
+ // response format:
280
+ response_format: (
281
+ // json object response format is not currently supported
282
+ void 0
283
+ ),
284
+ // messages:
285
+ messages: convertToXaiChatMessages(prompt)
286
+ };
287
+ switch (type) {
288
+ case "regular": {
289
+ const { tools, tool_choice, toolWarnings } = prepareTools({ mode });
290
+ return {
291
+ args: {
292
+ ...baseArgs,
293
+ tools,
294
+ tool_choice
295
+ },
296
+ warnings: [...warnings, ...toolWarnings]
297
+ };
298
+ }
299
+ case "object-json": {
300
+ throw new import_provider3.UnsupportedFunctionalityError({
301
+ functionality: "object-json mode"
302
+ });
303
+ }
304
+ case "object-tool": {
305
+ return {
306
+ args: {
307
+ ...baseArgs,
308
+ tool_choice: {
309
+ type: "function",
310
+ function: { name: mode.tool.name }
311
+ },
312
+ tools: [
313
+ {
314
+ type: "function",
315
+ function: {
316
+ name: mode.tool.name,
317
+ description: mode.tool.description,
318
+ parameters: mode.tool.parameters
319
+ }
320
+ }
321
+ ]
322
+ },
323
+ warnings
324
+ };
325
+ }
326
+ default: {
327
+ const _exhaustiveCheck = type;
328
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
329
+ }
330
+ }
331
+ }
332
+ async doGenerate(options) {
333
+ var _a, _b, _c, _d, _e, _f;
334
+ const { args, warnings } = this.getArgs({ ...options, stream: false });
335
+ const body = JSON.stringify(args);
336
+ const { responseHeaders, value: response } = await (0, import_provider_utils2.postJsonToApi)({
337
+ url: this.config.url({
338
+ path: "/chat/completions",
339
+ modelId: this.modelId
340
+ }),
341
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
342
+ body: args,
343
+ failedResponseHandler: xaiFailedResponseHandler,
344
+ successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(
345
+ xaiChatResponseSchema
346
+ ),
347
+ abortSignal: options.abortSignal,
348
+ fetch: this.config.fetch
349
+ });
350
+ const { messages: rawPrompt, ...rawSettings } = args;
351
+ const choice = response.choices[0];
352
+ return {
353
+ text: (_a = choice.message.content) != null ? _a : void 0,
354
+ toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => {
355
+ var _a2;
356
+ return {
357
+ toolCallType: "function",
358
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : (0, import_provider_utils2.generateId)(),
359
+ toolName: toolCall.function.name,
360
+ args: toolCall.function.arguments
361
+ };
362
+ }),
363
+ finishReason: mapXaiFinishReason(choice.finish_reason),
364
+ usage: {
365
+ promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : NaN,
366
+ completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : NaN
367
+ },
368
+ rawCall: { rawPrompt, rawSettings },
369
+ rawResponse: { headers: responseHeaders },
370
+ response: getResponseMetadata(response),
371
+ warnings,
372
+ request: { body }
373
+ };
374
+ }
375
+ async doStream(options) {
376
+ const { args, warnings } = this.getArgs({ ...options, stream: true });
377
+ const body = JSON.stringify({ ...args, stream: true });
378
+ const { responseHeaders, value: response } = await (0, import_provider_utils2.postJsonToApi)({
379
+ url: this.config.url({
380
+ path: "/chat/completions",
381
+ modelId: this.modelId
382
+ }),
383
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
384
+ body: {
385
+ ...args,
386
+ stream: true
387
+ },
388
+ failedResponseHandler: xaiFailedResponseHandler,
389
+ successfulResponseHandler: (0, import_provider_utils2.createEventSourceResponseHandler)(xaiChatChunkSchema),
390
+ abortSignal: options.abortSignal,
391
+ fetch: this.config.fetch
392
+ });
393
+ const { messages: rawPrompt, ...rawSettings } = args;
394
+ const toolCalls = [];
395
+ let finishReason = "unknown";
396
+ let usage = {
397
+ promptTokens: void 0,
398
+ completionTokens: void 0
399
+ };
400
+ let isFirstChunk = true;
401
+ let providerMetadata;
402
+ return {
403
+ stream: response.pipeThrough(
404
+ new TransformStream({
405
+ transform(chunk, controller) {
406
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
407
+ if (!chunk.success) {
408
+ finishReason = "error";
409
+ controller.enqueue({ type: "error", error: chunk.error });
410
+ return;
411
+ }
412
+ const value = chunk.value;
413
+ if ("error" in value) {
414
+ finishReason = "error";
415
+ controller.enqueue({ type: "error", error: value.error });
416
+ return;
417
+ }
418
+ if (isFirstChunk) {
419
+ isFirstChunk = false;
420
+ controller.enqueue({
421
+ type: "response-metadata",
422
+ ...getResponseMetadata(value)
423
+ });
424
+ }
425
+ if (value.usage != null) {
426
+ usage = {
427
+ promptTokens: (_a = value.usage.prompt_tokens) != null ? _a : void 0,
428
+ completionTokens: (_b = value.usage.completion_tokens) != null ? _b : void 0
429
+ };
430
+ }
431
+ const choice = value.choices[0];
432
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
433
+ finishReason = mapXaiFinishReason(choice.finish_reason);
434
+ }
435
+ if ((choice == null ? void 0 : choice.delta) == null) {
436
+ return;
437
+ }
438
+ const delta = choice.delta;
439
+ if (delta.content != null) {
440
+ controller.enqueue({
441
+ type: "text-delta",
442
+ textDelta: delta.content
443
+ });
444
+ }
445
+ if (delta.tool_calls != null) {
446
+ for (const toolCallDelta of delta.tool_calls) {
447
+ const index = toolCallDelta.index;
448
+ if (toolCalls[index] == null) {
449
+ if (toolCallDelta.type !== "function") {
450
+ throw new import_provider3.InvalidResponseDataError({
451
+ data: toolCallDelta,
452
+ message: `Expected 'function' type.`
453
+ });
454
+ }
455
+ if (toolCallDelta.id == null) {
456
+ throw new import_provider3.InvalidResponseDataError({
457
+ data: toolCallDelta,
458
+ message: `Expected 'id' to be a string.`
459
+ });
460
+ }
461
+ if (((_c = toolCallDelta.function) == null ? void 0 : _c.name) == null) {
462
+ throw new import_provider3.InvalidResponseDataError({
463
+ data: toolCallDelta,
464
+ message: `Expected 'function.name' to be a string.`
465
+ });
466
+ }
467
+ toolCalls[index] = {
468
+ id: toolCallDelta.id,
469
+ type: "function",
470
+ function: {
471
+ name: toolCallDelta.function.name,
472
+ arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
473
+ }
474
+ };
475
+ const toolCall2 = toolCalls[index];
476
+ if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.arguments) != null) {
477
+ if (toolCall2.function.arguments.length > 0) {
478
+ controller.enqueue({
479
+ type: "tool-call-delta",
480
+ toolCallType: "function",
481
+ toolCallId: toolCall2.id,
482
+ toolName: toolCall2.function.name,
483
+ argsTextDelta: toolCall2.function.arguments
484
+ });
485
+ }
486
+ if ((0, import_provider_utils2.isParsableJson)(toolCall2.function.arguments)) {
487
+ controller.enqueue({
488
+ type: "tool-call",
489
+ toolCallType: "function",
490
+ toolCallId: (_g = toolCall2.id) != null ? _g : (0, import_provider_utils2.generateId)(),
491
+ toolName: toolCall2.function.name,
492
+ args: toolCall2.function.arguments
493
+ });
494
+ }
495
+ }
496
+ continue;
497
+ }
498
+ const toolCall = toolCalls[index];
499
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
500
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
501
+ }
502
+ controller.enqueue({
503
+ type: "tool-call-delta",
504
+ toolCallType: "function",
505
+ toolCallId: toolCall.id,
506
+ toolName: toolCall.function.name,
507
+ argsTextDelta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
508
+ });
509
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && (0, import_provider_utils2.isParsableJson)(toolCall.function.arguments)) {
510
+ controller.enqueue({
511
+ type: "tool-call",
512
+ toolCallType: "function",
513
+ toolCallId: (_n = toolCall.id) != null ? _n : (0, import_provider_utils2.generateId)(),
514
+ toolName: toolCall.function.name,
515
+ args: toolCall.function.arguments
516
+ });
517
+ }
518
+ }
519
+ }
520
+ },
521
+ flush(controller) {
522
+ var _a, _b;
523
+ controller.enqueue({
524
+ type: "finish",
525
+ finishReason,
526
+ usage: {
527
+ promptTokens: (_a = usage.promptTokens) != null ? _a : NaN,
528
+ completionTokens: (_b = usage.completionTokens) != null ? _b : NaN
529
+ },
530
+ ...providerMetadata != null ? { providerMetadata } : {}
531
+ });
532
+ }
533
+ })
534
+ ),
535
+ rawCall: { rawPrompt, rawSettings },
536
+ rawResponse: { headers: responseHeaders },
537
+ warnings,
538
+ request: { body }
539
+ };
540
+ }
541
+ };
542
+ var xaiChatResponseSchema = import_zod2.z.object({
543
+ id: import_zod2.z.string().nullish(),
544
+ created: import_zod2.z.number().nullish(),
545
+ model: import_zod2.z.string().nullish(),
546
+ choices: import_zod2.z.array(
547
+ import_zod2.z.object({
548
+ message: import_zod2.z.object({
549
+ role: import_zod2.z.literal("assistant").nullish(),
550
+ content: import_zod2.z.string().nullish(),
551
+ tool_calls: import_zod2.z.array(
552
+ import_zod2.z.object({
553
+ id: import_zod2.z.string().nullish(),
554
+ type: import_zod2.z.literal("function"),
555
+ function: import_zod2.z.object({
556
+ name: import_zod2.z.string(),
557
+ arguments: import_zod2.z.string()
558
+ })
559
+ })
560
+ ).nullish()
561
+ }),
562
+ index: import_zod2.z.number(),
563
+ finish_reason: import_zod2.z.string().nullish()
564
+ })
565
+ ),
566
+ usage: import_zod2.z.object({
567
+ prompt_tokens: import_zod2.z.number().nullish(),
568
+ completion_tokens: import_zod2.z.number().nullish()
569
+ }).nullish()
570
+ });
571
+ var xaiChatChunkSchema = import_zod2.z.union([
572
+ import_zod2.z.object({
573
+ id: import_zod2.z.string().nullish(),
574
+ created: import_zod2.z.number().nullish(),
575
+ model: import_zod2.z.string().nullish(),
576
+ choices: import_zod2.z.array(
577
+ import_zod2.z.object({
578
+ delta: import_zod2.z.object({
579
+ role: import_zod2.z.enum(["assistant"]).nullish(),
580
+ content: import_zod2.z.string().nullish(),
581
+ tool_calls: import_zod2.z.array(
582
+ import_zod2.z.object({
583
+ index: import_zod2.z.number(),
584
+ id: import_zod2.z.string().nullish(),
585
+ type: import_zod2.z.literal("function").optional(),
586
+ function: import_zod2.z.object({
587
+ name: import_zod2.z.string().nullish(),
588
+ arguments: import_zod2.z.string().nullish()
589
+ })
590
+ })
591
+ ).nullish()
592
+ }).nullish(),
593
+ finish_reason: import_zod2.z.string().nullable().optional(),
594
+ index: import_zod2.z.number()
595
+ })
596
+ ),
597
+ usage: import_zod2.z.object({
598
+ prompt_tokens: import_zod2.z.number().nullish(),
599
+ completion_tokens: import_zod2.z.number().nullish()
600
+ }).nullish()
601
+ }),
602
+ xaiErrorDataSchema
603
+ ]);
604
+
605
+ // src/xai-provider.ts
606
+ function createXai(options = {}) {
607
+ var _a;
608
+ const baseURL = (_a = (0, import_provider_utils3.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://api.x.ai/v1";
609
+ const getHeaders = () => ({
610
+ Authorization: `Bearer ${(0, import_provider_utils3.loadApiKey)({
611
+ apiKey: options.apiKey,
612
+ environmentVariableName: "XAI_API_KEY",
613
+ description: "xAI"
614
+ })}`,
615
+ ...options.headers
616
+ });
617
+ const createChatModel = (modelId, settings = {}) => new XaiChatLanguageModel(modelId, settings, {
618
+ provider: "xai.chat",
619
+ url: ({ path }) => `${baseURL}${path}`,
620
+ headers: getHeaders,
621
+ fetch: options.fetch
622
+ });
623
+ const createLanguageModel = (modelId, settings) => {
624
+ if (new.target) {
625
+ throw new Error(
626
+ "The xAI model function cannot be called with the new keyword."
627
+ );
628
+ }
629
+ return createChatModel(modelId, settings);
630
+ };
631
+ const provider = function(modelId, settings) {
632
+ return createLanguageModel(modelId, settings);
633
+ };
634
+ provider.languageModel = createLanguageModel;
635
+ provider.chat = createChatModel;
636
+ provider.textEmbeddingModel = (modelId) => {
637
+ throw new import_provider4.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
638
+ };
639
+ return provider;
640
+ }
641
+ var xai = createXai();
642
+ // Annotate the CommonJS export names for ESM import in node:
643
+ 0 && (module.exports = {
644
+ createXai,
645
+ xai
646
+ });
647
+ //# sourceMappingURL=index.js.map