@mastra/server 0.20.1-alpha.3 → 0.20.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{chunk-TMU7NSW7.js → chunk-HKW2536J.js} +5852 -2557
  3. package/dist/chunk-HKW2536J.js.map +1 -0
  4. package/dist/{chunk-AFJBHPHA.cjs → chunk-KJJA7GPJ.cjs} +6308 -2994
  5. package/dist/chunk-KJJA7GPJ.cjs.map +1 -0
  6. package/dist/server/handlers/agent-builder.cjs +16 -16
  7. package/dist/server/handlers/agent-builder.js +1 -1
  8. package/dist/server/handlers.cjs +2 -2
  9. package/dist/server/handlers.js +1 -1
  10. package/package.json +6 -6
  11. package/dist/chunk-44GFD2TF.js +0 -419
  12. package/dist/chunk-44GFD2TF.js.map +0 -1
  13. package/dist/chunk-75KU7JB6.cjs +0 -588
  14. package/dist/chunk-75KU7JB6.cjs.map +0 -1
  15. package/dist/chunk-77TGJGDW.cjs +0 -1279
  16. package/dist/chunk-77TGJGDW.cjs.map +0 -1
  17. package/dist/chunk-AFJBHPHA.cjs.map +0 -1
  18. package/dist/chunk-CHDN4NEY.js +0 -1277
  19. package/dist/chunk-CHDN4NEY.js.map +0 -1
  20. package/dist/chunk-EAIAF7Z6.js +0 -571
  21. package/dist/chunk-EAIAF7Z6.js.map +0 -1
  22. package/dist/chunk-TMU7NSW7.js.map +0 -1
  23. package/dist/chunk-WO2SYFUI.js +0 -5945
  24. package/dist/chunk-WO2SYFUI.js.map +0 -1
  25. package/dist/chunk-XCR65STK.cjs +0 -433
  26. package/dist/chunk-XCR65STK.cjs.map +0 -1
  27. package/dist/chunk-YWACVZRO.cjs +0 -5985
  28. package/dist/chunk-YWACVZRO.cjs.map +0 -1
  29. package/dist/dist-36GPHJSB.cjs +0 -2014
  30. package/dist/dist-36GPHJSB.cjs.map +0 -1
  31. package/dist/dist-3WEYC4YO.js +0 -2007
  32. package/dist/dist-3WEYC4YO.js.map +0 -1
  33. package/dist/dist-7MBYKZSM.js +0 -846
  34. package/dist/dist-7MBYKZSM.js.map +0 -1
  35. package/dist/dist-FGYSUA65.cjs +0 -935
  36. package/dist/dist-FGYSUA65.cjs.map +0 -1
  37. package/dist/dist-FNKPY5I5.cjs +0 -1412
  38. package/dist/dist-FNKPY5I5.cjs.map +0 -1
  39. package/dist/dist-H5ZHQKYG.js +0 -3
  40. package/dist/dist-H5ZHQKYG.js.map +0 -1
  41. package/dist/dist-HBUYSRRO.cjs +0 -850
  42. package/dist/dist-HBUYSRRO.cjs.map +0 -1
  43. package/dist/dist-IUCBLZK6.js +0 -1409
  44. package/dist/dist-IUCBLZK6.js.map +0 -1
  45. package/dist/dist-M4HXCUXC.cjs +0 -20
  46. package/dist/dist-M4HXCUXC.cjs.map +0 -1
  47. package/dist/dist-P32YPL35.js +0 -932
  48. package/dist/dist-P32YPL35.js.map +0 -1
@@ -1,935 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk75KU7JB6_cjs = require('./chunk-75KU7JB6.cjs');
4
- var chunkXCR65STK_cjs = require('./chunk-XCR65STK.cjs');
5
- var v4 = require('zod/v4');
6
-
7
- v4.z.object({
8
- /**
9
- * A unique identifier representing your end-user, which can help the provider to
10
- * monitor and detect abuse.
11
- */
12
- user: v4.z.string().optional(),
13
- /**
14
- * Reasoning effort for reasoning models. Defaults to `medium`.
15
- */
16
- reasoningEffort: v4.z.string().optional()
17
- });
18
- var openaiCompatibleErrorDataSchema = v4.z.object({
19
- error: v4.z.object({
20
- message: v4.z.string(),
21
- // The additional information below is handled loosely to support
22
- // OpenAI-compatible providers that have slightly different error
23
- // responses:
24
- type: v4.z.string().nullish(),
25
- param: v4.z.any().nullish(),
26
- code: v4.z.union([v4.z.string(), v4.z.number()]).nullish()
27
- })
28
- });
29
- var defaultOpenAICompatibleErrorStructure = {
30
- errorSchema: openaiCompatibleErrorDataSchema,
31
- errorToMessage: (data) => data.error.message
32
- };
33
- var openaiCompatibleTokenUsageSchema = v4.z.object({
34
- prompt_tokens: v4.z.number().nullish(),
35
- completion_tokens: v4.z.number().nullish(),
36
- total_tokens: v4.z.number().nullish(),
37
- prompt_tokens_details: v4.z.object({
38
- cached_tokens: v4.z.number().nullish()
39
- }).nullish(),
40
- completion_tokens_details: v4.z.object({
41
- reasoning_tokens: v4.z.number().nullish(),
42
- accepted_prediction_tokens: v4.z.number().nullish(),
43
- rejected_prediction_tokens: v4.z.number().nullish()
44
- }).nullish()
45
- }).nullish();
46
- v4.z.object({
47
- id: v4.z.string().nullish(),
48
- created: v4.z.number().nullish(),
49
- model: v4.z.string().nullish(),
50
- choices: v4.z.array(
51
- v4.z.object({
52
- message: v4.z.object({
53
- role: v4.z.literal("assistant").nullish(),
54
- content: v4.z.string().nullish(),
55
- reasoning_content: v4.z.string().nullish(),
56
- reasoning: v4.z.string().nullish(),
57
- tool_calls: v4.z.array(
58
- v4.z.object({
59
- id: v4.z.string().nullish(),
60
- function: v4.z.object({
61
- name: v4.z.string(),
62
- arguments: v4.z.string()
63
- })
64
- })
65
- ).nullish()
66
- }),
67
- finish_reason: v4.z.string().nullish()
68
- })
69
- ),
70
- usage: openaiCompatibleTokenUsageSchema
71
- });
72
- v4.z.object({
73
- /**
74
- * Echo back the prompt in addition to the completion.
75
- */
76
- echo: v4.z.boolean().optional(),
77
- /**
78
- * Modify the likelihood of specified tokens appearing in the completion.
79
- *
80
- * Accepts a JSON object that maps tokens (specified by their token ID in
81
- * the GPT tokenizer) to an associated bias value from -100 to 100.
82
- */
83
- logitBias: v4.z.record(v4.z.string(), v4.z.number()).optional(),
84
- /**
85
- * The suffix that comes after a completion of inserted text.
86
- */
87
- suffix: v4.z.string().optional(),
88
- /**
89
- * A unique identifier representing your end-user, which can help providers to
90
- * monitor and detect abuse.
91
- */
92
- user: v4.z.string().optional()
93
- });
94
- var usageSchema = v4.z.object({
95
- prompt_tokens: v4.z.number(),
96
- completion_tokens: v4.z.number(),
97
- total_tokens: v4.z.number()
98
- });
99
- v4.z.object({
100
- id: v4.z.string().nullish(),
101
- created: v4.z.number().nullish(),
102
- model: v4.z.string().nullish(),
103
- choices: v4.z.array(
104
- v4.z.object({
105
- text: v4.z.string(),
106
- finish_reason: v4.z.string()
107
- })
108
- ),
109
- usage: usageSchema.nullish()
110
- });
111
- v4.z.object({
112
- /**
113
- * The number of dimensions the resulting output embeddings should have.
114
- * Only supported in text-embedding-3 and later models.
115
- */
116
- dimensions: v4.z.number().optional(),
117
- /**
118
- * A unique identifier representing your end-user, which can help providers to
119
- * monitor and detect abuse.
120
- */
121
- user: v4.z.string().optional()
122
- });
123
- v4.z.object({
124
- data: v4.z.array(v4.z.object({ embedding: v4.z.array(v4.z.number()) })),
125
- usage: v4.z.object({ prompt_tokens: v4.z.number() }).nullish(),
126
- providerMetadata: v4.z.record(v4.z.string(), v4.z.record(v4.z.string(), v4.z.any())).optional()
127
- });
128
- var OpenAICompatibleImageModel = class {
129
- constructor(modelId, config) {
130
- this.modelId = modelId;
131
- this.config = config;
132
- this.specificationVersion = "v2";
133
- this.maxImagesPerCall = 10;
134
- }
135
- get provider() {
136
- return this.config.provider;
137
- }
138
- async doGenerate({
139
- prompt,
140
- n,
141
- size,
142
- aspectRatio,
143
- seed,
144
- providerOptions,
145
- headers,
146
- abortSignal
147
- }) {
148
- var _a, _b, _c, _d, _e;
149
- const warnings = [];
150
- if (aspectRatio != null) {
151
- warnings.push({
152
- type: "unsupported-setting",
153
- setting: "aspectRatio",
154
- details: "This model does not support aspect ratio. Use `size` instead."
155
- });
156
- }
157
- if (seed != null) {
158
- warnings.push({ type: "unsupported-setting", setting: "seed" });
159
- }
160
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
161
- const { value: response, responseHeaders } = await chunk75KU7JB6_cjs.postJsonToApi({
162
- url: this.config.url({
163
- path: "/images/generations",
164
- modelId: this.modelId
165
- }),
166
- headers: chunk75KU7JB6_cjs.combineHeaders(this.config.headers(), headers),
167
- body: {
168
- model: this.modelId,
169
- prompt,
170
- n,
171
- size,
172
- ...(_d = providerOptions.openai) != null ? _d : {},
173
- response_format: "b64_json"
174
- },
175
- failedResponseHandler: chunk75KU7JB6_cjs.createJsonErrorResponseHandler(
176
- (_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure
177
- ),
178
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(
179
- openaiCompatibleImageResponseSchema
180
- ),
181
- abortSignal,
182
- fetch: this.config.fetch
183
- });
184
- return {
185
- images: response.data.map((item) => item.b64_json),
186
- warnings,
187
- response: {
188
- timestamp: currentDate,
189
- modelId: this.modelId,
190
- headers: responseHeaders
191
- }
192
- };
193
- }
194
- };
195
- var openaiCompatibleImageResponseSchema = v4.z.object({
196
- data: v4.z.array(v4.z.object({ b64_json: v4.z.string() }))
197
- });
198
- function convertToXaiChatMessages(prompt) {
199
- const messages = [];
200
- const warnings = [];
201
- for (const { role, content } of prompt) {
202
- switch (role) {
203
- case "system": {
204
- messages.push({ role: "system", content });
205
- break;
206
- }
207
- case "user": {
208
- if (content.length === 1 && content[0].type === "text") {
209
- messages.push({ role: "user", content: content[0].text });
210
- break;
211
- }
212
- messages.push({
213
- role: "user",
214
- content: content.map((part) => {
215
- switch (part.type) {
216
- case "text": {
217
- return { type: "text", text: part.text };
218
- }
219
- case "file": {
220
- if (part.mediaType.startsWith("image/")) {
221
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
222
- return {
223
- type: "image_url",
224
- image_url: {
225
- url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunk75KU7JB6_cjs.convertToBase64(part.data)}`
226
- }
227
- };
228
- } else {
229
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
230
- functionality: `file part media type ${part.mediaType}`
231
- });
232
- }
233
- }
234
- }
235
- })
236
- });
237
- break;
238
- }
239
- case "assistant": {
240
- let text = "";
241
- const toolCalls = [];
242
- for (const part of content) {
243
- switch (part.type) {
244
- case "text": {
245
- text += part.text;
246
- break;
247
- }
248
- case "tool-call": {
249
- toolCalls.push({
250
- id: part.toolCallId,
251
- type: "function",
252
- function: {
253
- name: part.toolName,
254
- arguments: JSON.stringify(part.input)
255
- }
256
- });
257
- break;
258
- }
259
- }
260
- }
261
- messages.push({
262
- role: "assistant",
263
- content: text,
264
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
265
- });
266
- break;
267
- }
268
- case "tool": {
269
- for (const toolResponse of content) {
270
- const output = toolResponse.output;
271
- let contentValue;
272
- switch (output.type) {
273
- case "text":
274
- case "error-text":
275
- contentValue = output.value;
276
- break;
277
- case "content":
278
- case "json":
279
- case "error-json":
280
- contentValue = JSON.stringify(output.value);
281
- break;
282
- }
283
- messages.push({
284
- role: "tool",
285
- tool_call_id: toolResponse.toolCallId,
286
- content: contentValue
287
- });
288
- }
289
- break;
290
- }
291
- default: {
292
- const _exhaustiveCheck = role;
293
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
294
- }
295
- }
296
- }
297
- return { messages, warnings };
298
- }
299
- function getResponseMetadata({
300
- id,
301
- model,
302
- created
303
- }) {
304
- return {
305
- id: id != null ? id : void 0,
306
- modelId: model != null ? model : void 0,
307
- timestamp: created != null ? new Date(created * 1e3) : void 0
308
- };
309
- }
310
- function mapXaiFinishReason(finishReason) {
311
- switch (finishReason) {
312
- case "stop":
313
- return "stop";
314
- case "length":
315
- return "length";
316
- case "tool_calls":
317
- case "function_call":
318
- return "tool-calls";
319
- case "content_filter":
320
- return "content-filter";
321
- default:
322
- return "unknown";
323
- }
324
- }
325
- var webSourceSchema = v4.z.object({
326
- type: v4.z.literal("web"),
327
- country: v4.z.string().length(2).optional(),
328
- excludedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
329
- allowedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
330
- safeSearch: v4.z.boolean().optional()
331
- });
332
- var xSourceSchema = v4.z.object({
333
- type: v4.z.literal("x"),
334
- xHandles: v4.z.array(v4.z.string()).optional()
335
- });
336
- var newsSourceSchema = v4.z.object({
337
- type: v4.z.literal("news"),
338
- country: v4.z.string().length(2).optional(),
339
- excludedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
340
- safeSearch: v4.z.boolean().optional()
341
- });
342
- var rssSourceSchema = v4.z.object({
343
- type: v4.z.literal("rss"),
344
- links: v4.z.array(v4.z.string().url()).max(1)
345
- // currently only supports one RSS link
346
- });
347
- var searchSourceSchema = v4.z.discriminatedUnion("type", [
348
- webSourceSchema,
349
- xSourceSchema,
350
- newsSourceSchema,
351
- rssSourceSchema
352
- ]);
353
- var xaiProviderOptions = v4.z.object({
354
- /**
355
- * reasoning effort for reasoning models
356
- * only supported by grok-3-mini and grok-3-mini-fast models
357
- */
358
- reasoningEffort: v4.z.enum(["low", "high"]).optional(),
359
- searchParameters: v4.z.object({
360
- /**
361
- * search mode preference
362
- * - "off": disables search completely
363
- * - "auto": model decides whether to search (default)
364
- * - "on": always enables search
365
- */
366
- mode: v4.z.enum(["off", "auto", "on"]),
367
- /**
368
- * whether to return citations in the response
369
- * defaults to true
370
- */
371
- returnCitations: v4.z.boolean().optional(),
372
- /**
373
- * start date for search data (ISO8601 format: YYYY-MM-DD)
374
- */
375
- fromDate: v4.z.string().optional(),
376
- /**
377
- * end date for search data (ISO8601 format: YYYY-MM-DD)
378
- */
379
- toDate: v4.z.string().optional(),
380
- /**
381
- * maximum number of search results to consider
382
- * defaults to 20
383
- */
384
- maxSearchResults: v4.z.number().min(1).max(50).optional(),
385
- /**
386
- * data sources to search from
387
- * defaults to ["web", "x"] if not specified
388
- */
389
- sources: v4.z.array(searchSourceSchema).optional()
390
- }).optional()
391
- });
392
- var xaiErrorDataSchema = v4.z.object({
393
- error: v4.z.object({
394
- message: v4.z.string(),
395
- type: v4.z.string().nullish(),
396
- param: v4.z.any().nullish(),
397
- code: v4.z.union([v4.z.string(), v4.z.number()]).nullish()
398
- })
399
- });
400
- var xaiFailedResponseHandler = chunk75KU7JB6_cjs.createJsonErrorResponseHandler({
401
- errorSchema: xaiErrorDataSchema,
402
- errorToMessage: (data) => data.error.message
403
- });
404
- function prepareTools({
405
- tools,
406
- toolChoice
407
- }) {
408
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
409
- const toolWarnings = [];
410
- if (tools == null) {
411
- return { tools: void 0, toolChoice: void 0, toolWarnings };
412
- }
413
- const xaiTools = [];
414
- for (const tool of tools) {
415
- if (tool.type === "provider-defined") {
416
- toolWarnings.push({ type: "unsupported-tool", tool });
417
- } else {
418
- xaiTools.push({
419
- type: "function",
420
- function: {
421
- name: tool.name,
422
- description: tool.description,
423
- parameters: tool.inputSchema
424
- }
425
- });
426
- }
427
- }
428
- if (toolChoice == null) {
429
- return { tools: xaiTools, toolChoice: void 0, toolWarnings };
430
- }
431
- const type = toolChoice.type;
432
- switch (type) {
433
- case "auto":
434
- case "none":
435
- return { tools: xaiTools, toolChoice: type, toolWarnings };
436
- case "required":
437
- return { tools: xaiTools, toolChoice: "required", toolWarnings };
438
- case "tool":
439
- return {
440
- tools: xaiTools,
441
- toolChoice: {
442
- type: "function",
443
- function: { name: toolChoice.toolName }
444
- },
445
- toolWarnings
446
- };
447
- default: {
448
- const _exhaustiveCheck = type;
449
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
450
- functionality: `tool choice type: ${_exhaustiveCheck}`
451
- });
452
- }
453
- }
454
- }
455
- var XaiChatLanguageModel = class {
456
- constructor(modelId, config) {
457
- this.specificationVersion = "v2";
458
- this.supportedUrls = {
459
- "image/*": [/^https?:\/\/.*$/]
460
- };
461
- this.modelId = modelId;
462
- this.config = config;
463
- }
464
- get provider() {
465
- return this.config.provider;
466
- }
467
- async getArgs({
468
- prompt,
469
- maxOutputTokens,
470
- temperature,
471
- topP,
472
- topK,
473
- frequencyPenalty,
474
- presencePenalty,
475
- stopSequences,
476
- seed,
477
- responseFormat,
478
- providerOptions,
479
- tools,
480
- toolChoice
481
- }) {
482
- var _a, _b, _c;
483
- const warnings = [];
484
- const options = (_a = await chunk75KU7JB6_cjs.parseProviderOptions({
485
- provider: "xai",
486
- providerOptions,
487
- schema: xaiProviderOptions
488
- })) != null ? _a : {};
489
- if (topK != null) {
490
- warnings.push({
491
- type: "unsupported-setting",
492
- setting: "topK"
493
- });
494
- }
495
- if (frequencyPenalty != null) {
496
- warnings.push({
497
- type: "unsupported-setting",
498
- setting: "frequencyPenalty"
499
- });
500
- }
501
- if (presencePenalty != null) {
502
- warnings.push({
503
- type: "unsupported-setting",
504
- setting: "presencePenalty"
505
- });
506
- }
507
- if (stopSequences != null) {
508
- warnings.push({
509
- type: "unsupported-setting",
510
- setting: "stopSequences"
511
- });
512
- }
513
- if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
514
- warnings.push({
515
- type: "unsupported-setting",
516
- setting: "responseFormat",
517
- details: "JSON response format schema is not supported"
518
- });
519
- }
520
- const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
521
- warnings.push(...messageWarnings);
522
- const {
523
- tools: xaiTools,
524
- toolChoice: xaiToolChoice,
525
- toolWarnings
526
- } = prepareTools({
527
- tools,
528
- toolChoice
529
- });
530
- warnings.push(...toolWarnings);
531
- const baseArgs = {
532
- // model id
533
- model: this.modelId,
534
- // standard generation settings
535
- max_tokens: maxOutputTokens,
536
- temperature,
537
- top_p: topP,
538
- seed,
539
- reasoning_effort: options.reasoningEffort,
540
- // response format
541
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
542
- type: "json_schema",
543
- json_schema: {
544
- name: (_b = responseFormat.name) != null ? _b : "response",
545
- schema: responseFormat.schema,
546
- strict: true
547
- }
548
- } : { type: "json_object" } : void 0,
549
- // search parameters
550
- search_parameters: options.searchParameters ? {
551
- mode: options.searchParameters.mode,
552
- return_citations: options.searchParameters.returnCitations,
553
- from_date: options.searchParameters.fromDate,
554
- to_date: options.searchParameters.toDate,
555
- max_search_results: options.searchParameters.maxSearchResults,
556
- sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => ({
557
- type: source.type,
558
- ...source.type === "web" && {
559
- country: source.country,
560
- excluded_websites: source.excludedWebsites,
561
- allowed_websites: source.allowedWebsites,
562
- safe_search: source.safeSearch
563
- },
564
- ...source.type === "x" && {
565
- x_handles: source.xHandles
566
- },
567
- ...source.type === "news" && {
568
- country: source.country,
569
- excluded_websites: source.excludedWebsites,
570
- safe_search: source.safeSearch
571
- },
572
- ...source.type === "rss" && {
573
- links: source.links
574
- }
575
- }))
576
- } : void 0,
577
- // messages in xai format
578
- messages,
579
- // tools in xai format
580
- tools: xaiTools,
581
- tool_choice: xaiToolChoice
582
- };
583
- return {
584
- args: baseArgs,
585
- warnings
586
- };
587
- }
588
- async doGenerate(options) {
589
- var _a, _b, _c;
590
- const { args: body, warnings } = await this.getArgs(options);
591
- const {
592
- responseHeaders,
593
- value: response,
594
- rawValue: rawResponse
595
- } = await chunk75KU7JB6_cjs.postJsonToApi({
596
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
597
- headers: chunk75KU7JB6_cjs.combineHeaders(this.config.headers(), options.headers),
598
- body,
599
- failedResponseHandler: xaiFailedResponseHandler,
600
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(
601
- xaiChatResponseSchema
602
- ),
603
- abortSignal: options.abortSignal,
604
- fetch: this.config.fetch
605
- });
606
- const choice = response.choices[0];
607
- const content = [];
608
- if (choice.message.content != null && choice.message.content.length > 0) {
609
- let text = choice.message.content;
610
- const lastMessage = body.messages[body.messages.length - 1];
611
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
612
- text = "";
613
- }
614
- if (text.length > 0) {
615
- content.push({ type: "text", text });
616
- }
617
- }
618
- if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
619
- content.push({
620
- type: "reasoning",
621
- text: choice.message.reasoning_content
622
- });
623
- }
624
- if (choice.message.tool_calls != null) {
625
- for (const toolCall of choice.message.tool_calls) {
626
- content.push({
627
- type: "tool-call",
628
- toolCallId: toolCall.id,
629
- toolName: toolCall.function.name,
630
- input: toolCall.function.arguments
631
- });
632
- }
633
- }
634
- if (response.citations != null) {
635
- for (const url of response.citations) {
636
- content.push({
637
- type: "source",
638
- sourceType: "url",
639
- id: this.config.generateId(),
640
- url
641
- });
642
- }
643
- }
644
- return {
645
- content,
646
- finishReason: mapXaiFinishReason(choice.finish_reason),
647
- usage: {
648
- inputTokens: response.usage.prompt_tokens,
649
- outputTokens: response.usage.completion_tokens,
650
- totalTokens: response.usage.total_tokens,
651
- reasoningTokens: (_c = (_b = response.usage.completion_tokens_details) == null ? void 0 : _b.reasoning_tokens) != null ? _c : void 0
652
- },
653
- request: { body },
654
- response: {
655
- ...getResponseMetadata(response),
656
- headers: responseHeaders,
657
- body: rawResponse
658
- },
659
- warnings
660
- };
661
- }
662
- async doStream(options) {
663
- var _a;
664
- const { args, warnings } = await this.getArgs(options);
665
- const body = {
666
- ...args,
667
- stream: true,
668
- stream_options: {
669
- include_usage: true
670
- }
671
- };
672
- const { responseHeaders, value: response } = await chunk75KU7JB6_cjs.postJsonToApi({
673
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
674
- headers: chunk75KU7JB6_cjs.combineHeaders(this.config.headers(), options.headers),
675
- body,
676
- failedResponseHandler: xaiFailedResponseHandler,
677
- successfulResponseHandler: chunk75KU7JB6_cjs.createEventSourceResponseHandler(xaiChatChunkSchema),
678
- abortSignal: options.abortSignal,
679
- fetch: this.config.fetch
680
- });
681
- let finishReason = "unknown";
682
- const usage = {
683
- inputTokens: void 0,
684
- outputTokens: void 0,
685
- totalTokens: void 0
686
- };
687
- let isFirstChunk = true;
688
- const contentBlocks = {};
689
- const lastReasoningDeltas = {};
690
- const self = this;
691
- return {
692
- stream: response.pipeThrough(
693
- new TransformStream({
694
- start(controller) {
695
- controller.enqueue({ type: "stream-start", warnings });
696
- },
697
- transform(chunk, controller) {
698
- var _a2, _b;
699
- if (options.includeRawChunks) {
700
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
701
- }
702
- if (!chunk.success) {
703
- controller.enqueue({ type: "error", error: chunk.error });
704
- return;
705
- }
706
- const value = chunk.value;
707
- if (isFirstChunk) {
708
- controller.enqueue({
709
- type: "response-metadata",
710
- ...getResponseMetadata(value)
711
- });
712
- isFirstChunk = false;
713
- }
714
- if (value.citations != null) {
715
- for (const url of value.citations) {
716
- controller.enqueue({
717
- type: "source",
718
- sourceType: "url",
719
- id: self.config.generateId(),
720
- url
721
- });
722
- }
723
- }
724
- if (value.usage != null) {
725
- usage.inputTokens = value.usage.prompt_tokens;
726
- usage.outputTokens = value.usage.completion_tokens;
727
- usage.totalTokens = value.usage.total_tokens;
728
- usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
729
- }
730
- const choice = value.choices[0];
731
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
732
- finishReason = mapXaiFinishReason(choice.finish_reason);
733
- }
734
- if ((choice == null ? void 0 : choice.delta) == null) {
735
- return;
736
- }
737
- const delta = choice.delta;
738
- const choiceIndex = choice.index;
739
- if (delta.content != null && delta.content.length > 0) {
740
- const textContent = delta.content;
741
- const lastMessage = body.messages[body.messages.length - 1];
742
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
743
- return;
744
- }
745
- const blockId = `text-${value.id || choiceIndex}`;
746
- if (contentBlocks[blockId] == null) {
747
- contentBlocks[blockId] = { type: "text" };
748
- controller.enqueue({
749
- type: "text-start",
750
- id: blockId
751
- });
752
- }
753
- controller.enqueue({
754
- type: "text-delta",
755
- id: blockId,
756
- delta: textContent
757
- });
758
- }
759
- if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
760
- const blockId = `reasoning-${value.id || choiceIndex}`;
761
- if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
762
- return;
763
- }
764
- lastReasoningDeltas[blockId] = delta.reasoning_content;
765
- if (contentBlocks[blockId] == null) {
766
- contentBlocks[blockId] = { type: "reasoning" };
767
- controller.enqueue({
768
- type: "reasoning-start",
769
- id: blockId
770
- });
771
- }
772
- controller.enqueue({
773
- type: "reasoning-delta",
774
- id: blockId,
775
- delta: delta.reasoning_content
776
- });
777
- }
778
- if (delta.tool_calls != null) {
779
- for (const toolCall of delta.tool_calls) {
780
- const toolCallId = toolCall.id;
781
- controller.enqueue({
782
- type: "tool-input-start",
783
- id: toolCallId,
784
- toolName: toolCall.function.name
785
- });
786
- controller.enqueue({
787
- type: "tool-input-delta",
788
- id: toolCallId,
789
- delta: toolCall.function.arguments
790
- });
791
- controller.enqueue({
792
- type: "tool-input-end",
793
- id: toolCallId
794
- });
795
- controller.enqueue({
796
- type: "tool-call",
797
- toolCallId,
798
- toolName: toolCall.function.name,
799
- input: toolCall.function.arguments
800
- });
801
- }
802
- }
803
- },
804
- flush(controller) {
805
- for (const [blockId, block] of Object.entries(contentBlocks)) {
806
- controller.enqueue({
807
- type: block.type === "text" ? "text-end" : "reasoning-end",
808
- id: blockId
809
- });
810
- }
811
- controller.enqueue({ type: "finish", finishReason, usage });
812
- }
813
- })
814
- ),
815
- request: { body },
816
- response: { headers: responseHeaders }
817
- };
818
- }
819
- };
820
- var xaiUsageSchema = v4.z.object({
821
- prompt_tokens: v4.z.number(),
822
- completion_tokens: v4.z.number(),
823
- total_tokens: v4.z.number(),
824
- completion_tokens_details: v4.z.object({
825
- reasoning_tokens: v4.z.number().nullish()
826
- }).nullish()
827
- });
828
- var xaiChatResponseSchema = v4.z.object({
829
- id: v4.z.string().nullish(),
830
- created: v4.z.number().nullish(),
831
- model: v4.z.string().nullish(),
832
- choices: v4.z.array(
833
- v4.z.object({
834
- message: v4.z.object({
835
- role: v4.z.literal("assistant"),
836
- content: v4.z.string().nullish(),
837
- reasoning_content: v4.z.string().nullish(),
838
- tool_calls: v4.z.array(
839
- v4.z.object({
840
- id: v4.z.string(),
841
- type: v4.z.literal("function"),
842
- function: v4.z.object({
843
- name: v4.z.string(),
844
- arguments: v4.z.string()
845
- })
846
- })
847
- ).nullish()
848
- }),
849
- index: v4.z.number(),
850
- finish_reason: v4.z.string().nullish()
851
- })
852
- ),
853
- object: v4.z.literal("chat.completion"),
854
- usage: xaiUsageSchema,
855
- citations: v4.z.array(v4.z.string().url()).nullish()
856
- });
857
- var xaiChatChunkSchema = v4.z.object({
858
- id: v4.z.string().nullish(),
859
- created: v4.z.number().nullish(),
860
- model: v4.z.string().nullish(),
861
- choices: v4.z.array(
862
- v4.z.object({
863
- delta: v4.z.object({
864
- role: v4.z.enum(["assistant"]).optional(),
865
- content: v4.z.string().nullish(),
866
- reasoning_content: v4.z.string().nullish(),
867
- tool_calls: v4.z.array(
868
- v4.z.object({
869
- id: v4.z.string(),
870
- type: v4.z.literal("function"),
871
- function: v4.z.object({
872
- name: v4.z.string(),
873
- arguments: v4.z.string()
874
- })
875
- })
876
- ).nullish()
877
- }),
878
- finish_reason: v4.z.string().nullish(),
879
- index: v4.z.number()
880
- })
881
- ),
882
- usage: xaiUsageSchema.nullish(),
883
- citations: v4.z.array(v4.z.string().url()).nullish()
884
- });
885
- var xaiErrorStructure = {
886
- errorSchema: xaiErrorDataSchema,
887
- errorToMessage: (data) => data.error.message
888
- };
889
- function createXai(options = {}) {
890
- var _a;
891
- const baseURL = chunk75KU7JB6_cjs.withoutTrailingSlash(
892
- (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
893
- );
894
- const getHeaders = () => ({
895
- Authorization: `Bearer ${chunk75KU7JB6_cjs.loadApiKey({
896
- apiKey: options.apiKey,
897
- environmentVariableName: "XAI_API_KEY",
898
- description: "xAI API key"
899
- })}`,
900
- ...options.headers
901
- });
902
- const createLanguageModel = (modelId) => {
903
- return new XaiChatLanguageModel(modelId, {
904
- provider: "xai.chat",
905
- baseURL,
906
- headers: getHeaders,
907
- generateId: chunk75KU7JB6_cjs.generateId,
908
- fetch: options.fetch
909
- });
910
- };
911
- const createImageModel = (modelId) => {
912
- return new OpenAICompatibleImageModel(modelId, {
913
- provider: "xai.image",
914
- url: ({ path }) => `${baseURL}${path}`,
915
- headers: getHeaders,
916
- fetch: options.fetch,
917
- errorStructure: xaiErrorStructure
918
- });
919
- };
920
- const provider = (modelId) => createLanguageModel(modelId);
921
- provider.languageModel = createLanguageModel;
922
- provider.chat = createLanguageModel;
923
- provider.textEmbeddingModel = (modelId) => {
924
- throw new chunkXCR65STK_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
925
- };
926
- provider.imageModel = createImageModel;
927
- provider.image = createImageModel;
928
- return provider;
929
- }
930
- var xai = createXai();
931
-
932
- exports.createXai = createXai;
933
- exports.xai = xai;
934
- //# sourceMappingURL=dist-FGYSUA65.cjs.map
935
- //# sourceMappingURL=dist-FGYSUA65.cjs.map