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