@ai-sdk/alibaba 2.0.0-beta.8 → 2.0.0-canary.39

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