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