@ai-sdk/alibaba 2.0.58 → 2.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1592 +1,1275 @@
1
- // src/alibaba-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- loadApiKey,
7
- withoutTrailingSlash,
8
- withUserAgentSuffix
9
- } from "@ai-sdk/provider-utils";
10
-
11
- // src/alibaba-chat-language-model.ts
12
- import {
13
- combineHeaders,
14
- createEventSourceResponseHandler,
15
- createJsonResponseHandler,
16
- createLanguageModelResponseMetadata as getResponseMetadata,
17
- generateId,
18
- injectJsonInstructionIntoMessages,
19
- isCustomReasoning,
20
- mapReasoningToProviderBudget,
21
- parseProviderOptions,
22
- postJsonToApi,
23
- serializeModelOptions,
24
- StreamingToolCallTracker,
25
- WORKFLOW_SERIALIZE,
26
- WORKFLOW_DESERIALIZE
27
- } from "@ai-sdk/provider-utils";
28
- import { z as z3 } from "zod/v4";
29
-
30
- // src/alibaba-chat-language-model-options.ts
1
+ import { AISDKError, NoSuchModelError, TooManyEmbeddingValuesForCallError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
2
+ import { StreamingToolCallTracker, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertImageModelFileToDataUri, convertToBase64, convertUint8ArrayToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata, createNullLanguageModelUsage, generateId, getFromApi, getTopLevelMediaType, injectJsonInstructionIntoMessages, isCustomReasoning, lazySchema, loadApiKey, mapReasoningToProviderBudget, parseProviderOptions, postJsonToApi, resolve, resolveFullMediaType, serializeModelOptions, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
31
3
  import { z } from "zod/v4";
32
- var alibabaLanguageModelChatOptions = z.object({
33
- /**
34
- * Enable thinking/reasoning mode for supported models.
35
- * When enabled, the model generates reasoning content before the response.
36
- *
37
- * @default false
38
- */
39
- enableThinking: z.boolean().optional(),
40
- /**
41
- * Maximum number of reasoning tokens to generate.
42
- */
43
- thinkingBudget: z.number().positive().optional(),
44
- /**
45
- * Whether to preserve reasoning from previous assistant messages.
46
- *
47
- * When enabled, historical reasoning is sent separately as
48
- * `reasoning_content` and Alibaba receives `preserve_thinking: true`.
49
- * Defaults to `true` for models that support preserved thinking; set to
50
- * `false` to opt out.
51
- */
52
- preserveThinking: z.boolean().optional(),
53
- /**
54
- * Whether to enable parallel function calling during tool use.
55
- *
56
- * @default true
57
- */
58
- parallelToolCalls: z.boolean().optional()
59
- });
60
-
61
- // src/alibaba-error.ts
62
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
63
- import { z as z2 } from "zod/v4";
64
- var alibabaErrorDataSchema = z2.object({
65
- error: z2.object({
66
- message: z2.string(),
67
- code: z2.string().nullish(),
68
- type: z2.string().nullish()
69
- })
4
+ //#region src/alibaba-chat-language-model-options.ts
5
+ const alibabaLanguageModelChatOptions = z.object({
6
+ /**
7
+ * Enable thinking/reasoning mode for supported models.
8
+ * When enabled, the model generates reasoning content before the response.
9
+ *
10
+ * @default false
11
+ */
12
+ enableThinking: z.boolean().optional(),
13
+ /**
14
+ * Maximum number of reasoning tokens to generate.
15
+ */
16
+ thinkingBudget: z.number().positive().optional(),
17
+ /**
18
+ * Whether to preserve reasoning from previous assistant messages.
19
+ *
20
+ * When enabled, historical reasoning is sent separately as
21
+ * `reasoning_content` and Alibaba receives `preserve_thinking: true`.
22
+ * Defaults to `true` for models that support preserved thinking; set to
23
+ * `false` to opt out.
24
+ */
25
+ preserveThinking: z.boolean().optional(),
26
+ /**
27
+ * Whether to enable parallel function calling during tool use.
28
+ *
29
+ * @default true
30
+ */
31
+ parallelToolCalls: z.boolean().optional()
70
32
  });
71
- var alibabaFailedResponseHandler = createJsonErrorResponseHandler({
72
- errorSchema: alibabaErrorDataSchema,
73
- errorToMessage: (data) => data.error.message
33
+ //#endregion
34
+ //#region src/alibaba-error.ts
35
+ const alibabaErrorDataSchema = z.object({ error: z.object({
36
+ message: z.string(),
37
+ code: z.string().nullish(),
38
+ type: z.string().nullish()
39
+ }) });
40
+ const alibabaFailedResponseHandler = createJsonErrorResponseHandler({
41
+ errorSchema: alibabaErrorDataSchema,
42
+ errorToMessage: (data) => data.error.message
74
43
  });
75
-
76
- // src/alibaba-prepare-tools.ts
77
- import {
78
- UnsupportedFunctionalityError
79
- } from "@ai-sdk/provider";
80
- function prepareTools({
81
- tools,
82
- toolChoice
83
- }) {
84
- tools = tools?.length ? tools : void 0;
85
- const toolWarnings = [];
86
- if (tools == null) {
87
- return { tools: void 0, toolChoice: void 0, toolWarnings };
88
- }
89
- const alibabaTools = [];
90
- for (const tool of tools) {
91
- if (tool.type === "provider") {
92
- toolWarnings.push({
93
- type: "unsupported",
94
- feature: `provider-defined tool ${tool.id}`
95
- });
96
- } else {
97
- alibabaTools.push({
98
- type: "function",
99
- function: {
100
- name: tool.name,
101
- description: tool.description,
102
- parameters: tool.inputSchema,
103
- ...tool.strict != null ? { strict: tool.strict } : {}
104
- }
105
- });
106
- }
107
- }
108
- if (toolChoice == null) {
109
- return { tools: alibabaTools, toolChoice: void 0, toolWarnings };
110
- }
111
- const type = toolChoice.type;
112
- switch (type) {
113
- case "auto":
114
- case "none":
115
- case "required":
116
- return { tools: alibabaTools, toolChoice: type, toolWarnings };
117
- case "tool":
118
- return {
119
- tools: alibabaTools,
120
- toolChoice: {
121
- type: "function",
122
- function: { name: toolChoice.toolName }
123
- },
124
- toolWarnings
125
- };
126
- default: {
127
- const _exhaustiveCheck = type;
128
- throw new UnsupportedFunctionalityError({
129
- functionality: `tool choice type: ${_exhaustiveCheck}`
130
- });
131
- }
132
- }
44
+ //#endregion
45
+ //#region src/alibaba-prepare-tools.ts
46
+ function prepareTools({ tools, toolChoice }) {
47
+ tools = tools?.length ? tools : void 0;
48
+ const toolWarnings = [];
49
+ if (tools == null) return {
50
+ tools: void 0,
51
+ toolChoice: void 0,
52
+ toolWarnings
53
+ };
54
+ const alibabaTools = [];
55
+ for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
56
+ type: "unsupported",
57
+ feature: `provider-defined tool ${tool.id}`
58
+ });
59
+ else alibabaTools.push({
60
+ type: "function",
61
+ function: {
62
+ name: tool.name,
63
+ description: tool.description,
64
+ parameters: tool.inputSchema,
65
+ ...tool.strict != null ? { strict: tool.strict } : {}
66
+ }
67
+ });
68
+ if (toolChoice == null) return {
69
+ tools: alibabaTools,
70
+ toolChoice: void 0,
71
+ toolWarnings
72
+ };
73
+ const type = toolChoice.type;
74
+ switch (type) {
75
+ case "auto":
76
+ case "none":
77
+ case "required": return {
78
+ tools: alibabaTools,
79
+ toolChoice: type,
80
+ toolWarnings
81
+ };
82
+ case "tool": return {
83
+ tools: alibabaTools,
84
+ toolChoice: {
85
+ type: "function",
86
+ function: { name: toolChoice.toolName }
87
+ },
88
+ toolWarnings
89
+ };
90
+ default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
91
+ }
133
92
  }
134
-
135
- // src/convert-alibaba-usage.ts
136
- import { createNullLanguageModelUsage } from "@ai-sdk/provider-utils";
93
+ //#endregion
94
+ //#region src/convert-alibaba-usage.ts
137
95
  function convertAlibabaUsage(usage) {
138
- if (usage == null) {
139
- return createNullLanguageModelUsage();
140
- }
141
- const promptTokens = usage.prompt_tokens ?? 0;
142
- const completionTokens = usage.completion_tokens ?? 0;
143
- const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
144
- const cacheWriteTokens = usage.prompt_tokens_details?.cache_creation_input_tokens ?? 0;
145
- const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
146
- return {
147
- inputTokens: {
148
- total: promptTokens,
149
- // Alibaba counts both cache reads and cache writes inside prompt_tokens.
150
- noCache: promptTokens - cacheReadTokens - cacheWriteTokens,
151
- cacheRead: cacheReadTokens,
152
- cacheWrite: cacheWriteTokens
153
- },
154
- outputTokens: {
155
- total: completionTokens,
156
- text: Math.max(0, completionTokens - reasoningTokens),
157
- reasoning: reasoningTokens
158
- },
159
- raw: usage
160
- };
96
+ if (usage == null) return createNullLanguageModelUsage();
97
+ const promptTokens = usage.prompt_tokens ?? 0;
98
+ const completionTokens = usage.completion_tokens ?? 0;
99
+ const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
100
+ const cacheWriteTokens = usage.prompt_tokens_details?.cache_creation_input_tokens ?? 0;
101
+ const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
102
+ return {
103
+ inputTokens: {
104
+ total: promptTokens,
105
+ noCache: promptTokens - cacheReadTokens - cacheWriteTokens,
106
+ cacheRead: cacheReadTokens,
107
+ cacheWrite: cacheWriteTokens
108
+ },
109
+ outputTokens: {
110
+ total: completionTokens,
111
+ text: Math.max(0, completionTokens - reasoningTokens),
112
+ reasoning: reasoningTokens
113
+ },
114
+ raw: usage
115
+ };
161
116
  }
162
-
163
- // src/convert-to-alibaba-chat-messages.ts
164
- import {
165
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
166
- } from "@ai-sdk/provider";
167
- import {
168
- convertToBase64,
169
- getTopLevelMediaType,
170
- resolveFullMediaType
171
- } from "@ai-sdk/provider-utils";
117
+ //#endregion
118
+ //#region src/convert-to-alibaba-chat-messages.ts
172
119
  function formatImageUrl({ part }) {
173
- if (part.data.type === "url") {
174
- return part.data.url.toString();
175
- }
176
- if (part.data.type === "data") {
177
- return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`;
178
- }
179
- throw new UnsupportedFunctionalityError2({
180
- functionality: `file part data type ${part.data.type}`
181
- });
120
+ if (part.data.type === "url") return part.data.url.toString();
121
+ if (part.data.type === "data") return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`;
122
+ throw new UnsupportedFunctionalityError({ functionality: `file part data type ${part.data.type}` });
182
123
  }
183
- function convertToAlibabaChatMessages({
184
- prompt,
185
- cacheControlValidator,
186
- preserveThinking = false
187
- }) {
188
- const messages = [];
189
- let lastUserMessageIndex = -1;
190
- for (let i = prompt.length - 1; i >= 0; i--) {
191
- if (prompt[i].role === "user") {
192
- lastUserMessageIndex = i;
193
- break;
194
- }
195
- }
196
- let index = -1;
197
- for (const { role, content, ...message } of prompt) {
198
- index++;
199
- const messageCacheControl = cacheControlValidator?.getCacheControl(
200
- message.providerOptions
201
- );
202
- switch (role) {
203
- case "system": {
204
- if (messageCacheControl) {
205
- messages.push({
206
- role: "system",
207
- content: [
208
- {
209
- type: "text",
210
- text: content,
211
- cache_control: messageCacheControl
212
- }
213
- ]
214
- });
215
- } else {
216
- messages.push({ role: "system", content });
217
- }
218
- break;
219
- }
220
- case "user": {
221
- messages.push({
222
- role: "user",
223
- content: content.map((part, index2) => {
224
- const isLastPart = index2 === content.length - 1;
225
- const partCacheControl = cacheControlValidator?.getCacheControl(part.providerOptions) ?? (isLastPart ? messageCacheControl : void 0);
226
- switch (part.type) {
227
- case "text": {
228
- return {
229
- type: "text",
230
- text: part.text,
231
- ...partCacheControl ? { cache_control: partCacheControl } : {}
232
- };
233
- }
234
- case "file": {
235
- switch (part.data.type) {
236
- case "reference": {
237
- throw new UnsupportedFunctionalityError2({
238
- functionality: "file parts with provider references"
239
- });
240
- }
241
- case "text": {
242
- throw new UnsupportedFunctionalityError2({
243
- functionality: "text file parts"
244
- });
245
- }
246
- case "url":
247
- case "data": {
248
- if (getTopLevelMediaType(part.mediaType) === "image") {
249
- return {
250
- type: "image_url",
251
- image_url: {
252
- url: formatImageUrl({ part })
253
- },
254
- ...partCacheControl ? { cache_control: partCacheControl } : {}
255
- };
256
- } else {
257
- throw new UnsupportedFunctionalityError2({
258
- functionality: "Only image file parts are supported"
259
- });
260
- }
261
- }
262
- }
263
- }
264
- }
265
- })
266
- });
267
- break;
268
- }
269
- case "assistant": {
270
- let text = "";
271
- let reasoningContent = "";
272
- const toolCalls = [];
273
- for (const part of content) {
274
- switch (part.type) {
275
- case "text": {
276
- text += part.text;
277
- break;
278
- }
279
- case "tool-call": {
280
- toolCalls.push({
281
- id: part.toolCallId,
282
- type: "function",
283
- function: {
284
- name: part.toolName,
285
- arguments: JSON.stringify(part.input)
286
- }
287
- });
288
- break;
289
- }
290
- case "reasoning": {
291
- if (preserveThinking || index > lastUserMessageIndex) {
292
- reasoningContent += part.text;
293
- }
294
- break;
295
- }
296
- }
297
- }
298
- if (text.length === 0 && toolCalls.length === 0 && reasoningContent.length === 0) {
299
- break;
300
- }
301
- messages.push({
302
- role: "assistant",
303
- content: text.length === 0 && toolCalls.length === 0 && reasoningContent.length > 0 ? null : messageCacheControl ? [{ type: "text", text, cache_control: messageCacheControl }] : text || null,
304
- ...reasoningContent.length > 0 ? { reasoning_content: reasoningContent } : {},
305
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
306
- });
307
- break;
308
- }
309
- case "tool": {
310
- const toolResponses = content.filter(
311
- (r) => r.type !== "tool-approval-response"
312
- );
313
- for (let i = 0; i < toolResponses.length; i++) {
314
- const toolResponse = toolResponses[i];
315
- const output = toolResponse.output;
316
- const isLastPart = i === toolResponses.length - 1;
317
- const partCacheControl = cacheControlValidator?.getCacheControl(
318
- toolResponse.providerOptions
319
- ) ?? (isLastPart ? messageCacheControl : void 0);
320
- let contentValue;
321
- switch (output.type) {
322
- case "text":
323
- case "error-text":
324
- contentValue = output.value;
325
- break;
326
- case "execution-denied":
327
- contentValue = output.reason ?? "Tool call execution denied.";
328
- break;
329
- case "content":
330
- case "json":
331
- case "error-json":
332
- contentValue = JSON.stringify(output.value);
333
- break;
334
- }
335
- messages.push({
336
- role: "tool",
337
- tool_call_id: toolResponse.toolCallId,
338
- content: partCacheControl ? [
339
- {
340
- type: "text",
341
- text: contentValue,
342
- cache_control: partCacheControl
343
- }
344
- ] : contentValue
345
- });
346
- }
347
- break;
348
- }
349
- default: {
350
- const _exhaustiveCheck = role;
351
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
352
- }
353
- }
354
- }
355
- return messages;
124
+ function convertToAlibabaChatMessages({ prompt, cacheControlValidator, preserveThinking = false }) {
125
+ const messages = [];
126
+ let lastUserMessageIndex = -1;
127
+ for (let i = prompt.length - 1; i >= 0; i--) if (prompt[i].role === "user") {
128
+ lastUserMessageIndex = i;
129
+ break;
130
+ }
131
+ let index = -1;
132
+ for (const { role, content, ...message } of prompt) {
133
+ index++;
134
+ const messageCacheControl = cacheControlValidator?.getCacheControl(message.providerOptions);
135
+ switch (role) {
136
+ case "system":
137
+ if (messageCacheControl) messages.push({
138
+ role: "system",
139
+ content: [{
140
+ type: "text",
141
+ text: content,
142
+ cache_control: messageCacheControl
143
+ }]
144
+ });
145
+ else messages.push({
146
+ role: "system",
147
+ content
148
+ });
149
+ break;
150
+ case "user":
151
+ messages.push({
152
+ role: "user",
153
+ content: content.map((part, index) => {
154
+ const isLastPart = index === content.length - 1;
155
+ const partCacheControl = cacheControlValidator?.getCacheControl(part.providerOptions) ?? (isLastPart ? messageCacheControl : void 0);
156
+ switch (part.type) {
157
+ case "text": return {
158
+ type: "text",
159
+ text: part.text,
160
+ ...partCacheControl ? { cache_control: partCacheControl } : {}
161
+ };
162
+ case "file": switch (part.data.type) {
163
+ case "reference": throw new UnsupportedFunctionalityError({ functionality: "file parts with provider references" });
164
+ case "text": throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
165
+ case "url":
166
+ case "data": if (getTopLevelMediaType(part.mediaType) === "image") return {
167
+ type: "image_url",
168
+ image_url: { url: formatImageUrl({ part }) },
169
+ ...partCacheControl ? { cache_control: partCacheControl } : {}
170
+ };
171
+ else throw new UnsupportedFunctionalityError({ functionality: "Only image file parts are supported" });
172
+ }
173
+ }
174
+ })
175
+ });
176
+ break;
177
+ case "assistant": {
178
+ let text = "";
179
+ let reasoningContent = "";
180
+ const toolCalls = [];
181
+ for (const part of content) switch (part.type) {
182
+ case "text":
183
+ text += part.text;
184
+ break;
185
+ case "tool-call":
186
+ toolCalls.push({
187
+ id: part.toolCallId,
188
+ type: "function",
189
+ function: {
190
+ name: part.toolName,
191
+ arguments: JSON.stringify(part.input)
192
+ }
193
+ });
194
+ break;
195
+ case "reasoning": if (preserveThinking || index > lastUserMessageIndex) reasoningContent += part.text;
196
+ }
197
+ if (text.length === 0 && toolCalls.length === 0 && reasoningContent.length === 0) break;
198
+ messages.push({
199
+ role: "assistant",
200
+ content: text.length === 0 && toolCalls.length === 0 && reasoningContent.length > 0 ? null : messageCacheControl ? [{
201
+ type: "text",
202
+ text,
203
+ cache_control: messageCacheControl
204
+ }] : text || null,
205
+ ...reasoningContent.length > 0 ? { reasoning_content: reasoningContent } : {},
206
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
207
+ });
208
+ break;
209
+ }
210
+ case "tool": {
211
+ const toolResponses = content.filter((r) => r.type !== "tool-approval-response");
212
+ for (let i = 0; i < toolResponses.length; i++) {
213
+ const toolResponse = toolResponses[i];
214
+ const output = toolResponse.output;
215
+ const isLastPart = i === toolResponses.length - 1;
216
+ const partCacheControl = cacheControlValidator?.getCacheControl(toolResponse.providerOptions) ?? (isLastPart ? messageCacheControl : void 0);
217
+ let contentValue;
218
+ switch (output.type) {
219
+ case "text":
220
+ case "error-text":
221
+ contentValue = output.value;
222
+ break;
223
+ case "execution-denied":
224
+ contentValue = output.reason ?? "Tool call execution denied.";
225
+ break;
226
+ case "content":
227
+ case "json":
228
+ case "error-json": contentValue = JSON.stringify(output.value);
229
+ }
230
+ messages.push({
231
+ role: "tool",
232
+ tool_call_id: toolResponse.toolCallId,
233
+ content: partCacheControl ? [{
234
+ type: "text",
235
+ text: contentValue,
236
+ cache_control: partCacheControl
237
+ }] : contentValue
238
+ });
239
+ }
240
+ break;
241
+ }
242
+ default: throw new Error(`Unsupported role: ${role}`);
243
+ }
244
+ }
245
+ return messages;
356
246
  }
357
-
358
- // src/get-cache-control.ts
359
- var MAX_CACHE_BREAKPOINTS = 4;
247
+ //#endregion
248
+ //#region src/get-cache-control.ts
249
+ const MAX_CACHE_BREAKPOINTS = 4;
360
250
  function getCacheControl(providerMetadata) {
361
- const alibaba2 = providerMetadata?.alibaba;
362
- const cacheControlValue = alibaba2?.cacheControl ?? alibaba2?.cache_control;
363
- return cacheControlValue;
251
+ const alibaba = providerMetadata?.alibaba;
252
+ return alibaba?.cacheControl ?? alibaba?.cache_control;
364
253
  }
365
254
  var CacheControlValidator = class {
366
- constructor() {
367
- this.breakpointCount = 0;
368
- this.warnings = [];
369
- }
370
- getCacheControl(providerMetadata) {
371
- const cacheControlValue = getCacheControl(providerMetadata);
372
- if (!cacheControlValue) {
373
- return void 0;
374
- }
375
- this.breakpointCount++;
376
- if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {
377
- this.warnings.push({
378
- type: "other",
379
- message: `Max breakpoint limit exceeded. Only the last ${MAX_CACHE_BREAKPOINTS} cache markers will take effect.`
380
- });
381
- }
382
- return cacheControlValue;
383
- }
384
- getWarnings() {
385
- return this.warnings;
386
- }
255
+ constructor() {
256
+ this.breakpointCount = 0;
257
+ this.warnings = [];
258
+ }
259
+ getCacheControl(providerMetadata) {
260
+ const cacheControlValue = getCacheControl(providerMetadata);
261
+ if (!cacheControlValue) return;
262
+ this.breakpointCount++;
263
+ if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) this.warnings.push({
264
+ type: "other",
265
+ message: `Max breakpoint limit exceeded. Only the last ${MAX_CACHE_BREAKPOINTS} cache markers will take effect.`
266
+ });
267
+ return cacheControlValue;
268
+ }
269
+ getWarnings() {
270
+ return this.warnings;
271
+ }
387
272
  };
388
-
389
- // src/map-alibaba-finish-reason.ts
273
+ //#endregion
274
+ //#region src/map-alibaba-finish-reason.ts
390
275
  function mapAlibabaFinishReason(finishReason) {
391
- switch (finishReason) {
392
- case "stop":
393
- return "stop";
394
- case "length":
395
- return "length";
396
- case "content_filter":
397
- return "content-filter";
398
- case "function_call":
399
- case "tool_calls":
400
- return "tool-calls";
401
- default:
402
- return "other";
403
- }
276
+ switch (finishReason) {
277
+ case "stop": return "stop";
278
+ case "length": return "length";
279
+ case "content_filter": return "content-filter";
280
+ case "function_call":
281
+ case "tool_calls": return "tool-calls";
282
+ default: return "other";
283
+ }
404
284
  }
405
-
406
- // src/supports-json-schema-output.ts
407
- var JSON_SCHEMA_MODEL_PREFIXES = [
408
- "qwen3.7-plus",
409
- "qwen3.7-flash",
410
- "qwen3.7-max",
411
- "qwen3.8-max",
412
- "qwen3.8-flash"
285
+ //#endregion
286
+ //#region src/supports-json-schema-output.ts
287
+ const JSON_SCHEMA_MODEL_PREFIXES = [
288
+ "qwen3.7-plus",
289
+ "qwen3.7-flash",
290
+ "qwen3.7-max",
291
+ "qwen3.8-max",
292
+ "qwen3.8-flash"
413
293
  ];
414
294
  function supportsJsonSchemaOutput(modelId) {
415
- return JSON_SCHEMA_MODEL_PREFIXES.some(
416
- (prefix) => modelId === prefix || modelId.startsWith(`${prefix}-`)
417
- );
295
+ return JSON_SCHEMA_MODEL_PREFIXES.some((prefix) => modelId === prefix || modelId.startsWith(`${prefix}-`));
418
296
  }
419
-
420
- // src/supports-preserved-thinking.ts
421
- var preservedThinkingModelIds = /* @__PURE__ */ new Set([
422
- "kimi-k2.7-code",
423
- "qwen3.6-max-preview",
424
- "qwen3.6-plus",
425
- "qwen3.6-plus-2026-04-02",
426
- "qwen3.7-flash",
427
- "qwen3.7-flash-2026-07-15",
428
- "qwen3.7-max",
429
- "qwen3.7-max-2026-05-17",
430
- "qwen3.7-max-2026-05-20",
431
- "qwen3.7-max-2026-06-08",
432
- "qwen3.7-max-preview",
433
- "qwen3.7-plus",
434
- "qwen3.7-plus-2026-05-26",
435
- "qwen3.8-flash",
436
- "qwen3.8-max",
437
- "qwen3.8-max-0902"
297
+ //#endregion
298
+ //#region src/supports-preserved-thinking.ts
299
+ /**
300
+ * Whether a model id supports Alibaba's preserved-thinking mode
301
+ * (`preserve_thinking`), which replays assistant `reasoning_content` from
302
+ * previous turns.
303
+ *
304
+ * Supported models per Alibaba's documentation:
305
+ * https://docs.qwencloud.com/developer-guides/text-generation/thinking#preserve-thinking-in-multi-turn
306
+ */
307
+ const preservedThinkingModelIds = /* @__PURE__ */ new Set([
308
+ "kimi-k2.7-code",
309
+ "qwen3.6-max-preview",
310
+ "qwen3.6-plus",
311
+ "qwen3.6-plus-2026-04-02",
312
+ "qwen3.7-flash",
313
+ "qwen3.7-flash-2026-07-15",
314
+ "qwen3.7-max",
315
+ "qwen3.7-max-2026-05-17",
316
+ "qwen3.7-max-2026-05-20",
317
+ "qwen3.7-max-2026-06-08",
318
+ "qwen3.7-max-preview",
319
+ "qwen3.7-plus",
320
+ "qwen3.7-plus-2026-05-26",
321
+ "qwen3.8-flash",
322
+ "qwen3.8-max",
323
+ "qwen3.8-max-0902"
438
324
  ]);
439
325
  function supportsPreservedThinking(modelId) {
440
- return preservedThinkingModelIds.has(modelId);
326
+ return preservedThinkingModelIds.has(modelId);
441
327
  }
442
-
443
- // src/alibaba-chat-language-model.ts
444
- var AlibabaChatLanguageModel = class _AlibabaChatLanguageModel {
445
- constructor(modelId, config) {
446
- this.specificationVersion = "v4";
447
- this.supportedUrls = {
448
- "image/*": [/^https?:\/\/.*$/]
449
- };
450
- this.modelId = modelId;
451
- this.config = config;
452
- }
453
- static [WORKFLOW_SERIALIZE](model) {
454
- return serializeModelOptions({
455
- modelId: model.modelId,
456
- config: model.config
457
- });
458
- }
459
- static [WORKFLOW_DESERIALIZE](options) {
460
- return new _AlibabaChatLanguageModel(options.modelId, options.config);
461
- }
462
- get provider() {
463
- return this.config.provider;
464
- }
465
- /**
466
- * Builds request arguments for Alibaba API call.
467
- * Converts AI SDK options to Alibaba API format.
468
- */
469
- async getArgs({
470
- prompt,
471
- maxOutputTokens,
472
- temperature,
473
- topP,
474
- topK,
475
- frequencyPenalty,
476
- presencePenalty,
477
- stopSequences,
478
- responseFormat,
479
- seed,
480
- reasoning,
481
- providerOptions,
482
- tools,
483
- toolChoice
484
- }) {
485
- const warnings = [];
486
- const cacheControlValidator = new CacheControlValidator();
487
- const alibabaOptions = await parseProviderOptions({
488
- provider: "alibaba",
489
- providerOptions,
490
- schema: alibabaLanguageModelChatOptions
491
- });
492
- if (frequencyPenalty != null) {
493
- warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
494
- }
495
- const preserveThinking = alibabaOptions?.preserveThinking ?? (supportsPreservedThinking(this.modelId) ? true : void 0);
496
- const useJsonSchema = responseFormat?.type === "json" && responseFormat.schema != null && supportsJsonSchemaOutput(this.modelId);
497
- const useJsonObject = responseFormat?.type === "json" && !useJsonSchema;
498
- if (useJsonObject && responseFormat.schema != null) {
499
- warnings.push({
500
- type: "compatibility",
501
- feature: "responseFormat JSON schema",
502
- details: `Alibaba does not support JSON Schema output for model ${this.modelId}. JSON Object mode is used instead. The schema was injected into the system message and will only be validated locally.`
503
- });
504
- }
505
- const resolvedPrompt = useJsonObject ? injectJsonInstructionIntoMessages({
506
- messages: prompt,
507
- schema: responseFormat.schema
508
- }) : prompt;
509
- const baseArgs = {
510
- model: this.modelId,
511
- max_tokens: maxOutputTokens,
512
- temperature,
513
- top_p: topP,
514
- top_k: topK,
515
- presence_penalty: presencePenalty,
516
- stop: stopSequences,
517
- seed,
518
- response_format: responseFormat?.type === "json" ? useJsonSchema ? {
519
- type: "json_schema",
520
- json_schema: {
521
- schema: responseFormat.schema,
522
- name: responseFormat.name ?? "response",
523
- description: responseFormat.description
524
- }
525
- } : { type: "json_object" } : void 0,
526
- ...resolveAlibabaThinking({
527
- reasoning,
528
- alibabaOptions,
529
- warnings
530
- }),
531
- ...preserveThinking != null ? { preserve_thinking: preserveThinking } : {},
532
- // Convert messages with cache control support
533
- messages: convertToAlibabaChatMessages({
534
- prompt: resolvedPrompt,
535
- cacheControlValidator,
536
- preserveThinking: preserveThinking ?? false
537
- })
538
- };
539
- const {
540
- tools: alibabaTools,
541
- toolChoice: alibabaToolChoice,
542
- toolWarnings
543
- } = prepareTools({ tools, toolChoice });
544
- warnings.push(...cacheControlValidator.getWarnings());
545
- return {
546
- args: {
547
- ...baseArgs,
548
- tools: alibabaTools,
549
- tool_choice: alibabaToolChoice,
550
- ...alibabaTools != null && alibabaOptions?.parallelToolCalls !== void 0 ? { parallel_tool_calls: alibabaOptions.parallelToolCalls } : {}
551
- },
552
- warnings: [...warnings, ...toolWarnings]
553
- };
554
- }
555
- async doGenerate(options) {
556
- const { args, warnings } = await this.getArgs(options);
557
- const {
558
- responseHeaders,
559
- value: response,
560
- rawValue: rawResponse
561
- } = await postJsonToApi({
562
- url: `${this.config.baseURL}/chat/completions`,
563
- headers: combineHeaders(this.config.headers?.(), options.headers),
564
- body: args,
565
- failedResponseHandler: alibabaFailedResponseHandler,
566
- successfulResponseHandler: createJsonResponseHandler(
567
- alibabaChatResponseSchema
568
- ),
569
- abortSignal: options.abortSignal,
570
- fetch: this.config.fetch
571
- });
572
- const choice = response.choices[0];
573
- const content = [];
574
- const text = choice.message.content;
575
- if (text != null && text.length > 0) {
576
- content.push({ type: "text", text });
577
- }
578
- const reasoning = choice.message.reasoning_content;
579
- if (reasoning != null && reasoning.length > 0) {
580
- content.push({
581
- type: "reasoning",
582
- text: reasoning
583
- });
584
- }
585
- if (choice.message.tool_calls != null) {
586
- for (const toolCall of choice.message.tool_calls) {
587
- content.push({
588
- type: "tool-call",
589
- toolCallId: toolCall.id || generateId(),
590
- toolName: toolCall.function.name,
591
- input: toolCall.function.arguments
592
- });
593
- }
594
- }
595
- return {
596
- content,
597
- finishReason: {
598
- unified: mapAlibabaFinishReason(choice.finish_reason),
599
- raw: choice.finish_reason ?? void 0
600
- },
601
- usage: convertAlibabaUsage(response.usage),
602
- request: { body: JSON.stringify(args) },
603
- response: {
604
- ...getResponseMetadata(response),
605
- headers: responseHeaders,
606
- body: rawResponse
607
- },
608
- warnings
609
- };
610
- }
611
- async doStream(options) {
612
- const { args, warnings } = await this.getArgs(options);
613
- const body = {
614
- ...args,
615
- stream: true,
616
- stream_options: this.config.includeUsage ? { include_usage: true } : void 0
617
- };
618
- const { responseHeaders, value: response } = await postJsonToApi({
619
- url: `${this.config.baseURL}/chat/completions`,
620
- headers: combineHeaders(this.config.headers?.(), options.headers),
621
- body,
622
- failedResponseHandler: alibabaFailedResponseHandler,
623
- successfulResponseHandler: createEventSourceResponseHandler(
624
- alibabaChatChunkSchema
625
- ),
626
- abortSignal: options.abortSignal,
627
- fetch: this.config.fetch
628
- });
629
- let finishReason = {
630
- unified: "other",
631
- raw: void 0
632
- };
633
- let usage = void 0;
634
- let isFirstChunk = true;
635
- let activeText = false;
636
- let activeReasoningId = null;
637
- let toolCallTracker;
638
- return {
639
- stream: response.pipeThrough(
640
- new TransformStream({
641
- start(controller) {
642
- toolCallTracker = new StreamingToolCallTracker(controller, {
643
- generateId
644
- });
645
- controller.enqueue({ type: "stream-start", warnings });
646
- },
647
- transform(chunk, controller) {
648
- if (options.includeRawChunks) {
649
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
650
- }
651
- if (!chunk.success) {
652
- controller.enqueue({ type: "error", error: chunk.error });
653
- return;
654
- }
655
- const value = chunk.value;
656
- if (isFirstChunk) {
657
- isFirstChunk = false;
658
- controller.enqueue({
659
- type: "response-metadata",
660
- ...getResponseMetadata(value)
661
- });
662
- }
663
- if (value.usage != null) {
664
- usage = value.usage;
665
- }
666
- if (value.choices.length === 0) {
667
- return;
668
- }
669
- const choice = value.choices[0];
670
- const delta = choice.delta;
671
- if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
672
- if (activeReasoningId == null) {
673
- if (activeText) {
674
- controller.enqueue({ type: "text-end", id: "0" });
675
- activeText = false;
676
- }
677
- activeReasoningId = generateId();
678
- controller.enqueue({
679
- type: "reasoning-start",
680
- id: activeReasoningId
681
- });
682
- }
683
- controller.enqueue({
684
- type: "reasoning-delta",
685
- id: activeReasoningId,
686
- delta: delta.reasoning_content
687
- });
688
- }
689
- if (delta.content != null && delta.content.length > 0) {
690
- if (activeReasoningId != null) {
691
- controller.enqueue({
692
- type: "reasoning-end",
693
- id: activeReasoningId
694
- });
695
- activeReasoningId = null;
696
- }
697
- if (!activeText) {
698
- controller.enqueue({ type: "text-start", id: "0" });
699
- activeText = true;
700
- }
701
- controller.enqueue({
702
- type: "text-delta",
703
- id: "0",
704
- delta: delta.content
705
- });
706
- }
707
- if (delta.tool_calls != null && delta.tool_calls.length > 0) {
708
- if (activeReasoningId != null) {
709
- controller.enqueue({
710
- type: "reasoning-end",
711
- id: activeReasoningId
712
- });
713
- activeReasoningId = null;
714
- }
715
- if (activeText) {
716
- controller.enqueue({ type: "text-end", id: "0" });
717
- activeText = false;
718
- }
719
- for (const toolCallDelta of delta.tool_calls) {
720
- toolCallTracker.processDelta(toolCallDelta);
721
- }
722
- }
723
- if (choice.finish_reason != null) {
724
- finishReason = {
725
- unified: mapAlibabaFinishReason(choice.finish_reason),
726
- raw: choice.finish_reason
727
- };
728
- }
729
- },
730
- flush(controller) {
731
- if (activeReasoningId != null) {
732
- controller.enqueue({
733
- type: "reasoning-end",
734
- id: activeReasoningId
735
- });
736
- }
737
- if (activeText) {
738
- controller.enqueue({ type: "text-end", id: "0" });
739
- }
740
- toolCallTracker.flush();
741
- controller.enqueue({
742
- type: "finish",
743
- finishReason,
744
- usage: convertAlibabaUsage(usage)
745
- });
746
- }
747
- })
748
- ),
749
- request: { body: JSON.stringify(body) },
750
- response: { headers: responseHeaders }
751
- };
752
- }
328
+ //#endregion
329
+ //#region src/alibaba-chat-language-model.ts
330
+ /**
331
+ * Alibaba language model implementation.
332
+ *
333
+ * Implements LanguageModelV4 interface for Alibaba Cloud's Qwen models.
334
+ * Supports OpenAI-compatible chat completions API with Alibaba-specific features:
335
+ * - Reasoning/thinking mode (enable_thinking, reasoning_content)
336
+ * - Thinking budget control (thinking_budget)
337
+ * - Prompt caching (cached_tokens tracking)
338
+ */
339
+ var AlibabaChatLanguageModel = class AlibabaChatLanguageModel {
340
+ static [WORKFLOW_SERIALIZE](model) {
341
+ return serializeModelOptions({
342
+ modelId: model.modelId,
343
+ config: model.config
344
+ });
345
+ }
346
+ static [WORKFLOW_DESERIALIZE](options) {
347
+ return new AlibabaChatLanguageModel(options.modelId, options.config);
348
+ }
349
+ constructor(modelId, config) {
350
+ this.specificationVersion = "v4";
351
+ this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
352
+ this.modelId = modelId;
353
+ this.config = config;
354
+ }
355
+ get provider() {
356
+ return this.config.provider;
357
+ }
358
+ /**
359
+ * Builds request arguments for Alibaba API call.
360
+ * Converts AI SDK options to Alibaba API format.
361
+ */
362
+ async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, reasoning, providerOptions, tools, toolChoice }) {
363
+ const warnings = [];
364
+ const cacheControlValidator = new CacheControlValidator();
365
+ const alibabaOptions = await parseProviderOptions({
366
+ provider: "alibaba",
367
+ providerOptions,
368
+ schema: alibabaLanguageModelChatOptions
369
+ });
370
+ if (frequencyPenalty != null) warnings.push({
371
+ type: "unsupported",
372
+ feature: "frequencyPenalty"
373
+ });
374
+ const preserveThinking = alibabaOptions?.preserveThinking ?? (supportsPreservedThinking(this.modelId) ? true : void 0);
375
+ const useJsonSchema = responseFormat?.type === "json" && responseFormat.schema != null && supportsJsonSchemaOutput(this.modelId);
376
+ const useJsonObject = responseFormat?.type === "json" && !useJsonSchema;
377
+ if (useJsonObject && responseFormat.schema != null) warnings.push({
378
+ type: "compatibility",
379
+ feature: "responseFormat JSON schema",
380
+ details: `Alibaba does not support JSON Schema output for model ${this.modelId}. JSON Object mode is used instead. The schema was injected into the system message and will only be validated locally.`
381
+ });
382
+ const resolvedPrompt = useJsonObject ? injectJsonInstructionIntoMessages({
383
+ messages: prompt,
384
+ schema: responseFormat.schema
385
+ }) : prompt;
386
+ const baseArgs = {
387
+ model: this.modelId,
388
+ max_tokens: maxOutputTokens,
389
+ temperature,
390
+ top_p: topP,
391
+ top_k: topK,
392
+ presence_penalty: presencePenalty,
393
+ stop: stopSequences,
394
+ seed,
395
+ response_format: responseFormat?.type === "json" ? useJsonSchema ? {
396
+ type: "json_schema",
397
+ json_schema: {
398
+ schema: responseFormat.schema,
399
+ name: responseFormat.name ?? "response",
400
+ description: responseFormat.description
401
+ }
402
+ } : { type: "json_object" } : void 0,
403
+ ...resolveAlibabaThinking({
404
+ reasoning,
405
+ alibabaOptions,
406
+ warnings
407
+ }),
408
+ ...preserveThinking != null ? { preserve_thinking: preserveThinking } : {},
409
+ messages: convertToAlibabaChatMessages({
410
+ prompt: resolvedPrompt,
411
+ cacheControlValidator,
412
+ preserveThinking: preserveThinking ?? false
413
+ })
414
+ };
415
+ const { tools: alibabaTools, toolChoice: alibabaToolChoice, toolWarnings } = prepareTools({
416
+ tools,
417
+ toolChoice
418
+ });
419
+ warnings.push(...cacheControlValidator.getWarnings());
420
+ return {
421
+ args: {
422
+ ...baseArgs,
423
+ tools: alibabaTools,
424
+ tool_choice: alibabaToolChoice,
425
+ ...alibabaTools != null && alibabaOptions?.parallelToolCalls !== void 0 ? { parallel_tool_calls: alibabaOptions.parallelToolCalls } : {}
426
+ },
427
+ warnings: [...warnings, ...toolWarnings]
428
+ };
429
+ }
430
+ async doGenerate(options) {
431
+ const { args, warnings } = await this.getArgs(options);
432
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
433
+ url: `${this.config.baseURL}/chat/completions`,
434
+ headers: combineHeaders(this.config.headers?.(), options.headers),
435
+ body: args,
436
+ failedResponseHandler: alibabaFailedResponseHandler,
437
+ successfulResponseHandler: createJsonResponseHandler(alibabaChatResponseSchema),
438
+ abortSignal: options.abortSignal,
439
+ fetch: this.config.fetch
440
+ });
441
+ const choice = response.choices[0];
442
+ const content = [];
443
+ const text = choice.message.content;
444
+ if (text != null && text.length > 0) content.push({
445
+ type: "text",
446
+ text
447
+ });
448
+ const reasoning = choice.message.reasoning_content;
449
+ if (reasoning != null && reasoning.length > 0) content.push({
450
+ type: "reasoning",
451
+ text: reasoning
452
+ });
453
+ if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) content.push({
454
+ type: "tool-call",
455
+ toolCallId: toolCall.id || generateId(),
456
+ toolName: toolCall.function.name,
457
+ input: toolCall.function.arguments
458
+ });
459
+ return {
460
+ content,
461
+ finishReason: {
462
+ unified: mapAlibabaFinishReason(choice.finish_reason),
463
+ raw: choice.finish_reason ?? void 0
464
+ },
465
+ usage: convertAlibabaUsage(response.usage),
466
+ request: { body: JSON.stringify(args) },
467
+ response: {
468
+ ...createLanguageModelResponseMetadata(response),
469
+ headers: responseHeaders,
470
+ body: rawResponse
471
+ },
472
+ warnings
473
+ };
474
+ }
475
+ async doStream(options) {
476
+ const { args, warnings } = await this.getArgs(options);
477
+ const body = {
478
+ ...args,
479
+ stream: true,
480
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
481
+ };
482
+ const { responseHeaders, value: response } = await postJsonToApi({
483
+ url: `${this.config.baseURL}/chat/completions`,
484
+ headers: combineHeaders(this.config.headers?.(), options.headers),
485
+ body,
486
+ failedResponseHandler: alibabaFailedResponseHandler,
487
+ successfulResponseHandler: createEventSourceResponseHandler(alibabaChatChunkSchema),
488
+ abortSignal: options.abortSignal,
489
+ fetch: this.config.fetch
490
+ });
491
+ let finishReason = {
492
+ unified: "other",
493
+ raw: void 0
494
+ };
495
+ let usage = void 0;
496
+ let isFirstChunk = true;
497
+ let activeText = false;
498
+ let activeReasoningId = null;
499
+ let toolCallTracker;
500
+ return {
501
+ stream: response.pipeThrough(new TransformStream({
502
+ start(controller) {
503
+ toolCallTracker = new StreamingToolCallTracker(controller, { generateId });
504
+ controller.enqueue({
505
+ type: "stream-start",
506
+ warnings
507
+ });
508
+ },
509
+ transform(chunk, controller) {
510
+ if (options.includeRawChunks) controller.enqueue({
511
+ type: "raw",
512
+ rawValue: chunk.rawValue
513
+ });
514
+ if (!chunk.success) {
515
+ controller.enqueue({
516
+ type: "error",
517
+ error: chunk.error
518
+ });
519
+ return;
520
+ }
521
+ const value = chunk.value;
522
+ if (isFirstChunk) {
523
+ isFirstChunk = false;
524
+ controller.enqueue({
525
+ type: "response-metadata",
526
+ ...createLanguageModelResponseMetadata(value)
527
+ });
528
+ }
529
+ if (value.usage != null) usage = value.usage;
530
+ if (value.choices.length === 0) return;
531
+ const choice = value.choices[0];
532
+ const delta = choice.delta;
533
+ if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
534
+ if (activeReasoningId == null) {
535
+ if (activeText) {
536
+ controller.enqueue({
537
+ type: "text-end",
538
+ id: "0"
539
+ });
540
+ activeText = false;
541
+ }
542
+ activeReasoningId = generateId();
543
+ controller.enqueue({
544
+ type: "reasoning-start",
545
+ id: activeReasoningId
546
+ });
547
+ }
548
+ controller.enqueue({
549
+ type: "reasoning-delta",
550
+ id: activeReasoningId,
551
+ delta: delta.reasoning_content
552
+ });
553
+ }
554
+ if (delta.content != null && delta.content.length > 0) {
555
+ if (activeReasoningId != null) {
556
+ controller.enqueue({
557
+ type: "reasoning-end",
558
+ id: activeReasoningId
559
+ });
560
+ activeReasoningId = null;
561
+ }
562
+ if (!activeText) {
563
+ controller.enqueue({
564
+ type: "text-start",
565
+ id: "0"
566
+ });
567
+ activeText = true;
568
+ }
569
+ controller.enqueue({
570
+ type: "text-delta",
571
+ id: "0",
572
+ delta: delta.content
573
+ });
574
+ }
575
+ if (delta.tool_calls != null && delta.tool_calls.length > 0) {
576
+ if (activeReasoningId != null) {
577
+ controller.enqueue({
578
+ type: "reasoning-end",
579
+ id: activeReasoningId
580
+ });
581
+ activeReasoningId = null;
582
+ }
583
+ if (activeText) {
584
+ controller.enqueue({
585
+ type: "text-end",
586
+ id: "0"
587
+ });
588
+ activeText = false;
589
+ }
590
+ for (const toolCallDelta of delta.tool_calls) toolCallTracker.processDelta(toolCallDelta);
591
+ }
592
+ if (choice.finish_reason != null) finishReason = {
593
+ unified: mapAlibabaFinishReason(choice.finish_reason),
594
+ raw: choice.finish_reason
595
+ };
596
+ },
597
+ flush(controller) {
598
+ if (activeReasoningId != null) controller.enqueue({
599
+ type: "reasoning-end",
600
+ id: activeReasoningId
601
+ });
602
+ if (activeText) controller.enqueue({
603
+ type: "text-end",
604
+ id: "0"
605
+ });
606
+ toolCallTracker.flush();
607
+ controller.enqueue({
608
+ type: "finish",
609
+ finishReason,
610
+ usage: convertAlibabaUsage(usage)
611
+ });
612
+ }
613
+ })),
614
+ request: { body: JSON.stringify(body) },
615
+ response: { headers: responseHeaders }
616
+ };
617
+ }
753
618
  };
754
- function resolveAlibabaThinking({
755
- reasoning,
756
- alibabaOptions,
757
- warnings
758
- }) {
759
- if (alibabaOptions?.enableThinking != null || alibabaOptions?.thinkingBudget != null) {
760
- return {
761
- ...alibabaOptions.enableThinking != null ? { enable_thinking: alibabaOptions.enableThinking } : {},
762
- ...alibabaOptions.thinkingBudget != null ? { thinking_budget: alibabaOptions.thinkingBudget } : {}
763
- };
764
- }
765
- if (!isCustomReasoning(reasoning)) {
766
- return {};
767
- }
768
- if (reasoning === "none") {
769
- return { enable_thinking: false };
770
- }
771
- const thinkingBudget = mapReasoningToProviderBudget({
772
- reasoning,
773
- maxOutputTokens: 16384,
774
- maxReasoningBudget: 16384,
775
- warnings
776
- });
777
- return {
778
- enable_thinking: true,
779
- ...thinkingBudget != null ? { thinking_budget: thinkingBudget } : {}
780
- };
619
+ function resolveAlibabaThinking({ reasoning, alibabaOptions, warnings }) {
620
+ if (alibabaOptions?.enableThinking != null || alibabaOptions?.thinkingBudget != null) return {
621
+ ...alibabaOptions.enableThinking != null ? { enable_thinking: alibabaOptions.enableThinking } : {},
622
+ ...alibabaOptions.thinkingBudget != null ? { thinking_budget: alibabaOptions.thinkingBudget } : {}
623
+ };
624
+ if (!isCustomReasoning(reasoning)) return {};
625
+ if (reasoning === "none") return { enable_thinking: false };
626
+ const thinkingBudget = mapReasoningToProviderBudget({
627
+ reasoning,
628
+ maxOutputTokens: 16384,
629
+ maxReasoningBudget: 16384,
630
+ warnings
631
+ });
632
+ return {
633
+ enable_thinking: true,
634
+ ...thinkingBudget != null ? { thinking_budget: thinkingBudget } : {}
635
+ };
781
636
  }
782
- var alibabaUsageSchema = z3.looseObject({
783
- prompt_tokens: z3.number(),
784
- completion_tokens: z3.number(),
785
- total_tokens: z3.number(),
786
- prompt_tokens_details: z3.looseObject({
787
- cached_tokens: z3.number().nullish(),
788
- cache_creation_input_tokens: z3.number().nullish(),
789
- cache_type: z3.string().nullish()
790
- }).nullish(),
791
- completion_tokens_details: z3.looseObject({
792
- reasoning_tokens: z3.number().nullish()
793
- }).nullish()
637
+ /**
638
+ * Reference for schemas below:
639
+ * https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-openai-chat-completions
640
+ */
641
+ const alibabaUsageSchema = z.looseObject({
642
+ prompt_tokens: z.number(),
643
+ completion_tokens: z.number(),
644
+ total_tokens: z.number(),
645
+ prompt_tokens_details: z.looseObject({
646
+ cached_tokens: z.number().nullish(),
647
+ cache_creation_input_tokens: z.number().nullish(),
648
+ cache_type: z.string().nullish()
649
+ }).nullish(),
650
+ completion_tokens_details: z.looseObject({ reasoning_tokens: z.number().nullish() }).nullish()
794
651
  });
795
- var alibabaChatResponseSchema = z3.object({
796
- id: z3.string().nullish(),
797
- created: z3.number().nullish(),
798
- model: z3.string().nullish(),
799
- choices: z3.array(
800
- z3.object({
801
- message: z3.object({
802
- role: z3.literal("assistant").nullish(),
803
- content: z3.string().nullish(),
804
- reasoning_content: z3.string().nullish(),
805
- // Alibaba thinking mode
806
- tool_calls: z3.array(
807
- z3.object({
808
- id: z3.string(),
809
- type: z3.literal("function"),
810
- function: z3.object({
811
- name: z3.string(),
812
- arguments: z3.string()
813
- })
814
- })
815
- ).nullish()
816
- }),
817
- finish_reason: z3.string().nullish(),
818
- index: z3.number()
819
- })
820
- ),
821
- usage: alibabaUsageSchema.nullish()
652
+ const alibabaChatResponseSchema = z.object({
653
+ id: z.string().nullish(),
654
+ created: z.number().nullish(),
655
+ model: z.string().nullish(),
656
+ choices: z.array(z.object({
657
+ message: z.object({
658
+ role: z.literal("assistant").nullish(),
659
+ content: z.string().nullish(),
660
+ reasoning_content: z.string().nullish(),
661
+ tool_calls: z.array(z.object({
662
+ id: z.string(),
663
+ type: z.literal("function"),
664
+ function: z.object({
665
+ name: z.string(),
666
+ arguments: z.string()
667
+ })
668
+ })).nullish()
669
+ }),
670
+ finish_reason: z.string().nullish(),
671
+ index: z.number()
672
+ })),
673
+ usage: alibabaUsageSchema.nullish()
822
674
  });
823
- var alibabaChatChunkSchema = z3.object({
824
- id: z3.string().nullish(),
825
- created: z3.number().nullish(),
826
- model: z3.string().nullish(),
827
- choices: z3.array(
828
- z3.object({
829
- delta: z3.object({
830
- role: z3.enum(["assistant"]).nullish(),
831
- content: z3.string().nullish(),
832
- reasoning_content: z3.string().nullish(),
833
- // Alibaba thinking mode delta
834
- tool_calls: z3.array(
835
- z3.object({
836
- index: z3.number().nullish(),
837
- // Index for accumulating tool calls
838
- id: z3.string().nullish(),
839
- type: z3.literal("function").nullish(),
840
- function: z3.object({
841
- name: z3.string().nullish(),
842
- arguments: z3.string().nullish()
843
- }).nullish()
844
- })
845
- ).nullish()
846
- }),
847
- finish_reason: z3.string().nullish(),
848
- index: z3.number()
849
- })
850
- ),
851
- usage: alibabaUsageSchema.nullish()
852
- // Usage only appears in final chunk
675
+ const alibabaChatChunkSchema = z.object({
676
+ id: z.string().nullish(),
677
+ created: z.number().nullish(),
678
+ model: z.string().nullish(),
679
+ choices: z.array(z.object({
680
+ delta: z.object({
681
+ role: z.enum(["assistant"]).nullish(),
682
+ content: z.string().nullish(),
683
+ reasoning_content: z.string().nullish(),
684
+ tool_calls: z.array(z.object({
685
+ index: z.number().nullish(),
686
+ id: z.string().nullish(),
687
+ type: z.literal("function").nullish(),
688
+ function: z.object({
689
+ name: z.string().nullish(),
690
+ arguments: z.string().nullish()
691
+ }).nullish()
692
+ })).nullish()
693
+ }),
694
+ finish_reason: z.string().nullish(),
695
+ index: z.number()
696
+ })),
697
+ usage: alibabaUsageSchema.nullish()
853
698
  });
854
-
855
- // src/alibaba-embedding-model.ts
856
- import {
857
- TooManyEmbeddingValuesForCallError,
858
- UnsupportedFunctionalityError as UnsupportedFunctionalityError3
859
- } from "@ai-sdk/provider";
860
- import {
861
- combineHeaders as combineHeaders2,
862
- createJsonErrorResponseHandler as createJsonErrorResponseHandler2,
863
- createJsonResponseHandler as createJsonResponseHandler2,
864
- parseProviderOptions as parseProviderOptions2,
865
- postJsonToApi as postJsonToApi2,
866
- serializeModelOptions as serializeModelOptions2,
867
- WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE2,
868
- WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE2
869
- } from "@ai-sdk/provider-utils";
870
- import { z as z5 } from "zod/v4";
871
-
872
- // src/alibaba-embedding-model-options.ts
873
- import { z as z4 } from "zod/v4";
874
- var alibabaEmbeddingModelOptions = z4.object({
875
- /**
876
- * Differentiates query text from document text for asymmetric retrieval tasks.
877
- * Defaults to `document`.
878
- */
879
- textType: z4.enum(["query", "document"]).optional(),
880
- /**
881
- * The dimension of the output embedding vectors. Defaults to 1024.
882
- *
883
- * `text-embedding-v4` also supports 1536 and 2048 dimensions.
884
- */
885
- dimension: z4.number().optional(),
886
- /**
887
- * The output vector type. Defaults to `dense`.
888
- *
889
- * Sparse-only output is not supported by the AI SDK embedding interface,
890
- * which requires dense number arrays.
891
- */
892
- outputType: z4.enum(["dense", "sparse", "dense&sparse"]).optional()
699
+ //#endregion
700
+ //#region src/alibaba-embedding-model-options.ts
701
+ const alibabaEmbeddingModelOptions = z.object({
702
+ /**
703
+ * Differentiates query text from document text for asymmetric retrieval tasks.
704
+ * Defaults to `document`.
705
+ */
706
+ textType: z.enum(["query", "document"]).optional(),
707
+ /**
708
+ * The dimension of the output embedding vectors. Defaults to 1024.
709
+ *
710
+ * `text-embedding-v4` also supports 1536 and 2048 dimensions.
711
+ */
712
+ dimension: z.number().optional(),
713
+ /**
714
+ * The output vector type. Defaults to `dense`.
715
+ *
716
+ * Sparse-only output is not supported by the AI SDK embedding interface,
717
+ * which requires dense number arrays.
718
+ */
719
+ outputType: z.enum([
720
+ "dense",
721
+ "sparse",
722
+ "dense&sparse"
723
+ ]).optional()
893
724
  });
894
-
895
- // src/alibaba-embedding-model.ts
896
- var alibabaEmbeddingFailedResponseHandler = createJsonErrorResponseHandler2({
897
- errorSchema: z5.object({
898
- code: z5.string().nullish(),
899
- message: z5.string(),
900
- request_id: z5.string().nullish()
901
- }),
902
- errorToMessage: (data) => data.message
725
+ //#endregion
726
+ //#region src/alibaba-embedding-model.ts
727
+ const alibabaEmbeddingFailedResponseHandler = createJsonErrorResponseHandler({
728
+ errorSchema: z.object({
729
+ code: z.string().nullish(),
730
+ message: z.string(),
731
+ request_id: z.string().nullish()
732
+ }),
733
+ errorToMessage: (data) => data.message
903
734
  });
904
- var AlibabaEmbeddingModel = class _AlibabaEmbeddingModel {
905
- constructor(modelId, config) {
906
- this.specificationVersion = "v4";
907
- this.maxEmbeddingsPerCall = 10;
908
- this.supportsParallelCalls = false;
909
- this.modelId = modelId;
910
- this.config = config;
911
- }
912
- static [WORKFLOW_SERIALIZE2](model) {
913
- return serializeModelOptions2({
914
- modelId: model.modelId,
915
- config: model.config
916
- });
917
- }
918
- static [WORKFLOW_DESERIALIZE2](options) {
919
- return new _AlibabaEmbeddingModel(options.modelId, options.config);
920
- }
921
- get provider() {
922
- return this.config.provider;
923
- }
924
- async doEmbed({
925
- values,
926
- headers,
927
- abortSignal,
928
- providerOptions
929
- }) {
930
- if (values.length > this.maxEmbeddingsPerCall) {
931
- throw new TooManyEmbeddingValuesForCallError({
932
- provider: this.provider,
933
- modelId: this.modelId,
934
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
935
- values
936
- });
937
- }
938
- const alibabaOptions = await parseProviderOptions2({
939
- provider: "alibaba",
940
- providerOptions,
941
- schema: alibabaEmbeddingModelOptions
942
- });
943
- if (alibabaOptions?.outputType === "sparse") {
944
- throw new UnsupportedFunctionalityError3({
945
- functionality: "Alibaba embedding outputType 'sparse'",
946
- message: "Alibaba embedding outputType 'sparse' is not supported because AI SDK embeddings require dense number arrays. Use 'dense' or 'dense&sparse' instead."
947
- });
948
- }
949
- const {
950
- responseHeaders,
951
- value: response,
952
- rawValue
953
- } = await postJsonToApi2({
954
- url: `${this.config.baseURL}/services/embeddings/text-embedding/text-embedding`,
955
- headers: combineHeaders2(this.config.headers?.(), headers),
956
- body: {
957
- model: this.modelId,
958
- input: {
959
- texts: values
960
- },
961
- parameters: {
962
- text_type: alibabaOptions?.textType,
963
- dimension: alibabaOptions?.dimension,
964
- output_type: alibabaOptions?.outputType
965
- }
966
- },
967
- failedResponseHandler: alibabaEmbeddingFailedResponseHandler,
968
- successfulResponseHandler: createJsonResponseHandler2(
969
- alibabaTextEmbeddingResponseSchema
970
- ),
971
- abortSignal,
972
- fetch: this.config.fetch
973
- });
974
- const sortedEmbeddings = response.output.embeddings.sort(
975
- (a, b) => a.text_index - b.text_index
976
- );
977
- const sparseEmbeddings = sortedEmbeddings.map(
978
- (item) => item.sparse_embedding == null ? void 0 : {
979
- textIndex: item.text_index,
980
- sparseEmbedding: item.sparse_embedding
981
- }
982
- ).filter((item) => item != null);
983
- return {
984
- warnings: [],
985
- embeddings: sortedEmbeddings.map((item) => item.embedding),
986
- usage: response.usage ? { tokens: response.usage.total_tokens } : void 0,
987
- providerMetadata: sparseEmbeddings.length > 0 ? {
988
- alibaba: {
989
- sparseEmbeddings
990
- }
991
- } : void 0,
992
- response: { headers: responseHeaders, body: rawValue }
993
- };
994
- }
735
+ var AlibabaEmbeddingModel = class AlibabaEmbeddingModel {
736
+ static [WORKFLOW_SERIALIZE](model) {
737
+ return serializeModelOptions({
738
+ modelId: model.modelId,
739
+ config: model.config
740
+ });
741
+ }
742
+ static [WORKFLOW_DESERIALIZE](options) {
743
+ return new AlibabaEmbeddingModel(options.modelId, options.config);
744
+ }
745
+ constructor(modelId, config) {
746
+ this.specificationVersion = "v4";
747
+ this.maxEmbeddingsPerCall = 10;
748
+ this.supportsParallelCalls = false;
749
+ this.modelId = modelId;
750
+ this.config = config;
751
+ }
752
+ get provider() {
753
+ return this.config.provider;
754
+ }
755
+ async doEmbed({ values, headers, abortSignal, providerOptions }) {
756
+ if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
757
+ provider: this.provider,
758
+ modelId: this.modelId,
759
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
760
+ values
761
+ });
762
+ const alibabaOptions = await parseProviderOptions({
763
+ provider: "alibaba",
764
+ providerOptions,
765
+ schema: alibabaEmbeddingModelOptions
766
+ });
767
+ if (alibabaOptions?.outputType === "sparse") throw new UnsupportedFunctionalityError({
768
+ functionality: "Alibaba embedding outputType 'sparse'",
769
+ message: "Alibaba embedding outputType 'sparse' is not supported because AI SDK embeddings require dense number arrays. Use 'dense' or 'dense&sparse' instead."
770
+ });
771
+ const { responseHeaders, value: response, rawValue } = await postJsonToApi({
772
+ url: `${this.config.baseURL}/services/embeddings/text-embedding/text-embedding`,
773
+ headers: combineHeaders(this.config.headers?.(), headers),
774
+ body: {
775
+ model: this.modelId,
776
+ input: { texts: values },
777
+ parameters: {
778
+ text_type: alibabaOptions?.textType,
779
+ dimension: alibabaOptions?.dimension,
780
+ output_type: alibabaOptions?.outputType
781
+ }
782
+ },
783
+ failedResponseHandler: alibabaEmbeddingFailedResponseHandler,
784
+ successfulResponseHandler: createJsonResponseHandler(alibabaTextEmbeddingResponseSchema),
785
+ abortSignal,
786
+ fetch: this.config.fetch
787
+ });
788
+ const sortedEmbeddings = response.output.embeddings.sort((a, b) => a.text_index - b.text_index);
789
+ const sparseEmbeddings = sortedEmbeddings.map((item) => item.sparse_embedding == null ? void 0 : {
790
+ textIndex: item.text_index,
791
+ sparseEmbedding: item.sparse_embedding
792
+ }).filter((item) => item != null);
793
+ return {
794
+ warnings: [],
795
+ embeddings: sortedEmbeddings.map((item) => item.embedding),
796
+ usage: response.usage ? { tokens: response.usage.total_tokens } : void 0,
797
+ providerMetadata: sparseEmbeddings.length > 0 ? { alibaba: { sparseEmbeddings } } : void 0,
798
+ response: {
799
+ headers: responseHeaders,
800
+ body: rawValue
801
+ }
802
+ };
803
+ }
995
804
  };
996
- var alibabaTextEmbeddingSparseEmbeddingSchema = z5.object({
997
- index: z5.number(),
998
- value: z5.number(),
999
- token: z5.string().nullish()
805
+ const alibabaTextEmbeddingSparseEmbeddingSchema = z.object({
806
+ index: z.number(),
807
+ value: z.number(),
808
+ token: z.string().nullish()
1000
809
  });
1001
- var alibabaTextEmbeddingResponseSchema = z5.object({
1002
- output: z5.object({
1003
- embeddings: z5.array(
1004
- z5.object({
1005
- embedding: z5.array(z5.number()),
1006
- text_index: z5.number(),
1007
- sparse_embedding: z5.array(alibabaTextEmbeddingSparseEmbeddingSchema).nullish()
1008
- })
1009
- )
1010
- }),
1011
- usage: z5.object({
1012
- total_tokens: z5.number()
1013
- }).nullish()
810
+ const alibabaTextEmbeddingResponseSchema = z.object({
811
+ output: z.object({ embeddings: z.array(z.object({
812
+ embedding: z.array(z.number()),
813
+ text_index: z.number(),
814
+ sparse_embedding: z.array(alibabaTextEmbeddingSparseEmbeddingSchema).nullish()
815
+ })) }),
816
+ usage: z.object({ total_tokens: z.number() }).nullish()
1014
817
  });
1015
-
1016
- // src/alibaba-video-model.ts
1017
- import {
1018
- AISDKError
1019
- } from "@ai-sdk/provider";
1020
- import {
1021
- combineHeaders as combineHeaders3,
1022
- convertImageModelFileToDataUri,
1023
- convertUint8ArrayToBase64,
1024
- createJsonErrorResponseHandler as createJsonErrorResponseHandler3,
1025
- createJsonResponseHandler as createJsonResponseHandler3,
1026
- getFromApi,
1027
- parseProviderOptions as parseProviderOptions3,
1028
- postJsonToApi as postJsonToApi3,
1029
- resolve
1030
- } from "@ai-sdk/provider-utils";
1031
- import { z as z7 } from "zod/v4";
1032
-
1033
- // src/alibaba-video-model-options.ts
1034
- import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
1035
- import { z as z6 } from "zod/v4";
1036
- var alibabaVideoModelOptionsSchema = lazySchema(
1037
- () => zodSchema(
1038
- z6.looseObject({
1039
- negativePrompt: z6.string().nullish(),
1040
- audioUrl: z6.string().nullish(),
1041
- promptExtend: z6.boolean().nullish(),
1042
- shotType: z6.enum(["single", "multi"]).nullish(),
1043
- watermark: z6.boolean().nullish(),
1044
- audio: z6.boolean().nullish(),
1045
- referenceUrls: z6.array(z6.string()).nullish(),
1046
- media: z6.array(
1047
- z6.object({
1048
- type: z6.enum([
1049
- "reference_image",
1050
- "reference_video",
1051
- "reference_audio",
1052
- "first_frame",
1053
- "last_frame",
1054
- "file",
1055
- "link"
1056
- ]),
1057
- url: z6.string(),
1058
- referenceVoice: z6.string().nullish()
1059
- })
1060
- ).nullish(),
1061
- ratio: z6.enum(["adaptive", "16:9", "9:16", "1:1", "4:3", "3:4"]).nullish(),
1062
- pollIntervalMs: z6.number().positive().nullish(),
1063
- pollTimeoutMs: z6.number().positive().nullish()
1064
- })
1065
- )
1066
- );
1067
-
1068
- // src/alibaba-video-model.ts
1069
- var alibabaVideoErrorSchema = z7.object({
1070
- code: z7.string().nullish(),
1071
- message: z7.string(),
1072
- request_id: z7.string().nullish()
818
+ //#endregion
819
+ //#region src/alibaba-video-model-options.ts
820
+ const alibabaVideoModelOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
821
+ negativePrompt: z.string().nullish(),
822
+ audioUrl: z.string().nullish(),
823
+ promptExtend: z.boolean().nullish(),
824
+ shotType: z.enum(["single", "multi"]).nullish(),
825
+ watermark: z.boolean().nullish(),
826
+ audio: z.boolean().nullish(),
827
+ referenceUrls: z.array(z.string()).nullish(),
828
+ media: z.array(z.object({
829
+ type: z.enum([
830
+ "reference_image",
831
+ "reference_video",
832
+ "reference_audio",
833
+ "first_frame",
834
+ "last_frame",
835
+ "file",
836
+ "link"
837
+ ]),
838
+ url: z.string(),
839
+ referenceVoice: z.string().nullish()
840
+ })).nullish(),
841
+ ratio: z.enum([
842
+ "adaptive",
843
+ "16:9",
844
+ "9:16",
845
+ "1:1",
846
+ "4:3",
847
+ "3:4"
848
+ ]).nullish(),
849
+ pollIntervalMs: z.number().positive().nullish(),
850
+ pollTimeoutMs: z.number().positive().nullish()
851
+ })));
852
+ //#endregion
853
+ //#region src/alibaba-video-model.ts
854
+ const alibabaVideoErrorSchema = z.object({
855
+ code: z.string().nullish(),
856
+ message: z.string(),
857
+ request_id: z.string().nullish()
1073
858
  });
1074
- var alibabaVideoFailedResponseHandler = createJsonErrorResponseHandler3({
1075
- errorSchema: alibabaVideoErrorSchema,
1076
- errorToMessage: (data) => data.message
859
+ const alibabaVideoFailedResponseHandler = createJsonErrorResponseHandler({
860
+ errorSchema: alibabaVideoErrorSchema,
861
+ errorToMessage: (data) => data.message
1077
862
  });
1078
- var alibabaVideoCreateTaskSchema = z7.object({
1079
- output: z7.object({
1080
- task_status: z7.string(),
1081
- task_id: z7.string()
1082
- }).nullish(),
1083
- request_id: z7.string().nullish()
863
+ const alibabaVideoCreateTaskSchema = z.object({
864
+ output: z.object({
865
+ task_status: z.string(),
866
+ task_id: z.string()
867
+ }).nullish(),
868
+ request_id: z.string().nullish()
1084
869
  });
1085
- var alibabaVideoTaskStatusSchema = z7.object({
1086
- output: z7.object({
1087
- task_id: z7.string(),
1088
- task_status: z7.string(),
1089
- video_url: z7.string().nullish(),
1090
- submit_time: z7.string().nullish(),
1091
- scheduled_time: z7.string().nullish(),
1092
- end_time: z7.string().nullish(),
1093
- orig_prompt: z7.string().nullish(),
1094
- actual_prompt: z7.string().nullish(),
1095
- code: z7.string().nullish(),
1096
- message: z7.string().nullish()
1097
- }).nullish(),
1098
- usage: z7.object({
1099
- duration: z7.number().nullish(),
1100
- output_video_duration: z7.number().nullish(),
1101
- // wan3 splits the total: input video counts toward its 30s ceiling.
1102
- input_video_duration: z7.number().nullish(),
1103
- fps: z7.number().nullish(),
1104
- SR: z7.number().nullish(),
1105
- size: z7.string().nullish(),
1106
- ratio: z7.string().nullish()
1107
- }).nullish(),
1108
- request_id: z7.string().nullish()
870
+ const alibabaVideoTaskStatusSchema = z.object({
871
+ output: z.object({
872
+ task_id: z.string(),
873
+ task_status: z.string(),
874
+ video_url: z.string().nullish(),
875
+ submit_time: z.string().nullish(),
876
+ scheduled_time: z.string().nullish(),
877
+ end_time: z.string().nullish(),
878
+ orig_prompt: z.string().nullish(),
879
+ actual_prompt: z.string().nullish(),
880
+ code: z.string().nullish(),
881
+ message: z.string().nullish()
882
+ }).nullish(),
883
+ usage: z.object({
884
+ duration: z.number().nullish(),
885
+ output_video_duration: z.number().nullish(),
886
+ input_video_duration: z.number().nullish(),
887
+ fps: z.number().nullish(),
888
+ SR: z.number().nullish(),
889
+ size: z.string().nullish(),
890
+ ratio: z.string().nullish()
891
+ }).nullish(),
892
+ request_id: z.string().nullish()
1109
893
  });
1110
894
  function detectMode(modelId) {
1111
- if (modelId.includes("-i2v")) return "i2v";
1112
- if (modelId.includes("-r2v")) return "r2v";
1113
- return "t2v";
895
+ if (modelId.includes("-i2v")) return "i2v";
896
+ if (modelId.includes("-r2v")) return "r2v";
897
+ return "t2v";
1114
898
  }
1115
899
  function detectProtocol(modelId) {
1116
- if (modelId.startsWith("wan3")) return "wan3";
1117
- if (modelId.startsWith("wan2.7")) return "wan27";
1118
- return "legacy";
900
+ if (modelId.startsWith("wan3")) return "wan3";
901
+ if (modelId.startsWith("wan2.7")) return "wan27";
902
+ return "legacy";
1119
903
  }
1120
- var resolutionTierMap = {
1121
- "1280x720": "720P",
1122
- "720x1280": "720P",
1123
- "960x960": "720P",
1124
- "1088x832": "720P",
1125
- "832x1088": "720P",
1126
- "1920x1080": "1080P",
1127
- "1080x1920": "1080P",
1128
- "1440x1440": "1080P",
1129
- "1632x1248": "1080P",
1130
- "1248x1632": "1080P",
1131
- "832x480": "480P",
1132
- "480x832": "480P",
1133
- "624x624": "480P"
904
+ const resolutionTierMap = {
905
+ "1280x720": "720P",
906
+ "720x1280": "720P",
907
+ "960x960": "720P",
908
+ "1088x832": "720P",
909
+ "832x1088": "720P",
910
+ "1920x1080": "1080P",
911
+ "1080x1920": "1080P",
912
+ "1440x1440": "1080P",
913
+ "1632x1248": "1080P",
914
+ "1248x1632": "1080P",
915
+ "832x480": "480P",
916
+ "480x832": "480P",
917
+ "624x624": "480P"
1134
918
  };
1135
- var supportedRatios = /* @__PURE__ */ new Set(["16:9", "9:16", "1:1", "4:3", "3:4"]);
919
+ const supportedRatios = /* @__PURE__ */ new Set([
920
+ "16:9",
921
+ "9:16",
922
+ "1:1",
923
+ "4:3",
924
+ "3:4"
925
+ ]);
1136
926
  function deriveRatioFromResolution(resolution) {
1137
- const [width, height] = resolution.split("x").map(Number);
1138
- if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
1139
- return void 0;
1140
- }
1141
- let a = width;
1142
- let b = height;
1143
- while (b !== 0) {
1144
- [a, b] = [b, a % b];
1145
- }
1146
- const ratio = `${width / a}:${height / a}`;
1147
- return supportedRatios.has(ratio) ? ratio : void 0;
927
+ const [width, height] = resolution.split("x").map(Number);
928
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) return;
929
+ let a = width;
930
+ let b = height;
931
+ while (b !== 0) [a, b] = [b, a % b];
932
+ const ratio = `${width / a}:${height / a}`;
933
+ return supportedRatios.has(ratio) ? ratio : void 0;
1148
934
  }
1149
935
  function fileToImageString(file) {
1150
- if (file.type === "url") {
1151
- return file.url;
1152
- }
1153
- return typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data);
936
+ if (file.type === "url") return file.url;
937
+ return typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data);
1154
938
  }
1155
939
  function getFirstFrameImage(options) {
1156
- return options.frameImages?.find((frame) => frame.frameType === "first_frame")?.image;
940
+ return options.frameImages?.find((frame) => frame.frameType === "first_frame")?.image;
1157
941
  }
1158
942
  function getLastFrameImage(options) {
1159
- return options.frameImages?.find((frame) => frame.frameType === "last_frame")?.image;
943
+ return options.frameImages?.find((frame) => frame.frameType === "last_frame")?.image;
1160
944
  }
1161
945
  function resolveStartImage(options) {
1162
- return getFirstFrameImage(options) ?? options.image;
946
+ return getFirstFrameImage(options) ?? options.image;
1163
947
  }
1164
948
  function isVideoUrl(url) {
1165
- return /\.(mp4|mov)([?#]|$)/i.test(url);
949
+ return /\.(mp4|mov)([?#]|$)/i.test(url);
1166
950
  }
1167
951
  function resolveMedia(options, alibabaOptions, warnings, frames) {
1168
- if (alibabaOptions?.media != null && alibabaOptions.media.length > 0) {
1169
- return alibabaOptions.media.map((item) => ({
1170
- type: item.type,
1171
- url: item.url,
1172
- ...item.referenceVoice != null ? { reference_voice: item.referenceVoice } : {}
1173
- }));
1174
- }
1175
- const media = [];
1176
- for (const reference of options.inputReferences ?? []) {
1177
- if (reference.type === "url") {
1178
- media.push({
1179
- type: isVideoUrl(reference.url) ? "reference_video" : "reference_image",
1180
- url: reference.url
1181
- });
1182
- } else if (reference.mediaType.startsWith("image/")) {
1183
- media.push({
1184
- type: "reference_image",
1185
- url: convertImageModelFileToDataUri(reference)
1186
- });
1187
- } else {
1188
- warnings.push({
1189
- type: "unsupported",
1190
- feature: "inputReferences",
1191
- details: "Alibaba reference-to-video requires URL references for videos. Non-URL video reference was skipped."
1192
- });
1193
- }
1194
- }
1195
- if (frames.first != null) {
1196
- media.push({
1197
- type: "first_frame",
1198
- url: convertImageModelFileToDataUri(frames.first)
1199
- });
1200
- }
1201
- if (frames.last != null) {
1202
- media.push({
1203
- type: "last_frame",
1204
- url: convertImageModelFileToDataUri(frames.last)
1205
- });
1206
- }
1207
- return media.length > 0 ? media : void 0;
952
+ if (alibabaOptions?.media != null && alibabaOptions.media.length > 0) return alibabaOptions.media.map((item) => ({
953
+ type: item.type,
954
+ url: item.url,
955
+ ...item.referenceVoice != null ? { reference_voice: item.referenceVoice } : {}
956
+ }));
957
+ const media = [];
958
+ for (const reference of options.inputReferences ?? []) if (reference.type === "url") media.push({
959
+ type: isVideoUrl(reference.url) ? "reference_video" : "reference_image",
960
+ url: reference.url
961
+ });
962
+ else if (reference.mediaType.startsWith("image/")) media.push({
963
+ type: "reference_image",
964
+ url: convertImageModelFileToDataUri(reference)
965
+ });
966
+ else warnings.push({
967
+ type: "unsupported",
968
+ feature: "inputReferences",
969
+ details: "Alibaba reference-to-video requires URL references for videos. Non-URL video reference was skipped."
970
+ });
971
+ if (frames.first != null) media.push({
972
+ type: "first_frame",
973
+ url: convertImageModelFileToDataUri(frames.first)
974
+ });
975
+ if (frames.last != null) media.push({
976
+ type: "last_frame",
977
+ url: convertImageModelFileToDataUri(frames.last)
978
+ });
979
+ return media.length > 0 ? media : void 0;
1208
980
  }
1209
981
  function resolveReferenceUrls(options, alibabaOptions, warnings) {
1210
- if (options.frameImages != null && options.frameImages.length > 0) {
1211
- return void 0;
1212
- }
1213
- if (options.inputReferences != null && options.inputReferences.length > 0) {
1214
- const urls = [];
1215
- for (const reference of options.inputReferences) {
1216
- if (reference.type === "url") {
1217
- urls.push(reference.url);
1218
- } else {
1219
- warnings.push({
1220
- type: "unsupported",
1221
- feature: "inputReferences",
1222
- details: "Alibaba reference-to-video requires URL references. Non-URL reference was skipped."
1223
- });
1224
- }
1225
- }
1226
- return urls.length > 0 ? urls : void 0;
1227
- }
1228
- return alibabaOptions?.referenceUrls ?? void 0;
982
+ if (options.frameImages != null && options.frameImages.length > 0) return;
983
+ if (options.inputReferences != null && options.inputReferences.length > 0) {
984
+ const urls = [];
985
+ for (const reference of options.inputReferences) if (reference.type === "url") urls.push(reference.url);
986
+ else warnings.push({
987
+ type: "unsupported",
988
+ feature: "inputReferences",
989
+ details: "Alibaba reference-to-video requires URL references. Non-URL reference was skipped."
990
+ });
991
+ return urls.length > 0 ? urls : void 0;
992
+ }
993
+ return alibabaOptions?.referenceUrls ?? void 0;
1229
994
  }
1230
995
  var AlibabaVideoModel = class {
1231
- constructor(modelId, config) {
1232
- this.modelId = modelId;
1233
- this.config = config;
1234
- this.specificationVersion = "v4";
1235
- this.maxVideosPerCall = 1;
1236
- }
1237
- get provider() {
1238
- return this.config.provider;
1239
- }
1240
- async buildRequest(options) {
1241
- const warnings = [];
1242
- const mode = detectMode(this.modelId);
1243
- const alibabaOptions = await parseProviderOptions3({
1244
- provider: "alibaba",
1245
- providerOptions: options.providerOptions,
1246
- schema: alibabaVideoModelOptionsSchema
1247
- });
1248
- const input = {};
1249
- if (options.prompt != null) {
1250
- input.prompt = options.prompt;
1251
- }
1252
- if (alibabaOptions?.negativePrompt != null) {
1253
- input.negative_prompt = alibabaOptions.negativePrompt;
1254
- }
1255
- if (alibabaOptions?.audioUrl != null) {
1256
- input.audio_url = alibabaOptions.audioUrl;
1257
- }
1258
- const startImage = resolveStartImage(options);
1259
- const protocol = detectProtocol(this.modelId);
1260
- const wan27 = protocol === "wan27";
1261
- const wan3 = protocol === "wan3";
1262
- const tieredProtocol = wan27 || wan3;
1263
- const supportsRatio = wan3 || wan27 && mode !== "i2v";
1264
- if (!wan3 && mode === "i2v" && startImage != null) {
1265
- input.img_url = fileToImageString(startImage);
1266
- }
1267
- if (wan3) {
1268
- const media = resolveMedia(options, alibabaOptions, warnings, {
1269
- first: startImage,
1270
- last: getLastFrameImage(options)
1271
- });
1272
- if (media != null) {
1273
- input.media = media;
1274
- }
1275
- } else if (mode === "r2v") {
1276
- if (wan27) {
1277
- const media = resolveMedia(options, alibabaOptions, warnings, {
1278
- first: getFirstFrameImage(options)
1279
- });
1280
- if (media != null) {
1281
- input.media = media;
1282
- }
1283
- } else {
1284
- const referenceUrls = resolveReferenceUrls(
1285
- options,
1286
- alibabaOptions,
1287
- warnings
1288
- );
1289
- if (referenceUrls != null && referenceUrls.length > 0) {
1290
- input.reference_urls = referenceUrls;
1291
- }
1292
- }
1293
- }
1294
- const lastFrame = getLastFrameImage(options);
1295
- if (lastFrame != null && !wan3) {
1296
- warnings.push({
1297
- type: "unsupported",
1298
- feature: "frameImages",
1299
- details: "This model does not support last_frame. The last frame image was ignored."
1300
- });
1301
- }
1302
- if (options.inputReferences != null && options.inputReferences.length > 0 && mode !== "r2v" && !wan3) {
1303
- warnings.push({
1304
- type: "unsupported",
1305
- feature: "inputReferences",
1306
- details: "Alibaba only supports inputReferences (reference-to-video) on reference-to-video models. The reference images were ignored."
1307
- });
1308
- }
1309
- const parameters = {};
1310
- if (options.duration != null) {
1311
- parameters.duration = options.duration;
1312
- }
1313
- if (options.seed != null) {
1314
- parameters.seed = options.seed;
1315
- }
1316
- if (options.resolution != null) {
1317
- if (mode === "i2v" || tieredProtocol) {
1318
- const resolutionTier = resolutionTierMap[options.resolution] || options.resolution;
1319
- const supportedTiers = wan3 ? ["480P", "720P", "1080P"] : ["720P", "1080P"];
1320
- if (tieredProtocol && !supportedTiers.includes(resolutionTier)) {
1321
- warnings.push({
1322
- type: "unsupported",
1323
- feature: "resolution",
1324
- details: `${wan3 ? "wan3" : "wan2.7"} models only support the ${supportedTiers.join(", ")} resolution tiers. The resolution "${options.resolution}" was ignored.`
1325
- });
1326
- } else {
1327
- parameters.resolution = resolutionTier;
1328
- }
1329
- } else {
1330
- parameters.size = options.resolution.replace("x", "*");
1331
- }
1332
- }
1333
- if (supportsRatio) {
1334
- const ratio = alibabaOptions?.ratio ?? options.aspectRatio ?? (options.resolution != null ? deriveRatioFromResolution(options.resolution) : void 0);
1335
- if (ratio != null) {
1336
- parameters.ratio = ratio;
1337
- }
1338
- }
1339
- if (alibabaOptions?.promptExtend != null) {
1340
- parameters.prompt_extend = alibabaOptions.promptExtend;
1341
- }
1342
- if (alibabaOptions?.shotType != null) {
1343
- if (tieredProtocol) {
1344
- warnings.push({
1345
- type: "unsupported",
1346
- feature: "shotType",
1347
- details: `${wan3 ? "wan3" : "wan2.7"} models do not support the shotType option. Describe the shot structure in the prompt instead.`
1348
- });
1349
- } else {
1350
- parameters.shot_type = alibabaOptions.shotType;
1351
- }
1352
- }
1353
- if (alibabaOptions?.watermark != null) {
1354
- parameters.watermark = alibabaOptions.watermark;
1355
- }
1356
- const audio = options.generateAudio ?? alibabaOptions?.audio;
1357
- if (audio != null) {
1358
- if (wan27) {
1359
- warnings.push({
1360
- type: "unsupported",
1361
- feature: "generateAudio",
1362
- details: "wan2.7 models always generate audio. The audio option was ignored."
1363
- });
1364
- } else {
1365
- parameters.audio = audio;
1366
- }
1367
- }
1368
- if (options.aspectRatio && !supportsRatio) {
1369
- warnings.push({
1370
- type: "unsupported",
1371
- feature: "aspectRatio",
1372
- details: "Alibaba video models use explicit size/resolution dimensions. Use the resolution option or providerOptions.alibaba for size control."
1373
- });
1374
- }
1375
- if (options.fps) {
1376
- warnings.push({
1377
- type: "unsupported",
1378
- feature: "fps",
1379
- details: "Alibaba video models do not support custom FPS."
1380
- });
1381
- }
1382
- if (options.n != null && options.n > 1) {
1383
- warnings.push({
1384
- type: "unsupported",
1385
- feature: "n",
1386
- details: "Alibaba video models only support generating 1 video per call."
1387
- });
1388
- }
1389
- return { input, parameters, warnings, alibabaOptions };
1390
- }
1391
- buildCompletedResult(statusResponse, responseHeaders, warnings, currentDate) {
1392
- const taskId = statusResponse.output?.task_id;
1393
- const videoUrl = statusResponse.output?.video_url;
1394
- if (!videoUrl) {
1395
- throw new AISDKError({
1396
- name: "ALIBABA_VIDEO_GENERATION_ERROR",
1397
- message: `No video URL in response. Task ID: ${taskId}`
1398
- });
1399
- }
1400
- return {
1401
- status: "completed",
1402
- videos: [
1403
- {
1404
- type: "url",
1405
- url: videoUrl,
1406
- mediaType: "video/mp4"
1407
- }
1408
- ],
1409
- warnings,
1410
- response: {
1411
- timestamp: currentDate,
1412
- modelId: this.modelId,
1413
- headers: responseHeaders
1414
- },
1415
- providerMetadata: {
1416
- alibaba: {
1417
- taskId,
1418
- videoUrl,
1419
- ...statusResponse.output?.actual_prompt ? { actualPrompt: statusResponse.output.actual_prompt } : {},
1420
- ...statusResponse.usage ? {
1421
- usage: {
1422
- duration: statusResponse.usage.duration,
1423
- outputVideoDuration: statusResponse.usage.output_video_duration,
1424
- resolution: statusResponse.usage.SR,
1425
- size: statusResponse.usage.size,
1426
- // wan3-only. Spread rather than set to undefined so the
1427
- // metadata shape for older wan models is unchanged.
1428
- ...statusResponse.usage.input_video_duration != null ? {
1429
- inputVideoDuration: statusResponse.usage.input_video_duration
1430
- } : {},
1431
- ...statusResponse.usage.fps != null ? { fps: statusResponse.usage.fps } : {},
1432
- ...statusResponse.usage.ratio != null ? { ratio: statusResponse.usage.ratio } : {}
1433
- }
1434
- } : {}
1435
- }
1436
- }
1437
- };
1438
- }
1439
- async doStart(options) {
1440
- const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
1441
- const { input, parameters, warnings } = await this.buildRequest(options);
1442
- const { value: createResponse, responseHeaders } = await postJsonToApi3({
1443
- url: `${this.config.baseURL}/api/v1/services/aigc/video-generation/video-synthesis`,
1444
- headers: combineHeaders3(
1445
- await resolve(this.config.headers),
1446
- options.headers,
1447
- {
1448
- "X-DashScope-Async": "enable"
1449
- }
1450
- ),
1451
- body: {
1452
- model: this.modelId,
1453
- input,
1454
- parameters
1455
- },
1456
- successfulResponseHandler: createJsonResponseHandler3(
1457
- alibabaVideoCreateTaskSchema
1458
- ),
1459
- failedResponseHandler: alibabaVideoFailedResponseHandler,
1460
- abortSignal: options.abortSignal,
1461
- fetch: this.config.fetch
1462
- });
1463
- const taskId = createResponse.output?.task_id;
1464
- if (!taskId) {
1465
- throw new AISDKError({
1466
- name: "ALIBABA_VIDEO_GENERATION_ERROR",
1467
- message: `No task_id returned from Alibaba API. Response: ${JSON.stringify(createResponse)}`
1468
- });
1469
- }
1470
- return {
1471
- operation: { taskId },
1472
- warnings,
1473
- response: {
1474
- timestamp: currentDate,
1475
- modelId: this.modelId,
1476
- headers: responseHeaders
1477
- }
1478
- };
1479
- }
1480
- async doStatus(options) {
1481
- const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
1482
- const { taskId } = options.operation;
1483
- const { value: statusResponse, responseHeaders } = await getFromApi({
1484
- url: `${this.config.baseURL}/api/v1/tasks/${taskId}`,
1485
- validateUrl: false,
1486
- headers: combineHeaders3(
1487
- await resolve(this.config.headers),
1488
- options.headers
1489
- ),
1490
- successfulResponseHandler: createJsonResponseHandler3(
1491
- alibabaVideoTaskStatusSchema
1492
- ),
1493
- failedResponseHandler: alibabaVideoFailedResponseHandler,
1494
- abortSignal: options.abortSignal,
1495
- fetch: this.config.fetch
1496
- });
1497
- const taskStatus = statusResponse.output?.task_status;
1498
- if (taskStatus === "SUCCEEDED") {
1499
- return this.buildCompletedResult(
1500
- statusResponse,
1501
- responseHeaders,
1502
- [],
1503
- currentDate
1504
- );
1505
- }
1506
- if (taskStatus === "FAILED" || taskStatus === "CANCELED") {
1507
- return {
1508
- status: "error",
1509
- error: `Video generation ${taskStatus.toLowerCase()}. Task ID: ${taskId}. ${statusResponse.output?.message ?? ""}`.trim(),
1510
- response: {
1511
- timestamp: currentDate,
1512
- modelId: this.modelId,
1513
- headers: responseHeaders
1514
- }
1515
- };
1516
- }
1517
- return {
1518
- status: "pending",
1519
- response: {
1520
- timestamp: currentDate,
1521
- modelId: this.modelId,
1522
- headers: responseHeaders
1523
- }
1524
- };
1525
- }
996
+ get provider() {
997
+ return this.config.provider;
998
+ }
999
+ constructor(modelId, config) {
1000
+ this.modelId = modelId;
1001
+ this.config = config;
1002
+ this.specificationVersion = "v4";
1003
+ this.maxVideosPerCall = 1;
1004
+ }
1005
+ async buildRequest(options) {
1006
+ const warnings = [];
1007
+ const mode = detectMode(this.modelId);
1008
+ const alibabaOptions = await parseProviderOptions({
1009
+ provider: "alibaba",
1010
+ providerOptions: options.providerOptions,
1011
+ schema: alibabaVideoModelOptionsSchema
1012
+ });
1013
+ const input = {};
1014
+ if (options.prompt != null) input.prompt = options.prompt;
1015
+ if (alibabaOptions?.negativePrompt != null) input.negative_prompt = alibabaOptions.negativePrompt;
1016
+ if (alibabaOptions?.audioUrl != null) input.audio_url = alibabaOptions.audioUrl;
1017
+ const startImage = resolveStartImage(options);
1018
+ const protocol = detectProtocol(this.modelId);
1019
+ const wan27 = protocol === "wan27";
1020
+ const wan3 = protocol === "wan3";
1021
+ const tieredProtocol = wan27 || wan3;
1022
+ const supportsRatio = wan3 || wan27 && mode !== "i2v";
1023
+ if (!wan3 && mode === "i2v" && startImage != null) input.img_url = fileToImageString(startImage);
1024
+ if (wan3) {
1025
+ const media = resolveMedia(options, alibabaOptions, warnings, {
1026
+ first: startImage,
1027
+ last: getLastFrameImage(options)
1028
+ });
1029
+ if (media != null) input.media = media;
1030
+ } else if (mode === "r2v") {
1031
+ if (wan27) {
1032
+ const media = resolveMedia(options, alibabaOptions, warnings, { first: getFirstFrameImage(options) });
1033
+ if (media != null) input.media = media;
1034
+ } else {
1035
+ const referenceUrls = resolveReferenceUrls(options, alibabaOptions, warnings);
1036
+ if (referenceUrls != null && referenceUrls.length > 0) input.reference_urls = referenceUrls;
1037
+ }
1038
+ }
1039
+ if (getLastFrameImage(options) != null && !wan3) warnings.push({
1040
+ type: "unsupported",
1041
+ feature: "frameImages",
1042
+ details: "This model does not support last_frame. The last frame image was ignored."
1043
+ });
1044
+ if (options.inputReferences != null && options.inputReferences.length > 0 && mode !== "r2v" && !wan3) warnings.push({
1045
+ type: "unsupported",
1046
+ feature: "inputReferences",
1047
+ details: "Alibaba only supports inputReferences (reference-to-video) on reference-to-video models. The reference images were ignored."
1048
+ });
1049
+ const parameters = {};
1050
+ if (options.duration != null) parameters.duration = options.duration;
1051
+ if (options.seed != null) parameters.seed = options.seed;
1052
+ if (options.resolution != null) {
1053
+ if (mode === "i2v" || tieredProtocol) {
1054
+ const resolutionTier = resolutionTierMap[options.resolution] || options.resolution;
1055
+ const supportedTiers = wan3 ? [
1056
+ "480P",
1057
+ "720P",
1058
+ "1080P"
1059
+ ] : ["720P", "1080P"];
1060
+ if (tieredProtocol && !supportedTiers.includes(resolutionTier)) warnings.push({
1061
+ type: "unsupported",
1062
+ feature: "resolution",
1063
+ details: `${wan3 ? "wan3" : "wan2.7"} models only support the ${supportedTiers.join(", ")} resolution tiers. The resolution "${options.resolution}" was ignored.`
1064
+ });
1065
+ else parameters.resolution = resolutionTier;
1066
+ } else parameters.size = options.resolution.replace("x", "*");
1067
+ }
1068
+ if (supportsRatio) {
1069
+ const ratio = alibabaOptions?.ratio ?? options.aspectRatio ?? (options.resolution != null ? deriveRatioFromResolution(options.resolution) : void 0);
1070
+ if (ratio != null) parameters.ratio = ratio;
1071
+ }
1072
+ if (alibabaOptions?.promptExtend != null) parameters.prompt_extend = alibabaOptions.promptExtend;
1073
+ if (alibabaOptions?.shotType != null) {
1074
+ if (tieredProtocol) warnings.push({
1075
+ type: "unsupported",
1076
+ feature: "shotType",
1077
+ details: `${wan3 ? "wan3" : "wan2.7"} models do not support the shotType option. Describe the shot structure in the prompt instead.`
1078
+ });
1079
+ else parameters.shot_type = alibabaOptions.shotType;
1080
+ }
1081
+ if (alibabaOptions?.watermark != null) parameters.watermark = alibabaOptions.watermark;
1082
+ const audio = options.generateAudio ?? alibabaOptions?.audio;
1083
+ if (audio != null) {
1084
+ if (wan27) warnings.push({
1085
+ type: "unsupported",
1086
+ feature: "generateAudio",
1087
+ details: "wan2.7 models always generate audio. The audio option was ignored."
1088
+ });
1089
+ else parameters.audio = audio;
1090
+ }
1091
+ if (options.aspectRatio && !supportsRatio) warnings.push({
1092
+ type: "unsupported",
1093
+ feature: "aspectRatio",
1094
+ details: "Alibaba video models use explicit size/resolution dimensions. Use the resolution option or providerOptions.alibaba for size control."
1095
+ });
1096
+ if (options.fps) warnings.push({
1097
+ type: "unsupported",
1098
+ feature: "fps",
1099
+ details: "Alibaba video models do not support custom FPS."
1100
+ });
1101
+ if (options.n != null && options.n > 1) warnings.push({
1102
+ type: "unsupported",
1103
+ feature: "n",
1104
+ details: "Alibaba video models only support generating 1 video per call."
1105
+ });
1106
+ return {
1107
+ input,
1108
+ parameters,
1109
+ warnings,
1110
+ alibabaOptions
1111
+ };
1112
+ }
1113
+ buildCompletedResult(statusResponse, responseHeaders, warnings, currentDate) {
1114
+ const taskId = statusResponse.output?.task_id;
1115
+ const videoUrl = statusResponse.output?.video_url;
1116
+ if (!videoUrl) throw new AISDKError({
1117
+ name: "ALIBABA_VIDEO_GENERATION_ERROR",
1118
+ message: `No video URL in response. Task ID: ${taskId}`
1119
+ });
1120
+ return {
1121
+ status: "completed",
1122
+ videos: [{
1123
+ type: "url",
1124
+ url: videoUrl,
1125
+ mediaType: "video/mp4"
1126
+ }],
1127
+ warnings,
1128
+ response: {
1129
+ timestamp: currentDate,
1130
+ modelId: this.modelId,
1131
+ headers: responseHeaders
1132
+ },
1133
+ providerMetadata: { alibaba: {
1134
+ taskId,
1135
+ videoUrl,
1136
+ ...statusResponse.output?.actual_prompt ? { actualPrompt: statusResponse.output.actual_prompt } : {},
1137
+ ...statusResponse.usage ? { usage: {
1138
+ duration: statusResponse.usage.duration,
1139
+ outputVideoDuration: statusResponse.usage.output_video_duration,
1140
+ resolution: statusResponse.usage.SR,
1141
+ size: statusResponse.usage.size,
1142
+ ...statusResponse.usage.input_video_duration != null ? { inputVideoDuration: statusResponse.usage.input_video_duration } : {},
1143
+ ...statusResponse.usage.fps != null ? { fps: statusResponse.usage.fps } : {},
1144
+ ...statusResponse.usage.ratio != null ? { ratio: statusResponse.usage.ratio } : {}
1145
+ } } : {}
1146
+ } }
1147
+ };
1148
+ }
1149
+ async doStart(options) {
1150
+ const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
1151
+ const { input, parameters, warnings } = await this.buildRequest(options);
1152
+ const { value: createResponse, responseHeaders } = await postJsonToApi({
1153
+ url: `${this.config.baseURL}/api/v1/services/aigc/video-generation/video-synthesis`,
1154
+ headers: combineHeaders(await resolve(this.config.headers), options.headers, { "X-DashScope-Async": "enable" }),
1155
+ body: {
1156
+ model: this.modelId,
1157
+ input,
1158
+ parameters
1159
+ },
1160
+ successfulResponseHandler: createJsonResponseHandler(alibabaVideoCreateTaskSchema),
1161
+ failedResponseHandler: alibabaVideoFailedResponseHandler,
1162
+ abortSignal: options.abortSignal,
1163
+ fetch: this.config.fetch
1164
+ });
1165
+ const taskId = createResponse.output?.task_id;
1166
+ if (!taskId) throw new AISDKError({
1167
+ name: "ALIBABA_VIDEO_GENERATION_ERROR",
1168
+ message: `No task_id returned from Alibaba API. Response: ${JSON.stringify(createResponse)}`
1169
+ });
1170
+ return {
1171
+ operation: { taskId },
1172
+ warnings,
1173
+ response: {
1174
+ timestamp: currentDate,
1175
+ modelId: this.modelId,
1176
+ headers: responseHeaders
1177
+ }
1178
+ };
1179
+ }
1180
+ async doStatus(options) {
1181
+ const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
1182
+ const { taskId } = options.operation;
1183
+ const { value: statusResponse, responseHeaders } = await getFromApi({
1184
+ url: `${this.config.baseURL}/api/v1/tasks/${taskId}`,
1185
+ validateUrl: false,
1186
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
1187
+ successfulResponseHandler: createJsonResponseHandler(alibabaVideoTaskStatusSchema),
1188
+ failedResponseHandler: alibabaVideoFailedResponseHandler,
1189
+ abortSignal: options.abortSignal,
1190
+ fetch: this.config.fetch
1191
+ });
1192
+ const taskStatus = statusResponse.output?.task_status;
1193
+ if (taskStatus === "SUCCEEDED") return this.buildCompletedResult(statusResponse, responseHeaders, [], currentDate);
1194
+ if (taskStatus === "FAILED" || taskStatus === "CANCELED") return {
1195
+ status: "error",
1196
+ error: `Video generation ${taskStatus.toLowerCase()}. Task ID: ${taskId}. ${statusResponse.output?.message ?? ""}`.trim(),
1197
+ response: {
1198
+ timestamp: currentDate,
1199
+ modelId: this.modelId,
1200
+ headers: responseHeaders
1201
+ }
1202
+ };
1203
+ return {
1204
+ status: "pending",
1205
+ response: {
1206
+ timestamp: currentDate,
1207
+ modelId: this.modelId,
1208
+ headers: responseHeaders
1209
+ }
1210
+ };
1211
+ }
1526
1212
  };
1527
-
1528
- // src/version.ts
1529
- var VERSION = true ? "2.0.58" : "0.0.0-test";
1530
-
1531
- // src/alibaba-provider.ts
1213
+ //#endregion
1214
+ //#region src/version.ts
1215
+ const VERSION = "2.0.59";
1216
+ //#endregion
1217
+ //#region src/alibaba-provider.ts
1218
+ /**
1219
+ * Create an Alibaba Cloud (Qwen) provider instance.
1220
+ */
1532
1221
  function createAlibaba(options = {}) {
1533
- const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
1534
- const videoBaseURL = withoutTrailingSlash(options.videoBaseURL) ?? "https://dashscope-intl.aliyuncs.com";
1535
- const embeddingBaseURL = withoutTrailingSlash(options.embeddingBaseURL) ?? "https://dashscope-intl.aliyuncs.com/api/v1";
1536
- const getHeaders = () => withUserAgentSuffix(
1537
- {
1538
- Authorization: `Bearer ${loadApiKey({
1539
- apiKey: options.apiKey,
1540
- environmentVariableName: "ALIBABA_API_KEY",
1541
- description: "Alibaba Cloud (DashScope)"
1542
- })}`,
1543
- ...options.headers
1544
- },
1545
- `ai-sdk-alibaba/${VERSION}`
1546
- );
1547
- const createLanguageModel = (modelId) => new AlibabaChatLanguageModel(modelId, {
1548
- provider: "alibaba.chat",
1549
- baseURL,
1550
- headers: getHeaders,
1551
- fetch: options.fetch,
1552
- includeUsage: options.includeUsage ?? true
1553
- });
1554
- const createEmbeddingModel = (modelId) => new AlibabaEmbeddingModel(modelId, {
1555
- provider: "alibaba.embedding",
1556
- baseURL: embeddingBaseURL,
1557
- headers: getHeaders,
1558
- fetch: options.fetch
1559
- });
1560
- const createVideoModel = (modelId) => new AlibabaVideoModel(modelId, {
1561
- provider: "alibaba.video",
1562
- baseURL: videoBaseURL,
1563
- headers: getHeaders,
1564
- fetch: options.fetch
1565
- });
1566
- const provider = function(modelId) {
1567
- if (new.target) {
1568
- throw new Error(
1569
- "The Alibaba model function cannot be called with the new keyword."
1570
- );
1571
- }
1572
- return createLanguageModel(modelId);
1573
- };
1574
- provider.specificationVersion = "v4";
1575
- provider.languageModel = createLanguageModel;
1576
- provider.chatModel = createLanguageModel;
1577
- provider.embedding = createEmbeddingModel;
1578
- provider.embeddingModel = createEmbeddingModel;
1579
- provider.video = createVideoModel;
1580
- provider.videoModel = createVideoModel;
1581
- provider.imageModel = (modelId) => {
1582
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1583
- };
1584
- return provider;
1222
+ const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
1223
+ const videoBaseURL = withoutTrailingSlash(options.videoBaseURL) ?? "https://dashscope-intl.aliyuncs.com";
1224
+ const embeddingBaseURL = withoutTrailingSlash(options.embeddingBaseURL) ?? "https://dashscope-intl.aliyuncs.com/api/v1";
1225
+ const getHeaders = () => withUserAgentSuffix({
1226
+ Authorization: `Bearer ${loadApiKey({
1227
+ apiKey: options.apiKey,
1228
+ environmentVariableName: "ALIBABA_API_KEY",
1229
+ description: "Alibaba Cloud (DashScope)"
1230
+ })}`,
1231
+ ...options.headers
1232
+ }, `ai-sdk-alibaba/${VERSION}`);
1233
+ const createLanguageModel = (modelId) => new AlibabaChatLanguageModel(modelId, {
1234
+ provider: "alibaba.chat",
1235
+ baseURL,
1236
+ headers: getHeaders,
1237
+ fetch: options.fetch,
1238
+ includeUsage: options.includeUsage ?? true
1239
+ });
1240
+ const createEmbeddingModel = (modelId) => new AlibabaEmbeddingModel(modelId, {
1241
+ provider: "alibaba.embedding",
1242
+ baseURL: embeddingBaseURL,
1243
+ headers: getHeaders,
1244
+ fetch: options.fetch
1245
+ });
1246
+ const createVideoModel = (modelId) => new AlibabaVideoModel(modelId, {
1247
+ provider: "alibaba.video",
1248
+ baseURL: videoBaseURL,
1249
+ headers: getHeaders,
1250
+ fetch: options.fetch
1251
+ });
1252
+ const provider = function(modelId) {
1253
+ if (new.target) throw new Error("The Alibaba model function cannot be called with the new keyword.");
1254
+ return createLanguageModel(modelId);
1255
+ };
1256
+ provider.specificationVersion = "v4";
1257
+ provider.languageModel = createLanguageModel;
1258
+ provider.chatModel = createLanguageModel;
1259
+ provider.embedding = createEmbeddingModel;
1260
+ provider.embeddingModel = createEmbeddingModel;
1261
+ provider.video = createVideoModel;
1262
+ provider.videoModel = createVideoModel;
1263
+ provider.imageModel = (modelId) => {
1264
+ throw new NoSuchModelError({
1265
+ modelId,
1266
+ modelType: "imageModel"
1267
+ });
1268
+ };
1269
+ return provider;
1585
1270
  }
1586
- var alibaba = createAlibaba();
1587
- export {
1588
- VERSION,
1589
- alibaba,
1590
- createAlibaba
1591
- };
1271
+ const alibaba = createAlibaba();
1272
+ //#endregion
1273
+ export { VERSION, alibaba, createAlibaba };
1274
+
1592
1275
  //# sourceMappingURL=index.js.map