@ai-sdk/alibaba 2.0.0-beta.3 → 2.0.0-beta.30

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