@ai-sdk/alibaba 2.0.0-beta.25 → 2.0.0-beta.26

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