@ai-sdk/xai 2.0.0-alpha.8 → 2.0.0-alpha.9
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/CHANGELOG.md +14 -0
- package/dist/index.d.mts +30 -8
- package/dist/index.d.ts +30 -8
- package/dist/index.js +661 -17
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +667 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
// src/xai-provider.ts
|
|
2
2
|
import {
|
|
3
|
-
OpenAICompatibleChatLanguageModel,
|
|
4
3
|
OpenAICompatibleImageModel
|
|
5
4
|
} from "@ai-sdk/openai-compatible";
|
|
6
5
|
import {
|
|
7
6
|
NoSuchModelError
|
|
8
7
|
} from "@ai-sdk/provider";
|
|
9
8
|
import {
|
|
9
|
+
generateId,
|
|
10
10
|
loadApiKey,
|
|
11
11
|
withoutTrailingSlash
|
|
12
12
|
} from "@ai-sdk/provider-utils";
|
|
13
13
|
|
|
14
14
|
// src/xai-chat-options.ts
|
|
15
|
+
import { z } from "zod";
|
|
15
16
|
function supportsStructuredOutputs(modelId) {
|
|
16
17
|
return [
|
|
17
18
|
"grok-3",
|
|
@@ -30,18 +31,673 @@ function supportsStructuredOutputs(modelId) {
|
|
|
30
31
|
"grok-2-vision-1212"
|
|
31
32
|
].includes(modelId);
|
|
32
33
|
}
|
|
34
|
+
var webSourceSchema = z.object({
|
|
35
|
+
type: z.literal("web"),
|
|
36
|
+
country: z.string().length(2).optional(),
|
|
37
|
+
excludedWebsites: z.array(z.string()).max(5).optional(),
|
|
38
|
+
allowedWebsites: z.array(z.string()).max(5).optional(),
|
|
39
|
+
safeSearch: z.boolean().optional()
|
|
40
|
+
});
|
|
41
|
+
var xSourceSchema = z.object({
|
|
42
|
+
type: z.literal("x"),
|
|
43
|
+
xHandles: z.array(z.string()).optional()
|
|
44
|
+
});
|
|
45
|
+
var newsSourceSchema = z.object({
|
|
46
|
+
type: z.literal("news"),
|
|
47
|
+
country: z.string().length(2).optional(),
|
|
48
|
+
excludedWebsites: z.array(z.string()).max(5).optional(),
|
|
49
|
+
safeSearch: z.boolean().optional()
|
|
50
|
+
});
|
|
51
|
+
var rssSourceSchema = z.object({
|
|
52
|
+
type: z.literal("rss"),
|
|
53
|
+
links: z.array(z.string().url()).max(1)
|
|
54
|
+
// currently only supports one RSS link
|
|
55
|
+
});
|
|
56
|
+
var searchSourceSchema = z.discriminatedUnion("type", [
|
|
57
|
+
webSourceSchema,
|
|
58
|
+
xSourceSchema,
|
|
59
|
+
newsSourceSchema,
|
|
60
|
+
rssSourceSchema
|
|
61
|
+
]);
|
|
62
|
+
var xaiProviderOptions = z.object({
|
|
63
|
+
/**
|
|
64
|
+
* reasoning effort for reasoning models
|
|
65
|
+
* only supported by grok-3-mini and grok-3-mini-fast models
|
|
66
|
+
*/
|
|
67
|
+
reasoningEffort: z.enum(["low", "high"]).optional(),
|
|
68
|
+
searchParameters: z.object({
|
|
69
|
+
/**
|
|
70
|
+
* search mode preference
|
|
71
|
+
* - "off": disables search completely
|
|
72
|
+
* - "auto": model decides whether to search (default)
|
|
73
|
+
* - "on": always enables search
|
|
74
|
+
*/
|
|
75
|
+
mode: z.enum(["off", "auto", "on"]),
|
|
76
|
+
/**
|
|
77
|
+
* whether to return citations in the response
|
|
78
|
+
* defaults to true
|
|
79
|
+
*/
|
|
80
|
+
returnCitations: z.boolean().optional(),
|
|
81
|
+
/**
|
|
82
|
+
* start date for search data (ISO8601 format: YYYY-MM-DD)
|
|
83
|
+
*/
|
|
84
|
+
fromDate: z.string().optional(),
|
|
85
|
+
/**
|
|
86
|
+
* end date for search data (ISO8601 format: YYYY-MM-DD)
|
|
87
|
+
*/
|
|
88
|
+
toDate: z.string().optional(),
|
|
89
|
+
/**
|
|
90
|
+
* maximum number of search results to consider
|
|
91
|
+
* defaults to 20
|
|
92
|
+
*/
|
|
93
|
+
maxSearchResults: z.number().min(1).max(50).optional(),
|
|
94
|
+
/**
|
|
95
|
+
* data sources to search from
|
|
96
|
+
* defaults to ["web", "x"] if not specified
|
|
97
|
+
*/
|
|
98
|
+
sources: z.array(searchSourceSchema).optional()
|
|
99
|
+
}).optional()
|
|
100
|
+
});
|
|
33
101
|
|
|
34
102
|
// src/xai-error.ts
|
|
35
|
-
import {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
error:
|
|
103
|
+
import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
|
|
104
|
+
import { z as z2 } from "zod";
|
|
105
|
+
var xaiErrorDataSchema = z2.object({
|
|
106
|
+
error: z2.object({
|
|
107
|
+
message: z2.string(),
|
|
108
|
+
type: z2.string().nullish(),
|
|
109
|
+
param: z2.any().nullish(),
|
|
110
|
+
code: z2.union([z2.string(), z2.number()]).nullish()
|
|
111
|
+
})
|
|
112
|
+
});
|
|
113
|
+
var xaiFailedResponseHandler = createJsonErrorResponseHandler({
|
|
114
|
+
errorSchema: xaiErrorDataSchema,
|
|
115
|
+
errorToMessage: (data) => data.error.message
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// src/xai-chat-language-model.ts
|
|
119
|
+
import {
|
|
120
|
+
combineHeaders,
|
|
121
|
+
createEventSourceResponseHandler,
|
|
122
|
+
createJsonResponseHandler,
|
|
123
|
+
parseProviderOptions,
|
|
124
|
+
postJsonToApi
|
|
125
|
+
} from "@ai-sdk/provider-utils";
|
|
126
|
+
import { z as z3 } from "zod";
|
|
127
|
+
|
|
128
|
+
// src/convert-to-xai-chat-messages.ts
|
|
129
|
+
import {
|
|
130
|
+
UnsupportedFunctionalityError
|
|
131
|
+
} from "@ai-sdk/provider";
|
|
132
|
+
import { convertToBase64 } from "@ai-sdk/provider-utils";
|
|
133
|
+
function convertToXaiChatMessages(prompt) {
|
|
134
|
+
const messages = [];
|
|
135
|
+
const warnings = [];
|
|
136
|
+
for (const { role, content } of prompt) {
|
|
137
|
+
switch (role) {
|
|
138
|
+
case "system": {
|
|
139
|
+
messages.push({ role: "system", content });
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
case "user": {
|
|
143
|
+
if (content.length === 1 && content[0].type === "text") {
|
|
144
|
+
messages.push({ role: "user", content: content[0].text });
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
messages.push({
|
|
148
|
+
role: "user",
|
|
149
|
+
content: content.map((part) => {
|
|
150
|
+
switch (part.type) {
|
|
151
|
+
case "text": {
|
|
152
|
+
return { type: "text", text: part.text };
|
|
153
|
+
}
|
|
154
|
+
case "file": {
|
|
155
|
+
if (part.mediaType.startsWith("image/")) {
|
|
156
|
+
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
|
|
157
|
+
return {
|
|
158
|
+
type: "image_url",
|
|
159
|
+
image_url: {
|
|
160
|
+
url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
} else {
|
|
164
|
+
throw new UnsupportedFunctionalityError({
|
|
165
|
+
functionality: `file part media type ${part.mediaType}`
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
})
|
|
171
|
+
});
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
case "assistant": {
|
|
175
|
+
let text = "";
|
|
176
|
+
const toolCalls = [];
|
|
177
|
+
for (const part of content) {
|
|
178
|
+
switch (part.type) {
|
|
179
|
+
case "text": {
|
|
180
|
+
text += part.text;
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
case "tool-call": {
|
|
184
|
+
toolCalls.push({
|
|
185
|
+
id: part.toolCallId,
|
|
186
|
+
type: "function",
|
|
187
|
+
function: {
|
|
188
|
+
name: part.toolName,
|
|
189
|
+
arguments: JSON.stringify(part.args)
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
messages.push({
|
|
197
|
+
role: "assistant",
|
|
198
|
+
content: text,
|
|
199
|
+
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
|
|
200
|
+
});
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
case "tool": {
|
|
204
|
+
for (const toolResponse of content) {
|
|
205
|
+
messages.push({
|
|
206
|
+
role: "tool",
|
|
207
|
+
tool_call_id: toolResponse.toolCallId,
|
|
208
|
+
content: JSON.stringify(toolResponse.result)
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
default: {
|
|
214
|
+
const _exhaustiveCheck = role;
|
|
215
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return { messages, warnings };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// src/get-response-metadata.ts
|
|
223
|
+
function getResponseMetadata({
|
|
224
|
+
id,
|
|
225
|
+
model,
|
|
226
|
+
created
|
|
227
|
+
}) {
|
|
228
|
+
return {
|
|
229
|
+
id: id != null ? id : void 0,
|
|
230
|
+
modelId: model != null ? model : void 0,
|
|
231
|
+
timestamp: created != null ? new Date(created * 1e3) : void 0
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/map-xai-finish-reason.ts
|
|
236
|
+
function mapXaiFinishReason(finishReason) {
|
|
237
|
+
switch (finishReason) {
|
|
238
|
+
case "stop":
|
|
239
|
+
return "stop";
|
|
240
|
+
case "length":
|
|
241
|
+
return "length";
|
|
242
|
+
case "tool_calls":
|
|
243
|
+
case "function_call":
|
|
244
|
+
return "tool-calls";
|
|
245
|
+
case "content_filter":
|
|
246
|
+
return "content-filter";
|
|
247
|
+
default:
|
|
248
|
+
return "unknown";
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/xai-prepare-tools.ts
|
|
253
|
+
import {
|
|
254
|
+
UnsupportedFunctionalityError as UnsupportedFunctionalityError2
|
|
255
|
+
} from "@ai-sdk/provider";
|
|
256
|
+
function prepareTools({
|
|
257
|
+
tools,
|
|
258
|
+
toolChoice
|
|
259
|
+
}) {
|
|
260
|
+
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
|
|
261
|
+
const toolWarnings = [];
|
|
262
|
+
if (tools == null) {
|
|
263
|
+
return { tools: void 0, toolChoice: void 0, toolWarnings };
|
|
264
|
+
}
|
|
265
|
+
const xaiTools = [];
|
|
266
|
+
for (const tool of tools) {
|
|
267
|
+
if (tool.type === "provider-defined") {
|
|
268
|
+
toolWarnings.push({ type: "unsupported-tool", tool });
|
|
269
|
+
} else {
|
|
270
|
+
xaiTools.push({
|
|
271
|
+
type: "function",
|
|
272
|
+
function: {
|
|
273
|
+
name: tool.name,
|
|
274
|
+
description: tool.description,
|
|
275
|
+
parameters: tool.parameters
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (toolChoice == null) {
|
|
281
|
+
return { tools: xaiTools, toolChoice: void 0, toolWarnings };
|
|
282
|
+
}
|
|
283
|
+
const type = toolChoice.type;
|
|
284
|
+
switch (type) {
|
|
285
|
+
case "auto":
|
|
286
|
+
case "none":
|
|
287
|
+
return { tools: xaiTools, toolChoice: type, toolWarnings };
|
|
288
|
+
case "required":
|
|
289
|
+
return { tools: xaiTools, toolChoice: "required", toolWarnings };
|
|
290
|
+
case "tool":
|
|
291
|
+
return {
|
|
292
|
+
tools: xaiTools,
|
|
293
|
+
toolChoice: {
|
|
294
|
+
type: "function",
|
|
295
|
+
function: { name: toolChoice.toolName }
|
|
296
|
+
},
|
|
297
|
+
toolWarnings
|
|
298
|
+
};
|
|
299
|
+
default: {
|
|
300
|
+
const _exhaustiveCheck = type;
|
|
301
|
+
throw new UnsupportedFunctionalityError2({
|
|
302
|
+
functionality: `tool choice type: ${_exhaustiveCheck}`
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// src/xai-chat-language-model.ts
|
|
309
|
+
var XaiChatLanguageModel = class {
|
|
310
|
+
constructor(modelId, config) {
|
|
311
|
+
this.specificationVersion = "v2";
|
|
312
|
+
this.supportedUrls = {
|
|
313
|
+
"image/*": [/^https?:\/\/.*$/]
|
|
314
|
+
};
|
|
315
|
+
this.modelId = modelId;
|
|
316
|
+
this.config = config;
|
|
317
|
+
}
|
|
318
|
+
get provider() {
|
|
319
|
+
return this.config.provider;
|
|
320
|
+
}
|
|
321
|
+
async getArgs({
|
|
322
|
+
prompt,
|
|
323
|
+
maxOutputTokens,
|
|
324
|
+
temperature,
|
|
325
|
+
topP,
|
|
326
|
+
topK,
|
|
327
|
+
frequencyPenalty,
|
|
328
|
+
presencePenalty,
|
|
329
|
+
stopSequences,
|
|
330
|
+
seed,
|
|
331
|
+
responseFormat,
|
|
332
|
+
providerOptions,
|
|
333
|
+
tools,
|
|
334
|
+
toolChoice
|
|
335
|
+
}) {
|
|
336
|
+
var _a, _b, _c;
|
|
337
|
+
const warnings = [];
|
|
338
|
+
const options = (_a = await parseProviderOptions({
|
|
339
|
+
provider: "xai",
|
|
340
|
+
providerOptions,
|
|
341
|
+
schema: xaiProviderOptions
|
|
342
|
+
})) != null ? _a : {};
|
|
343
|
+
if (topK != null) {
|
|
344
|
+
warnings.push({
|
|
345
|
+
type: "unsupported-setting",
|
|
346
|
+
setting: "topK"
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
if (frequencyPenalty != null) {
|
|
350
|
+
warnings.push({
|
|
351
|
+
type: "unsupported-setting",
|
|
352
|
+
setting: "frequencyPenalty"
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
if (presencePenalty != null) {
|
|
356
|
+
warnings.push({
|
|
357
|
+
type: "unsupported-setting",
|
|
358
|
+
setting: "presencePenalty"
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
if (stopSequences != null) {
|
|
362
|
+
warnings.push({
|
|
363
|
+
type: "unsupported-setting",
|
|
364
|
+
setting: "stopSequences"
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
|
|
368
|
+
warnings.push({
|
|
369
|
+
type: "unsupported-setting",
|
|
370
|
+
setting: "responseFormat",
|
|
371
|
+
details: "JSON response format schema is not supported"
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
|
|
375
|
+
warnings.push(...messageWarnings);
|
|
376
|
+
const {
|
|
377
|
+
tools: xaiTools,
|
|
378
|
+
toolChoice: xaiToolChoice,
|
|
379
|
+
toolWarnings
|
|
380
|
+
} = prepareTools({
|
|
381
|
+
tools,
|
|
382
|
+
toolChoice
|
|
383
|
+
});
|
|
384
|
+
warnings.push(...toolWarnings);
|
|
385
|
+
const baseArgs = {
|
|
386
|
+
// model id
|
|
387
|
+
model: this.modelId,
|
|
388
|
+
// standard generation settings
|
|
389
|
+
max_tokens: maxOutputTokens,
|
|
390
|
+
temperature,
|
|
391
|
+
top_p: topP,
|
|
392
|
+
seed,
|
|
393
|
+
reasoning_effort: options.reasoningEffort,
|
|
394
|
+
// response format
|
|
395
|
+
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
|
|
396
|
+
type: "json_schema",
|
|
397
|
+
json_schema: {
|
|
398
|
+
name: (_b = responseFormat.name) != null ? _b : "response",
|
|
399
|
+
schema: responseFormat.schema,
|
|
400
|
+
strict: true
|
|
401
|
+
}
|
|
402
|
+
} : { type: "json_object" } : void 0,
|
|
403
|
+
// search parameters
|
|
404
|
+
search_parameters: options.searchParameters ? {
|
|
405
|
+
mode: options.searchParameters.mode,
|
|
406
|
+
return_citations: options.searchParameters.returnCitations,
|
|
407
|
+
from_date: options.searchParameters.fromDate,
|
|
408
|
+
to_date: options.searchParameters.toDate,
|
|
409
|
+
max_search_results: options.searchParameters.maxSearchResults,
|
|
410
|
+
sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => ({
|
|
411
|
+
type: source.type,
|
|
412
|
+
...source.type === "web" && {
|
|
413
|
+
country: source.country,
|
|
414
|
+
excluded_websites: source.excludedWebsites,
|
|
415
|
+
allowed_websites: source.allowedWebsites,
|
|
416
|
+
safe_search: source.safeSearch
|
|
417
|
+
},
|
|
418
|
+
...source.type === "x" && {
|
|
419
|
+
x_handles: source.xHandles
|
|
420
|
+
},
|
|
421
|
+
...source.type === "news" && {
|
|
422
|
+
country: source.country,
|
|
423
|
+
excluded_websites: source.excludedWebsites,
|
|
424
|
+
safe_search: source.safeSearch
|
|
425
|
+
},
|
|
426
|
+
...source.type === "rss" && {
|
|
427
|
+
links: source.links
|
|
428
|
+
}
|
|
429
|
+
}))
|
|
430
|
+
} : void 0,
|
|
431
|
+
// messages in xai format
|
|
432
|
+
messages,
|
|
433
|
+
// tools in xai format
|
|
434
|
+
tools: xaiTools,
|
|
435
|
+
tool_choice: xaiToolChoice
|
|
436
|
+
};
|
|
437
|
+
return {
|
|
438
|
+
args: baseArgs,
|
|
439
|
+
warnings
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
async doGenerate(options) {
|
|
443
|
+
var _a, _b, _c;
|
|
444
|
+
const { args: body, warnings } = await this.getArgs(options);
|
|
445
|
+
const {
|
|
446
|
+
responseHeaders,
|
|
447
|
+
value: response,
|
|
448
|
+
rawValue: rawResponse
|
|
449
|
+
} = await postJsonToApi({
|
|
450
|
+
url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
|
|
451
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
452
|
+
body,
|
|
453
|
+
failedResponseHandler: xaiFailedResponseHandler,
|
|
454
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
455
|
+
xaiChatResponseSchema
|
|
456
|
+
),
|
|
457
|
+
abortSignal: options.abortSignal,
|
|
458
|
+
fetch: this.config.fetch
|
|
459
|
+
});
|
|
460
|
+
const choice = response.choices[0];
|
|
461
|
+
const content = [];
|
|
462
|
+
if (choice.message.content != null && choice.message.content.length > 0) {
|
|
463
|
+
let text = choice.message.content;
|
|
464
|
+
const lastMessage = body.messages[body.messages.length - 1];
|
|
465
|
+
if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
|
|
466
|
+
text = "";
|
|
467
|
+
}
|
|
468
|
+
if (text.length > 0) {
|
|
469
|
+
content.push({ type: "text", text });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
|
|
473
|
+
content.push({
|
|
474
|
+
type: "reasoning",
|
|
475
|
+
text: choice.message.reasoning_content
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
if (choice.message.tool_calls != null) {
|
|
479
|
+
for (const toolCall of choice.message.tool_calls) {
|
|
480
|
+
content.push({
|
|
481
|
+
type: "tool-call",
|
|
482
|
+
toolCallType: "function",
|
|
483
|
+
toolCallId: toolCall.id,
|
|
484
|
+
toolName: toolCall.function.name,
|
|
485
|
+
args: toolCall.function.arguments
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (response.citations != null) {
|
|
490
|
+
for (const url of response.citations) {
|
|
491
|
+
content.push({
|
|
492
|
+
type: "source",
|
|
493
|
+
sourceType: "url",
|
|
494
|
+
id: this.config.generateId(),
|
|
495
|
+
url
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return {
|
|
500
|
+
content,
|
|
501
|
+
finishReason: mapXaiFinishReason(choice.finish_reason),
|
|
502
|
+
usage: {
|
|
503
|
+
inputTokens: response.usage.prompt_tokens,
|
|
504
|
+
outputTokens: response.usage.completion_tokens,
|
|
505
|
+
totalTokens: response.usage.total_tokens,
|
|
506
|
+
reasoningTokens: (_c = (_b = response.usage.completion_tokens_details) == null ? void 0 : _b.reasoning_tokens) != null ? _c : void 0
|
|
507
|
+
},
|
|
508
|
+
request: { body },
|
|
509
|
+
response: {
|
|
510
|
+
...getResponseMetadata(response),
|
|
511
|
+
headers: responseHeaders,
|
|
512
|
+
body: rawResponse
|
|
513
|
+
},
|
|
514
|
+
warnings
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
async doStream(options) {
|
|
518
|
+
var _a;
|
|
519
|
+
const { args, warnings } = await this.getArgs(options);
|
|
520
|
+
const body = {
|
|
521
|
+
...args,
|
|
522
|
+
stream: true,
|
|
523
|
+
stream_options: {
|
|
524
|
+
include_usage: true
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
528
|
+
url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
|
|
529
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
530
|
+
body,
|
|
531
|
+
failedResponseHandler: xaiFailedResponseHandler,
|
|
532
|
+
successfulResponseHandler: createEventSourceResponseHandler(xaiChatChunkSchema),
|
|
533
|
+
abortSignal: options.abortSignal,
|
|
534
|
+
fetch: this.config.fetch
|
|
535
|
+
});
|
|
536
|
+
let finishReason = "unknown";
|
|
537
|
+
const usage = {
|
|
538
|
+
inputTokens: void 0,
|
|
539
|
+
outputTokens: void 0,
|
|
540
|
+
totalTokens: void 0
|
|
541
|
+
};
|
|
542
|
+
let isFirstChunk = true;
|
|
543
|
+
const self = this;
|
|
544
|
+
return {
|
|
545
|
+
stream: response.pipeThrough(
|
|
546
|
+
new TransformStream({
|
|
547
|
+
start(controller) {
|
|
548
|
+
controller.enqueue({ type: "stream-start", warnings });
|
|
549
|
+
},
|
|
550
|
+
transform(chunk, controller) {
|
|
551
|
+
var _a2, _b;
|
|
552
|
+
if (!chunk.success) {
|
|
553
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const value = chunk.value;
|
|
557
|
+
if (isFirstChunk) {
|
|
558
|
+
controller.enqueue({
|
|
559
|
+
type: "response-metadata",
|
|
560
|
+
...getResponseMetadata(value)
|
|
561
|
+
});
|
|
562
|
+
isFirstChunk = false;
|
|
563
|
+
}
|
|
564
|
+
if (value.citations != null) {
|
|
565
|
+
for (const url of value.citations) {
|
|
566
|
+
controller.enqueue({
|
|
567
|
+
type: "source",
|
|
568
|
+
sourceType: "url",
|
|
569
|
+
id: self.config.generateId(),
|
|
570
|
+
url
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (value.usage != null) {
|
|
575
|
+
usage.inputTokens = value.usage.prompt_tokens;
|
|
576
|
+
usage.outputTokens = value.usage.completion_tokens;
|
|
577
|
+
usage.totalTokens = value.usage.total_tokens;
|
|
578
|
+
usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
|
|
579
|
+
}
|
|
580
|
+
const choice = value.choices[0];
|
|
581
|
+
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
582
|
+
finishReason = mapXaiFinishReason(choice.finish_reason);
|
|
583
|
+
}
|
|
584
|
+
if ((choice == null ? void 0 : choice.delta) == null) {
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const delta = choice.delta;
|
|
588
|
+
if (delta.content != null && delta.content.length > 0) {
|
|
589
|
+
let textContent = delta.content;
|
|
590
|
+
const lastMessage = body.messages[body.messages.length - 1];
|
|
591
|
+
if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
controller.enqueue({ type: "text", text: textContent });
|
|
595
|
+
}
|
|
596
|
+
if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
|
|
597
|
+
controller.enqueue({
|
|
598
|
+
type: "reasoning",
|
|
599
|
+
text: delta.reasoning_content
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
if (delta.tool_calls != null) {
|
|
603
|
+
for (const toolCall of delta.tool_calls) {
|
|
604
|
+
controller.enqueue({
|
|
605
|
+
type: "tool-call-delta",
|
|
606
|
+
toolCallType: "function",
|
|
607
|
+
toolCallId: toolCall.id,
|
|
608
|
+
toolName: toolCall.function.name,
|
|
609
|
+
argsTextDelta: toolCall.function.arguments
|
|
610
|
+
});
|
|
611
|
+
controller.enqueue({
|
|
612
|
+
type: "tool-call",
|
|
613
|
+
toolCallType: "function",
|
|
614
|
+
toolCallId: toolCall.id,
|
|
615
|
+
toolName: toolCall.function.name,
|
|
616
|
+
args: toolCall.function.arguments
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
},
|
|
621
|
+
flush(controller) {
|
|
622
|
+
controller.enqueue({ type: "finish", finishReason, usage });
|
|
623
|
+
}
|
|
624
|
+
})
|
|
625
|
+
),
|
|
626
|
+
request: { body },
|
|
627
|
+
response: { headers: responseHeaders }
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
var xaiUsageSchema = z3.object({
|
|
632
|
+
prompt_tokens: z3.number(),
|
|
633
|
+
completion_tokens: z3.number(),
|
|
634
|
+
total_tokens: z3.number(),
|
|
635
|
+
completion_tokens_details: z3.object({
|
|
636
|
+
reasoning_tokens: z3.number().nullish()
|
|
637
|
+
}).nullish()
|
|
638
|
+
});
|
|
639
|
+
var xaiChatResponseSchema = z3.object({
|
|
640
|
+
id: z3.string().nullish(),
|
|
641
|
+
created: z3.number().nullish(),
|
|
642
|
+
model: z3.string().nullish(),
|
|
643
|
+
choices: z3.array(
|
|
644
|
+
z3.object({
|
|
645
|
+
message: z3.object({
|
|
646
|
+
role: z3.literal("assistant"),
|
|
647
|
+
content: z3.string().nullish(),
|
|
648
|
+
reasoning_content: z3.string().nullish(),
|
|
649
|
+
tool_calls: z3.array(
|
|
650
|
+
z3.object({
|
|
651
|
+
id: z3.string(),
|
|
652
|
+
type: z3.literal("function"),
|
|
653
|
+
function: z3.object({
|
|
654
|
+
name: z3.string(),
|
|
655
|
+
arguments: z3.string()
|
|
656
|
+
})
|
|
657
|
+
})
|
|
658
|
+
).nullish()
|
|
659
|
+
}),
|
|
660
|
+
index: z3.number(),
|
|
661
|
+
finish_reason: z3.string().nullish()
|
|
662
|
+
})
|
|
663
|
+
),
|
|
664
|
+
object: z3.literal("chat.completion"),
|
|
665
|
+
usage: xaiUsageSchema,
|
|
666
|
+
citations: z3.array(z3.string().url()).nullish()
|
|
667
|
+
});
|
|
668
|
+
var xaiChatChunkSchema = z3.object({
|
|
669
|
+
id: z3.string().nullish(),
|
|
670
|
+
created: z3.number().nullish(),
|
|
671
|
+
model: z3.string().nullish(),
|
|
672
|
+
choices: z3.array(
|
|
673
|
+
z3.object({
|
|
674
|
+
delta: z3.object({
|
|
675
|
+
role: z3.enum(["assistant"]).optional(),
|
|
676
|
+
content: z3.string().nullish(),
|
|
677
|
+
reasoning_content: z3.string().nullish(),
|
|
678
|
+
tool_calls: z3.array(
|
|
679
|
+
z3.object({
|
|
680
|
+
id: z3.string(),
|
|
681
|
+
type: z3.literal("function"),
|
|
682
|
+
function: z3.object({
|
|
683
|
+
name: z3.string(),
|
|
684
|
+
arguments: z3.string()
|
|
685
|
+
})
|
|
686
|
+
})
|
|
687
|
+
).nullish()
|
|
688
|
+
}),
|
|
689
|
+
finish_reason: z3.string().nullish(),
|
|
690
|
+
index: z3.number()
|
|
691
|
+
})
|
|
692
|
+
),
|
|
693
|
+
usage: xaiUsageSchema.nullish(),
|
|
694
|
+
citations: z3.array(z3.string().url()).nullish()
|
|
39
695
|
});
|
|
40
696
|
|
|
41
697
|
// src/xai-provider.ts
|
|
42
698
|
var xaiErrorStructure = {
|
|
43
|
-
errorSchema:
|
|
44
|
-
errorToMessage: (data) => data.error
|
|
699
|
+
errorSchema: xaiErrorDataSchema,
|
|
700
|
+
errorToMessage: (data) => data.error.message
|
|
45
701
|
};
|
|
46
702
|
function createXai(options = {}) {
|
|
47
703
|
var _a;
|
|
@@ -58,14 +714,12 @@ function createXai(options = {}) {
|
|
|
58
714
|
});
|
|
59
715
|
const createLanguageModel = (modelId) => {
|
|
60
716
|
const structuredOutputs = supportsStructuredOutputs(modelId);
|
|
61
|
-
return new
|
|
717
|
+
return new XaiChatLanguageModel(modelId, {
|
|
62
718
|
provider: "xai.chat",
|
|
63
|
-
|
|
719
|
+
baseURL,
|
|
64
720
|
headers: getHeaders,
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
supportsStructuredOutputs: structuredOutputs,
|
|
68
|
-
includeUsage: true
|
|
721
|
+
generateId,
|
|
722
|
+
fetch: options.fetch
|
|
69
723
|
});
|
|
70
724
|
};
|
|
71
725
|
const createImageModel = (modelId) => {
|