@ai-sdk/alibaba 0.0.0-b66d09a8-20260328011513

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1071 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ VERSION: () => VERSION,
24
+ alibaba: () => alibaba,
25
+ createAlibaba: () => createAlibaba
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/alibaba-provider.ts
30
+ var import_provider4 = require("@ai-sdk/provider");
31
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
32
+ var import_v44 = require("zod/v4");
33
+
34
+ // src/alibaba-chat-language-model.ts
35
+ var import_internal2 = require("@ai-sdk/openai-compatible/internal");
36
+ var import_provider2 = require("@ai-sdk/provider");
37
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
38
+ var import_v42 = require("zod/v4");
39
+
40
+ // src/alibaba-chat-options.ts
41
+ var import_v4 = require("zod/v4");
42
+ var alibabaLanguageModelOptions = import_v4.z.object({
43
+ /**
44
+ * Enable thinking/reasoning mode for supported models.
45
+ * When enabled, the model generates reasoning content before the response.
46
+ *
47
+ * @default false
48
+ */
49
+ enableThinking: import_v4.z.boolean().optional(),
50
+ /**
51
+ * Maximum number of reasoning tokens to generate.
52
+ */
53
+ thinkingBudget: import_v4.z.number().positive().optional(),
54
+ /**
55
+ * Whether to enable parallel function calling during tool use.
56
+ *
57
+ * @default true
58
+ */
59
+ parallelToolCalls: import_v4.z.boolean().optional()
60
+ });
61
+
62
+ // src/convert-alibaba-usage.ts
63
+ var import_internal = require("@ai-sdk/openai-compatible/internal");
64
+ function convertAlibabaUsage(usage) {
65
+ var _a, _b, _c, _d;
66
+ const baseUsage = (0, import_internal.convertOpenAICompatibleChatUsage)(usage);
67
+ const cacheWriteTokens = (_b = (_a = usage == null ? void 0 : usage.prompt_tokens_details) == null ? void 0 : _a.cache_creation_input_tokens) != null ? _b : 0;
68
+ const noCacheTokens = ((_c = baseUsage.inputTokens.total) != null ? _c : 0) - ((_d = baseUsage.inputTokens.cacheRead) != null ? _d : 0) - cacheWriteTokens;
69
+ return {
70
+ ...baseUsage,
71
+ inputTokens: {
72
+ ...baseUsage.inputTokens,
73
+ cacheWrite: cacheWriteTokens,
74
+ noCache: noCacheTokens
75
+ }
76
+ };
77
+ }
78
+
79
+ // src/convert-to-alibaba-chat-messages.ts
80
+ var import_provider = require("@ai-sdk/provider");
81
+ var import_provider_utils = require("@ai-sdk/provider-utils");
82
+ function formatImageUrl({
83
+ data,
84
+ mediaType
85
+ }) {
86
+ return data instanceof URL ? data.toString() : `data:${mediaType};base64,${(0, import_provider_utils.convertToBase64)(data)}`;
87
+ }
88
+ function convertToAlibabaChatMessages({
89
+ prompt,
90
+ cacheControlValidator
91
+ }) {
92
+ var _a, _b;
93
+ const messages = [];
94
+ for (const { role, content, ...message } of prompt) {
95
+ const messageCacheControl = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(
96
+ message.providerOptions
97
+ );
98
+ switch (role) {
99
+ case "system": {
100
+ if (messageCacheControl) {
101
+ messages.push({
102
+ role: "system",
103
+ content: [
104
+ {
105
+ type: "text",
106
+ text: content,
107
+ cache_control: messageCacheControl
108
+ }
109
+ ]
110
+ });
111
+ } else {
112
+ messages.push({ role: "system", content });
113
+ }
114
+ break;
115
+ }
116
+ case "user": {
117
+ messages.push({
118
+ role: "user",
119
+ content: content.map((part, index) => {
120
+ var _a2;
121
+ const isLastPart = index === content.length - 1;
122
+ const partCacheControl = (_a2 = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(part.providerOptions)) != null ? _a2 : isLastPart ? messageCacheControl : void 0;
123
+ switch (part.type) {
124
+ case "text": {
125
+ return {
126
+ type: "text",
127
+ text: part.text,
128
+ ...partCacheControl ? { cache_control: partCacheControl } : {}
129
+ };
130
+ }
131
+ case "file": {
132
+ if (part.mediaType.startsWith("image/")) {
133
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
134
+ return {
135
+ type: "image_url",
136
+ image_url: {
137
+ url: formatImageUrl({ data: part.data, mediaType })
138
+ },
139
+ ...partCacheControl ? { cache_control: partCacheControl } : {}
140
+ };
141
+ } else {
142
+ throw new import_provider.UnsupportedFunctionalityError({
143
+ functionality: "Only image file parts are supported"
144
+ });
145
+ }
146
+ }
147
+ }
148
+ })
149
+ });
150
+ break;
151
+ }
152
+ case "assistant": {
153
+ let text = "";
154
+ const toolCalls = [];
155
+ for (const part of content) {
156
+ switch (part.type) {
157
+ case "text": {
158
+ text += part.text;
159
+ break;
160
+ }
161
+ case "tool-call": {
162
+ toolCalls.push({
163
+ id: part.toolCallId,
164
+ type: "function",
165
+ function: {
166
+ name: part.toolName,
167
+ arguments: JSON.stringify(part.input)
168
+ }
169
+ });
170
+ break;
171
+ }
172
+ case "reasoning": {
173
+ text += part.text;
174
+ break;
175
+ }
176
+ }
177
+ }
178
+ messages.push({
179
+ role: "assistant",
180
+ content: messageCacheControl ? [{ type: "text", text, cache_control: messageCacheControl }] : text || null,
181
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
182
+ });
183
+ break;
184
+ }
185
+ case "tool": {
186
+ const toolResponses = content.filter(
187
+ (r) => r.type !== "tool-approval-response"
188
+ );
189
+ for (let i = 0; i < toolResponses.length; i++) {
190
+ const toolResponse = toolResponses[i];
191
+ const output = toolResponse.output;
192
+ const isLastPart = i === toolResponses.length - 1;
193
+ const partCacheControl = (_a = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(
194
+ toolResponse.providerOptions
195
+ )) != null ? _a : isLastPart ? messageCacheControl : void 0;
196
+ let contentValue;
197
+ switch (output.type) {
198
+ case "text":
199
+ case "error-text":
200
+ contentValue = output.value;
201
+ break;
202
+ case "execution-denied":
203
+ contentValue = (_b = output.reason) != null ? _b : "Tool execution denied.";
204
+ break;
205
+ case "content":
206
+ case "json":
207
+ case "error-json":
208
+ contentValue = JSON.stringify(output.value);
209
+ break;
210
+ }
211
+ messages.push({
212
+ role: "tool",
213
+ tool_call_id: toolResponse.toolCallId,
214
+ content: partCacheControl ? [
215
+ {
216
+ type: "text",
217
+ text: contentValue,
218
+ cache_control: partCacheControl
219
+ }
220
+ ] : contentValue
221
+ });
222
+ }
223
+ break;
224
+ }
225
+ default: {
226
+ const _exhaustiveCheck = role;
227
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
228
+ }
229
+ }
230
+ }
231
+ return messages;
232
+ }
233
+
234
+ // src/get-cache-control.ts
235
+ var MAX_CACHE_BREAKPOINTS = 4;
236
+ function getCacheControl(providerMetadata) {
237
+ var _a;
238
+ const alibaba2 = providerMetadata == null ? void 0 : providerMetadata.alibaba;
239
+ const cacheControlValue = (_a = alibaba2 == null ? void 0 : alibaba2.cacheControl) != null ? _a : alibaba2 == null ? void 0 : alibaba2.cache_control;
240
+ return cacheControlValue;
241
+ }
242
+ var CacheControlValidator = class {
243
+ constructor() {
244
+ this.breakpointCount = 0;
245
+ this.warnings = [];
246
+ }
247
+ getCacheControl(providerMetadata) {
248
+ const cacheControlValue = getCacheControl(providerMetadata);
249
+ if (!cacheControlValue) {
250
+ return void 0;
251
+ }
252
+ this.breakpointCount++;
253
+ if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {
254
+ this.warnings.push({
255
+ type: "other",
256
+ message: `Max breakpoint limit exceeded. Only the last ${MAX_CACHE_BREAKPOINTS} cache markers will take effect.`
257
+ });
258
+ }
259
+ return cacheControlValue;
260
+ }
261
+ getWarnings() {
262
+ return this.warnings;
263
+ }
264
+ };
265
+
266
+ // src/alibaba-chat-language-model.ts
267
+ var AlibabaLanguageModel = class {
268
+ constructor(modelId, config) {
269
+ this.specificationVersion = "v4";
270
+ this.supportedUrls = {
271
+ "image/*": [/^https?:\/\/.*$/]
272
+ };
273
+ this.modelId = modelId;
274
+ this.config = config;
275
+ }
276
+ get provider() {
277
+ return this.config.provider;
278
+ }
279
+ /**
280
+ * Builds request arguments for Alibaba API call.
281
+ * Converts AI SDK options to Alibaba API format.
282
+ */
283
+ async getArgs({
284
+ prompt,
285
+ maxOutputTokens,
286
+ temperature,
287
+ topP,
288
+ topK,
289
+ frequencyPenalty,
290
+ presencePenalty,
291
+ stopSequences,
292
+ responseFormat,
293
+ seed,
294
+ reasoning,
295
+ providerOptions,
296
+ tools,
297
+ toolChoice
298
+ }) {
299
+ var _a;
300
+ const warnings = [];
301
+ const cacheControlValidator = new CacheControlValidator();
302
+ const alibabaOptions = await (0, import_provider_utils2.parseProviderOptions)({
303
+ provider: "alibaba",
304
+ providerOptions,
305
+ schema: alibabaLanguageModelOptions
306
+ });
307
+ if (frequencyPenalty != null) {
308
+ warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
309
+ }
310
+ const baseArgs = {
311
+ model: this.modelId,
312
+ max_tokens: maxOutputTokens,
313
+ temperature,
314
+ top_p: topP,
315
+ top_k: topK,
316
+ presence_penalty: presencePenalty,
317
+ stop: stopSequences,
318
+ seed,
319
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
320
+ type: "json_schema",
321
+ json_schema: {
322
+ schema: responseFormat.schema,
323
+ name: (_a = responseFormat.name) != null ? _a : "response",
324
+ description: responseFormat.description
325
+ }
326
+ } : { type: "json_object" } : void 0,
327
+ ...resolveAlibabaThinking({
328
+ reasoning,
329
+ alibabaOptions,
330
+ warnings
331
+ }),
332
+ // Convert messages with cache control support
333
+ messages: convertToAlibabaChatMessages({
334
+ prompt,
335
+ cacheControlValidator
336
+ })
337
+ };
338
+ const {
339
+ tools: alibabaTools,
340
+ toolChoice: alibabaToolChoice,
341
+ toolWarnings
342
+ } = (0, import_internal2.prepareTools)({ tools, toolChoice });
343
+ warnings.push(...cacheControlValidator.getWarnings());
344
+ return {
345
+ args: {
346
+ ...baseArgs,
347
+ tools: alibabaTools,
348
+ tool_choice: alibabaToolChoice,
349
+ ...alibabaTools != null && (alibabaOptions == null ? void 0 : alibabaOptions.parallelToolCalls) !== void 0 ? { parallel_tool_calls: alibabaOptions.parallelToolCalls } : {}
350
+ },
351
+ warnings: [...warnings, ...toolWarnings]
352
+ };
353
+ }
354
+ async doGenerate(options) {
355
+ var _a;
356
+ const { args, warnings } = await this.getArgs(options);
357
+ const {
358
+ responseHeaders,
359
+ value: response,
360
+ rawValue: rawResponse
361
+ } = await (0, import_provider_utils2.postJsonToApi)({
362
+ url: `${this.config.baseURL}/chat/completions`,
363
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
364
+ body: args,
365
+ failedResponseHandler: alibabaFailedResponseHandler,
366
+ successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(
367
+ alibabaChatResponseSchema
368
+ ),
369
+ abortSignal: options.abortSignal,
370
+ fetch: this.config.fetch
371
+ });
372
+ const choice = response.choices[0];
373
+ const content = [];
374
+ const text = choice.message.content;
375
+ if (text != null && text.length > 0) {
376
+ content.push({ type: "text", text });
377
+ }
378
+ const reasoning = choice.message.reasoning_content;
379
+ if (reasoning != null && reasoning.length > 0) {
380
+ content.push({
381
+ type: "reasoning",
382
+ text: reasoning
383
+ });
384
+ }
385
+ if (choice.message.tool_calls != null) {
386
+ for (const toolCall of choice.message.tool_calls) {
387
+ content.push({
388
+ type: "tool-call",
389
+ toolCallId: toolCall.id,
390
+ toolName: toolCall.function.name,
391
+ input: toolCall.function.arguments
392
+ });
393
+ }
394
+ }
395
+ return {
396
+ content,
397
+ finishReason: {
398
+ unified: (0, import_internal2.mapOpenAICompatibleFinishReason)(choice.finish_reason),
399
+ raw: (_a = choice.finish_reason) != null ? _a : void 0
400
+ },
401
+ usage: convertAlibabaUsage(response.usage),
402
+ request: { body: JSON.stringify(args) },
403
+ response: {
404
+ ...(0, import_internal2.getResponseMetadata)(response),
405
+ headers: responseHeaders,
406
+ body: rawResponse
407
+ },
408
+ warnings
409
+ };
410
+ }
411
+ async doStream(options) {
412
+ const { args, warnings } = await this.getArgs(options);
413
+ const body = {
414
+ ...args,
415
+ stream: true,
416
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
417
+ };
418
+ const { responseHeaders, value: response } = await (0, import_provider_utils2.postJsonToApi)({
419
+ url: `${this.config.baseURL}/chat/completions`,
420
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
421
+ body,
422
+ failedResponseHandler: alibabaFailedResponseHandler,
423
+ successfulResponseHandler: (0, import_provider_utils2.createEventSourceResponseHandler)(
424
+ alibabaChatChunkSchema
425
+ ),
426
+ abortSignal: options.abortSignal,
427
+ fetch: this.config.fetch
428
+ });
429
+ let finishReason = {
430
+ unified: "other",
431
+ raw: void 0
432
+ };
433
+ let usage = void 0;
434
+ let isFirstChunk = true;
435
+ let activeText = false;
436
+ let activeReasoningId = null;
437
+ const toolCalls = [];
438
+ return {
439
+ stream: response.pipeThrough(
440
+ new TransformStream({
441
+ start(controller) {
442
+ controller.enqueue({ type: "stream-start", warnings });
443
+ },
444
+ transform(chunk, controller) {
445
+ var _a, _b, _c, _d;
446
+ if (options.includeRawChunks) {
447
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
448
+ }
449
+ if (!chunk.success) {
450
+ controller.enqueue({ type: "error", error: chunk.error });
451
+ return;
452
+ }
453
+ const value = chunk.value;
454
+ if (isFirstChunk) {
455
+ isFirstChunk = false;
456
+ controller.enqueue({
457
+ type: "response-metadata",
458
+ ...(0, import_internal2.getResponseMetadata)(value)
459
+ });
460
+ }
461
+ if (value.usage != null) {
462
+ usage = value.usage;
463
+ }
464
+ if (value.choices.length === 0) {
465
+ return;
466
+ }
467
+ const choice = value.choices[0];
468
+ const delta = choice.delta;
469
+ if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
470
+ if (activeReasoningId == null) {
471
+ if (activeText) {
472
+ controller.enqueue({ type: "text-end", id: "0" });
473
+ activeText = false;
474
+ }
475
+ activeReasoningId = (0, import_provider_utils2.generateId)();
476
+ controller.enqueue({
477
+ type: "reasoning-start",
478
+ id: activeReasoningId
479
+ });
480
+ }
481
+ controller.enqueue({
482
+ type: "reasoning-delta",
483
+ id: activeReasoningId,
484
+ delta: delta.reasoning_content
485
+ });
486
+ }
487
+ if (delta.content != null && delta.content.length > 0) {
488
+ if (activeReasoningId != null) {
489
+ controller.enqueue({
490
+ type: "reasoning-end",
491
+ id: activeReasoningId
492
+ });
493
+ activeReasoningId = null;
494
+ }
495
+ if (!activeText) {
496
+ controller.enqueue({ type: "text-start", id: "0" });
497
+ activeText = true;
498
+ }
499
+ controller.enqueue({
500
+ type: "text-delta",
501
+ id: "0",
502
+ delta: delta.content
503
+ });
504
+ }
505
+ if (delta.tool_calls != null) {
506
+ if (activeReasoningId != null) {
507
+ controller.enqueue({
508
+ type: "reasoning-end",
509
+ id: activeReasoningId
510
+ });
511
+ activeReasoningId = null;
512
+ }
513
+ if (activeText) {
514
+ controller.enqueue({ type: "text-end", id: "0" });
515
+ activeText = false;
516
+ }
517
+ for (const toolCallDelta of delta.tool_calls) {
518
+ const index = (_a = toolCallDelta.index) != null ? _a : toolCalls.length;
519
+ if (toolCalls[index] == null) {
520
+ if (toolCallDelta.id == null) {
521
+ throw new import_provider2.InvalidResponseDataError({
522
+ data: toolCallDelta,
523
+ message: `Expected 'id' to be a string.`
524
+ });
525
+ }
526
+ if (((_b = toolCallDelta.function) == null ? void 0 : _b.name) == null) {
527
+ throw new import_provider2.InvalidResponseDataError({
528
+ data: toolCallDelta,
529
+ message: `Expected 'function.name' to be a string.`
530
+ });
531
+ }
532
+ controller.enqueue({
533
+ type: "tool-input-start",
534
+ id: toolCallDelta.id,
535
+ toolName: toolCallDelta.function.name
536
+ });
537
+ toolCalls[index] = {
538
+ id: toolCallDelta.id,
539
+ type: "function",
540
+ function: {
541
+ name: toolCallDelta.function.name,
542
+ arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
543
+ },
544
+ hasFinished: false
545
+ };
546
+ const toolCall2 = toolCalls[index];
547
+ if (toolCall2.function.arguments.length > 0) {
548
+ controller.enqueue({
549
+ type: "tool-input-delta",
550
+ id: toolCall2.id,
551
+ delta: toolCall2.function.arguments
552
+ });
553
+ }
554
+ if ((0, import_provider_utils2.isParsableJson)(toolCall2.function.arguments)) {
555
+ controller.enqueue({
556
+ type: "tool-input-end",
557
+ id: toolCall2.id
558
+ });
559
+ controller.enqueue({
560
+ type: "tool-call",
561
+ toolCallId: toolCall2.id,
562
+ toolName: toolCall2.function.name,
563
+ input: toolCall2.function.arguments
564
+ });
565
+ toolCall2.hasFinished = true;
566
+ }
567
+ continue;
568
+ }
569
+ const toolCall = toolCalls[index];
570
+ if (toolCall.hasFinished) {
571
+ continue;
572
+ }
573
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.arguments) != null) {
574
+ toolCall.function.arguments += toolCallDelta.function.arguments;
575
+ controller.enqueue({
576
+ type: "tool-input-delta",
577
+ id: toolCall.id,
578
+ delta: toolCallDelta.function.arguments
579
+ });
580
+ }
581
+ if ((0, import_provider_utils2.isParsableJson)(toolCall.function.arguments)) {
582
+ controller.enqueue({
583
+ type: "tool-input-end",
584
+ id: toolCall.id
585
+ });
586
+ controller.enqueue({
587
+ type: "tool-call",
588
+ toolCallId: toolCall.id,
589
+ toolName: toolCall.function.name,
590
+ input: toolCall.function.arguments
591
+ });
592
+ toolCall.hasFinished = true;
593
+ }
594
+ }
595
+ }
596
+ if (choice.finish_reason != null) {
597
+ finishReason = {
598
+ unified: (0, import_internal2.mapOpenAICompatibleFinishReason)(choice.finish_reason),
599
+ raw: choice.finish_reason
600
+ };
601
+ }
602
+ },
603
+ flush(controller) {
604
+ if (activeReasoningId != null) {
605
+ controller.enqueue({
606
+ type: "reasoning-end",
607
+ id: activeReasoningId
608
+ });
609
+ }
610
+ if (activeText) {
611
+ controller.enqueue({ type: "text-end", id: "0" });
612
+ }
613
+ controller.enqueue({
614
+ type: "finish",
615
+ finishReason,
616
+ usage: convertAlibabaUsage(usage)
617
+ });
618
+ }
619
+ })
620
+ ),
621
+ request: { body: JSON.stringify(body) },
622
+ response: { headers: responseHeaders }
623
+ };
624
+ }
625
+ };
626
+ function resolveAlibabaThinking({
627
+ reasoning,
628
+ alibabaOptions,
629
+ warnings
630
+ }) {
631
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.enableThinking) != null || (alibabaOptions == null ? void 0 : alibabaOptions.thinkingBudget) != null) {
632
+ return {
633
+ ...alibabaOptions.enableThinking != null ? { enable_thinking: alibabaOptions.enableThinking } : {},
634
+ ...alibabaOptions.thinkingBudget != null ? { thinking_budget: alibabaOptions.thinkingBudget } : {}
635
+ };
636
+ }
637
+ if (!(0, import_provider_utils2.isCustomReasoning)(reasoning)) {
638
+ return {};
639
+ }
640
+ if (reasoning === "none") {
641
+ return { enable_thinking: false };
642
+ }
643
+ const thinkingBudget = (0, import_provider_utils2.mapReasoningToProviderBudget)({
644
+ reasoning,
645
+ maxOutputTokens: 16384,
646
+ maxReasoningBudget: 16384,
647
+ warnings
648
+ });
649
+ return {
650
+ enable_thinking: true,
651
+ ...thinkingBudget != null ? { thinking_budget: thinkingBudget } : {}
652
+ };
653
+ }
654
+ var alibabaUsageSchema = import_v42.z.object({
655
+ prompt_tokens: import_v42.z.number(),
656
+ completion_tokens: import_v42.z.number(),
657
+ total_tokens: import_v42.z.number(),
658
+ prompt_tokens_details: import_v42.z.object({
659
+ cached_tokens: import_v42.z.number().nullish(),
660
+ cache_creation_input_tokens: import_v42.z.number().nullish()
661
+ }).nullish(),
662
+ completion_tokens_details: import_v42.z.object({
663
+ reasoning_tokens: import_v42.z.number().nullish()
664
+ }).nullish()
665
+ });
666
+ var alibabaChatResponseSchema = import_v42.z.object({
667
+ id: import_v42.z.string().nullish(),
668
+ created: import_v42.z.number().nullish(),
669
+ model: import_v42.z.string().nullish(),
670
+ choices: import_v42.z.array(
671
+ import_v42.z.object({
672
+ message: import_v42.z.object({
673
+ role: import_v42.z.literal("assistant").nullish(),
674
+ content: import_v42.z.string().nullish(),
675
+ reasoning_content: import_v42.z.string().nullish(),
676
+ // Alibaba thinking mode
677
+ tool_calls: import_v42.z.array(
678
+ import_v42.z.object({
679
+ id: import_v42.z.string(),
680
+ type: import_v42.z.literal("function"),
681
+ function: import_v42.z.object({
682
+ name: import_v42.z.string(),
683
+ arguments: import_v42.z.string()
684
+ })
685
+ })
686
+ ).nullish()
687
+ }),
688
+ finish_reason: import_v42.z.string().nullish(),
689
+ index: import_v42.z.number()
690
+ })
691
+ ),
692
+ usage: alibabaUsageSchema.nullish()
693
+ });
694
+ var alibabaChatChunkSchema = import_v42.z.object({
695
+ id: import_v42.z.string().nullish(),
696
+ created: import_v42.z.number().nullish(),
697
+ model: import_v42.z.string().nullish(),
698
+ choices: import_v42.z.array(
699
+ import_v42.z.object({
700
+ delta: import_v42.z.object({
701
+ role: import_v42.z.enum(["assistant"]).nullish(),
702
+ content: import_v42.z.string().nullish(),
703
+ reasoning_content: import_v42.z.string().nullish(),
704
+ // Alibaba thinking mode delta
705
+ tool_calls: import_v42.z.array(
706
+ import_v42.z.object({
707
+ index: import_v42.z.number().nullish(),
708
+ // Index for accumulating tool calls
709
+ id: import_v42.z.string().nullish(),
710
+ type: import_v42.z.literal("function").nullish(),
711
+ function: import_v42.z.object({
712
+ name: import_v42.z.string().nullish(),
713
+ arguments: import_v42.z.string().nullish()
714
+ }).nullish()
715
+ })
716
+ ).nullish()
717
+ }),
718
+ finish_reason: import_v42.z.string().nullish(),
719
+ index: import_v42.z.number()
720
+ })
721
+ ),
722
+ usage: alibabaUsageSchema.nullish()
723
+ // Usage only appears in final chunk
724
+ });
725
+
726
+ // src/alibaba-video-model.ts
727
+ var import_provider3 = require("@ai-sdk/provider");
728
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
729
+ var import_v43 = require("zod/v4");
730
+ var alibabaVideoModelOptionsSchema = (0, import_provider_utils3.lazySchema)(
731
+ () => (0, import_provider_utils3.zodSchema)(
732
+ import_v43.z.object({
733
+ negativePrompt: import_v43.z.string().nullish(),
734
+ audioUrl: import_v43.z.string().nullish(),
735
+ promptExtend: import_v43.z.boolean().nullish(),
736
+ shotType: import_v43.z.enum(["single", "multi"]).nullish(),
737
+ watermark: import_v43.z.boolean().nullish(),
738
+ audio: import_v43.z.boolean().nullish(),
739
+ referenceUrls: import_v43.z.array(import_v43.z.string()).nullish(),
740
+ pollIntervalMs: import_v43.z.number().positive().nullish(),
741
+ pollTimeoutMs: import_v43.z.number().positive().nullish()
742
+ }).passthrough()
743
+ )
744
+ );
745
+ var alibabaVideoErrorSchema = import_v43.z.object({
746
+ code: import_v43.z.string().nullish(),
747
+ message: import_v43.z.string(),
748
+ request_id: import_v43.z.string().nullish()
749
+ });
750
+ var alibabaVideoFailedResponseHandler = (0, import_provider_utils3.createJsonErrorResponseHandler)({
751
+ errorSchema: alibabaVideoErrorSchema,
752
+ errorToMessage: (data) => data.message
753
+ });
754
+ var alibabaVideoCreateTaskSchema = import_v43.z.object({
755
+ output: import_v43.z.object({
756
+ task_status: import_v43.z.string(),
757
+ task_id: import_v43.z.string()
758
+ }).nullish(),
759
+ request_id: import_v43.z.string().nullish()
760
+ });
761
+ var alibabaVideoTaskStatusSchema = import_v43.z.object({
762
+ output: import_v43.z.object({
763
+ task_id: import_v43.z.string(),
764
+ task_status: import_v43.z.string(),
765
+ video_url: import_v43.z.string().nullish(),
766
+ submit_time: import_v43.z.string().nullish(),
767
+ scheduled_time: import_v43.z.string().nullish(),
768
+ end_time: import_v43.z.string().nullish(),
769
+ orig_prompt: import_v43.z.string().nullish(),
770
+ actual_prompt: import_v43.z.string().nullish(),
771
+ code: import_v43.z.string().nullish(),
772
+ message: import_v43.z.string().nullish()
773
+ }).nullish(),
774
+ usage: import_v43.z.object({
775
+ duration: import_v43.z.number().nullish(),
776
+ output_video_duration: import_v43.z.number().nullish(),
777
+ SR: import_v43.z.number().nullish(),
778
+ size: import_v43.z.string().nullish()
779
+ }).nullish(),
780
+ request_id: import_v43.z.string().nullish()
781
+ });
782
+ function detectMode(modelId) {
783
+ if (modelId.includes("-i2v")) return "i2v";
784
+ if (modelId.includes("-r2v")) return "r2v";
785
+ return "t2v";
786
+ }
787
+ var AlibabaVideoModel = class {
788
+ constructor(modelId, config) {
789
+ this.modelId = modelId;
790
+ this.config = config;
791
+ this.specificationVersion = "v4";
792
+ this.maxVideosPerCall = 1;
793
+ }
794
+ get provider() {
795
+ return this.config.provider;
796
+ }
797
+ async doGenerate(options) {
798
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
799
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
800
+ const warnings = [];
801
+ const mode = detectMode(this.modelId);
802
+ const alibabaOptions = await (0, import_provider_utils3.parseProviderOptions)({
803
+ provider: "alibaba",
804
+ providerOptions: options.providerOptions,
805
+ schema: alibabaVideoModelOptionsSchema
806
+ });
807
+ const input = {};
808
+ if (options.prompt != null) {
809
+ input.prompt = options.prompt;
810
+ }
811
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.negativePrompt) != null) {
812
+ input.negative_prompt = alibabaOptions.negativePrompt;
813
+ }
814
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.audioUrl) != null) {
815
+ input.audio_url = alibabaOptions.audioUrl;
816
+ }
817
+ if (mode === "i2v" && options.image != null) {
818
+ if (options.image.type === "url") {
819
+ input.img_url = options.image.url;
820
+ } else {
821
+ const base64Data = typeof options.image.data === "string" ? options.image.data : (0, import_provider_utils3.convertUint8ArrayToBase64)(options.image.data);
822
+ input.img_url = base64Data;
823
+ }
824
+ }
825
+ if (mode === "r2v" && (alibabaOptions == null ? void 0 : alibabaOptions.referenceUrls) != null) {
826
+ input.reference_urls = alibabaOptions.referenceUrls;
827
+ }
828
+ const parameters = {};
829
+ if (options.duration != null) {
830
+ parameters.duration = options.duration;
831
+ }
832
+ if (options.seed != null) {
833
+ parameters.seed = options.seed;
834
+ }
835
+ if (options.resolution != null) {
836
+ if (mode === "i2v") {
837
+ const resolutionMap = {
838
+ "1280x720": "720P",
839
+ "720x1280": "720P",
840
+ "960x960": "720P",
841
+ "1088x832": "720P",
842
+ "832x1088": "720P",
843
+ "1920x1080": "1080P",
844
+ "1080x1920": "1080P",
845
+ "1440x1440": "1080P",
846
+ "1632x1248": "1080P",
847
+ "1248x1632": "1080P",
848
+ "832x480": "480P",
849
+ "480x832": "480P",
850
+ "624x624": "480P"
851
+ };
852
+ parameters.resolution = resolutionMap[options.resolution] || options.resolution;
853
+ } else {
854
+ parameters.size = options.resolution.replace("x", "*");
855
+ }
856
+ }
857
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.promptExtend) != null) {
858
+ parameters.prompt_extend = alibabaOptions.promptExtend;
859
+ }
860
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.shotType) != null) {
861
+ parameters.shot_type = alibabaOptions.shotType;
862
+ }
863
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.watermark) != null) {
864
+ parameters.watermark = alibabaOptions.watermark;
865
+ }
866
+ if ((alibabaOptions == null ? void 0 : alibabaOptions.audio) != null) {
867
+ parameters.audio = alibabaOptions.audio;
868
+ }
869
+ if (options.aspectRatio) {
870
+ warnings.push({
871
+ type: "unsupported",
872
+ feature: "aspectRatio",
873
+ details: "Alibaba video models use explicit size/resolution dimensions. Use the resolution option or providerOptions.alibaba for size control."
874
+ });
875
+ }
876
+ if (options.fps) {
877
+ warnings.push({
878
+ type: "unsupported",
879
+ feature: "fps",
880
+ details: "Alibaba video models do not support custom FPS."
881
+ });
882
+ }
883
+ if (options.n != null && options.n > 1) {
884
+ warnings.push({
885
+ type: "unsupported",
886
+ feature: "n",
887
+ details: "Alibaba video models only support generating 1 video per call."
888
+ });
889
+ }
890
+ const { value: createResponse } = await (0, import_provider_utils3.postJsonToApi)({
891
+ url: `${this.config.baseURL}/api/v1/services/aigc/video-generation/video-synthesis`,
892
+ headers: (0, import_provider_utils3.combineHeaders)(
893
+ await (0, import_provider_utils3.resolve)(this.config.headers),
894
+ options.headers,
895
+ {
896
+ "X-DashScope-Async": "enable"
897
+ }
898
+ ),
899
+ body: {
900
+ model: this.modelId,
901
+ input,
902
+ parameters
903
+ },
904
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
905
+ alibabaVideoCreateTaskSchema
906
+ ),
907
+ failedResponseHandler: alibabaVideoFailedResponseHandler,
908
+ abortSignal: options.abortSignal,
909
+ fetch: this.config.fetch
910
+ });
911
+ const taskId = (_d = createResponse.output) == null ? void 0 : _d.task_id;
912
+ if (!taskId) {
913
+ throw new import_provider3.AISDKError({
914
+ name: "ALIBABA_VIDEO_GENERATION_ERROR",
915
+ message: `No task_id returned from Alibaba API. Response: ${JSON.stringify(createResponse)}`
916
+ });
917
+ }
918
+ const pollIntervalMs = (_e = alibabaOptions == null ? void 0 : alibabaOptions.pollIntervalMs) != null ? _e : 5e3;
919
+ const pollTimeoutMs = (_f = alibabaOptions == null ? void 0 : alibabaOptions.pollTimeoutMs) != null ? _f : 6e5;
920
+ const startTime = Date.now();
921
+ let finalResponse;
922
+ let responseHeaders;
923
+ while (true) {
924
+ await (0, import_provider_utils3.delay)(pollIntervalMs, { abortSignal: options.abortSignal });
925
+ if (Date.now() - startTime > pollTimeoutMs) {
926
+ throw new import_provider3.AISDKError({
927
+ name: "ALIBABA_VIDEO_GENERATION_TIMEOUT",
928
+ message: `Video generation timed out after ${pollTimeoutMs}ms`
929
+ });
930
+ }
931
+ const { value: statusResponse, responseHeaders: pollHeaders } = await (0, import_provider_utils3.getFromApi)({
932
+ url: `${this.config.baseURL}/api/v1/tasks/${taskId}`,
933
+ headers: (0, import_provider_utils3.combineHeaders)(
934
+ await (0, import_provider_utils3.resolve)(this.config.headers),
935
+ options.headers
936
+ ),
937
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
938
+ alibabaVideoTaskStatusSchema
939
+ ),
940
+ failedResponseHandler: alibabaVideoFailedResponseHandler,
941
+ abortSignal: options.abortSignal,
942
+ fetch: this.config.fetch
943
+ });
944
+ responseHeaders = pollHeaders;
945
+ const taskStatus = (_g = statusResponse.output) == null ? void 0 : _g.task_status;
946
+ if (taskStatus === "SUCCEEDED") {
947
+ finalResponse = statusResponse;
948
+ break;
949
+ }
950
+ if (taskStatus === "FAILED" || taskStatus === "CANCELED") {
951
+ throw new import_provider3.AISDKError({
952
+ name: "ALIBABA_VIDEO_GENERATION_FAILED",
953
+ message: `Video generation ${taskStatus.toLowerCase()}. Task ID: ${taskId}. ${(_i = (_h = statusResponse.output) == null ? void 0 : _h.message) != null ? _i : ""}`
954
+ });
955
+ }
956
+ }
957
+ const videoUrl = (_j = finalResponse == null ? void 0 : finalResponse.output) == null ? void 0 : _j.video_url;
958
+ if (!videoUrl) {
959
+ throw new import_provider3.AISDKError({
960
+ name: "ALIBABA_VIDEO_GENERATION_ERROR",
961
+ message: `No video URL in response. Task ID: ${taskId}`
962
+ });
963
+ }
964
+ return {
965
+ videos: [
966
+ {
967
+ type: "url",
968
+ url: videoUrl,
969
+ mediaType: "video/mp4"
970
+ }
971
+ ],
972
+ warnings,
973
+ response: {
974
+ timestamp: currentDate,
975
+ modelId: this.modelId,
976
+ headers: responseHeaders
977
+ },
978
+ providerMetadata: {
979
+ alibaba: {
980
+ taskId,
981
+ videoUrl,
982
+ ...((_k = finalResponse == null ? void 0 : finalResponse.output) == null ? void 0 : _k.actual_prompt) ? { actualPrompt: finalResponse.output.actual_prompt } : {},
983
+ ...(finalResponse == null ? void 0 : finalResponse.usage) ? {
984
+ usage: {
985
+ duration: finalResponse.usage.duration,
986
+ outputVideoDuration: finalResponse.usage.output_video_duration,
987
+ resolution: finalResponse.usage.SR,
988
+ size: finalResponse.usage.size
989
+ }
990
+ } : {}
991
+ }
992
+ }
993
+ };
994
+ }
995
+ };
996
+
997
+ // src/version.ts
998
+ var VERSION = "0.0.0-b66d09a8-20260328011513";
999
+
1000
+ // src/alibaba-provider.ts
1001
+ var alibabaErrorDataSchema = import_v44.z.object({
1002
+ error: import_v44.z.object({
1003
+ message: import_v44.z.string(),
1004
+ code: import_v44.z.string().nullish(),
1005
+ type: import_v44.z.string().nullish()
1006
+ })
1007
+ });
1008
+ var alibabaFailedResponseHandler = (0, import_provider_utils4.createJsonErrorResponseHandler)({
1009
+ errorSchema: alibabaErrorDataSchema,
1010
+ errorToMessage: (data) => data.error.message
1011
+ });
1012
+ function createAlibaba(options = {}) {
1013
+ var _a, _b;
1014
+ const baseURL = (_a = (0, import_provider_utils4.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
1015
+ const videoBaseURL = (_b = (0, import_provider_utils4.withoutTrailingSlash)(options.videoBaseURL)) != null ? _b : "https://dashscope-intl.aliyuncs.com";
1016
+ const getHeaders = () => (0, import_provider_utils4.withUserAgentSuffix)(
1017
+ {
1018
+ Authorization: `Bearer ${(0, import_provider_utils4.loadApiKey)({
1019
+ apiKey: options.apiKey,
1020
+ environmentVariableName: "ALIBABA_API_KEY",
1021
+ description: "Alibaba Cloud (DashScope)"
1022
+ })}`,
1023
+ ...options.headers
1024
+ },
1025
+ `ai-sdk/alibaba/${VERSION}`
1026
+ );
1027
+ const createLanguageModel = (modelId) => {
1028
+ var _a2;
1029
+ return new AlibabaLanguageModel(modelId, {
1030
+ provider: "alibaba.chat",
1031
+ baseURL,
1032
+ headers: getHeaders,
1033
+ fetch: options.fetch,
1034
+ includeUsage: (_a2 = options.includeUsage) != null ? _a2 : true
1035
+ });
1036
+ };
1037
+ const createVideoModel = (modelId) => new AlibabaVideoModel(modelId, {
1038
+ provider: "alibaba.video",
1039
+ baseURL: videoBaseURL,
1040
+ headers: getHeaders,
1041
+ fetch: options.fetch
1042
+ });
1043
+ const provider = function(modelId) {
1044
+ if (new.target) {
1045
+ throw new Error(
1046
+ "The Alibaba model function cannot be called with the new keyword."
1047
+ );
1048
+ }
1049
+ return createLanguageModel(modelId);
1050
+ };
1051
+ provider.specificationVersion = "v4";
1052
+ provider.languageModel = createLanguageModel;
1053
+ provider.chatModel = createLanguageModel;
1054
+ provider.video = createVideoModel;
1055
+ provider.videoModel = createVideoModel;
1056
+ provider.imageModel = (modelId) => {
1057
+ throw new import_provider4.NoSuchModelError({ modelId, modelType: "imageModel" });
1058
+ };
1059
+ provider.embeddingModel = (modelId) => {
1060
+ throw new import_provider4.NoSuchModelError({ modelId, modelType: "embeddingModel" });
1061
+ };
1062
+ return provider;
1063
+ }
1064
+ var alibaba = createAlibaba();
1065
+ // Annotate the CommonJS export names for ESM import in node:
1066
+ 0 && (module.exports = {
1067
+ VERSION,
1068
+ alibaba,
1069
+ createAlibaba
1070
+ });
1071
+ //# sourceMappingURL=index.js.map