@mastra/core
Version:
1,499 lines (1,497 loc) • 359 kB
JavaScript
'use strict';
var chunk24WS5SQV_cjs = require('./chunk-24WS5SQV.cjs');
var chunk4SCYX53T_cjs = require('./chunk-4SCYX53T.cjs');
var v4 = require('zod/v4');
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai-compatible/2.0.48/6bc655d386f10be38a51d245d1ac2f722ea6d3a404005744bd9a8345d698d3e5/node_modules/@ai-sdk/openai-compatible/dist/internal/index.mjs
function convertOpenAICompatibleChatUsage(usage) {
var _a15, _b, _c, _d, _e, _f;
if (usage == null) {
return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
}
const promptTokens = (_a15 = usage.prompt_tokens) != null ? _a15 : 0;
const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
const cacheReadTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
const reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: usage
};
}
function mapOpenAICompatibleFinishReason(finishReason) {
switch (finishReason) {
case "stop":
return "stop";
case "length":
return "length";
case "content_filter":
return "content-filter";
case "function_call":
case "tool_calls":
return "tool-calls";
default:
return "other";
}
}
function getResponseMetadata({
id,
model,
created
}) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created != null ? new Date(created * 1e3) : void 0
};
}
function prepareTools({
tools,
toolChoice
}) {
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
if (tools == null) {
return { tools: void 0, toolChoice: void 0, toolWarnings };
}
const openaiCompatTools = [];
for (const tool of tools) {
if (tool.type === "provider") {
toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
} else {
openaiCompatTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
}
}
if (toolChoice == null) {
return { tools: openaiCompatTools, toolChoice: void 0, toolWarnings };
}
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required":
return { tools: openaiCompatTools, toolChoice: type, toolWarnings };
case "tool":
return {
tools: openaiCompatTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: {
const _exhaustiveCheck = type;
throw new chunk24WS5SQV_cjs.UnsupportedFunctionalityError2({
functionality: `tool choice type: ${_exhaustiveCheck}`
});
}
}
}
var alibabaLanguageModelOptions = v4.z.object({
/**
* Enable thinking/reasoning mode for supported models.
* When enabled, the model generates reasoning content before the response.
*
* @default false
*/
enableThinking: v4.z.boolean().optional(),
/**
* Maximum number of reasoning tokens to generate.
*/
thinkingBudget: v4.z.number().positive().optional(),
/**
* Whether to enable parallel function calling during tool use.
*
* @default true
*/
parallelToolCalls: v4.z.boolean().optional()
});
var alibabaErrorDataSchema = v4.z.object({
error: v4.z.object({
message: v4.z.string(),
code: v4.z.string().nullish(),
type: v4.z.string().nullish()
})
});
var alibabaFailedResponseHandler = chunk24WS5SQV_cjs.createJsonErrorResponseHandler2({
errorSchema: alibabaErrorDataSchema,
errorToMessage: (data) => data.error.message
});
function convertAlibabaUsage(usage) {
var _a15, _b, _c, _d;
const baseUsage = convertOpenAICompatibleChatUsage(usage);
const cacheWriteTokens = (_b = (_a15 = usage == null ? void 0 : usage.prompt_tokens_details) == null ? void 0 : _a15.cache_creation_input_tokens) != null ? _b : 0;
const noCacheTokens = ((_c = baseUsage.inputTokens.total) != null ? _c : 0) - ((_d = baseUsage.inputTokens.cacheRead) != null ? _d : 0) - cacheWriteTokens;
return {
...baseUsage,
inputTokens: {
...baseUsage.inputTokens,
cacheWrite: cacheWriteTokens,
noCache: noCacheTokens
}
};
}
function formatImageUrl({
data,
mediaType
}) {
return data instanceof URL ? data.toString() : `data:${mediaType};base64,${chunk24WS5SQV_cjs.convertToBase642(data)}`;
}
function convertToAlibabaChatMessages({
prompt,
cacheControlValidator
}) {
var _a15, _b;
const messages = [];
for (const { role, content, ...message } of prompt) {
const messageCacheControl = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(
message.providerOptions
);
switch (role) {
case "system": {
if (messageCacheControl) {
messages.push({
role: "system",
content: [
{
type: "text",
text: content,
cache_control: messageCacheControl
}
]
});
} else {
messages.push({ role: "system", content });
}
break;
}
case "user": {
messages.push({
role: "user",
content: content.map((part, index) => {
var _a22;
const isLastPart = index === content.length - 1;
const partCacheControl = (_a22 = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(part.providerOptions)) != null ? _a22 : isLastPart ? messageCacheControl : void 0;
switch (part.type) {
case "text": {
return {
type: "text",
text: part.text,
...partCacheControl ? { cache_control: partCacheControl } : {}
};
}
case "file": {
if (part.mediaType.startsWith("image/")) {
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
return {
type: "image_url",
image_url: {
url: formatImageUrl({ data: part.data, mediaType })
},
...partCacheControl ? { cache_control: partCacheControl } : {}
};
} else {
throw new chunk24WS5SQV_cjs.UnsupportedFunctionalityError2({
functionality: "Only image file parts are supported"
});
}
}
}
})
});
break;
}
case "assistant": {
let text = "";
const toolCalls = [];
for (const part of content) {
switch (part.type) {
case "text": {
text += part.text;
break;
}
case "tool-call": {
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
break;
}
case "reasoning": {
text += part.text;
break;
}
}
}
messages.push({
role: "assistant",
content: messageCacheControl ? [{ type: "text", text, cache_control: messageCacheControl }] : text || null,
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool": {
const toolResponses = content.filter(
(r) => r.type !== "tool-approval-response"
);
for (let i = 0; i < toolResponses.length; i++) {
const toolResponse = toolResponses[i];
const output = toolResponse.output;
const isLastPart = i === toolResponses.length - 1;
const partCacheControl = (_a15 = cacheControlValidator == null ? void 0 : cacheControlValidator.getCacheControl(
toolResponse.providerOptions
)) != null ? _a15 : isLastPart ? messageCacheControl : void 0;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = (_b = output.reason) != null ? _b : "Tool execution denied.";
break;
case "content":
case "json":
case "error-json":
contentValue = JSON.stringify(output.value);
break;
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: partCacheControl ? [
{
type: "text",
text: contentValue,
cache_control: partCacheControl
}
] : contentValue
});
}
break;
}
default: {
const _exhaustiveCheck = role;
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
}
}
}
return messages;
}
var MAX_CACHE_BREAKPOINTS = 4;
function getCacheControl(providerMetadata) {
var _a15;
const alibaba2 = providerMetadata == null ? void 0 : providerMetadata.alibaba;
const cacheControlValue = (_a15 = alibaba2 == null ? void 0 : alibaba2.cacheControl) != null ? _a15 : alibaba2 == null ? void 0 : alibaba2.cache_control;
return cacheControlValue;
}
var CacheControlValidator = class {
constructor() {
this.breakpointCount = 0;
this.warnings = [];
}
getCacheControl(providerMetadata) {
const cacheControlValue = getCacheControl(providerMetadata);
if (!cacheControlValue) {
return void 0;
}
this.breakpointCount++;
if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {
this.warnings.push({
type: "other",
message: `Max breakpoint limit exceeded. Only the last ${MAX_CACHE_BREAKPOINTS} cache markers will take effect.`
});
}
return cacheControlValue;
}
getWarnings() {
return this.warnings;
}
};
var AlibabaLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.supportedUrls = {
"image/*": [/^https?:\/\/.*$/]
};
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
/**
* Builds request arguments for Alibaba API call.
* Converts AI SDK options to Alibaba API format.
*/
async getArgs({
prompt,
maxOutputTokens,
temperature,
topP,
topK,
frequencyPenalty,
presencePenalty,
stopSequences,
responseFormat,
seed,
providerOptions,
tools,
toolChoice
}) {
var _a15;
const warnings = [];
const cacheControlValidator = new CacheControlValidator();
const alibabaOptions = await chunk24WS5SQV_cjs.parseProviderOptions2({
provider: "alibaba",
providerOptions,
schema: alibabaLanguageModelOptions
});
if (frequencyPenalty != null) {
warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
}
const baseArgs = {
model: this.modelId,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
top_k: topK,
presence_penalty: presencePenalty,
stop: stopSequences,
seed,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
name: (_a15 = responseFormat.name) != null ? _a15 : "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
// Alibaba-specific options
...(alibabaOptions == null ? void 0 : alibabaOptions.enableThinking) != null ? { enable_thinking: alibabaOptions.enableThinking } : {},
...(alibabaOptions == null ? void 0 : alibabaOptions.thinkingBudget) != null ? { thinking_budget: alibabaOptions.thinkingBudget } : {},
// Convert messages with cache control support
messages: convertToAlibabaChatMessages({
prompt,
cacheControlValidator
})
};
const {
tools: alibabaTools,
toolChoice: alibabaToolChoice,
toolWarnings
} = prepareTools({ tools, toolChoice });
warnings.push(...cacheControlValidator.getWarnings());
return {
args: {
...baseArgs,
tools: alibabaTools,
tool_choice: alibabaToolChoice,
...alibabaTools != null && (alibabaOptions == null ? void 0 : alibabaOptions.parallelToolCalls) !== void 0 ? { parallel_tool_calls: alibabaOptions.parallelToolCalls } : {}
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
var _a15;
const { args, warnings } = await this.getArgs(options);
const {
responseHeaders,
value: response,
rawValue: rawResponse
} = await chunk24WS5SQV_cjs.postJsonToApi2({
url: `${this.config.baseURL}/chat/completions`,
headers: chunk24WS5SQV_cjs.combineHeaders2(this.config.headers(), options.headers),
body: args,
failedResponseHandler: alibabaFailedResponseHandler,
successfulResponseHandler: chunk24WS5SQV_cjs.createJsonResponseHandler2(
alibabaChatResponseSchema
),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const content = [];
const text = choice.message.content;
if (text != null && text.length > 0) {
content.push({ type: "text", text });
}
const reasoning = choice.message.reasoning_content;
if (reasoning != null && reasoning.length > 0) {
content.push({
type: "reasoning",
text: reasoning
});
}
if (choice.message.tool_calls != null) {
for (const toolCall of choice.message.tool_calls) {
content.push({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
}
}
return {
content,
finishReason: {
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
raw: (_a15 = choice.finish_reason) != null ? _a15 : void 0
},
usage: convertAlibabaUsage(response.usage),
request: { body: JSON.stringify(args) },
response: {
...getResponseMetadata(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
};
const { responseHeaders, value: response } = await chunk24WS5SQV_cjs.postJsonToApi2({
url: `${this.config.baseURL}/chat/completions`,
headers: chunk24WS5SQV_cjs.combineHeaders2(this.config.headers(), options.headers),
body,
failedResponseHandler: alibabaFailedResponseHandler,
successfulResponseHandler: chunk24WS5SQV_cjs.createEventSourceResponseHandler2(
alibabaChatChunkSchema
),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
let activeText = false;
let activeReasoningId = null;
const toolCalls = [];
return {
stream: response.pipeThrough(
new TransformStream({
start(controller) {
controller.enqueue({ type: "stream-start", warnings });
},
transform(chunk, controller) {
var _a15, _b, _c, _d;
if (options.includeRawChunks) {
controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
}
if (!chunk.success) {
controller.enqueue({ type: "error", error: chunk.error });
return;
}
const value = chunk.value;
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata(value)
});
}
if (value.usage != null) {
usage = value.usage;
}
if (value.choices.length === 0) {
return;
}
const choice = value.choices[0];
const delta = choice.delta;
if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
if (activeReasoningId == null) {
if (activeText) {
controller.enqueue({ type: "text-end", id: "0" });
activeText = false;
}
activeReasoningId = chunk24WS5SQV_cjs.generateId2();
controller.enqueue({
type: "reasoning-start",
id: activeReasoningId
});
}
controller.enqueue({
type: "reasoning-delta",
id: activeReasoningId,
delta: delta.reasoning_content
});
}
if (delta.content != null && delta.content.length > 0) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = null;
}
if (!activeText) {
controller.enqueue({ type: "text-start", id: "0" });
activeText = true;
}
controller.enqueue({
type: "text-delta",
id: "0",
delta: delta.content
});
}
if (delta.tool_calls != null) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = null;
}
if (activeText) {
controller.enqueue({ type: "text-end", id: "0" });
activeText = false;
}
for (const toolCallDelta of delta.tool_calls) {
const index = (_a15 = toolCallDelta.index) != null ? _a15 : toolCalls.length;
if (toolCalls[index] == null) {
if (toolCallDelta.id == null) {
throw new chunk24WS5SQV_cjs.InvalidResponseDataError2({
data: toolCallDelta,
message: `Expected 'id' to be a string.`
});
}
if (((_b = toolCallDelta.function) == null ? void 0 : _b.name) == null) {
throw new chunk24WS5SQV_cjs.InvalidResponseDataError2({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
}
controller.enqueue({
type: "tool-input-start",
id: toolCallDelta.id,
toolName: toolCallDelta.function.name
});
toolCalls[index] = {
id: toolCallDelta.id,
type: "function",
function: {
name: toolCallDelta.function.name,
arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
},
hasFinished: false
};
const toolCall2 = toolCalls[index];
if (toolCall2.function.arguments.length > 0) {
controller.enqueue({
type: "tool-input-delta",
id: toolCall2.id,
delta: toolCall2.function.arguments
});
}
if (chunk24WS5SQV_cjs.isParsableJson2(toolCall2.function.arguments)) {
controller.enqueue({
type: "tool-input-end",
id: toolCall2.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall2.id,
toolName: toolCall2.function.name,
input: toolCall2.function.arguments
});
toolCall2.hasFinished = true;
}
continue;
}
const toolCall = toolCalls[index];
if (toolCall.hasFinished) {
continue;
}
if (((_d = toolCallDelta.function) == null ? void 0 : _d.arguments) != null) {
toolCall.function.arguments += toolCallDelta.function.arguments;
controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCallDelta.function.arguments
});
}
if (chunk24WS5SQV_cjs.isParsableJson2(toolCall.function.arguments)) {
controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
toolCall.hasFinished = true;
}
}
}
if (choice.finish_reason != null) {
finishReason = {
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
}
},
flush(controller) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
}
if (activeText) {
controller.enqueue({ type: "text-end", id: "0" });
}
controller.enqueue({
type: "finish",
finishReason,
usage: convertAlibabaUsage(usage)
});
}
})
),
request: { body: JSON.stringify(body) },
response: { headers: responseHeaders }
};
}
};
var alibabaUsageSchema = v4.z.object({
prompt_tokens: v4.z.number(),
completion_tokens: v4.z.number(),
total_tokens: v4.z.number(),
prompt_tokens_details: v4.z.object({
cached_tokens: v4.z.number().nullish(),
cache_creation_input_tokens: v4.z.number().nullish()
}).nullish(),
completion_tokens_details: v4.z.object({
reasoning_tokens: v4.z.number().nullish()
}).nullish()
});
var alibabaChatResponseSchema = v4.z.object({
id: v4.z.string().nullish(),
created: v4.z.number().nullish(),
model: v4.z.string().nullish(),
choices: v4.z.array(
v4.z.object({
message: v4.z.object({
role: v4.z.literal("assistant").nullish(),
content: v4.z.string().nullish(),
reasoning_content: v4.z.string().nullish(),
// Alibaba thinking mode
tool_calls: v4.z.array(
v4.z.object({
id: v4.z.string(),
type: v4.z.literal("function"),
function: v4.z.object({
name: v4.z.string(),
arguments: v4.z.string()
})
})
).nullish()
}),
finish_reason: v4.z.string().nullish(),
index: v4.z.number()
})
),
usage: alibabaUsageSchema.nullish()
});
var alibabaChatChunkSchema = v4.z.object({
id: v4.z.string().nullish(),
created: v4.z.number().nullish(),
model: v4.z.string().nullish(),
choices: v4.z.array(
v4.z.object({
delta: v4.z.object({
role: v4.z.enum(["assistant"]).nullish(),
content: v4.z.string().nullish(),
reasoning_content: v4.z.string().nullish(),
// Alibaba thinking mode delta
tool_calls: v4.z.array(
v4.z.object({
index: v4.z.number().nullish(),
// Index for accumulating tool calls
id: v4.z.string().nullish(),
type: v4.z.literal("function").nullish(),
function: v4.z.object({
name: v4.z.string().nullish(),
arguments: v4.z.string().nullish()
}).nullish()
})
).nullish()
}),
finish_reason: v4.z.string().nullish(),
index: v4.z.number()
})
),
usage: alibabaUsageSchema.nullish()
// Usage only appears in final chunk
});
var alibabaVideoModelOptionsSchema = chunk24WS5SQV_cjs.lazySchema2(
() => chunk24WS5SQV_cjs.zodSchema2(
v4.z.object({
negativePrompt: v4.z.string().nullish(),
audioUrl: v4.z.string().nullish(),
promptExtend: v4.z.boolean().nullish(),
shotType: v4.z.enum(["single", "multi"]).nullish(),
watermark: v4.z.boolean().nullish(),
audio: v4.z.boolean().nullish(),
referenceUrls: v4.z.array(v4.z.string()).nullish(),
pollIntervalMs: v4.z.number().positive().nullish(),
pollTimeoutMs: v4.z.number().positive().nullish()
}).passthrough()
)
);
var alibabaVideoErrorSchema = v4.z.object({
code: v4.z.string().nullish(),
message: v4.z.string(),
request_id: v4.z.string().nullish()
});
var alibabaVideoFailedResponseHandler = chunk24WS5SQV_cjs.createJsonErrorResponseHandler2({
errorSchema: alibabaVideoErrorSchema,
errorToMessage: (data) => data.message
});
var alibabaVideoCreateTaskSchema = v4.z.object({
output: v4.z.object({
task_status: v4.z.string(),
task_id: v4.z.string()
}).nullish(),
request_id: v4.z.string().nullish()
});
var alibabaVideoTaskStatusSchema = v4.z.object({
output: v4.z.object({
task_id: v4.z.string(),
task_status: v4.z.string(),
video_url: v4.z.string().nullish(),
submit_time: v4.z.string().nullish(),
scheduled_time: v4.z.string().nullish(),
end_time: v4.z.string().nullish(),
orig_prompt: v4.z.string().nullish(),
actual_prompt: v4.z.string().nullish(),
code: v4.z.string().nullish(),
message: v4.z.string().nullish()
}).nullish(),
usage: v4.z.object({
duration: v4.z.number().nullish(),
output_video_duration: v4.z.number().nullish(),
SR: v4.z.number().nullish(),
size: v4.z.string().nullish()
}).nullish(),
request_id: v4.z.string().nullish()
});
function detectMode(modelId) {
if (modelId.includes("-i2v")) return "i2v";
if (modelId.includes("-r2v")) return "r2v";
return "t2v";
}
var AlibabaVideoModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
this.maxVideosPerCall = 1;
}
get provider() {
return this.config.provider;
}
async doGenerate(options) {
var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date();
const warnings = [];
const mode = detectMode(this.modelId);
const alibabaOptions = await chunk24WS5SQV_cjs.parseProviderOptions2({
provider: "alibaba",
providerOptions: options.providerOptions,
schema: alibabaVideoModelOptionsSchema
});
const input = {};
if (options.prompt != null) {
input.prompt = options.prompt;
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.negativePrompt) != null) {
input.negative_prompt = alibabaOptions.negativePrompt;
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.audioUrl) != null) {
input.audio_url = alibabaOptions.audioUrl;
}
if (mode === "i2v" && options.image != null) {
if (options.image.type === "url") {
input.img_url = options.image.url;
} else {
const base64Data = typeof options.image.data === "string" ? options.image.data : chunk24WS5SQV_cjs.convertUint8ArrayToBase642(options.image.data);
input.img_url = base64Data;
}
}
if (mode === "r2v" && (alibabaOptions == null ? void 0 : alibabaOptions.referenceUrls) != null) {
input.reference_urls = alibabaOptions.referenceUrls;
}
const parameters = {};
if (options.duration != null) {
parameters.duration = options.duration;
}
if (options.seed != null) {
parameters.seed = options.seed;
}
if (options.resolution != null) {
if (mode === "i2v") {
const resolutionMap = {
"1280x720": "720P",
"720x1280": "720P",
"960x960": "720P",
"1088x832": "720P",
"832x1088": "720P",
"1920x1080": "1080P",
"1080x1920": "1080P",
"1440x1440": "1080P",
"1632x1248": "1080P",
"1248x1632": "1080P",
"832x480": "480P",
"480x832": "480P",
"624x624": "480P"
};
parameters.resolution = resolutionMap[options.resolution] || options.resolution;
} else {
parameters.size = options.resolution.replace("x", "*");
}
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.promptExtend) != null) {
parameters.prompt_extend = alibabaOptions.promptExtend;
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.shotType) != null) {
parameters.shot_type = alibabaOptions.shotType;
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.watermark) != null) {
parameters.watermark = alibabaOptions.watermark;
}
if ((alibabaOptions == null ? void 0 : alibabaOptions.audio) != null) {
parameters.audio = alibabaOptions.audio;
}
if (options.aspectRatio) {
warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "Alibaba video models use explicit size/resolution dimensions. Use the resolution option or providerOptions.alibaba for size control."
});
}
if (options.fps) {
warnings.push({
type: "unsupported",
feature: "fps",
details: "Alibaba video models do not support custom FPS."
});
}
if (options.n != null && options.n > 1) {
warnings.push({
type: "unsupported",
feature: "n",
details: "Alibaba video models only support generating 1 video per call."
});
}
const { value: createResponse } = await chunk24WS5SQV_cjs.postJsonToApi2({
url: `${this.config.baseURL}/api/v1/services/aigc/video-generation/video-synthesis`,
headers: chunk24WS5SQV_cjs.combineHeaders2(
await chunk24WS5SQV_cjs.resolve2(this.config.headers),
options.headers,
{
"X-DashScope-Async": "enable"
}
),
body: {
model: this.modelId,
input,
parameters
},
successfulResponseHandler: chunk24WS5SQV_cjs.createJsonResponseHandler2(
alibabaVideoCreateTaskSchema
),
failedResponseHandler: alibabaVideoFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const taskId = (_d = createResponse.output) == null ? void 0 : _d.task_id;
if (!taskId) {
throw new chunk24WS5SQV_cjs.AISDKError({
name: "ALIBABA_VIDEO_GENERATION_ERROR",
message: `No task_id returned from Alibaba API. Response: ${JSON.stringify(createResponse)}`
});
}
const pollIntervalMs = (_e = alibabaOptions == null ? void 0 : alibabaOptions.pollIntervalMs) != null ? _e : 5e3;
const pollTimeoutMs = (_f = alibabaOptions == null ? void 0 : alibabaOptions.pollTimeoutMs) != null ? _f : 6e5;
const startTime = Date.now();
let finalResponse;
let responseHeaders;
while (true) {
await chunk24WS5SQV_cjs.delay(pollIntervalMs, { abortSignal: options.abortSignal });
if (Date.now() - startTime > pollTimeoutMs) {
throw new chunk24WS5SQV_cjs.AISDKError({
name: "ALIBABA_VIDEO_GENERATION_TIMEOUT",
message: `Video generation timed out after ${pollTimeoutMs}ms`
});
}
const { value: statusResponse, responseHeaders: pollHeaders } = await chunk24WS5SQV_cjs.getFromApi({
url: `${this.config.baseURL}/api/v1/tasks/${taskId}`,
headers: chunk24WS5SQV_cjs.combineHeaders2(
await chunk24WS5SQV_cjs.resolve2(this.config.headers),
options.headers
),
successfulResponseHandler: chunk24WS5SQV_cjs.createJsonResponseHandler2(
alibabaVideoTaskStatusSchema
),
failedResponseHandler: alibabaVideoFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
responseHeaders = pollHeaders;
const taskStatus = (_g = statusResponse.output) == null ? void 0 : _g.task_status;
if (taskStatus === "SUCCEEDED") {
finalResponse = statusResponse;
break;
}
if (taskStatus === "FAILED" || taskStatus === "CANCELED") {
throw new chunk24WS5SQV_cjs.AISDKError({
name: "ALIBABA_VIDEO_GENERATION_FAILED",
message: `Video generation ${taskStatus.toLowerCase()}. Task ID: ${taskId}. ${(_i = (_h = statusResponse.output) == null ? void 0 : _h.message) != null ? _i : ""}`
});
}
}
const videoUrl = (_j = finalResponse == null ? void 0 : finalResponse.output) == null ? void 0 : _j.video_url;
if (!videoUrl) {
throw new chunk24WS5SQV_cjs.AISDKError({
name: "ALIBABA_VIDEO_GENERATION_ERROR",
message: `No video URL in response. Task ID: ${taskId}`
});
}
return {
videos: [
{
type: "url",
url: videoUrl,
mediaType: "video/mp4"
}
],
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: {
alibaba: {
taskId,
videoUrl,
...((_k = finalResponse == null ? void 0 : finalResponse.output) == null ? void 0 : _k.actual_prompt) ? { actualPrompt: finalResponse.output.actual_prompt } : {},
...(finalResponse == null ? void 0 : finalResponse.usage) ? {
usage: {
duration: finalResponse.usage.duration,
outputVideoDuration: finalResponse.usage.output_video_duration,
resolution: finalResponse.usage.SR,
size: finalResponse.usage.size
}
} : {}
}
}
};
}
};
var VERSION = "1.0.25" ;
function createAlibaba(options = {}) {
var _a15, _b;
const baseURL = (_a15 = chunk24WS5SQV_cjs.withoutTrailingSlash2(options.baseURL)) != null ? _a15 : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
const videoBaseURL = (_b = chunk24WS5SQV_cjs.withoutTrailingSlash2(options.videoBaseURL)) != null ? _b : "https://dashscope-intl.aliyuncs.com";
const getHeaders = () => chunk24WS5SQV_cjs.withUserAgentSuffix2(
{
Authorization: `Bearer ${chunk24WS5SQV_cjs.loadApiKey2({
apiKey: options.apiKey,
environmentVariableName: "ALIBABA_API_KEY",
description: "Alibaba Cloud (DashScope)"
})}`,
...options.headers
},
`ai-sdk/alibaba/${VERSION}`
);
const createLanguageModel = (modelId) => {
var _a22;
return new AlibabaLanguageModel(modelId, {
provider: "alibaba.chat",
baseURL,
headers: getHeaders,
fetch: options.fetch,
includeUsage: (_a22 = options.includeUsage) != null ? _a22 : true
});
};
const createVideoModel = (modelId) => new AlibabaVideoModel(modelId, {
provider: "alibaba.video",
baseURL: videoBaseURL,
headers: getHeaders,
fetch: options.fetch
});
const provider = function(modelId) {
if (new.target) {
throw new Error(
"The Alibaba model function cannot be called with the new keyword."
);
}
return createLanguageModel(modelId);
};
provider.specificationVersion = "v3";
provider.languageModel = createLanguageModel;
provider.chatModel = createLanguageModel;
provider.video = createVideoModel;
provider.videoModel = createVideoModel;
provider.imageModel = (modelId) => {
throw new chunk24WS5SQV_cjs.NoSuchModelError2({ modelId, modelType: "imageModel" });
};
provider.embeddingModel = (modelId) => {
throw new chunk24WS5SQV_cjs.NoSuchModelError2({ modelId, modelType: "embeddingModel" });
};
return provider;
}
createAlibaba();
var VERSION2 = "1.0.44" ;
var cerebrasErrorSchema = v4.z.object({
message: v4.z.string(),
type: v4.z.string(),
param: v4.z.string(),
code: v4.z.string()
});
var cerebrasErrorStructure = {
errorSchema: cerebrasErrorSchema,
errorToMessage: (data) => data.message
};
function createCerebras(options = {}) {
var _a15;
const baseURL = chunk24WS5SQV_cjs.withoutTrailingSlash(
(_a15 = options.baseURL) != null ? _a15 : "https://api.cerebras.ai/v1"
);
const getHeaders = () => chunk24WS5SQV_cjs.withUserAgentSuffix(
{
Authorization: `Bearer ${chunk24WS5SQV_cjs.loadApiKey({
apiKey: options.apiKey,
environmentVariableName: "CEREBRAS_API_KEY",
description: "Cerebras API key"
})}`,
...options.headers
},
`ai-sdk/cerebras/${VERSION2}`
);
const createLanguageModel = (modelId) => {
return new chunk24WS5SQV_cjs.OpenAICompatibleChatLanguageModel(modelId, {
provider: `cerebras.chat`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
errorStructure: cerebrasErrorStructure,
supportsStructuredOutputs: true
});
};
const provider = (modelId) => createLanguageModel(modelId);
provider.languageModel = createLanguageModel;
provider.chat = createLanguageModel;
provider.textEmbeddingModel = (modelId) => {
throw new chunk24WS5SQV_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
};
provider.imageModel = (modelId) => {
throw new chunk24WS5SQV_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
};
return provider;
}
createCerebras();
var DeepInfraImageModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v2";
this.maxImagesPerCall = 1;
}
get provider() {
return this.config.provider;
}
async doGenerate({
prompt,
n,
size,
aspectRatio,
seed,
providerOptions,
headers,
abortSignal
}) {
var _a15, _b, _c, _d;
const warnings = [];
const splitSize = size == null ? void 0 : size.split("x");
const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date();
const { value: response, responseHeaders } = await chunk24WS5SQV_cjs.postJsonToApi({
url: `${this.config.baseURL}/${this.modelId}`,
headers: chunk24WS5SQV_cjs.combineHeaders(this.config.headers(), headers),
body: {
prompt,
num_images: n,
...aspectRatio && { aspect_ratio: aspectRatio },
...splitSize && { width: splitSize[0], height: splitSize[1] },
...seed != null && { seed },
...(_d = providerOptions.deepinfra) != null ? _d : {}
},
failedResponseHandler: chunk24WS5SQV_cjs.createJsonErrorResponseHandler({
errorSchema: deepInfraErrorSchema,
errorToMessage: (error) => error.detail.error
}),
successfulResponseHandler: chunk24WS5SQV_cjs.createJsonResponseHandler(
deepInfraImageResponseSchema
),
abortSignal,
fetch: this.config.fetch
});
return {
images: response.images.map(
(image) => image.replace(/^data:image\/\w+;base64,/, "")
),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
};
var deepInfraErrorSchema = v4.z.object({
detail: v4.z.object({
error: v4.z.string()
})
});
var deepInfraImageResponseSchema = v4.z.object({
images: v4.z.array(v4.z.string())
});
var DeepInfraChatLanguageModel = class extends chunk24WS5SQV_cjs.OpenAICompatibleChatLanguageModel {
constructor(modelId, config) {
super(modelId, config);
}
fixUsage(usage) {
var _a15, _b;
const outputTokens = (_a15 = usage.outputTokens) != null ? _a15 : 0;
const reasoningTokens = (_b = usage.reasoningTokens) != null ? _b : 0;
if (reasoningTokens > outputTokens) {
const correctedOutputTokens = outputTokens + reasoningTokens;
return {
...usage,
outputTokens: correctedOutputTokens,
totalTokens: usage.totalTokens != null ? usage.totalTokens + reasoningTokens : void 0
};
}
return usage;
}
async doGenerate(options) {
const result = await super.doGenerate(options);
return {
...result,
usage: this.fixUsage(result.usage)
};
}
async doStream(options) {
const result = await super.doStream(options);
const fixUsage = this.fixUsage.bind(this);
const transformedStream = result.stream.pipeThrough(
new TransformStream({
transform(chunk, controller) {
if (chunk.type === "finish") {
controller.enqueue({
...chunk,
usage: fixUsage(chunk.usage)
});
} else {
controller.enqueue(chunk);
}
}
})
);
return {
...result,
stream: transformedStream
};
}
};
var VERSION3 = "1.0.42" ;
function createDeepInfra(options = {}) {
var _a15;
const baseURL = chunk24WS5SQV_cjs.withoutTrailingSlash(
(_a15 = options.baseURL) != null ? _a15 : "https://api.deepinfra.com/v1"
);
const getHeaders = () => chunk24WS5SQV_cjs.withUserAgentSuffix(
{
Authorization: `Bearer ${chunk24WS5SQV_cjs.loadApiKey({
apiKey: options.apiKey,
environmentVariableName: "DEEPINFRA_API_KEY",
description: "DeepInfra's API key"
})}`,
...options.headers
},
`ai-sdk/deepinfra/${VERSION3}`
);
const getCommonModelConfig = (modelType) => ({
provider: `deepinfra.${modelType}`,
url: ({ path }) => `${baseURL}/openai${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createChatModel = (modelId) => {
return new DeepInfraChatLanguageModel(
modelId,
getCommonModelConfig("chat")
);
};
const createCompletionModel = (modelId) => new chunk24WS5SQV_cjs.OpenAICompatibleCompletionLanguageModel(
modelId,
getCommonModelConfig("completion")
);
const createTextEmbeddingModel = (modelId) => new chunk24WS5SQV_cjs.OpenAICompatibleEmbeddingModel(
modelId,
getCommonModelConfig("embedding")
);
const createImageModel = (modelId) => new DeepInfraImageModel(modelId, {
...getCommonModelConfig("image"),
baseURL: baseURL ? `${baseURL}/inference` : "https://api.deepinfra.com/v1/inference"
});
const provider = (modelId) => createChatModel(modelId);
provider.completionModel = createCompletionModel;
provider.chatModel = createChatModel;
provider.image = createImageModel;
provider.imageModel = createImageModel;
provider.languageModel = createChatModel;
provider.textEmbeddingModel = createTextEmbeddingModel;
return provider;
}
createDeepInfra();
function convertToDeepSeekChatMessages({
prompt,
responseFormat,
modelId
}) {
const isDeepSeekV4 = modelId.includes("deepseek-v4");
const messages = [];
const warnings = [];
if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
if (responseFormat.schema == null) {
messages.push({
role: "system",
content: "Return JSON."
});
} else {
messages.push({
role: "system",
content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema)
});
}
}
let lastUserMessageIndex = -1;
for (let i = prompt.length - 1; i >= 0; i--) {
if (prompt[i].role === "user") {
lastUserMessageIndex = i;
break;
}
}
let index = -1;
for (const { role, content } of prompt) {
index++;
switch (role) {
case "system": {
messages.push({ role: "system", content });
break;
}
case "user": {
let userContent = "";
for (const part of content) {
if (part.type === "text") {
userContent += part.text;
} else {
warnings.push({
type: "other",
message: `Unsupported user message part type: ${part.type}`
});
}
}
messages.push({
role: "user",
content: userContent
});
break;
}
case "assistant": {
let text = "";
let reasoning;
const toolCalls = [];
for (const part of content) {
switch (part.type) {
case "text": {
text += part.text;
break;
}
case "reasoning": {
if (index <= lastUserMessageIndex && !isDeepSeekV4) {
break;
}
if (reasoning == null) {
reasoning = part.text;
} else {
reasoning += part.text;
}
break;
}
case "tool-call": {
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
break;
}
}
}
messages.push({
role: "assistant",
content: text,
reasoning_content: reasoning != null ? reasoning : isDeepSeekV4 ? "" : void 0,
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool": {
for (const toolResponse of content) {
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "content":
case "json":
case "error-json":
contentValue = JSON.stringify(output.value);
break;
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: contentValue
});
}
break;
}
default: {
warnings.push({
type: "other",
message: `Unsupported message role: ${role}`
});
break;
}
}
}
return { messages, warnings };
}
var tokenUsageSchema = v4.z.object({
prompt_tokens: v4.z.number().nullish(),
completion_tokens: v4.z.number().nullish(),
prompt_cache_hit_tokens: v4.z.number().nullish(),
prompt_cache_miss_tokens: v4.z.number().nullish(),
total_tokens: v4.z.number().nullish(),
completion_tokens_details: v4.z.object({
reasoning_tokens: v4.z.number().nullish()
}).nullish()
}).nullish();
var deepSeekErrorSchema = v4.z.object({
error: v4.z.object({
message: v4.z.string(),
type: v4.z.string().nullish(),
param: v4.z.any().nullish(),
code: v4.z.union([v4.z.string(), v4.z.number()]).nullish()
})
});
var deepseekChatResponseSchema = v4.z.object({
id: v4.z.string().nullish(),
created: v4.z.number().nullish(),
model: v4.z.string().nullish(),
choices: v4.z.array(
v4.z.object({
message: v4.z.object({
role: v4.z.literal("assistant").nullish(),
content: v4.z.string().nullish(),
reasoning_content: v4.z.string().nullish(),
tool_calls: v4.z.array(
v4.z.object({
id: v4.z.string().nullish(),
function: v4.z.object({
name: v4.z.string(),
arguments: v4.z.string()
})
})
).nullish()
}),
finish_reason: v4.z.string().nullish()
})
),
usage: tokenUsageSchema
});
var deepseekChatChunkSchema = chunk24WS5SQV_cjs.lazySchema(
() => chunk24WS5SQV_cjs.zodSchema(
v4.z.union([
v4.z.object({
id: v4.z.string().nullish(),
created: v4.z.number().nullish(),
model: v4.z.string().nullish(),
choices: v4.z.array(
v4.z.object({
delta: v4.z.object({
role: v4.z.enum(["assistant"]).nullish(),
content: v4.z.string().nullish(),
reasoning_content: v4.z.string().nullish(),
tool_calls: v4.z.array(
v4.z.object({
index: v4.z.number()