🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style: add more videoGen provider support (#13428)
Zhijie He9f2d7daa177f
diff --git a/locales/en-US/video.json b/locales/en-US/video.jsonindex d9303748868..d05c2823add 100644--- a/locales/en-US/video.json+++ b/locales/en-US/video.json@@ -12,6 +12,7 @@"config.resolution.label": "Resolution","config.seed.label": "Seed","config.seed.random": "Random",+ "config.size.label": "Size","generation.actions.copyError": "Copy Error Message","generation.actions.errorCopied": "Error Message Copied to Clipboard","generation.actions.errorCopyFailed": "Failed to Copy Error Message",diff --git a/locales/zh-CN/video.json b/locales/zh-CN/video.jsonindex 1d25890be9a..a5af8201f6b 100644--- a/locales/zh-CN/video.json+++ b/locales/zh-CN/video.json@@ -12,6 +12,7 @@"config.resolution.label": "分辨率","config.seed.label": "种子","config.seed.random": "随机",+ "config.size.label": "尺寸","generation.actions.copyError": "复制错误信息","generation.actions.errorCopied": "错误信息已复制到剪贴板","generation.actions.errorCopyFailed": "复制错误信息失败",diff --git a/package.json b/package.jsonindex 8352b035243..8c0bf1cba78 100644--- a/package.json+++ b/package.json@@ -108,7 +108,7 @@"test-app": "vitest run","test-app:coverage": "vitest --coverage --silent='passed-only'","tunnel:cloudflare": "cloudflared tunnel --url http://localhost:3010",- "tunnel:ngrok": "ngrok http http://localhost:3011",+ "tunnel:ngrok": "ngrok http http://localhost:3010","type-check": "tsgo --noEmit","type-check:tsc": "tsc --noEmit","workflow:cdn": "tsx ./scripts/cdnWorkflow/index.ts",diff --git a/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts b/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.tsindex 3d4a6ce8700..6b325fa5008 100644--- a/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts+++ b/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts@@ -709,5 +709,87 @@ describe('AiInfraRepos', () => {// 无 settingsexpect(merged?.settings).toBeUndefined();});++ it('should preserve builtin model type when DB record has wrong type (e.g. video model stored as chat)', async () => {+ const providerId = 'openai';++ // DB record from remote fetch incorrectly defaulted to 'chat'+ const userModels: AiProviderModelListItem[] = [+ {+ id: 'sora-2',+ type: 'chat',+ enabled: true,+ },+ ];++ // Builtin correctly defines it as 'video'+ const builtinModels: AiProviderModelListItem[] = [+ {+ id: 'sora-2',+ type: 'video',+ enabled: true,+ } as AiProviderModelListItem,+ ];++ vi.spyOn(repo.aiModelModel, 'getModelListByProviderId').mockResolvedValue(userModels);+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue(builtinModels);++ const result = await repo.getAiProviderModelList(providerId);++ const merged = result.find((m) => m.id === 'sora-2');+ expect(merged).toBeDefined();+ expect(merged!.type).toBe('video');+ });++ it('should preserve builtin type for all model types (image, embedding, tts, stt)', async () => {+ const providerId = 'openai';++ // DB records all incorrectly stored as 'chat'+ const userModels: AiProviderModelListItem[] = [+ { id: 'dall-e-3', type: 'chat', enabled: true },+ { id: 'text-embedding-3-small', type: 'chat', enabled: true },+ { id: 'tts-1', type: 'chat', enabled: true },+ { id: 'whisper-1', type: 'chat', enabled: true },+ ] as AiProviderModelListItem[];++ const builtinModels: AiProviderModelListItem[] = [+ { id: 'dall-e-3', type: 'image', enabled: true },+ { id: 'text-embedding-3-small', type: 'embedding', enabled: true },+ { id: 'tts-1', type: 'tts', enabled: true },+ { id: 'whisper-1', type: 'stt', enabled: true },+ ] as AiProviderModelListItem[];++ vi.spyOn(repo.aiModelModel, 'getModelListByProviderId').mockResolvedValue(userModels);+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue(builtinModels);++ const result = await repo.getAiProviderModelList(providerId);++ expect(result.find((m) => m.id === 'dall-e-3')!.type).toBe('image');+ expect(result.find((m) => m.id === 'text-embedding-3-small')!.type).toBe('embedding');+ expect(result.find((m) => m.id === 'tts-1')!.type).toBe('tts');+ expect(result.find((m) => m.id === 'whisper-1')!.type).toBe('stt');+ });++ it('should keep user type for custom models not in builtin list', async () => {+ const providerId = 'openai';++ const userModels: AiProviderModelListItem[] = [+ { id: 'my-custom-model', type: 'chat', enabled: true },+ ] as AiProviderModelListItem[];++ // Builtin list does not contain this model+ const builtinModels: AiProviderModelListItem[] = [+ { id: 'gpt-4', type: 'chat', enabled: true },+ ] as AiProviderModelListItem[];++ vi.spyOn(repo.aiModelModel, 'getModelListByProviderId').mockResolvedValue(userModels);+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue(builtinModels);++ const result = await repo.getAiProviderModelList(providerId);++ const custom = result.find((m) => m.id === 'my-custom-model');+ expect(custom).toBeDefined();+ expect(custom!.type).toBe('chat');+ });});});diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.tsindex c5d9c5e1903..dd8f660f35b 100644--- a/packages/database/src/repositories/aiInfra/index.ts+++ b/packages/database/src/repositories/aiInfra/index.ts@@ -408,6 +408,16 @@ export class AiInfraRepos {// Not modifying search settings here doesn't affect usage, but done for data consistency on getlet mergedModel = mergeArrayById(defaultModels, aiModels) as AiProviderModelListItem[];+ // Model type (chat/video/image/embedding/tts/stt) should always come from builtin config,+ // because remote-fetched models from provider API (e.g. OpenAI /v1/models) don't return+ // a type field, causing them to fallback to 'chat' and get saved to DB with wrong type.+ // e.g. sora-2 is a video model but gets stored as 'chat' after "Fetch models".+ const builtinTypeMap = new Map(defaultModels.map((m) => [m.id, m.type]));+ for (const m of mergedModel) {+ const builtinType = builtinTypeMap.get(m.id);+ if (builtinType) m.type = builtinType;+ }+// Filter out DB residual models that are no longer in the builtin list for branding providerif (providerId === BRANDING_PROVIDER) {const builtinIds = new Set(defaultModels.map((m) => m.id));diff --git a/packages/model-bank/src/aiModels/google.ts b/packages/model-bank/src/aiModels/google.tsindex 1aee242cc66..922810aec26 100644--- a/packages/model-bank/src/aiModels/google.ts+++ b/packages/model-bank/src/aiModels/google.ts@@ -1,5 +1,5 @@import { type ModelParamsSchema } from '../standard-parameters';-import { type AIChatModelCard, type AIImageModelCard } from '../types';+import { type AIChatModelCard, type AIImageModelCard, type AIVideoModelCard } from '../types';/*** gemini implicit caching not extra cost@@ -869,6 +869,155 @@ const googleImageModels: AIImageModelCard[] = [},},];-export const allModels = [...googleChatModels, ...googleImageModels];++const googleVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Our latest video generation model, available to developers on the paid tier of the Gemini API.',+ displayName: 'Veo 3.1 Generate Preview',+ enabled: true,+ id: 'veo-3.1-generate-preview',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16'],+ },+ duration: { default: 8, enum: [4, 6, 8] },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720p',+ enum: ['720p', '1080p', '4k'],+ },+ seed: { default: null },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.6, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2026-01-13',+ type: 'video',+ },+ {+ description:+ 'Our latest video generation model, available to developers on the paid tier of the Gemini API.',+ displayName: 'Veo 3.1 Fast Generate Preview',+ enabled: true,+ id: 'veo-3.1-fast-generate-preview',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16'],+ },+ duration: { default: 8, enum: [4, 6, 8] },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720p',+ enum: ['720p', '1080p', '4k'],+ },+ seed: { default: null },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.35, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2026-01-13',+ type: 'video',+ },+ {+ description:+ 'Our stable video generation model, available to developers on the paid tier of the Gemini API.',+ displayName: 'Veo 3.0 Generate 001',+ enabled: true,+ id: 'veo-3.0-generate-001',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16'],+ },+ duration: { default: 8, enum: [8] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720p',+ enum: ['720p', '1080p'],+ },+ seed: { default: null },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.4, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-11-11',+ type: 'video',+ },+ {+ description:+ 'Our stable video generation model, available to developers on the paid tier of the Gemini API.',+ displayName: 'Veo 3.0 Fast Generate 001',+ enabled: true,+ id: 'veo-3.0-fast-generate-001',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16'],+ },+ duration: { default: 8, enum: [8] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720p',+ enum: ['720p', '1080p'],+ },+ seed: { default: null },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.15, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-11-11',+ type: 'video',+ },+ {+ description:+ 'Our state-of-the-art video generation model, available to developers on the paid tier of the Gemini API.',+ displayName: 'Veo 2.0 Generate 001',+ id: 'veo-2.0-generate-001',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16'],+ },+ duration: { default: 8, max: 8, min: 5 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720p',+ enum: ['720p', '1080p'],+ },+ seed: { default: null },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.35, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-04-09',+ type: 'video',+ },+];++export const allModels = [...googleChatModels, ...googleImageModels, ...googleVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/minimax.ts b/packages/model-bank/src/aiModels/minimax.tsindex 14f4c812291..ed8a045acba 100644--- a/packages/model-bank/src/aiModels/minimax.ts+++ b/packages/model-bank/src/aiModels/minimax.ts@@ -1,4 +1,8 @@-import { type AIChatModelCard, type AIImageModelCard } from '../types/aiModel';+import {+ type AIChatModelCard,+ type AIImageModelCard,+ type AIVideoModelCard,+} from '../types/aiModel';const minimaxChatModels: AIChatModelCard[] = [{@@ -336,6 +340,183 @@ const minimaxImageModels: AIImageModelCard[] = [},];-export const allModels = [...minimaxChatModels, ...minimaxImageModels];+const minimaxVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Brand-new video generation model with comprehensive upgrades in body motion, physical realism, and instruction following.',+ displayName: 'MiniMax Hailuo 2.3 Fast',+ enabled: true,+ id: 'MiniMax-Hailuo-2.3-Fast',+ parameters: {+ duration: { default: 6, enum: [6, 10] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '768P',+ enum: ['768P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1.35, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-10-28',+ type: 'video',+ },+ {+ description:+ 'Brand-new video generation model with comprehensive upgrades in body motion, physical realism, and instruction following.',+ displayName: 'MiniMax Hailuo 2.3',+ enabled: true,+ id: 'MiniMax-Hailuo-2.3',+ parameters: {+ duration: { default: 6, enum: [6, 10] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '768P',+ enum: ['768P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-10-28',+ type: 'video',+ },+ {+ description:+ 'The next-generation video generation model, MiniMax Hailuo 02, has been officially released, supporting 1080P resolution and 10-second video generation.',+ displayName: 'MiniMax Hailuo 02',+ enabled: true,+ id: 'MiniMax-Hailuo-02',+ parameters: {+ duration: { default: 6, enum: [6, 10] },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '768P',+ enum: ['512P', '768P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.6, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'A director-level video generation model has been officially released, offering improved adherence to camera movement instructions and cinematic shot storytelling language.',+ displayName: 'I2V 01 Director',+ id: 'I2V-01-Director',+ parameters: {+ duration: { default: 6, enum: [6] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ releasedAt: '2025-02-11',+ type: 'video',+ },+ {+ description:+ 'A director-level video generation model has been officially released, offering improved adherence to camera movement instructions and cinematic shot storytelling language.',+ displayName: 'T2V 01 Director',+ id: 'T2V-01-Director',+ parameters: {+ duration: { default: 6, enum: [6] },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ releasedAt: '2025-02-11',+ type: 'video',+ },+ {+ description: 'Enhanced character performance: more stable, smoother, and more vivid.',+ displayName: 'I2V 01 Live',+ id: 'I2V-01-live',+ parameters: {+ duration: { default: 6, enum: [6] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ releasedAt: '2025-03-03',+ type: 'video',+ },+ {+ description: 'The foundational image-to-video model of the 01 series.',+ displayName: 'I2V 01',+ id: 'I2V-01',+ parameters: {+ duration: { default: 6, enum: [6] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ releasedAt: '2025-03-03',+ type: 'video',+ },+ {+ description: 'The foundational reference-to-video model of the 01 series.',+ displayName: 'S2V 01',+ id: 'S2V-01',+ parameters: {+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ releasedAt: '2025-01-10',+ type: 'video',+ },+ {+ description: 'The foundational text-to-video model of the 01 series.',+ displayName: 'T2V 01',+ id: 'T2V-01',+ parameters: {+ duration: { default: 6, enum: [6] },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ releasedAt: '2025-03-03',+ type: 'video',+ },+];++export const allModels = [...minimaxChatModels, ...minimaxImageModels, ...minimaxVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/openai.ts b/packages/model-bank/src/aiModels/openai.tsindex 08ba31bb764..8464d14e659 100644--- a/packages/model-bank/src/aiModels/openai.ts+++ b/packages/model-bank/src/aiModels/openai.ts@@ -6,6 +6,7 @@ import {type AIRealtimeModelCard,type AISTTModelCard,type AITTSModelCard,+ type AIVideoModelCard,} from '../types/aiModel';export const gptImage1ParamsSchema: ModelParamsSchema = {@@ -1686,6 +1687,55 @@ export const openaiRealtimeModels: AIRealtimeModelCard[] = [},];+export const openaiVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Sora 2 is our new powerful media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',+ displayName: 'Sora 2',+ enabled: true,+ id: 'sora-2',+ parameters: {+ duration: { default: 4, enum: [4, 8, 12] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '720x1280',+ enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],+ },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-08',+ type: 'video',+ },+ {+ description:+ 'Sora 2 Pro is our state-of-the-art, most advanced media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',+ displayName: 'Sora 2 Pro',+ enabled: true,+ id: 'sora-2-pro',+ parameters: {+ duration: { default: 4, enum: [4, 8, 12] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '720x1280',+ enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],+ },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-10-06',+ type: 'video',+ },+];+export const allModels = [...openaiChatModels,...openaiEmbeddingModels,@@ -1693,6 +1743,7 @@ export const allModels = [...openaiSTTModels,...openaiImageModels,...openaiRealtimeModels,+ ...openaiVideoModels,];export default allModels;diff --git a/packages/model-bank/src/aiModels/qwen.ts b/packages/model-bank/src/aiModels/qwen.tsindex 2c8fa066f9a..3a5b030f61a 100644--- a/packages/model-bank/src/aiModels/qwen.ts+++ b/packages/model-bank/src/aiModels/qwen.ts@@ -1,4 +1,8 @@-import { type AIChatModelCard, type AIImageModelCard } from '../types/aiModel';+import {+ type AIChatModelCard,+ type AIImageModelCard,+ type AIVideoModelCard,+} from '../types/aiModel';// https://help.aliyun.com/zh/model-studio/models?spm=a2c4g.11186623@@ -3481,6 +3485,1158 @@ const qwenImageModels: AIImageModelCard[] = [},];-export const allModels = [...qwenChatModels, ...qwenImageModels];+const qwenVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Wanxiang 2.6 introduces multi-shot narrative capabilities, while also supporting automatic voiceover generation and the ability to incorporate custom audio files.',+ displayName: 'Wan2.6 I2V Flash',+ enabled: true,+ id: 'wan2.6-i2v-flash',+ parameters: {+ duration: { default: 5, max: 15, min: 2 },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '1080P',+ enum: ['720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2026-01-17',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.6 introduces multi-shot narrative capabilities, while also supporting automatic voiceover generation and the ability to incorporate custom audio files.',+ displayName: 'Wan2.6 I2V',+ id: 'wan2.6-i2v',+ parameters: {+ duration: { default: 5, max: 15, min: 2 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '1080P',+ enum: ['720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-16',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.6 Reference-to-Video – Flash offers faster generation and better cost performance. It supports referencing specific characters or any objects, accurately maintaining consistency in appearance and voice, and enables multi-character reference for co-performance.',+ displayName: 'Wan2.6 R2V Flash',+ enabled: true,+ id: 'wan2.6-r2v-flash',+ parameters: {+ duration: { default: 5, max: 10, min: 2 },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '1280x720',+ '720x1280',+ '960x960',+ '1088x832',+ '832x1088',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1632x1248',+ '1248x1632',+ ],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-16',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.6 Reference-to-Video supports referencing specific characters or any objects, accurately maintaining consistency in appearance and voice, and enabling multi-character reference for co-performance. Note: When using videos as references, the input video will also be counted toward the cost. Please refer to the model pricing documentation for details.',+ displayName: 'Wan2.6 R2V',+ id: 'wan2.6-r2v',+ parameters: {+ duration: { default: 5, max: 10, min: 2 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '1280x720',+ '720x1280',+ '960x960',+ '1088x832',+ '832x1088',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1632x1248',+ '1248x1632',+ ],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-16',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.6 introduces multi-shot narrative capabilities, while also supporting automatic voiceover generation and the ability to incorporate custom audio files.',+ displayName: 'Wan2.6 T2V',+ enabled: true,+ id: 'wan2.6-t2v',+ parameters: {+ duration: { default: 5, max: 15, min: 2 },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '1280x720',+ '720x1280',+ '960x960',+ '1088x832',+ '832x1088',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1632x1248',+ '1248x1632',+ ],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-16',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.5 Preview supports automatic voiceover generation and the ability to incorporate custom audio files.',+ displayName: 'Wan2.5 I2V Preview',+ id: 'wan2.5-i2v-preview',+ parameters: {+ imageUrl: {+ default: null,+ },+ duration: { default: 5, enum: [5, 10] },+ prompt: { default: '' },+ resolution: {+ default: '1080P',+ enum: ['480P', '720P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-09-23',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.5 Preview supports automatic voiceover generation and the ability to incorporate custom audio files.',+ displayName: 'Wan2.5 T2V Preview',+ id: 'wan2.5-t2v-preview',+ parameters: {+ duration: { default: 5, enum: [5, 10] },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '848x480',+ '480x832',+ '624x624',+ '1280x720',+ '720x1280',+ '960x960',+ '1088x832',+ '832x1088',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1632x1248',+ '1248x1632',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-09-23',+ type: 'video',+ },+ {+ description: 'Wanxiang 2.2 Speed Edition',+ displayName: 'Wan2.2 KF2V Flash',+ id: 'wan2.2-kf2v-flash',+ parameters: {+ duration: { default: 5, enum: [5] },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['480P', '720P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.2, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-09-12',+ type: 'video',+ },+ {+ description: 'Wanxiang 2.2 Plus Edition',+ displayName: 'Wan2.2 KF2V Plus',+ id: 'wan2.2-kf2v-plus',+ parameters: {+ duration: { default: 5, enum: [5] },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-09-12',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.2 Speed Edition delivers ultra-fast generation, with more accurate prompt understanding and camera control. It maintains consistency of visual elements while significantly improving overall stability and success rate.',+ displayName: 'Wan2.2 I2V Flash',+ id: 'wan2.2-i2v-flash',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['480P', '720P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.2, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-08-11',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.2 Pro Edition offers more accurate prompt understanding and controllable camera movements. It maintains consistency of visual elements while significantly improving stability and success rate, and generates richer, more detailed content.',+ displayName: 'Wan2.2 I2V Plus',+ id: 'wan2.2-i2v-plus',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '1080P',+ enum: ['480P', '1080P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-07-28',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.2 Pro Edition provides more accurate prompt understanding, delivers stable and smooth motion generation, and produces richer, more detailed visuals.',+ displayName: 'Wan2.2 T2V Plus',+ id: 'wan2.2-t2v-plus',+ parameters: {+ duration: { default: 5, enum: [5] },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '848x480',+ '480x832',+ '624x624',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1632x1248',+ '1248x1632',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-07-28',+ type: 'video',+ },+ {+ description: 'Wanxiang 2.1 Speed Edition offers high cost-performance.',+ displayName: 'Wanxiang2.1 I2V Turbo',+ id: 'wanx2.1-i2v-turbo',+ parameters: {+ duration: { default: 5, enum: [3, 4, 5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['480P', '720P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.24, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-02-25',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.1 Pro Edition delivers more visually refined and higher-quality imagery.',+ displayName: 'Wanxiang2.1 I2V Plus',+ id: 'wanx2.1-i2v-plus',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-01-17',+ type: 'video',+ },+ {+ description: 'Wanxiang 2.1 Speed Edition offers excellent cost-performance.',+ displayName: 'Wanxiang2.1 T2V Turbo',+ id: 'wanx2.1-t2v-turbo',+ parameters: {+ duration: { default: 5, enum: [5] },+ prompt: { default: '' },+ size: {+ default: '1280x720',+ enum: [+ '848x480',+ '480x832',+ '624x624',+ '1280x720',+ '720x1280',+ '960x960',+ '1088x832',+ '832x1088',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.24, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-01-08',+ type: 'video',+ },+ {+ description:+ 'Wanxiang 2.1 Pro Edition delivers richer visual texture and higher-quality imagery.',+ displayName: 'Wanxiang2.1 T2V Plus',+ id: 'wanx2.1-t2v-plus',+ parameters: {+ duration: { default: 5, enum: [5] },+ prompt: { default: '' },+ size: {+ default: '1280x720',+ enum: ['1280x720', '720x1280', '960x960', '1088x832', '832x1088'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-01-08',+ type: 'video',+ },+ {+ description:+ 'Intelligent storyboarding understands scene transitions within scripts, automatically arranging camera positions and shot types. A native multimodal framework ensures audiovisual consistency. Removes duration constraints, enabling more flexible multi-shot storytelling.',+ displayName: 'Kling V3 Video Generation',+ enabled: true,+ id: 'kling/kling-v3-video-generation',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16', '1:1'],+ },+ duration: { default: 5, max: 12, min: 3 },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '1080p',+ enum: ['720p', '1080p'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.9, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'New “All-in-One Reference” feature supports 3–8 second videos or multiple images to anchor character elements. Can match original audio and lip movements for authentic character representation. Enhances video consistency and dynamic expression. Supports audiovisual synchronization and intelligent storyboarding.',+ displayName: 'Kling V3 Omni Video Generation',+ enabled: true,+ id: 'kling/kling-v3-omni-video-generation',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16', '1:1'],+ },+ duration: { default: 5, max: 12, min: 3 },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '1080p',+ enum: ['720p', '1080p'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.9, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Enter a text prompt to generate video. ViduQ3-Pro text-to-video is a flagship-level audio-visual native model. Supports up to 16 seconds of synchronized audio-visual generation, allowing free multi-shot switching while precisely controlling pacing, emotion, and narrative continuity. With a leading parameter scale, it delivers exceptional image quality, character consistency, and emotional expression, meeting cinematic standards. Ideal for professional production scenarios such as advertising (e-commerce, TVC, performance campaigns), animated series, live-action drama, and games.',+ displayName: 'Vidu Q3 Pro Text-to-Video',+ enabled: true,+ id: 'vidu/viduq3-pro_text2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ generateAudio: { default: true },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '960x528',+ '528x960',+ '720x720',+ '816x608',+ '608x816',+ '1280x720',+ '720x1280',+ '960x960',+ '1104x816',+ '816x1104',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1674x1238',+ '1238x1674',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.78125, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Enter a text prompt to generate video. ViduQ3-Turbo text-to-video is a high-performance accelerated model. It offers extremely fast generation while maintaining high-quality visuals and dynamic expression, excelling in action scenes, emotional rendering, and semantic understanding. Cost-effective and well-suited for casual entertainment scenarios such as social media images, AI companions, and special effects assets.',+ displayName: 'Vidu Q3 Turbo Text-to-Video',+ id: 'vidu/viduq3-turbo_text2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ generateAudio: { default: true },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '960x528',+ '528x960',+ '720x720',+ '816x608',+ '608x816',+ '1280x720',+ '720x1280',+ '960x960',+ '1104x816',+ '816x1104',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1674x1238',+ '1238x1674',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.375, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Enter a text prompt to generate video. ViduQ2 text-to-video is a model designed for precise instruction adherence and nuanced emotion capture. It offers outstanding narrative control, accurately interpreting and expressing micro-expression changes; features rich cinematic language, smooth camera movements, and strong visual tension. Widely applicable to film and animation, advertising and e-commerce, short dramas, and cultural tourism industries.',+ displayName: 'Vidu Q2 Turbo Text-to-Video',+ id: 'vidu/viduq2_text2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '960x528',+ '528x960',+ '720x720',+ '816x608',+ '608x816',+ '1280x720',+ '720x1280',+ '960x960',+ '1104x816',+ '816x1104',+ '1920x1080',+ '1080x1920',+ '1440x1440',+ '1674x1238',+ '1238x1674',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.21875, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input an image and a text description to generate video. ViduQ3-Pro image-to-video is a flagship-level audio-visual native model. It supports up to 16 seconds of synchronized audio-visual generation, enabling free multi-shot switching while precisely controlling pacing, emotion, and narrative continuity. With a leading parameter scale, it delivers exceptional image quality, character consistency, and emotional expression, meeting cinematic standards. Ideal for professional production scenarios such as advertising (e-commerce, TVC, performance campaigns), animated series, live-action drama, and games.',+ displayName: 'Vidu Q3 Pro Image-to-Video',+ enabled: true,+ id: 'vidu/viduq3-pro_img2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.78125, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input an image and a text description to generate video. ViduQ3-Turbo image-to-video is a high-performance accelerated model. It offers extremely fast generation while maintaining high-quality visuals and dynamic expression, excelling in action scenes, emotional rendering, and semantic understanding. Cost-effective and ideal for casual entertainment scenarios such as social media images, AI companions, and special effects assets.',+ displayName: 'Vidu Q3 Turbo Image-to-Video',+ id: 'vidu/viduq3-turbo_img2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.375, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input an image and a text description to generate video. ViduQ2-Pro image-to-video is the world’s first “Everything Can Be Referenced” video model. It supports six reference dimensions—effects, expressions, textures, actions, characters, and scenes—enabling fully evolved video editing. Through controllable addition, deletion, and modification, it achieves fine-grained video editing, designed as a production-grade creation engine for animated series, short dramas, and film production.',+ displayName: 'Vidu Q2 Pro Image-to-Video',+ id: 'vidu/viduq2-pro_img2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.34375, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input an image and a text description to generate video. ViduQ2-Turbo image-to-video is an ultra-fast generation engine. A 5-second 720P video can be generated in as little as 19 seconds, and a 5-second 1080P video in about 27 seconds. Character actions and expressions are natural and realistic, delivering strong authenticity and excellent performance in high-dynamic scenes such as action sequences, with wide-ranging motion.',+ displayName: 'Vidu Q2 Turbo Image-to-Video',+ id: 'vidu/viduq2-turbo_img2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.25, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input the first and last frame images along with a text description to generate video. ViduQ3-Pro keyframe-to-video is a flagship-level audio-visual native model. It supports up to 16 seconds of synchronized audio-visual generation, enabling free multi-shot switching while precisely controlling pacing, emotion, and narrative continuity. With a leading parameter scale, it delivers exceptional image quality, character consistency, and emotional expression, meeting cinematic standards. Ideal for professional production scenarios such as advertising (e-commerce, TVC, performance campaigns), animated series, live-action drama, and games.',+ displayName: 'Vidu Q3 Pro Start-to-End Video',+ enabled: true,+ id: 'vidu/viduq3-pro_start-end2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.78125, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input the first and last frame images along with a text description to generate video. ViduQ3-Turbo keyframe-to-video is a high-performance accelerated model. It delivers extremely fast generation while maintaining high-quality visuals and dynamic expression, excelling in action scenes, emotional rendering, and semantic understanding. Cost-effective and ideal for casual entertainment scenarios such as social media images, AI companions, and special effects assets.',+ displayName: 'Vidu Q3 Turbo Start-to-End Video',+ id: 'vidu/viduq3-turbo_start-end2video',+ parameters: {+ duration: { default: 5, max: 16, min: 1 },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.375, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input the first and last frame images along with a text description to generate video. ViduQ2-Pro keyframe-to-video is the world’s first “Everything Can Be Referenced” video model. It supports six reference dimensions—effects, expressions, textures, actions, characters, and scenes—enabling fully evolved video editing. Through controllable addition, deletion, and modification, it achieves fine-grained video editing, designed as a production-grade creation engine for animated series, short dramas, and film production.',+ displayName: 'Vidu Q2 Pro Start-to-End Video',+ id: 'vidu/viduq2-pro_start-end2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.34375, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input the first and last frame images along with a text description to generate video. ViduQ2-Turbo keyframe-to-video is an ultra-fast generation engine. A 5-second 720P video can be produced in as little as 19 seconds, and a 5-second 1080P video in about 27 seconds. Character actions and expressions are natural and realistic, with strong authenticity, excelling in high-dynamic scenes such as action sequences, and supporting wide-ranging motion.',+ displayName: 'Vidu Q2 Turbo Start-to-End Video',+ id: 'vidu/viduq2-turbo_start-end2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ endImageUrl: {+ default: null,+ },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.25, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input reference videos, images, and a text description to generate video. ViduQ2-Pro reference-to-video is the world’s first “Everything Can Be Referenced” video model. It supports six reference dimensions—effects, expressions, textures, actions, characters, and scenes—enabling fully evolved video editing. Through controllable addition, deletion, and modification, it achieves fine-grained video editing, designed as a production-grade creation engine for animated series, short dramas, and film production.',+ displayName: 'Vidu Q2 Pro Reference-to-Video',+ id: 'vidu/viduq2-pro_reference2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '960x540',+ '720x540',+ '540x540',+ '540x720',+ '540x960',+ '1280x720',+ '960x720',+ '720x720',+ '720x960',+ '720x1280',+ '1920x1080',+ '1440x1080',+ '1080x1080',+ '1080x1440',+ '1080x1920',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.3125, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input reference images along with a text description to generate video. ViduQ2 reference-to-video is a model designed for precise instruction adherence and nuanced emotion capture. It offers outstanding narrative control, accurately interpreting and expressing micro-expression changes; features rich cinematic language, smooth camera movements, and strong visual tension. Widely applicable to film and animation, advertising and e-commerce, short dramas, and cultural tourism industries.',+ displayName: 'Vidu Q2 Reference-to-Video',+ id: 'vidu/viduq2_reference2video',+ parameters: {+ duration: { default: 5, max: 10, min: 1 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['540P', '720P', '1080P'],+ },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '960x540',+ '720x540',+ '540x540',+ '540x720',+ '540x960',+ '1280x720',+ '960x720',+ '720x720',+ '720x960',+ '720x1280',+ '1920x1080',+ '1440x1080',+ '1080x1080',+ '1080x1440',+ '1080x1920',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.28125, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'V6 is PixVerse’s new model launched at the end of March 2026. Its t2v (text-to-video) model allows precise control of video visuals through prompts, accurately reproducing various cinematic techniques. Camera movements such as push, pull, pan, tilt, tracking, and follow are smooth and natural, with precise and controllable perspective switching. It supports up to 15-second videos, direct output of music and video, and multiple languages.',+ displayName: 'PixVerse V6 T2V',+ enabled: true,+ id: 'pixverse/pixverse-v6-t2v',+ parameters: {+ duration: { default: 5, max: 15, min: 1 },+ generateAudio: { default: true },+ prompt: { default: '' },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '640x360',+ '640x480',+ '640x640',+ '480x640',+ '360x640',+ '640x432',+ '432x640',+ '640x288',+ '1024x576',+ '1024x768',+ '1024x1024',+ '768x1024',+ '576x1024',+ '1024x688',+ '688x1024',+ '1024x448',+ '1280x720',+ '1280x960',+ '1280x1280',+ '960x1280',+ '720x1280',+ '1200x800',+ '800x1200',+ '1280x560',+ '1920x1080',+ '1920x1440',+ '1808x1808',+ '1440x1920',+ '1080x1920',+ '1776x1184',+ '1184x1776',+ '1920x832',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input a text description to generate high-quality videos with second-level speed and precise semantic alignment, supporting multiple styles. PixVerse V5.6 is a self-developed video generation large model by Aishi Technology, offering comprehensive upgrades in both text-to-video and image-to-video capabilities. The model significantly improves image clarity, stability in complex motion, and audio-visual synchronization. Lip-sync accuracy and natural emotional expression are enhanced in multi-character dialogue scenes. Composition, lighting, and texture consistency are also optimized, further raising overall generation quality. PixVerse V5.6 ranks in the top global tier on the Artificial Analysis text-to-video and image-to-video leaderboard.',+ displayName: 'PixVerse V5.6 T2V',+ id: 'pixverse/pixverse-v5.6-t2v',+ parameters: {+ duration: { default: 5, enum: [5, 8, 10] },+ generateAudio: { default: true },+ prompt: { default: '' },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '640x360',+ '640x480',+ '640x640',+ '480x640',+ '360x640',+ '1024x576',+ '1024x768',+ '1024x1024',+ '768x1024',+ '576x1024',+ '1280x720',+ '1280x960',+ '1280x1280',+ '960x1280',+ '720x1280',+ '1920x1080',+ '1920x1440',+ '1808x1808',+ '1440x1920',+ '1080x1920',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'V6 is PixVerse’s new model launched at the end of March 2026. Its it2v (image-to-video) model ranks second globally. In addition to the prompt-control capabilities of t2v (text-to-video), it2v can accurately reproduce the colors, saturation, scenes, and character features of reference images, delivering stronger character emotions and high-speed motion performance. It supports up to 15-second videos, direct output of music and video, and multiple languages. Ideal for scenarios such as e-commerce product close-ups, advertising promos, and simulated C4D modeling to showcase product structures, with one-click direct output.',+ displayName: 'PixVerse V6 IT2V',+ enabled: true,+ id: 'pixverse/pixverse-v6-it2v',+ parameters: {+ duration: { default: 5, max: 15, min: 1 },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['360P', '540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Upload any image to freely customize the story, pacing, and style, generating vivid and coherent videos. PixVerse V5.6 is a self-developed video generation large model by Aishi Technology, offering comprehensive upgrades in both text-to-video and image-to-video capabilities. The model significantly enhances image clarity, stability in complex motion, and audio-visual synchronization. Lip-sync accuracy and natural emotional expression are improved in multi-character dialogue scenes. Composition, lighting, and texture consistency are also optimized, further elevating overall generation quality. PixVerse V5.6 ranks in the top global tier on the Artificial Analysis text-to-video and image-to-video leaderboard.',+ displayName: 'PixVerse V5.6 IT2V',+ id: 'pixverse/pixverse-v5.6-it2v',+ parameters: {+ duration: { default: 5, enum: [5, 8, 10] },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['360P', '540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'V6 is PixVerse’s new model launched at the end of March 2026. Its kf2v (keyframe-to-video) model can seamlessly connect any two images, producing smoother and more natural video transitions. It supports up to 15-second videos, direct output of music and video, and multiple languages.',+ displayName: 'PixVerse V6 KF2V',+ enabled: true,+ id: 'pixverse/pixverse-v6-kf2v',+ parameters: {+ duration: { default: 5, max: 15, min: 1 },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['360P', '540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Achieve seamless transitions between any two images, creating smoother and more natural scene changes with visually striking effects. PixVerse V5.6 is a self-developed video generation large model by Aishi Technology, offering comprehensive upgrades in both text-to-video and image-to-video capabilities. The model significantly improves image clarity, stability in complex motion, and audio-visual synchronization. Lip-sync accuracy and natural emotional expression are enhanced in multi-character dialogue scenes. Composition, lighting, and texture consistency are also optimized, further elevating overall generation quality. PixVerse V5.6 ranks in the top global tier on the Artificial Analysis text-to-video and image-to-video leaderboard.',+ displayName: 'PixVerse V5.6 KF2V',+ id: 'pixverse/pixverse-v5.6-kf2v',+ parameters: {+ duration: { default: 5, enum: [5, 8, 10] },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '720P',+ enum: ['360P', '540P', '720P', '1080P'],+ },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+ {+ description:+ 'Input 2–7 images to intelligently merge different subjects while maintaining unified style and coordinated motion, easily building rich narrative scenes and enhancing content controllability and creative freedom. PixVerse V5.6 is a self-developed video generation large model by Aishi Technology, offering comprehensive upgrades in both text-to-video and image-to-video capabilities. The model significantly improves image clarity, stability in complex motion, and audio-visual synchronization. Lip-sync accuracy and natural emotional expression are enhanced in multi-character dialogue scenes. Composition, lighting, and texture consistency are also optimized, further elevating overall generation quality. PixVerse V5.6 ranks in the top global tier on the Artificial Analysis text-to-video and image-to-video leaderboard.',+ displayName: 'PixVerse V5.6 R2V',+ id: 'pixverse/pixverse-v5.6-r2v',+ parameters: {+ duration: { default: 5, enum: [5, 8, 10] },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: [+ '640x360',+ '640x480',+ '640x640',+ '480x640',+ '360x640',+ '1024x576',+ '1024x768',+ '1024x1024',+ '768x1024',+ '576x1024',+ '1280x720',+ '1280x960',+ '1280x1280',+ '960x1280',+ '720x1280',+ '1920x1080',+ '1920x1440',+ '1808x1808',+ '1440x1920',+ '1080x1920',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.53, strategy: 'fixed', unit: 'second' }],+ },+ type: 'video',+ },+];++export const allModels = [...qwenChatModels, ...qwenImageModels, ...qwenVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/siliconcloud.ts b/packages/model-bank/src/aiModels/siliconcloud.tsindex 61319c44204..adc6828c499 100644--- a/packages/model-bank/src/aiModels/siliconcloud.ts+++ b/packages/model-bank/src/aiModels/siliconcloud.ts@@ -1,4 +1,8 @@-import { type AIChatModelCard, type AIImageModelCard } from '../types/aiModel';+import {+ type AIChatModelCard,+ type AIImageModelCard,+ type AIVideoModelCard,+} from '../types/aiModel';// https://siliconflow.cn/zh-cn/modelsconst siliconcloudChatModels: AIChatModelCard[] = [@@ -2329,6 +2333,54 @@ const siliconcloudImageModels: AIImageModelCard[] = [},];-export const allModels = [...siliconcloudChatModels, ...siliconcloudImageModels];+const siliconcloudVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Wan2.2-I2V-A14B is one of the first open-source image-to-video (I2V) generation models released by Wan-AI, an AI initiative under Alibaba, to adopt a Mixture of Experts (MoE) architecture. The model focuses on generating smooth and natural dynamic video sequences by combining static images with text prompts. Its core innovation lies in the MoE architecture: a high-noise expert is responsible for handling the coarse structure in the early stages of video generation, while a low-noise expert refines fine-grained details in the later stages. This design improves overall model performance without increasing inference cost. Compared to previous versions, Wan2.2 is trained on a significantly larger dataset, leading to notable improvements in understanding complex motion, aesthetic styles, and semantic content. It produces more stable videos and reduces unrealistic camera movements.',+ displayName: 'Wan-AI/Wan2.2-I2V-A14B',+ enabled: true,+ id: 'Wan-AI/Wan2.2-I2V-A14B',+ parameters: {+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ seed: { default: null },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2026-01-28',+ type: 'video',+ },+ {+ description:+ 'Wan2.2-T2V-A14B is the first open-source video generation model released by Alibaba to adopt a Mixture of Experts (MoE) architecture. The model is designed for text-to-video (T2V) generation tasks and is capable of producing videos up to 5 seconds in length at resolutions of 480P or 720P. By introducing the MoE architecture, the model significantly increases its overall capacity while keeping inference costs nearly unchanged. It includes a high-noise expert that handles the global structure in the early stages of generation, and a low-noise expert that refines fine details in the later stages of the video. In addition, Wan2.2 incorporates carefully curated aesthetic data, with detailed annotations across dimensions such as lighting, composition, and color. This enables more precise and controllable generation of cinematic-quality visuals. Compared to previous versions, the model is trained on a larger dataset, resulting in significantly improved generalization in motion, semantics, and aesthetics, and better handling of complex dynamic effects.',+ displayName: 'Wan-AI/Wan2.2-T2V-A14B',+ enabled: true,+ id: 'Wan-AI/Wan2.2-T2V-A14B',+ parameters: {+ prompt: { default: '' },+ seed: { default: null },+ size: {+ default: '1280x720',+ enum: ['1280x720', '720x1280', '960x960'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2026-01-28',+ type: 'video',+ },+];++export const allModels = [+ ...siliconcloudChatModels,+ ...siliconcloudImageModels,+ ...siliconcloudVideoModels,+];export default allModels;diff --git a/packages/model-bank/src/aiModels/wenxin.ts b/packages/model-bank/src/aiModels/wenxin.tsindex fdbcdcef85e..afb30f4480f 100644--- a/packages/model-bank/src/aiModels/wenxin.ts+++ b/packages/model-bank/src/aiModels/wenxin.ts@@ -1,4 +1,4 @@-import type { AIChatModelCard, AIImageModelCard } from '../types/aiModel';+import type { AIChatModelCard, AIImageModelCard, AIVideoModelCard } from '../types/aiModel';// https://cloud.baidu.com/doc/qianfan/s/rmh4stp0j@@ -1886,6 +1886,103 @@ const wenxinImageModels: AIImageModelCard[] = [},];-export const allModels = [...wenxinChatModels, ...wenxinImageModels];+const wenxinVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Supports 5s and 10s 720P dynamic video generation with sound. Enables multi-person conversational audio-visual creation, with synchronized sound and visuals, cinematic-quality imagery, and master-level camera movements.',+ displayName: 'MuseSteamer 2.0 Turbo I2V Audio',+ enabled: true,+ id: 'musesteamer-2.0-turbo-i2v-audio',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2.5, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+ {+ description:+ 'Supports 5-second 720P silent dynamic video generation, featuring cinematic-quality visuals, complex camera movements, and realistic character emotions and actions.',+ displayName: 'MuseSteamer 2.0 Turbo I2V',+ enabled: true,+ id: 'musesteamer-2.0-turbo-i2v',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1.4, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+ {+ description:+ 'Based on Turbo, supports 1080P dynamic video generation, offering higher visual quality and enhanced video expressiveness.',+ displayName: 'MuseSteamer 2.0 Pro I2V',+ enabled: true,+ id: 'musesteamer-2.0-pro-i2v',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2.5, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+ {+ description:+ 'Compared to Turbo, it offers superior performance with excellent cost-effectiveness.',+ displayName: 'MuseSteamer 2.0 Lite I2V',+ enabled: true,+ id: 'musesteamer-2.0-lite-i2v',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.7, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+ {+ description:+ 'The Baidu MuseSteamer Air video generation model performs well in subject consistency, physical realism, camera movement effects, and generation speed. It supports 5-second 720P silent dynamic video generation, delivering cinematic-quality visuals, fast generation, and excellent cost-effectiveness.',+ displayName: 'MuseSteamer Air I2V',+ id: 'musesteamer-air-i2v',+ parameters: {+ duration: { default: 5, enum: [5] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+];++export const allModels = [...wenxinChatModels, ...wenxinImageModels, ...wenxinVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/xai.ts b/packages/model-bank/src/aiModels/xai.tsindex 51146f61572..67974d5251b 100644--- a/packages/model-bank/src/aiModels/xai.ts+++ b/packages/model-bank/src/aiModels/xai.ts@@ -1,4 +1,4 @@-import type { AIChatModelCard, AIImageModelCard } from '../types/aiModel';+import type { AIChatModelCard, AIImageModelCard, AIVideoModelCard } from '../types/aiModel';// https://docs.x.ai/docs/modelsconst xaiChatModels: AIChatModelCard[] = [@@ -508,6 +508,39 @@ const xaiImageModels: AIImageModelCard[] = [},];-export const allModels = [...xaiChatModels, ...xaiImageModels];+const xaiVideoModels: AIVideoModelCard[] = [+ {+ description: 'State-of-the-art video generation across quality, cost, and latency.',+ displayName: 'Grok Imagine Video',+ enabled: true,+ id: 'grok-imagine-video',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'],+ },+ duration: { default: 8, max: 15, min: 1 },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ resolution: {+ default: '480p',+ enum: ['480p', '720p'],+ },+ size: {+ default: '848x480',+ enum: ['848x480', '1696x960', '1280x720', '1920x1080'],+ },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.05, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2026-01-28',+ type: 'video',+ },+];++export const allModels = [...xaiChatModels, ...xaiImageModels, ...xaiVideoModels];export default allModels;diff --git a/packages/model-bank/src/aiModels/zhipu.ts b/packages/model-bank/src/aiModels/zhipu.tsindex d90b607c000..d25ef200e3f 100644--- a/packages/model-bank/src/aiModels/zhipu.ts+++ b/packages/model-bank/src/aiModels/zhipu.ts@@ -1,4 +1,8 @@-import { type AIChatModelCard, type AIImageModelCard } from '../types/aiModel';+import {+ type AIChatModelCard,+ type AIImageModelCard,+ type AIVideoModelCard,+} from '../types/aiModel';// price: https://bigmodel.cn/pricing// ref: https://docs.bigmodel.cn/cn/guide/start/model-overview@@ -1317,6 +1321,277 @@ const zhipuImageModels: AIImageModelCard[] = [},];-export const allModels = [...zhipuChatModels, ...zhipuImageModels];+const zhipuVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Vidu 2 is a video generation foundation model designed to balance speed and quality. It focuses on image-to-video generation and start–end frame control, supporting 4-second videos at 720P resolution. The generation speed is significantly improved while costs are substantially reduced. Image-to-video generation fixes previous color shift issues, delivering stable and controllable visuals suitable for e-commerce and similar applications. In addition, semantic understanding of start and end frames and consistency across multiple reference images have been enhanced, making it an efficient tool for large-scale content production in general entertainment, internet media, animated short dramas, and advertising.',+ displayName: 'Vidu 2 Reference',+ enabled: true,+ id: 'vidu2-reference',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16', '1:1'],+ },+ duration: { default: 4, enum: [4] },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1280x720',+ enum: ['1280x720'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1.25, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'Vidu 2 is a video generation foundation model designed to balance speed and quality. It focuses on image-to-video generation and start–end frame control, supporting 4-second videos at 720P resolution. The generation speed is significantly improved while costs are substantially reduced. Image-to-video generation fixes previous color shift issues, delivering stable and controllable visuals suitable for e-commerce and similar applications. In addition, semantic understanding of start and end frames and consistency across multiple reference images have been enhanced, making it an efficient tool for large-scale content production in general entertainment, internet media, animated short dramas, and advertising.',+ displayName: 'Vidu 2 Start End',+ enabled: true,+ id: 'vidu2-start-end',+ parameters: {+ duration: { default: 5, enum: [5] },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: ['1920x1080'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1.25, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'Vidu Q1 is Vidu’s next-generation video generation foundation model, focused on high-quality video creation. It produces content with fixed specifications of 5 seconds, 24 FPS, and 1080P resolution. Through deep optimization of visual clarity, the overall image quality and texture are significantly improved, while issues such as hand deformation and frame jitter are greatly reduced. The realistic style closely approaches real-world scenes, and 2D animation styles are preserved with high fidelity. Transitions between start and end frames are smoother, making it well suited for high-demand creative scenarios such as film production, advertising, and animated short dramas.',+ displayName: 'Vidu Q1 Start End',+ id: 'viduq1-start-end',+ parameters: {+ duration: { default: 5, enum: [5] },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: ['1920x1080'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2.5, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'Vidu 2 is a video generation foundation model designed to balance speed and quality. It focuses on image-to-video generation and start–end frame control, supporting 4-second videos at 720P resolution. The generation speed is significantly improved while costs are substantially reduced. Image-to-video generation fixes previous color shift issues, delivering stable and controllable visuals suitable for e-commerce and similar applications. In addition, semantic understanding of start and end frames and consistency across multiple reference images have been enhanced, making it an efficient tool for large-scale content production in general entertainment, internet media, animated short dramas, and advertising.',+ displayName: 'Vidu 2 Image',+ enabled: true,+ id: 'vidu2-image',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['21:9', '16:9', '4:3', '1:1', '3:4', '9:16'],+ },+ duration: { default: 5, enum: [5] },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: ['1920x1080'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1.25, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'Vidu Q1 is Vidu’s next-generation video generation foundation model, focused on high-quality video creation. It produces content with fixed specifications of 5 seconds, 24 FPS, and 1080P resolution. Through deep optimization of visual clarity, the overall image quality and texture are significantly improved, while issues such as hand deformation and frame jitter are greatly reduced. The realistic style closely approaches real-world scenes, and 2D animation styles are preserved with high fidelity. Transitions between start and end frames are smoother, making it well suited for high-demand creative scenarios such as film production, advertising, and animated short dramas.',+ displayName: 'Vidu Q1 Image',+ id: 'viduq1-image',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['21:9', '16:9', '4:3', '1:1', '3:4', '9:16'],+ },+ duration: { default: 5, enum: [5] },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: ['1920x1080'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2.5, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'Vidu Q1 is Vidu’s next-generation video generation foundation model, focused on high-quality video creation. It produces content with fixed specifications of 5 seconds, 24 FPS, and 1080P resolution. Through deep optimization of visual clarity, the overall image quality and texture are significantly improved, while issues such as hand deformation and frame jitter are greatly reduced. The realistic style closely approaches real-world scenes, and 2D animation styles are preserved with high fidelity. Transitions between start and end frames are smoother, making it well suited for high-demand creative scenarios such as film production, advertising, and animated short dramas.',+ displayName: 'Vidu Q1 Text',+ enabled: true,+ id: 'viduq1-text',+ parameters: {+ aspectRatio: {+ default: '16:9',+ enum: ['16:9', '9:16', '1:1'],+ },+ duration: { default: 5, enum: [5] },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: ['1920x1080'],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 2.5, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-06-18',+ type: 'video',+ },+ {+ description:+ 'CogVideoX-3 adds a start-and-end frame generation feature, significantly improving visual stability and clarity. It enables smooth and natural large-scale subject motion, offers better instruction adherence and more realistic physical simulation, and further enhances performance in high-definition realistic and 3D-style scenes.',+ displayName: 'CogVideoX-3',+ enabled: true,+ id: 'cogvideox-3',+ parameters: {+ duration: { default: 5, enum: [5, 10] },+ endImageUrl: {+ default: null,+ },+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '1280x720',+ '720x1280',+ '1024x1024',+ '1920x1080',+ '1080x1920',+ '2048x1080',+ '3840x2160',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 1, strategy: 'fixed', unit: 'video' }],+ },+ releasedAt: '2025-07-15',+ type: 'video',+ },+ {+ description:+ 'CogVideoX-2 is Zhipu’s new-generation video generation foundation model, with image-to-video capabilities improved by 38%. It delivers significant enhancements in large-scale motion handling, visual stability, instruction adherence, artistic style, and overall visual aesthetics.',+ displayName: 'CogVideoX-2',+ id: 'cogvideox-2',+ parameters: {+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '720x480',+ '1024x1024',+ '1280x960',+ '960x1280',+ '1920x1080',+ '1080x1920',+ '2048x1080',+ '3840x2160',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+ {+ description:+ 'CogVideoX-Flash is a free video generation model released by Zhipu, capable of generating videos that follow user instructions while achieving higher aesthetic quality scores.',+ displayName: 'CogVideoX-Flash',+ enabled: true,+ id: 'cogvideox-flash',+ parameters: {+ generateAudio: { default: true },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '1920x1080',+ enum: [+ '720x480',+ '1024x1024',+ '1280x960',+ '960x1280',+ '1920x1080',+ '1080x1920',+ '2048x1080',+ '3840x2160',+ ],+ },+ },+ pricing: {+ currency: 'CNY',+ units: [{ name: 'videoGeneration', rate: 0, strategy: 'fixed', unit: 'video' }],+ },+ type: 'video',+ },+];++export const allModels = [...zhipuChatModels, ...zhipuImageModels, ...zhipuVideoModels];export default allModels;diff --git a/packages/model-bank/src/standard-parameters/video.ts b/packages/model-bank/src/standard-parameters/video.tsindex b2951e0f006..c6c4c7002b0 100644--- a/packages/model-bank/src/standard-parameters/video.ts+++ b/packages/model-bank/src/standard-parameters/video.ts@@ -3,6 +3,13 @@ import { z } from 'zod';export const MAX_VIDEO_SEED = 2 ** 32 - 1;+export const PRESET_VIDEO_SIZES = [+ '720x1280', // Portrait (default)+ '1280x720', // Landscape+ '1024x1792', // Portrait large+ '1792x1024', // Landscape large+];+export const PRESET_VIDEO_ASPECT_RATIOS = ['16:9', // Landscape video standard'9:16', // Portrait/short-form video@@ -66,12 +73,22 @@ export const VideoModelParamsMetaSchema = z.object({}).optional(),+ size: z+ .object({+ default: z.string(),+ description: z.string().optional(),+ enum: z.array(z.string()),+ type: z.literal('string').optional(),+ })+ .optional(),+duration: z.object({default: z.number(),description: z.string().optional(),- max: z.number(),- min: z.number(),+ enum: z.array(z.number()).optional(),+ max: z.number().optional(),+ min: z.number().optional(),step: z.number().optional().default(1),type: z.literal('number').optional(),})diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 635f815696d..d03fc577b0d 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -153,6 +153,7 @@ export type PricingUnitType =| 'millionTokens' // per 1M tokens| 'millionCharacters' // per 1M characters| 'image' // per image+ | 'video' // per video| 'megapixel' // per megapixel| 'second'; // per seconddiff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.tsindex ea49612f819..8c6c445ce76 100644--- a/packages/model-runtime/src/core/BaseAI.ts+++ b/packages/model-runtime/src/core/BaseAI.ts@@ -39,6 +39,14 @@ export interface LobeRuntimeAI {payload: HandleCreateVideoWebhookPayload,) => Promise<HandleCreateVideoWebhookResult>;+ handlePollVideoStatus?: (+ inferenceId: string,+ ) => Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+ >;+models?: () => Promise<any>;// Model management related interfacediff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 27df1ea3d49..07e79d2b3c0 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -210,6 +210,10 @@ export class ModelRuntime {return this._runtime.handleCreateVideoWebhook?.(payload);}+ async handlePollVideoStatus(inferenceId: string) {+ return this._runtime.handlePollVideoStatus?.(inferenceId);+ }+async models() {return this._runtime.models?.();}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.test.tsnew file mode 100644index 00000000000..fb6829b5616--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.test.ts@@ -0,0 +1,283 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import {+ createOpenAICompatibleVideo,+ pollOpenAICompatibleVideoStatus,+ queryOpenAICompatibleVideoStatus,+} from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://api.openai.com/v1',+ provider: 'openai',+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('createOpenAICompatibleVideo', () => {+ describe('Success scenarios', () => {+ it('should create video task with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'video-task-123' }),+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: {+ prompt: 'A beautiful sunset over the ocean',+ },+ };++ const result = await createOpenAICompatibleVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith('https://api.openai.com/v1/videos', {+ method: 'POST',+ headers: {+ 'Authorization': 'Bearer test-api-key',+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ model: 'sora-2.0',+ prompt: 'A beautiful sunset over the ocean',+ }),+ });++ expect(result).toEqual({ inferenceId: 'video-task-123' });+ });++ it('should include duration as string', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'video-task-456' }),+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: {+ prompt: 'A short clip',+ duration: 10,+ },+ };++ await createOpenAICompatibleVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.seconds).toBe('10');+ });++ it('should include size parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'video-task-789' }),+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: {+ prompt: 'HD video',+ size: '1920x1080',+ },+ };++ await createOpenAICompatibleVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.size).toBe('1920x1080');+ });++ it('should include imageUrl as input_reference', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'video-task-img' }),+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: {+ prompt: 'Continue this scene',+ imageUrl: 'https://example.com/image.jpg',+ },+ };++ await createOpenAICompatibleVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.input_reference).toBe('https://example.com/image.jpg');+ });+ });++ describe('Error scenarios', () => {+ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 401,+ statusText: 'Unauthorized',+ text: async () => 'Invalid API key',+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: { prompt: 'Test' },+ };++ await expect(createOpenAICompatibleVideo(payload, mockOptions)).rejects.toThrow(+ 'OpenAI-compatible video API error: 401 Invalid API key',+ );+ });++ it('should throw when response missing id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const payload: CreateVideoPayload = {+ model: 'sora-2.0',+ params: { prompt: 'Test' },+ };++ await expect(createOpenAICompatibleVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing id',+ );+ });+ });+});++describe('pollOpenAICompatibleVideoStatus', () => {+ it('should return success with videoUrl when completed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'completed',+ url: 'https://cdn.openai.com/video.mp4',+ }),+ });++ const result = await pollOpenAICompatibleVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ });++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.openai.com/video.mp4',+ headers: {+ Authorization: 'Bearer test-key',+ },+ });+ });++ it('should construct content endpoint URL when no url returned', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'completed',+ }),+ });++ const result = await pollOpenAICompatibleVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ });++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://api.openai.com/v1/videos/task-123/content',+ headers: {+ Authorization: 'Bearer test-key',+ },+ });+ });++ it('should return failed status when task failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'failed',+ error: { message: 'Content policy violation' },+ }),+ });++ const result = await pollOpenAICompatibleVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ });++ expect(result).toEqual({+ status: 'failed',+ error: 'Content policy violation',+ });+ });++ it('should return pending status when still processing', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'in_progress',+ progress: 50,+ }),+ });++ const result = await pollOpenAICompatibleVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ });++ expect(result).toEqual({ status: 'pending' });+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 404,+ text: async () => 'Task not found',+ });++ await expect(+ pollOpenAICompatibleVideoStatus('invalid-task', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ }),+ ).rejects.toThrow('OpenAI-compatible video status API error: 404 Task not found');+ });+});++describe('queryOpenAICompatibleVideoStatus', () => {+ it('should return parsed JSON response', async () => {+ const mockResponse = {+ id: 'task-123',+ status: 'completed',+ url: 'https://cdn.example.com/video.mp4',+ created_at: 1234567890,+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryOpenAICompatibleVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.openai.com/v1',+ });++ expect(result).toEqual(mockResponse);+ expect(fetch).toHaveBeenCalledWith('https://api.openai.com/v1/videos/task-123', {+ method: 'GET',+ headers: {+ 'Authorization': 'Bearer test-key',+ 'Content-Type': 'application/json',+ },+ });+ });+});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.tsnew file mode 100644index 00000000000..97b3a9159cf--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts@@ -0,0 +1,187 @@+import createDebug from 'debug';++import type {+ CreateVideoPayload,+ CreateVideoResponse,+ PollVideoStatusResult,+} from '../../types/video';+import type { CreateVideoOptions } from '../openaiCompatibleFactory';++const log = createDebug('lobe-video:openai-compatible');++interface OpenAIVideoStatusResponse {+ completed_at?: number;+ created?: number;+ created_at?: number;+ duration?: number;+ error?: {+ code?: string;+ message?: string;+ };+ expires_at?: number;+ height?: number;+ id?: string;+ model?: string;+ object?: string;+ progress?: number;+ prompt?: string;+ seconds?: string;+ size?: string;+ status?: string;+ url?: string;+ width?: number;+}++/**+ * Query the status of a video generation task+ * Compatible with OpenAI Sora API+ */+export async function queryOpenAICompatibleVideoStatus(+ inferenceId: string,+ options: { apiKey: string; baseURL: string },+): Promise<OpenAIVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/videos/${inferenceId}`;++ log('Querying video status for: %s', inferenceId);++ const response = await fetch(statusUrl, {+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`OpenAI-compatible video status API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as OpenAIVideoStatusResponse;+ log('Video status response: %O', data);++ return data;+}++/**+ * Poll video status and return standardized result+ * Compatible with OpenAI Sora API+ */+export async function pollOpenAICompatibleVideoStatus(+ inferenceId: string,+ options: { apiKey: string; baseURL: string },+): Promise<PollVideoStatusResult> {+ const response = await queryOpenAICompatibleVideoStatus(inferenceId, options);++ if (response.status === 'completed') {+ // Some providers return the download URL directly in the url field+ // Others require calling /videos/{id}/content endpoint+ let videoUrl = response.url;++ if (!videoUrl) {+ // If no URL returned, construct the content endpoint URL+ videoUrl = `${options.baseURL}/videos/${inferenceId}/content`;+ }++ // Return headers for authenticated download+ // OpenAI-compatible providers use Bearer token+ return {+ headers: {+ Authorization: `Bearer ${options.apiKey}`,+ },+ status: 'success',+ videoUrl,+ };+ }++ if (response.status === 'failed') {+ return {+ error: response.error?.message || 'Video generation failed',+ status: 'failed',+ };+ }++ // queued, in_progress, or any other status means still pending+ return { status: 'pending' };+}++/**+ * OpenAI-compatible video generation implementation+ * Works with OpenAI Sora, and other OpenAI-compatible providers+ *+ * API Format:+ * POST /v1/videos+ * {+ * model: string,+ * prompt: string,+ * seconds?: string, // OpenAI Sora format (string type)+ * input_reference?: string | object, // For image-to-video+ * }+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createOpenAICompatibleVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, size, duration } = params;++ log('Creating video with OpenAI-compatible API - model: %s, params: %O', model, params);++ const baseURL = options.baseURL || 'https://api.openai.com/v1';++ // Build request body compatible with OpenAI Sora+ const body: Record<string, unknown> = {+ model,+ prompt,+ };++ // Duration: prefer 'seconds' (string) for OpenAI Sora compatibility+ if (duration !== undefined && duration !== null) {+ body['seconds'] = duration.toString();+ }++ // Size/resolution+ if (size) {+ body['size'] = size;+ }++ // Image-to-video support+ if (imageUrl) {+ body['input_reference'] = imageUrl;+ }++ log('OpenAI-compatible video API request body: %O', body);++ const response = await fetch(`${baseURL}/videos`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log('OpenAI-compatible video API error: %s %s', response.status, errorText);+ throw new Error(`OpenAI-compatible video API error: ${response.status} ${errorText}`);+ }++ const data = await response.json();+ log('OpenAI-compatible video API response: %O', data);++ if (!data?.id) {+ throw new Error('Invalid response: missing id');+ }++ const inferenceId = data.id;+ log('Video task created with id: %s, returning immediately for frontend polling', inferenceId);++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30 seconds during server-side polling+ return { inferenceId };+}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 1693198f95d..a8a4df966f2 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -31,6 +31,7 @@ import type {CreateVideoResponse,HandleCreateVideoWebhookPayload,HandleCreateVideoWebhookResult,+ PollVideoStatusResult,} from '../../types/video';import { AgentRuntimeError } from '../../utils/createError';import { debugResponse, debugStream } from '../../utils/debugStream';@@ -50,8 +51,11 @@ import { OpenAIResponsesStream, OpenAIStream } from '../streams';import type { ChatPayloadForTransformStream } from '../streams/protocol';import { convertOpenAIResponseUsage, convertOpenAIUsage } from '../usageConverters/openai';import { createOpenAICompatibleImage } from './createImage';+import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';+export type { PollVideoStatusResult };+export * from './createVideo';export * from './nonStreamToStream';// the model contains the following keywords is not a chat model, so we should filter them out@@ -169,6 +173,10 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =payload: HandleCreateVideoWebhookPayload,options: CreateVideoOptions,) => Promise<HandleCreateVideoWebhookResult>;+ handlePollVideoStatus?: (+ inferenceId: string,+ options: CreateVideoOptions,+ ) => Promise<PollVideoStatusResult>;models?:| ((params: { client: OpenAI }) => Promise<ChatModelCard[]>)| {@@ -197,6 +205,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = ancreateImage: customCreateImage,createVideo: customCreateVideo,handleCreateVideoWebhook: customHandleCreateVideoWebhook,+ handlePollVideoStatus: customHandlePollVideoStatus,generateObject: generateObjectConfig,}: OpenAICompatibleFactoryOptions<T>) => {const ErrorType = {@@ -573,12 +582,22 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}async createVideo(payload: CreateVideoPayload) {- if (!customCreateVideo) {- throw new Error('createVideo is not supported by this provider');+ const log = debug(`${this.logPrefix}:createVideo`);++ if (customCreateVideo) {+ log('using custom createVideo implementation');+ return customCreateVideo(payload, {+ ...this._options,+ apiKey: this._options.apiKey!,+ provider,+ });}- return customCreateVideo(payload, {++ log('using default createOpenAICompatibleVideo');+ return createOpenAICompatibleVideo(payload, {...this._options,apiKey: this._options.apiKey!,+ baseURL: this._options.baseURL || '',provider,});}@@ -594,6 +613,27 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an});}+ async handlePollVideoStatus(inferenceId: string): Promise<PollVideoStatusResult> {+ const log = debug(`${this.logPrefix}:handlePollVideoStatus`);++ if (customHandlePollVideoStatus) {+ log('using custom handlePollVideoStatus implementation');+ return customHandlePollVideoStatus(inferenceId, {+ ...this._options,+ apiKey: this._options.apiKey!,+ provider,+ });+ }++ log('using default pollOpenAICompatibleVideoStatus');+ return pollOpenAICompatibleVideoStatus(inferenceId, {+ ...this._options,+ apiKey: this._options.apiKey!,+ baseURL: this._options.baseURL || '',+ provider,+ });+ }+async models() {const log = debug(`${this.logPrefix}:models`);log('fetching available models');diff --git a/packages/model-runtime/src/providers/google/createVideo.test.ts b/packages/model-runtime/src/providers/google/createVideo.test.tsnew file mode 100644index 00000000000..2233018baad--- /dev/null+++ b/packages/model-runtime/src/providers/google/createVideo.test.ts@@ -0,0 +1,896 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoPayload } from '../../types/video';+import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++vi.mock('../../utils/googleErrorParser', () => ({+ parseGoogleErrorMessage: vi.fn((message) => ({+ error: message,+ errorType: 'GoogleAPIError',+ })),+}));++vi.mock('../../utils/uriParser', () => ({+ parseDataUri: vi.fn((url) => {+ if (url.startsWith('data:')) {+ const matches = url.match(/^data:(image\/\w+);base64,(.+)$/);+ if (matches) {+ return { base64: matches[2], mimeType: matches[1], type: 'base64' };+ }+ return { base64: null, mimeType: null, type: 'base64' };+ }+ return { base64: null, mimeType: null, type: 'url' };+ }),+}));++vi.mock('@lobechat/utils', () => ({+ imageUrlToBase64: vi.fn(async (url) => ({+ base64: 'mock-base64-data',+ mimeType: 'image/jpeg',+ })),+}));++vi.mock('@google/genai', () => ({+ GenerateVideosOperation: class {+ name: string = '';+ },+}));++describe('createGoogleVideo', () => {+ const mockClient = {+ models: {+ generateVideos: vi.fn(),+ },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('successful creation', () => {+ it('should create video with basic prompt', async () => {+ const mockOperation = { name: 'operations/test-op-123' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'A cat playing guitar',+ },+ };++ const result = await createGoogleVideo(mockClient as any, 'google', payload);++ expect(mockClient.models.generateVideos).toHaveBeenCalledWith({+ model: 'veo-2.0-generate-001',+ prompt: 'A cat playing guitar',+ config: {},+ });++ expect(result).toEqual({ inferenceId: 'operations/test-op-123' });+ });++ it('should return inferenceId from operation name', async () => {+ const mockOperation = { name: 'operations/custom-op-456' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ const result = await createGoogleVideo(mockClient as any, 'google', payload);++ expect(result.inferenceId).toBe('operations/custom-op-456');+ });++ it('should return empty string when operation name is undefined', async () => {+ const mockOperation = { name: undefined };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ const result = await createGoogleVideo(mockClient as any, 'google', payload);++ expect(result.inferenceId).toBe('');+ });+ });++ describe('optional parameters', () => {+ it('should include aspectRatio in config', async () => {+ const mockOperation = { name: 'operations/test-op-aspect' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Landscape video',+ aspectRatio: '16:9',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config).toEqual({ aspectRatio: '16:9' });+ });++ it('should include resolution in config', async () => {+ const mockOperation = { name: 'operations/test-op-res' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'High quality video',+ resolution: '4k',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.resolution).toBe('4k');+ });++ it('should include both aspectRatio and resolution in config', async () => {+ const mockOperation = { name: 'operations/test-op-both' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Full options',+ aspectRatio: '21:9',+ resolution: '1080p',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config).toEqual({+ aspectRatio: '21:9',+ resolution: '1080p',+ });+ });++ it('should include imageUrl as image at root level', async () => {+ const mockOperation = { name: 'operations/image-to-video' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Animate this',+ imageUrl: 'https://example.com/first.jpg',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.image).toBeDefined();+ expect(callArgs.image.mimeType).toBe('image/jpeg');+ expect(callArgs.image.imageBytes).toBe('mock-base64-data');+ });++ it('should include endImageUrl as lastFrame in config', async () => {+ const mockOperation = { name: 'operations/transformer' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Transform first to last',+ imageUrl: 'https://example.com/first.jpg',+ endImageUrl: 'https://example.com/last.jpg',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.image).toBeDefined();+ expect(callArgs.config.lastFrame).toBeDefined();+ expect(callArgs.config.lastFrame.mimeType).toBe('image/jpeg');+ expect(callArgs.config.lastFrame.imageBytes).toBe('mock-base64-data');+ });++ it('should include duration as durationSeconds in config', async () => {+ const mockOperation = { name: 'operations/duration-test' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Short clip',+ duration: 5,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.durationSeconds).toBe(5);+ });++ it('should include generateAudio in config when true', async () => {+ const mockOperation = { name: 'operations/audio-test' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Video with audio',+ generateAudio: true,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.generateAudio).toBe(true);+ });++ it('should not include generateAudio when undefined or false', async () => {+ const mockOperation = { name: 'operations/no-audio' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Silent video',+ generateAudio: false,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.generateAudio).toBeUndefined();+ });++ it('should include seed in config', async () => {+ const mockOperation = { name: 'operations/seed-test' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Reproducible video',+ seed: 42,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.seed).toBe(42);+ });++ it('should not include seed when undefined', async () => {+ const mockOperation = { name: 'operations/no-seed' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Random video',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.seed).toBeUndefined();+ });++ it('should include different seed values', async () => {+ const mockOperation = { name: 'operations/seed-123' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Specific seed',+ seed: 999999,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.seed).toBe(999999);+ });++ it('should not include duration when undefined', async () => {+ const mockOperation = { name: 'operations/no-duration' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'No duration specified',+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.config.durationSeconds).toBeUndefined();+ });++ it('should include all optional parameters together', async () => {+ const mockOperation = { name: 'operations/full-params' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Full featured video',+ imageUrl: 'https://example.com/start.jpg',+ endImageUrl: 'https://example.com/end.jpg',+ aspectRatio: '16:9',+ resolution: '4k',+ duration: 10,+ generateAudio: true,+ seed: 12345,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs).toEqual({+ model: 'veo-2.0-generate-001',+ prompt: 'Full featured video',+ config: {+ aspectRatio: '16:9',+ resolution: '4k',+ lastFrame: {+ imageBytes: 'mock-base64-data',+ mimeType: 'image/jpeg',+ },+ durationSeconds: 10,+ generateAudio: true,+ seed: 12345,+ },+ image: {+ imageBytes: 'mock-base64-data',+ mimeType: 'image/jpeg',+ },+ });+ });++ it('should handle base64 image URL', async () => {+ const mockOperation = { name: 'operations/base64-image' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const base64Url =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: {+ prompt: 'Video from base64',+ imageUrl: base64Url,+ },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ const callArgs = mockClient.models.generateVideos.mock.calls[0][0];+ expect(callArgs.image).toEqual({+ imageBytes:+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',+ mimeType: 'image/png',+ });+ });+ });++ describe('error handling', () => {+ it('should handle Google API errors', async () => {+ mockClient.models.generateVideos.mockRejectedValueOnce(+ new Error('Invalid value for parameter'),+ );++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ await expect(createGoogleVideo(mockClient as any, 'google', payload)).rejects.toMatchObject({+ errorType: 'GoogleAPIError',+ provider: 'google',+ });+ });++ it('should throw error with parsed Google error message', async () => {+ mockClient.models.generateVideos.mockRejectedValueOnce(+ new Error('[GoogleGenerativeAI Error]: Invalid request'),+ );++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ await expect(createGoogleVideo(mockClient as any, 'google', payload)).rejects.toThrow();+ });++ it('should pass through errors that already have errorType', async () => {+ const customError = new Error('Custom error');+ (customError as any).errorType = 'AgentRuntimeError';+ mockClient.models.generateVideos.mockRejectedValueOnce(customError);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ await expect(createGoogleVideo(mockClient as any, 'google', payload)).rejects.toBe(+ customError,+ );+ });++ it('should include provider in error payload', async () => {+ mockClient.models.generateVideos.mockRejectedValueOnce(new Error('API quota exceeded'));++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test' },+ };++ try {+ await createGoogleVideo(mockClient as any, 'google', payload);+ expect.fail('Should have thrown');+ } catch (error: any) {+ expect(error.provider).toBe('google');+ }+ });+ });++ describe('logging', () => {+ it('should log video creation request params', async () => {+ const mockOperation = { name: 'operations/test-log' };+ mockClient.models.generateVideos.mockResolvedValueOnce(mockOperation);++ const payload: CreateVideoPayload = {+ model: 'veo-2.0-generate-001',+ params: { prompt: 'Test logging' },+ };++ await createGoogleVideo(mockClient as any, 'google', payload);++ expect(mockClient.models.generateVideos).toHaveBeenCalled();+ });+ });+});++describe('pollGoogleVideoOperation', () => {+ const mockClient = {+ operations: {+ getVideosOperation: vi.fn(),+ },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('successful completion', () => {+ it('should return success when operation is done', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [+ {+ video: {+ uri: 'https://storage.googleapis.com/video.mp4',+ },+ },+ ],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://storage.googleapis.com/video.mp4',+ headers: {+ 'x-goog-api-key': 'test-api-key',+ },+ });+ });++ it('should include x-goog-api-key header for authenticated download', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [{ video: { uri: 'https://example.com/video.mp4' } }],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'custom-api-key',+ );++ if (result.status === 'success') {+ expect(result.headers).toEqual({+ 'x-goog-api-key': 'custom-api-key',+ });+ }+ });++ it('should handle operation with multiple generated videos', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [+ { video: { uri: 'https://example.com/video1.mp4' } },+ { video: { uri: 'https://example.com/video2.mp4' } },+ ],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ if (result.status === 'success') {+ expect(result.videoUrl).toBe('https://example.com/video1.mp4');+ }+ });+ });++ describe('error scenarios', () => {+ it('should return failed when operation has error', async () => {+ const mockOperation = {+ done: true,+ error: {+ message: 'Quota exceeded',+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Quota exceeded',+ });+ });++ it('should return failed when no video in response', async () => {+ const mockOperation = {+ done: true,+ response: {},+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'No video generated',+ });+ });++ it('should return failed when raiMediaFilteredReasons present', async () => {+ const mockOperation = {+ done: true,+ response: {+ raiMediaFilteredReasons: ['Content policy violation'],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Content policy violation',+ });+ });++ it('should return failed when raiMediaFilteredReasons has multiple reasons', async () => {+ const mockOperation = {+ done: true,+ response: {+ raiMediaFilteredReasons: ['Content policy violation', 'Unsafe content'],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Content policy violation',+ });+ });++ it('should return failed when video object is missing uri', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [{ video: {} }],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Video URL is empty',+ });+ });++ it('should return failed when generatedVideos array is empty', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'No video generated',+ });+ });++ it('should return failed when video uri is empty string', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [{ video: { uri: '' } }],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Video URL is empty',+ });+ });++ it('should return failed when error message is missing', async () => {+ const mockOperation = {+ done: true,+ error: {},+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Video generation failed',+ });+ });+ });++ describe('pending state', () => {+ it('should return pending when operation not done', async () => {+ const mockOperation = { done: false };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return pending when operation is partially done', async () => {+ const mockOperation = {+ done: false,+ name: 'operations/test-123',+ metadata: { progress: 50 },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({ status: 'pending' });+ });+ });++ describe('error handling', () => {+ it('should handle polling errors gracefully', async () => {+ mockClient.operations.getVideosOperation.mockRejectedValueOnce(new Error('Network error'));++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Network error',+ });+ });++ it('should return failed status when inferenceId is empty', async () => {+ const result = await pollGoogleVideoOperation(+ mockClient as any,+ '',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Invalid operation name',+ });+ });++ it('should return failed status when inferenceId is null', async () => {+ const result = await pollGoogleVideoOperation(+ mockClient as any,+ null as any,+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Invalid operation name',+ });+ });++ it('should handle errors without message property', async () => {+ mockClient.operations.getVideosOperation.mockRejectedValueOnce({});++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'Failed to poll video status',+ });+ });++ it('should handle network timeout errors', async () => {+ mockClient.operations.getVideosOperation.mockRejectedValueOnce(new Error('ETIMEDOUT'));++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'ETIMEDOUT',+ });+ });++ it('should handle authentication errors', async () => {+ mockClient.operations.getVideosOperation.mockRejectedValueOnce(new Error('API_KEY_INVALID'));++ const result = await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'invalid-key',+ );++ expect(result).toEqual({+ status: 'failed',+ error: 'API_KEY_INVALID',+ });+ });+ });++ describe('logging', () => {+ it('should log polling request', async () => {+ const mockOperation = {+ done: true,+ response: {+ generatedVideos: [{ video: { uri: 'https://example.com/video.mp4' } }],+ },+ };+ mockClient.operations.getVideosOperation.mockResolvedValueOnce(mockOperation);++ await pollGoogleVideoOperation(+ mockClient as any,+ 'operations/test-123',+ 'google',+ 'test-api-key',+ );++ expect(mockClient.operations.getVideosOperation).toHaveBeenCalledWith({+ operation: expect.objectContaining({+ name: 'operations/test-123',+ }),+ });+ });+ });+});diff --git a/packages/model-runtime/src/providers/google/createVideo.ts b/packages/model-runtime/src/providers/google/createVideo.tsnew file mode 100644index 00000000000..f169fae1dda--- /dev/null+++ b/packages/model-runtime/src/providers/google/createVideo.ts@@ -0,0 +1,187 @@+import type { GenerateVideosConfig, GoogleGenAI, Image } from '@google/genai';+import { GenerateVideosOperation } from '@google/genai';+import { imageUrlToBase64 } from '@lobechat/utils';+import debug from 'debug';++import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';+import { AgentRuntimeError } from '../../utils/createError';+import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';+import { parseDataUri } from '../../utils/uriParser';++const log = debug('lobe-video:google');++/**+ * Convert image URL to Google Image format+ * Supports: data URI, HTTP URL, and file paths+ */+async function imageToGoogleImageFormat(imageUrl: string): Promise<Image> {+ const { mimeType, base64, type } = parseDataUri(imageUrl);++ if (type === 'base64') {+ if (!base64) {+ throw new TypeError("Image URL doesn't contain base64 data");+ }++ return {+ imageBytes: base64,+ mimeType: mimeType || 'image/png',+ };+ } else if (type === 'url') {+ // Handle both HTTP URLs and file paths (files/...)+ const { base64: urlBase64, mimeType: urlMimeType } = await imageUrlToBase64(imageUrl);++ return {+ imageBytes: urlBase64,+ mimeType: urlMimeType,+ };+ } else {+ throw new TypeError(`currently we don't support image url: ${imageUrl}`);+ }+}++export async function createGoogleVideo(+ client: GoogleGenAI,+ provider: string,+ payload: CreateVideoPayload,+): Promise<CreateVideoResponse> {+ try {+ const { model, params } = payload;+ const {+ prompt,+ imageUrl,+ endImageUrl,+ aspectRatio,+ duration,+ resolution,+ seed,+ generateAudio, // generateAudio parameter is not supported in Gemini API.+ } = params;++ log('Creating video with Google AI - model: %s, params: %O', model, params);++ // https://github.com/googleapis/js-genai/blob/main/src/types.ts+ const config: GenerateVideosConfig = {+ ...(aspectRatio && { aspectRatio }),+ ...(duration && { durationSeconds: duration }),+ ...(endImageUrl && { lastFrame: await imageToGoogleImageFormat(endImageUrl) }),+ ...(generateAudio && { generateAudio }),+ ...(resolution && { resolution }),+ ...(seed !== undefined && seed !== null && { seed }),+ };++ const requestParams: any = {+ model,+ prompt,+ ...(imageUrl && { image: await imageToGoogleImageFormat(imageUrl) }),+ ...(config && { config }),+ };++ log('Google video generation request params: %O', requestParams);++ const operation = await client.models.generateVideos(requestParams);++ log('Video generation started, operation name: %s', operation.name);++ return { inferenceId: operation.name || '' };+ } catch (error) {+ const err = error as Error;+ log('Error creating video with Google AI: %O', err);++ if ((err as any)?.errorType) {+ throw err;+ }++ const { errorType, error: parsedError } = parseGoogleErrorMessage(err.message);+ throw AgentRuntimeError.createVideo({+ error: parsedError,+ errorType,+ provider,+ });+ }+}++export async function pollGoogleVideoOperation(+ client: GoogleGenAI,+ inferenceId: string,+ provider: string,+ apiKey: string,+): Promise<+ | { headers?: Record<string, string>; status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ try {+ log('Polling video operation status: %s', inferenceId);++ if (!inferenceId) {+ return { error: 'Invalid operation name', status: 'failed' };+ }++ // Create a proper GenerateVideosOperation instance from the operation name+ const operation = new GenerateVideosOperation();+ operation.name = inferenceId;++ const updatedOperation = await client.operations.getVideosOperation({+ operation,+ });++ log('Video operation status: %O', updatedOperation);++ if (updatedOperation.done) {+ if (updatedOperation.error) {+ const errorMessage = (updatedOperation.error as any)?.message || 'Video generation failed';+ return {+ error: errorMessage,+ status: 'failed',+ };+ }++ if (!updatedOperation.response?.generatedVideos?.[0]?.video) {+ if (updatedOperation?.response?.raiMediaFilteredReasons) {+ return {+ error: updatedOperation.response.raiMediaFilteredReasons[0],+ status: 'failed',+ };+ }++ return {+ error: 'No video generated',+ status: 'failed',+ };+ }++ const video = updatedOperation.response.generatedVideos[0].video;+ const videoUrl = video.uri;++ if (!videoUrl) {+ return {+ error: 'Video URL is empty',+ status: 'failed',+ };+ }++ log('Video generation completed, download URI: %s', videoUrl);++ // Return headers for authenticated download+ // Google uses x-goog-api-key header+ return {+ headers: {+ 'x-goog-api-key': apiKey,+ },+ status: 'success',+ videoUrl,+ };+ }++ log('Video generation still in progress');+ return { status: 'pending' };+ } catch (error) {+ const err = error as Error;+ log('Error polling video operation: %O', err);++ return {+ error: err.message || 'Failed to poll video status',+ status: 'failed',+ };+ }+}diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex 7fdfdbb0169..492b7eec67f 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -20,12 +20,14 @@ import {} from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { type CreateImagePayload, type CreateImageResponse } from '../../types/image';+import { type CreateVideoPayload, type CreateVideoResponse } from '../../types/video';import { AgentRuntimeError } from '../../utils/createError';import { debugStream } from '../../utils/debugStream';import { getModelPricing } from '../../utils/getModelPricing';import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';import { StreamingResponse } from '../../utils/response';import { createGoogleImage } from './createImage';+import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';import { resolveGoogleThinkingConfig } from './thinkingResolver';@@ -284,6 +286,14 @@ export class LobeGoogleAI implements LobeRuntimeAI {return createGoogleImage(this.client, this.provider, payload);}+ async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResponse> {+ return createGoogleVideo(this.client, this.provider, payload);+ }++ async handlePollVideoStatus(inferenceId: string) {+ return pollGoogleVideoOperation(this.client, inferenceId, this.provider, this.apiKey!);+ }+/*** Generate structured output using Google Gemini API* @see https://ai.google.dev/gemini-api/docs/structured-outputdiff --git a/packages/model-runtime/src/providers/minimax/createVideo.test.ts b/packages/model-runtime/src/providers/minimax/createVideo.test.tsnew file mode 100644index 00000000000..f8de37ef201--- /dev/null+++ b/packages/model-runtime/src/providers/minimax/createVideo.test.ts@@ -0,0 +1,327 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import {+ createMiniMaxVideo,+ pollMiniMaxVideoStatus,+ queryMiniMaxVideoStatus,+ retrieveMiniMaxVideoFile,+} from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createMiniMaxVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://api.minimaxi.com/v1',+ provider: 'minimax',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create video with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_id: 'minimax-task-123',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: {+ prompt: 'A beautiful landscape',+ },+ };++ const result = await createMiniMaxVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ 'https://api.minimaxi.com/v1/video_generation',+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'minimax-task-123' });+ });++ it('should include custom duration', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_id: 'task-custom-duration',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: {+ prompt: 'Test',+ duration: 10,+ },+ };++ await createMiniMaxVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.duration).toBe(10);+ });++ it('should include imageUrl as first_frame_image', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_id: 'task-image-input',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: {+ prompt: 'Animate this',+ imageUrl: 'https://example.com/first.jpg',+ },+ };++ await createMiniMaxVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.first_frame_image).toBe('https://example.com/first.jpg');+ });++ it('should include endImageUrl as last_frame_image', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_id: 'task-two-images',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: {+ prompt: 'Transform',+ imageUrl: 'https://example.com/first.jpg',+ endImageUrl: 'https://example.com/last.jpg',+ },+ };++ await createMiniMaxVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.first_frame_image).toBe('https://example.com/first.jpg');+ expect(body.last_frame_image).toBe('https://example.com/last.jpg');+ });++ it('should throw on non-zero status_code', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_id: 'task-error',+ base_resp: { status_code: 4001, status_msg: 'Invalid prompt' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: { prompt: 'Test' },+ };++ await expect(createMiniMaxVideo(payload, mockOptions)).rejects.toThrow(+ 'MiniMax video API error: Invalid prompt',+ );+ });++ it('should throw when missing task_id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'video-01',+ params: { prompt: 'Test' },+ };++ await expect(createMiniMaxVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing task_id',+ );+ });+});++describe('pollMiniMaxVideoStatus', () => {+ const options = {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ };++ it('should return success when task succeeded', async () => {+ global.fetch = vi+ .fn()+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Success',+ file_id: 'file-123',+ task_id: 'task-123',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ file: { download_url: 'https://cdn.minimax.com/video.mp4' },+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const result = await pollMiniMaxVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.minimax.com/video.mp4',+ });+ });++ it('should return failed when task failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Fail',+ base_resp: { status_code: 500, status_msg: 'Processing error' },+ }),+ });++ const result = await pollMiniMaxVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Processing error',+ });+ });++ it('should return pending when task in progress', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Processing',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const result = await pollMiniMaxVideoStatus('task-123', options);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when succeeded but no file_id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Success',+ task_id: 'task-123',+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ const result = await pollMiniMaxVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no file_id found',+ });+ });+});++describe('queryMiniMaxVideoStatus', () => {+ it('should query status endpoint with task_id param', async () => {+ const mockResponse = {+ status: 'Success',+ task_id: 'task-123',+ base_resp: { status_code: 0, status_msg: 'success' },+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryMiniMaxVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ });++ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/query/video_generation?task_id=task-123'),+ expect.any(Object),+ );+ expect(result).toEqual(mockResponse);+ });+});++describe('retrieveMiniMaxVideoFile', () => {+ it('should retrieve file download URL', async () => {+ const mockResponse = {+ file: {+ download_url: 'https://cdn.minimax.com/video.mp4',+ file_id: 'file-123',+ },+ base_resp: { status_code: 0, status_msg: 'success' },+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await retrieveMiniMaxVideoFile('file-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ });++ expect(result).toBe('https://cdn.minimax.com/video.mp4');+ });++ it('should throw on non-zero status_code', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ base_resp: { status_code: 404, status_msg: 'File not found' },+ }),+ });++ await expect(+ retrieveMiniMaxVideoFile('invalid-file', {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ }),+ ).rejects.toThrow('MiniMax file retrieve error: File not found');+ });++ it('should throw when missing download_url', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ file: {},+ base_resp: { status_code: 0, status_msg: 'success' },+ }),+ });++ await expect(+ retrieveMiniMaxVideoFile('file-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ }),+ ).rejects.toThrow('Missing download_url in MiniMax file retrieve response');+ });+});diff --git a/packages/model-runtime/src/providers/minimax/createVideo.ts b/packages/model-runtime/src/providers/minimax/createVideo.tsnew file mode 100644index 00000000000..0bbf9d2779e--- /dev/null+++ b/packages/model-runtime/src/providers/minimax/createVideo.ts@@ -0,0 +1,194 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';++const log = createDebug('lobe-video:minimax');++interface MiniMaxVideoCreateResponse {+ base_resp: {+ status_code: number;+ status_msg: string;+ };+ task_id: string;+}++interface MiniMaxVideoStatusResponse {+ base_resp: {+ status_code: number;+ status_msg: string;+ };+ duration?: number;+ file_id?: string;+ status: 'Success' | 'Fail' | 'Preparing' | 'Processing' | 'Queueing';+ task_id: string;+ video_height?: number;+ video_width?: number;+}++interface MiniMaxFileRetrieveResponse {+ base_resp: {+ status_code: number;+ status_msg: string;+ };+ file: {+ bytes: number;+ created_at: number;+ download_url: string;+ file_id: string;+ filename: string;+ purpose: string;+ };+}++export async function queryMiniMaxVideoStatus(+ taskId: string,+ options: { apiKey: string; baseURL: string },+): Promise<MiniMaxVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/query/video_generation`;+ const urlWithParams = new URL(statusUrl);+ urlWithParams.searchParams.append('task_id', taskId);++ const response = await fetch(urlWithParams.toString(), {+ headers: {+ Authorization: `Bearer ${options.apiKey}`,+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`MiniMax status API error: ${response.status} ${errorText}`);+ }++ return (await response.json()) as MiniMaxVideoStatusResponse;+}++export async function retrieveMiniMaxVideoFile(+ fileId: string,+ options: { apiKey: string; baseURL: string },+): Promise<string> {+ const retrieveUrl = `${options.baseURL}/files/retrieve`;+ const urlWithParams = new URL(retrieveUrl);+ urlWithParams.searchParams.append('file_id', fileId);++ const response = await fetch(urlWithParams.toString(), {+ headers: {+ Authorization: `Bearer ${options.apiKey}`,+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`MiniMax file retrieve API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as MiniMaxFileRetrieveResponse;++ if (data.base_resp?.status_code !== 0) {+ throw new Error(`MiniMax file retrieve error: ${data.base_resp?.status_msg}`);+ }++ if (!data.file?.download_url) {+ throw new Error('Missing download_url in MiniMax file retrieve response');+ }++ return data.file.download_url;+}++export async function pollMiniMaxVideoStatus(+ taskId: string,+ options: { apiKey: string; baseURL: string },+): Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ const response = await queryMiniMaxVideoStatus(taskId, options);++ if (response.status === 'Success') {+ const fileId = response.file_id;+ if (!fileId) {+ return { error: 'Task succeeded but no file_id found', status: 'failed' };+ }++ try {+ const videoUrl = await retrieveMiniMaxVideoFile(fileId, options);+ return { status: 'success', videoUrl };+ } catch (error) {+ return {+ error: `Failed to retrieve video file: ${error instanceof Error ? error.message : 'Unknown error'}`,+ status: 'failed',+ };+ }+ }++ if (response.status === 'Fail') {+ return { error: response.base_resp?.status_msg || 'Video generation failed', status: 'failed' };+ }++ return { status: 'pending' };+}++export async function createMiniMaxVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, endImageUrl, duration, resolution } = params;++ const baseURL = options.baseURL || 'https://api.minimaxi.com/v1';++ const body: Record<string, unknown> = {+ model,+ prompt,+ aigc_watermark: false, // Disable watermark for better user experience+ ...(typeof duration === 'number' ? { duration } : {}),+ ...(typeof resolution === 'string' ? { resolution } : {}),+ };++ if (imageUrl) {+ // For S2V-01 model, the image is treated as subject reference and included in the prompt.+ if (model === 'S2V-01') {+ body.subject_reference = [+ {+ type: 'character',+ image: [imageUrl],+ },+ ];+ } else {+ // For other models, the image is treated as the first frame of the video.+ body.first_frame_image = imageUrl;+ }+ }+ if (endImageUrl) {+ body.last_frame_image = endImageUrl;+ }++ const response = await fetch(`${baseURL}/video_generation`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`MiniMax video API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as MiniMaxVideoCreateResponse;++ if (data.base_resp.status_code !== 0) {+ throw new Error(`MiniMax video API error: ${data.base_resp.status_msg}`);+ }++ if (!data.task_id) {+ throw new Error('Invalid response: missing task_id');+ }++ return { inferenceId: data.task_id };+}diff --git a/packages/model-runtime/src/providers/minimax/index.ts b/packages/model-runtime/src/providers/minimax/index.tsindex 7c0f659ac8f..08841e9b24c 100644--- a/packages/model-runtime/src/providers/minimax/index.ts+++ b/packages/model-runtime/src/providers/minimax/index.ts@@ -4,6 +4,7 @@ import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactorimport { resolveParameters } from '../../core/parameterResolver';import { getModelMaxOutputs } from '../../utils/getModelMaxOutputs';import { createMiniMaxImage } from './createImage';+import { createMiniMaxVideo } from './createVideo';export const LobeMinimaxAI = createOpenAICompatibleRuntime({baseURL: 'https://api.minimaxi.com/v1',@@ -72,6 +73,14 @@ export const LobeMinimaxAI = createOpenAICompatibleRuntime({},},createImage: createMiniMaxImage,+ createVideo: createMiniMaxVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollMiniMaxVideoStatus } = await import('./createVideo');+ return pollMiniMaxVideoStatus(inferenceId, {+ apiKey: options.apiKey,+ baseURL: options.baseURL || '',+ });+ },debug: {chatCompletion: () => process.env.DEBUG_MINIMAX_CHAT_COMPLETION === '1',},diff --git a/packages/model-runtime/src/providers/qwen/createVideo.test.ts b/packages/model-runtime/src/providers/qwen/createVideo.test.tsnew file mode 100644index 00000000000..b17d62cc9a2--- /dev/null+++ b/packages/model-runtime/src/providers/qwen/createVideo.test.ts@@ -0,0 +1,351 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import { createQwenVideo, pollQwenVideoStatus, queryQwenVideoStatus } from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createQwenVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://dashscope.aliyuncs.com',+ provider: 'qwen',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create text-to-video task', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'qwen-task-123', task_status: 'PENDING' },+ request_id: 'req-456',+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'wan2.2-t2v-plus',+ params: {+ prompt: 'A beautiful sunset',+ },+ };++ const result = await createQwenVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/api/v1/services/aigc/video-generation/video-synthesis'),+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'qwen-task-123' });+ });++ it('should create image-to-video task for i2v models', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'i2v-task-789', task_status: 'PENDING' },+ request_id: 'req-000',+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'wan2.2-i2v-plus',+ params: {+ prompt: 'Animate this image',+ imageUrl: 'https://example.com/image.jpg',+ },+ };++ await createQwenVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.input.img_url).toBe('https://example.com/image.jpg');+ expect(body.input.prompt).toBe('Animate this image');+ });++ it('should create keyframe-to-video task for kf2v models', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'kf2v-task-111', task_status: 'PENDING' },+ request_id: 'req-222',+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'wan2.2-kf2v-flash',+ params: {+ prompt: 'Transform between frames',+ imageUrl: 'https://example.com/first.jpg',+ endImageUrl: 'https://example.com/last.jpg',+ },+ };++ await createQwenVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.input.first_frame_url).toBe('https://example.com/first.jpg');+ expect(body.input.last_frame_url).toBe('https://example.com/last.jpg');+ expect(body.input.prompt).toBe('Transform between frames');+ });++ it('should create vidu task with images in input.media', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'vidu-task-321', task_status: 'PENDING' },+ request_id: 'req-654',+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'vidu/viduq3-turbo_start-end2video',+ params: {+ duration: 5,+ imageUrl: 'https://example.com/first.jpg',+ endImageUrl: 'https://example.com/last.jpg',+ prompt: 'A cat jumps from the windowsill to the sofa',+ resolution: '720p',+ },+ };++ await createQwenVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.input.media).toEqual([+ { type: 'image', url: 'https://example.com/first.jpg' },+ { type: 'image', url: 'https://example.com/last.jpg' },+ ]);+ expect(body.input.prompt).toBe('A cat jumps from the windowsill to the sofa');+ expect(body.parameters.duration).toBe(5);+ expect(body.parameters.resolution).toBe('720p');+ });++ it('should include optional parameters', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'full-params-task', task_status: 'PENDING' },+ request_id: 'req-333',+ }),+ });++ const payload: CreateVideoPayload = {+ model: 'wan2.2-t2v-plus',+ params: {+ prompt: 'Test',+ size: '1920x1080',+ duration: 10,+ generateAudio: true,+ },+ };++ await createQwenVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.parameters.size).toBe('1920*1080');+ expect(body.parameters.duration).toBe(10);+ expect(body.parameters.audio).toBe(true);+ });++ it('should remove /compatible-mode/v1 suffix from baseURL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: { task_id: 'task-suffix-removal', task_status: 'PENDING' },+ request_id: 'req-444',+ }),+ });++ const options: CreateVideoOptions = {+ ...mockOptions,+ baseURL: 'https://custom-endpoint.com/compatible-mode/v1',+ };++ const payload: CreateVideoPayload = {+ model: 'wan2.2-t2v-plus',+ params: { prompt: 'Test' },+ };++ await createQwenVideo(payload, options);++ const url = (global.fetch as any).mock.calls[0][0];+ expect(url).not.toContain('/compatible-mode/v1');+ expect(url).toContain('https://custom-endpoint.com');+ });++ it('should throw error when image required but missing for i2v model', async () => {+ const payload: CreateVideoPayload = {+ model: 'wan2.2-i2v-plus',+ params: {+ prompt: 'Animate this',+ },+ };++ await expect(createQwenVideo(payload, mockOptions)).rejects.toMatchObject({+ errorType: 'ProviderBizError',+ provider: 'qwen',+ });+ });++ it('should throw error when keyframe images required but missing', async () => {+ const payload: CreateVideoPayload = {+ model: 'wan2.2-kf2v-flash',+ params: {+ prompt: 'Transform',+ },+ };++ await expect(createQwenVideo(payload, mockOptions)).rejects.toMatchObject({+ errorType: 'ProviderBizError',+ provider: 'qwen',+ });+ });++ it('should throw error when vidu image required but missing', async () => {+ const payload: CreateVideoPayload = {+ model: 'vidu/viduq3-turbo_start-end2video',+ params: {+ prompt: 'Transform',+ },+ };++ await expect(createQwenVideo(payload, mockOptions)).rejects.toMatchObject({+ errorType: 'ProviderBizError',+ provider: 'qwen',+ });+ });+});++describe('pollQwenVideoStatus', () => {+ const apiKey = 'test-key';+ const baseUrl = 'https://dashscope.aliyuncs.com';++ it('should return success when task succeeded', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: {+ task_id: 'task-123',+ task_status: 'SUCCEEDED',+ video_url: 'https://cdn.qwen.com/video.mp4',+ },+ request_id: 'req-555',+ }),+ });++ const result = await pollQwenVideoStatus('task-123', apiKey, baseUrl);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.qwen.com/video.mp4',+ });+ });++ it('should return failed when task failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: {+ task_id: 'task-123',+ task_status: 'FAILED',+ error_message: 'Content policy violation',+ },+ request_id: 'req-666',+ }),+ });++ const result = await pollQwenVideoStatus('task-123', apiKey, baseUrl);++ expect(result).toEqual({+ status: 'failed',+ error: 'Content policy violation',+ });+ });++ it('should return pending when task running', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: {+ task_id: 'task-123',+ task_status: 'RUNNING',+ },+ request_id: 'req-777',+ }),+ });++ const result = await pollQwenVideoStatus('task-123', apiKey, baseUrl);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when succeeded but no video URL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ output: {+ task_id: 'task-123',+ task_status: 'SUCCEEDED',+ },+ request_id: 'req-888',+ }),+ });++ const result = await pollQwenVideoStatus('task-123', apiKey, baseUrl);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no video URL found',+ });+ });+});++describe('queryQwenVideoStatus', () => {+ it('should query task status endpoint', async () => {+ const mockResponse = {+ output: { task_id: 'task-123', task_status: 'RUNNING' },+ request_id: 'req-999',+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryQwenVideoStatus(+ 'task-123',+ 'test-key',+ 'https://dashscope.aliyuncs.com',+ );++ expect(fetch).toHaveBeenCalledWith(+ 'https://dashscope.aliyuncs.com/api/v1/tasks/task-123',+ expect.objectContaining({+ method: 'GET',+ headers: {+ Authorization: 'Bearer test-key',+ },+ }),+ );+ expect(result).toEqual(mockResponse);+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ await expect(+ queryQwenVideoStatus('invalid-task', 'test-key', 'https://dashscope.aliyuncs.com'),+ ).rejects.toThrow('Failed to query task status');+ });+});diff --git a/packages/model-runtime/src/providers/qwen/createVideo.ts b/packages/model-runtime/src/providers/qwen/createVideo.tsnew file mode 100644index 00000000000..397f81c456a--- /dev/null+++ b/packages/model-runtime/src/providers/qwen/createVideo.ts@@ -0,0 +1,335 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';+import { AgentRuntimeError } from '../../utils/createError';++const log = createDebug('lobe-video:qwen');++interface QwenVideoTaskResponse {+ output: {+ error_message?: string;+ task_id: string;+ task_status: 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED';+ video_url?: string;+ cover_image_url?: string;+ // For keyframe models+ first_frame_url?: string;+ last_frame_url?: string;+ };+ request_id: string;+ usage?: {+ duration?: number;+ size?: string;+ video_count?: number;+ };+}++// Model patterns for different video generation types+const image2VideoModels = [+ /^wan2\.(2|5)-i2v-/,+ /^wanx2\.(0|1)-i2v-/,+ /img2video$/,+ /reference2video$/,+ /it2v$/,+ /r2v$/,+];+const keyframe2VideoModels = [/^wan2\.(2|5)-kf2v-/, /start-end2video$/, /kf2v$/];+const reference2VideoModels = [/^wan2\.6-r2v/];++/**+ * Query the status of a video generation task+ */+export async function queryQwenVideoStatus(+ taskId: string,+ apiKey: string,+ baseUrl: string,+): Promise<QwenVideoTaskResponse> {+ const endpoint = `${baseUrl}/api/v1/tasks/${taskId}`;++ log('Querying task status for: %s', taskId);++ const response = await fetch(endpoint, {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ },+ method: 'GET',+ });++ if (!response.ok) {+ let errorData;+ try {+ errorData = await response.json();+ } catch {+ // Failed to parse JSON error response+ }+ throw new Error(+ `Failed to query task status for ${taskId} (${response.status}): ${errorData?.message || response.statusText}`,+ );+ }++ return response.json();+}++/**+ * Poll video status and return standardized result+ */+export async function pollQwenVideoStatus(+ taskId: string,+ apiKey: string,+ baseUrl: string,+): Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ const response = await queryQwenVideoStatus(taskId, apiKey, baseUrl);++ if (response.output.task_status === 'SUCCEEDED') {+ const videoUrl = response.output.video_url;+ if (!videoUrl) {+ return { error: 'Task succeeded but no video URL found', status: 'failed' };+ }+ return { status: 'success', videoUrl };+ }++ if (response.output.task_status === 'FAILED') {+ return { error: response.output.error_message || 'Video generation failed', status: 'failed' };+ }++ return { status: 'pending' };+}++// Helper function to check if model matches any pattern in the array+function matchesModelPattern(model: string, patterns: Array<RegExp>): boolean {+ return patterns.some((pattern) => pattern.test(model));+}++/**+ * Create a video generation task with Qwen DashScope API+ * Supports text-to-video, image-to-video, and keyframe-to-video+ */+async function createVideoTask(+ payload: CreateVideoPayload,+ apiKey: string,+ taskType: 'video-generation' | 'image2video',+ provider: string,+ baseUrl: string,+): Promise<string> {+ const { model, params } = payload;+ const { prompt, imageUrl, endImageUrl } = params;++ // Determine the endpoint based on task type+ const url = `${baseUrl}/api/v1/services/aigc/${taskType}/video-synthesis`;++ log('Creating %s task with model: %s, endpoint: %s', taskType, model, url);++ const input: Record<string, any> = {};+ const parameters: Record<string, any> = {};++ // Validate required parameters based on model type+ if (+ matchesModelPattern(model, image2VideoModels) ||+ matchesModelPattern(model, reference2VideoModels)+ ) {+ if (!imageUrl) {+ throw AgentRuntimeError.createVideo({+ error: new Error('imageUrl is required for image-to-video models'),+ errorType: 'ProviderBizError',+ provider,+ });+ }+ } else if (matchesModelPattern(model, keyframe2VideoModels) && (!imageUrl || !endImageUrl)) {+ throw AgentRuntimeError.createVideo({+ error: new Error(+ 'imageUrl (first frame) and endImageUrl (last frame) are required for keyframe-to-video models',+ ),+ errorType: 'ProviderBizError',+ provider,+ });+ }++ // Handle media input based on model type+ if (model.startsWith('vidu/')) {+ const media = [];+ if (imageUrl) {+ media.push({+ type: 'image',+ url: imageUrl,+ });+ }+ if (endImageUrl) {+ media.push({+ type: 'image',+ url: endImageUrl,+ });+ }+ if (media.length > 0) {+ input.media = media;+ }+ } else if (model.startsWith('kling/')) {+ const media = [];+ if (imageUrl) {+ media.push({+ type: 'first_frame',+ url: imageUrl,+ });+ }+ if (endImageUrl) {+ media.push({+ type: 'last_frame',+ url: endImageUrl,+ });+ }+ if (media.length > 0) {+ input.media = media;+ }+ } else if (model.startsWith('pixverse/')) {+ if (imageUrl && !endImageUrl) {+ input.media = [+ {+ type: 'image_url',+ url: imageUrl,+ },+ ];+ } else if (imageUrl && endImageUrl) {+ input.media = [+ {+ type: 'first_frame',+ url: imageUrl,+ },+ {+ type: 'last_frame',+ url: endImageUrl,+ },+ ];+ }+ } else if (matchesModelPattern(model, reference2VideoModels)) {+ input.reference_urls = [imageUrl];+ } else if (matchesModelPattern(model, keyframe2VideoModels)) {+ input.first_frame_url = imageUrl;+ input.last_frame_url = endImageUrl;+ } else if (matchesModelPattern(model, image2VideoModels)) {+ input.img_url = imageUrl;+ }++ // Add prompt to input for all models+ input.prompt = prompt;++ // Add optional parameters+ if (params.aspectRatio) {+ parameters.aspectRatio = params.aspectRatio;+ }++ if (params.size) {+ // Convert size format from "widthxheight" to "width*height" if needed+ parameters.size = params.size.replace('x', '*');+ }++ if (params.duration) {+ parameters.duration = params.duration;+ }++ if (params.generateAudio) {+ parameters.audio = params.generateAudio;+ }++ if (params.resolution) {+ if (model.startsWith('kling/')) {+ // For Kling models, resolution is determined by mode parameter. Map 1080p to pro mode, others to std mode.+ parameters.mode = params.resolution === '1080p' ? 'pro' : 'std';+ } else {+ parameters.resolution = params.resolution;+ }+ }++ const response = await fetch(url, {+ body: JSON.stringify({+ input,+ model,+ parameters,+ }),+ headers: {+ 'Authorization': `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ 'X-DashScope-Async': 'enable',+ },+ method: 'POST',+ });++ if (!response.ok) {+ let errorData;+ try {+ errorData = await response.json();+ } catch {+ // Failed to parse JSON error response+ }+ throw new Error(+ `Failed to create ${taskType} task for model ${model} (${response.status}): ${errorData?.message || response.statusText}`,+ );+ }++ const data: QwenVideoTaskResponse = await response.json();+ log('Video task created with ID: %s', data.output.task_id);++ return data.output.task_id;+}++/**+ * Create video using Qwen DashScope API+ * Supports three types:+ * - text-to-video (wan2.2-t2v-plus, wanx2.0-t2v-*)+ * - image-to-video (wan2.2-i2v-plus, wanx2.0-i2v-*)+ * - keyframe-to-video (wan2.2-kf2v-flash)+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createQwenVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { apiKey, baseURL, provider } = options;+ const { model, params } = payload;++ // Check if URL has /compatible-mode/v1 suffix and remove it+ const suffixIndex = baseURL ? baseURL.indexOf('/compatible-mode/v1') : -1;+ const dashscopeURL: string =+ suffixIndex > -1 ? baseURL!.slice(0, suffixIndex) : baseURL || 'https://dashscope.aliyuncs.com';++ log('Using dashscopeURL: %s', dashscopeURL);+ log('Creating video with model: %s, params: %O', model, params);++ try {+ const isKeyframe2Video = matchesModelPattern(model, keyframe2VideoModels);++ // Determine task type based on model+ let taskType: 'video-generation' | 'image2video';++ if (isKeyframe2Video) {+ taskType = 'image2video';+ log('Using image2video API for model: %s', model);+ } else {+ taskType = 'video-generation';+ log('Using video-generation API for model: %s', model);+ }++ // Create the video task+ const taskId = await createVideoTask(payload, apiKey, taskType, provider, dashscopeURL);++ log('Video task created with id: %s, returning immediately for frontend polling', taskId);++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30+ seconds during server-side polling+ return { inferenceId: taskId };+ } catch (error) {+ log('Error in createQwenVideo: %O', error);++ throw AgentRuntimeError.createVideo({+ error: error as any,+ errorType: 'ProviderBizError',+ provider,+ });+ }+}diff --git a/packages/model-runtime/src/providers/qwen/index.ts b/packages/model-runtime/src/providers/qwen/index.tsindex 0cae27c2711..13f5833fea9 100644--- a/packages/model-runtime/src/providers/qwen/index.ts+++ b/packages/model-runtime/src/providers/qwen/index.ts@@ -5,6 +5,7 @@ import { resolveParameters } from '../../core/parameterResolver';import { QwenAIStream } from '../../core/streams';import { processMultiProviderModelList } from '../../utils/modelParse';import { createQwenImage } from './createImage';+import { createQwenVideo } from './createVideo';export interface QwenModelCard {id: string;@@ -83,6 +84,16 @@ export const LobeQwenAI = createOpenAICompatibleRuntime({debug: {chatCompletion: () => process.env.DEBUG_QWEN_CHAT_COMPLETION === '1',},+ createVideo: createQwenVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollQwenVideoStatus } = await import('./createVideo');+ const baseURL = options.baseURL || '';++ const suffixIndex = baseURL.indexOf('/compatible-mode/v1');+ const dashscopeURL = suffixIndex > -1 ? baseURL.slice(0, suffixIndex) : baseURL;++ return pollQwenVideoStatus(inferenceId, options.apiKey || '', dashscopeURL);+ },models: async ({ client }) => {const modelsPage = (await client.models.list()) as any;const modelList: QwenModelCard[] = modelsPage.data;diff --git a/packages/model-runtime/src/providers/siliconcloud/createVideo.test.ts b/packages/model-runtime/src/providers/siliconcloud/createVideo.test.tsnew file mode 100644index 00000000000..6a410cc60bc--- /dev/null+++ b/packages/model-runtime/src/providers/siliconcloud/createVideo.test.ts@@ -0,0 +1,264 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import {+ createSiliconCloudVideo,+ pollSiliconCloudVideoStatus,+ querySiliconCloudVideoStatus,+} from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createSiliconCloudVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://api.siliconflow.cn/v1',+ provider: 'siliconcloud',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create video with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ requestId: 'sc-request-123' }),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: {+ prompt: 'A futuristic city',+ },+ };++ const result = await createSiliconCloudVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ 'https://api.siliconflow.cn/v1/video/submit',+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'sc-request-123' });+ });++ it('should include image_size parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ requestId: 'sc-size-test' }),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: {+ prompt: 'Test',+ size: '1920x1080',+ },+ };++ await createSiliconCloudVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.image_size).toBe('1920x1080');+ });++ it('should include seed parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ requestId: 'sc-seed-test' }),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: {+ prompt: 'Test',+ seed: 42,+ },+ };++ await createSiliconCloudVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.seed).toBe(42);+ });++ it('should not include seed when null', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ requestId: 'sc-null-seed' }),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: {+ prompt: 'Test',+ seed: null,+ },+ };++ await createSiliconCloudVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.seed).toBeUndefined();+ });++ it('should include imageUrl as image parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ requestId: 'sc-image-test' }),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: {+ prompt: 'Animate this',+ imageUrl: 'https://example.com/image.jpg',+ },+ };++ await createSiliconCloudVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.image).toBe('https://example.com/image.jpg');+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 402,+ text: async () => 'Insufficient balance',+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: { prompt: 'Test' },+ };++ await expect(createSiliconCloudVideo(payload, mockOptions)).rejects.toThrow(+ 'SiliconCloud video API error: 402 Insufficient balance',+ );+ });++ it('should throw when response missing requestId', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const payload: CreateVideoPayload = {+ model: 'stabilityai/stable-video-diffusion',+ params: { prompt: 'Test' },+ };++ await expect(createSiliconCloudVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing requestId',+ );+ });+});++describe('pollSiliconCloudVideoStatus', () => {+ const options = {+ apiKey: 'test-key',+ baseURL: 'https://api.siliconflow.cn/v1',+ };++ it('should return success when status is Succeed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Succeed',+ results: {+ videos: [{ url: 'https://cdn.siliconcloud.cn/video.mp4' }],+ },+ }),+ });++ const result = await pollSiliconCloudVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.siliconcloud.cn/video.mp4',+ });+ });++ it('should return failed when status is Failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Failed',+ reason: 'Content moderation failed',+ }),+ });++ const result = await pollSiliconCloudVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Content moderation failed',+ });+ });++ it('should return pending when status is Processing', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'Processing' }),+ });++ const result = await pollSiliconCloudVideoStatus('request-123', options);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when succeeded but no video URL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'Succeed',+ results: { videos: [] },+ }),+ });++ const result = await pollSiliconCloudVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no video URL found',+ });+ });+});++describe('querySiliconCloudVideoStatus', () => {+ it('should query status with POST request', async () => {+ const mockResponse = {+ status: 'Processing',+ requestId: 'request-123',+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await querySiliconCloudVideoStatus('request-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.siliconflow.cn/v1',+ });++ expect(fetch).toHaveBeenCalledWith(+ 'https://api.siliconflow.cn/v1/video/status',+ expect.objectContaining({+ method: 'POST',+ body: JSON.stringify({ requestId: 'request-123' }),+ headers: {+ 'Authorization': 'Bearer test-key',+ 'Content-Type': 'application/json',+ },+ }),+ );+ expect(result).toEqual(mockResponse);+ });+});diff --git a/packages/model-runtime/src/providers/siliconcloud/createVideo.ts b/packages/model-runtime/src/providers/siliconcloud/createVideo.tsnew file mode 100644index 00000000000..0257fb0b1a8--- /dev/null+++ b/packages/model-runtime/src/providers/siliconcloud/createVideo.ts@@ -0,0 +1,152 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';++const log = createDebug('lobe-video:siliconcloud');++interface SiliconCloudVideoStatusResponse {+ error?: {+ code?: string;+ message?: string;+ };+ reason?: string;+ requestId?: string;+ results?: {+ videos?: Array<{+ url?: string;+ }>;+ timings?: {+ inference: number;+ };+ seed?: number;+ };+ status?: string;+}++/**+ * Query the status of a video generation task+ */+export async function querySiliconCloudVideoStatus(+ requestId: string,+ options: { apiKey: string; baseURL: string },+): Promise<SiliconCloudVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/video/status`;++ log('Querying video status for: %s', requestId);++ const response = await fetch(statusUrl, {+ body: JSON.stringify({ requestId }),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`SiliconCloud status API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as SiliconCloudVideoStatusResponse;+ log('Video status response: %O', data);++ return data;+}++/**+ * Poll video status and return standardized result+ */+export async function pollSiliconCloudVideoStatus(+ requestId: string,+ options: { apiKey: string; baseURL: string },+): Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ const response = await querySiliconCloudVideoStatus(requestId, options);++ if (response.status === 'Succeed') {+ const videoUrl = response.results?.videos?.[0]?.url;+ if (!videoUrl) {+ return { error: 'Task succeeded but no video URL found', status: 'failed' };+ }+ return { status: 'success', videoUrl };+ }++ if (response.status === 'Failed') {+ return {+ error: response.reason || response.error?.message || 'Video generation failed',+ status: 'failed',+ };+ }++ return { status: 'pending' };+}++/**+ * SiliconCloud video generation implementation+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createSiliconCloudVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, size, seed } = params;++ log('Creating video with SiliconCloud API - model: %s, params: %O', model, params);++ const baseURL = options.baseURL || 'https://api.siliconflow.cn/v1';++ const body: Record<string, unknown> = {+ model,+ prompt,+ };++ if (size) {+ body['image_size'] = size;+ }++ if (seed !== undefined && seed !== null) body['seed'] = seed;++ if (imageUrl) {+ body['image'] = imageUrl;+ }++ log('SiliconCloud video API request body: %O', body);++ const response = await fetch(`${baseURL}/video/submit`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log('SiliconCloud video API error: %s %s', response.status, errorText);+ throw new Error(`SiliconCloud video API error: ${response.status} ${errorText}`);+ }++ const data = await response.json();+ log('SiliconCloud video API response: %O', data);++ if (!data?.requestId) {+ throw new Error('Invalid response: missing requestId');+ }++ const inferenceId = data.requestId;+ log('Video task created with id: %s, returning immediately for frontend polling', inferenceId);++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30+ seconds during server-side polling+ return { inferenceId };+}diff --git a/packages/model-runtime/src/providers/siliconcloud/index.ts b/packages/model-runtime/src/providers/siliconcloud/index.tsindex b072daffdb8..feaae02c0ca 100644--- a/packages/model-runtime/src/providers/siliconcloud/index.ts+++ b/packages/model-runtime/src/providers/siliconcloud/index.ts@@ -6,6 +6,7 @@ import type { ChatCompletionErrorPayload } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { processMultiProviderModelList } from '../../utils/modelParse';import { createSiliconCloudImage } from './createImage';+import { createSiliconCloudVideo } from './createVideo';export interface SiliconCloudModelCard {id: string;@@ -119,6 +120,14 @@ export const params = {fetch: siliconFetch,},createImage: createSiliconCloudImage,+ createVideo: createSiliconCloudVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollSiliconCloudVideoStatus } = await import('./createVideo');+ return pollSiliconCloudVideoStatus(inferenceId, {+ apiKey: options.apiKey,+ baseURL: options.baseURL || '',+ });+ },debug: {chatCompletion: () => process.env.DEBUG_SILICONCLOUD_CHAT_COMPLETION === '1',},diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.tsindex 1f1116fb8c6..80be91141fe 100644--- a/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts@@ -40,7 +40,18 @@ describe('createVolcengineVideo', () => {const result = await createVolcengineVideo(payload, options);- expect(result).toEqual({ inferenceId: 'task-abc-123' });+ expect(result).toEqual({ inferenceId: 'task-abc-123', useWebhook: true });+ });++ it('should return useWebhook: true to indicate webhook-based async flow', async () => {+ mockFetch.mockResolvedValue({+ json: () => Promise.resolve({ id: 'task-webhook' }),+ ok: true,+ });++ const result = await createVolcengineVideo(payload, options);++ expect((result as any).useWebhook).toBe(true);});it('should send minimal body with only prompt', async () => {diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.tsindex f78a1304c05..02d9165cafb 100644--- a/packages/model-runtime/src/providers/volcengine/video/createVideo.ts+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.ts@@ -81,5 +81,5 @@ export async function createVolcengineVideo(throw new Error('Invalid response: missing task id');}- return { inferenceId: data.id };+ return { inferenceId: data.id, useWebhook: true };}diff --git a/packages/model-runtime/src/providers/wenxin/createVideo.test.ts b/packages/model-runtime/src/providers/wenxin/createVideo.test.tsnew file mode 100644index 00000000000..6ae3fba4570--- /dev/null+++ b/packages/model-runtime/src/providers/wenxin/createVideo.test.ts@@ -0,0 +1,291 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import { createWenxinVideo, pollWenxinVideoStatus, queryWenxinVideoStatus } from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createWenxinVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://qianfan.baidubce.com',+ provider: 'wenxin',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create video with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'wenxin-task-123' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'A beautiful landscape',+ },+ };++ const result = await createWenxinVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ 'https://qianfan.baidubce.com/video/generations',+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'wenxin-task-123' });+ });++ it('should build content array with text', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'wenxin-text-only' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Test prompt',+ },+ };++ await createWenxinVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.content).toEqual([{ type: 'text', text: 'Test prompt' }]);+ });++ it('should add image_url entry when imageUrl provided', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'wenxin-image2vid' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Animate this',+ imageUrl: 'https://example.com/image.jpg',+ },+ };++ await createWenxinVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.content).toHaveLength(2);+ expect(body.content[1]).toEqual({+ type: 'image_url',+ image_url: { url: 'https://example.com/image.jpg' },+ });+ });++ it('should include optional parameters', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'wenxin-full' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Test',+ aspectRatio: '16:9',+ duration: 10,+ generateAudio: true,+ },+ };++ await createWenxinVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.aspect_ratio).toBe('16:9');+ expect(body.duration).toBe(10);+ expect(body.generate_audio).toBe(true);+ });++ it('should remove /v2 suffix from baseURL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_id: 'wenxin-v2-removal' }),+ });++ const options: CreateVideoOptions = {+ ...mockOptions,+ baseURL: 'https://custom.baidubce.com/v2',+ };++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: { prompt: 'Test' },+ };++ await createWenxinVideo(payload, options);++ const url = (global.fetch as any).mock.calls[0][0];+ expect(url).not.toContain('/v2');+ expect(url).toContain('https://custom.baidubce.com/video/generations');+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 400,+ text: async () => 'Invalid parameters',+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: { prompt: 'Test' },+ };++ await expect(createWenxinVideo(payload, mockOptions)).rejects.toThrow(+ 'Wenxin video API error: 400 Invalid parameters',+ );+ });++ it('should throw when response missing task_id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: { prompt: 'Test' },+ };++ await expect(createWenxinVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing task_id',+ );+ });+});++describe('pollWenxinVideoStatus', () => {+ const options = {+ apiKey: 'test-key',+ baseURL: 'https://qianfan.baidubce.com',+ };++ it('should return success when status is succeeded', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'succeeded',+ content: { video_url: 'https://cdn.wenxin.com/video.mp4' },+ }),+ });++ const result = await pollWenxinVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.wenxin.com/video.mp4',+ });+ });++ it('should return failed when status is failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'failed' }),+ });++ const result = await pollWenxinVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Video generation failed',+ });+ });++ it('should return pending when status is processing', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'processing' }),+ });++ const result = await pollWenxinVideoStatus('task-123', options);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when succeeded but no video URL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'succeeded',+ content: {},+ }),+ });++ const result = await pollWenxinVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no video URL found',+ });+ });+});++describe('queryWenxinVideoStatus', () => {+ it('should query status endpoint with task_id query param', async () => {+ const mockResponse = {+ status: 'processing',+ task_id: 'task-123',+ width: 1920,+ height: 1080,+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryWenxinVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://qianfan.baidubce.com',+ });++ expect(fetch).toHaveBeenCalledWith(+ expect.stringContaining('/video/generations?task_id=task-123'),+ expect.any(Object),+ );+ expect(result).toEqual(mockResponse);+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 404,+ text: async () => 'Task not found',+ });++ await expect(+ queryWenxinVideoStatus('invalid-task', {+ apiKey: 'test-key',+ baseURL: 'https://qianfan.baidubce.com',+ }),+ ).rejects.toThrow('Wenxin status API error: 404 Task not found');+ });++ it('should not include /v2 in the polling URL when baseURL contains /v2', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'processing', task_id: 'task-v2' }),+ });++ await queryWenxinVideoStatus('task-v2', {+ apiKey: 'test-key',+ baseURL: 'https://qianfan.baidubce.com',+ });++ const url = (global.fetch as any).mock.calls[0][0];+ expect(url).toBe('https://qianfan.baidubce.com/video/generations?task_id=task-v2');+ expect(url).not.toContain('/v2/');+ });+});diff --git a/packages/model-runtime/src/providers/wenxin/createVideo.ts b/packages/model-runtime/src/providers/wenxin/createVideo.tsnew file mode 100644index 00000000000..e3274f63584--- /dev/null+++ b/packages/model-runtime/src/providers/wenxin/createVideo.ts@@ -0,0 +1,160 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';++const log = createDebug('lobe-video:wenxin');++interface WenxinVideoStatusResponse {+ content?: {+ video_url?: string;+ };+ created_at?: number;+ duration?: number;+ height?: number;+ id?: string;+ model?: string;+ status?: string;+ task_id?: string;+ updated_at?: number;+ width?: number;+}++/**+ * Query the status of a video generation task+ * API docs: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Blf7thw8d+ */+export async function queryWenxinVideoStatus(+ task_id: string,+ options: { apiKey: string; baseURL: string },+): Promise<WenxinVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/video/generations?task_id=${task_id}`;++ log('Querying video status for task: %s', task_id);++ const response = await fetch(statusUrl, {+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Wenxin status API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as WenxinVideoStatusResponse;+ log('Video status response: %O', data);++ return data;+}++/**+ * Poll video status and return standardized result+ */+export async function pollWenxinVideoStatus(+ task_id: string,+ options: { apiKey: string; baseURL: string },+): Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ const response = await queryWenxinVideoStatus(task_id, options);++ if (response.status === 'succeeded') {+ const videoUrl = response.content?.video_url;+ if (!videoUrl) {+ return { error: 'Task succeeded but no video URL found', status: 'failed' };+ }+ return { status: 'success', videoUrl };+ }++ if (response.status === 'failed') {+ return { error: 'Video generation failed', status: 'failed' };+ }++ return { status: 'pending' };+}++/**+ * Wenxin video generation implementation+ * API docs: https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Blf7thw8d+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createWenxinVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, aspectRatio, duration, generateAudio } = params;++ log('Creating video with Wenxin API - model: %s, params: %O', model, params);++ const baseURL = options.baseURL?.replace('/v2', '') || 'https://qianfan.baidubce.com';++ // Build content array based on Wenxin API format+ const content: Array<{ type: string; text?: string; image_url?: { url: string } }> = [+ {+ text: prompt,+ type: 'text',+ },+ ];++ // Add image if provided (for image-to-video)+ if (imageUrl) {+ content.push({+ image_url: {+ url: imageUrl,+ },+ type: 'image_url',+ });+ }++ // Build request body+ const body: Record<string, unknown> = {+ content,+ model,+ };++ // Add optional parameters based on Wenxin API+ if (aspectRatio) body.aspect_ratio = aspectRatio;+ if (duration) body.duration = duration;+ if (generateAudio !== undefined) body.generate_audio = generateAudio;++ log('Wenxin video API request body: %O', body);++ const response = await fetch(`${baseURL}/video/generations`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log('Wenxin video API error: %s %s', response.status, errorText);+ throw new Error(`Wenxin video API error: ${response.status} ${errorText}`);+ }++ const data = await response.json();+ log('Wenxin video API response: %O', data);++ if (!data?.task_id) {+ throw new Error('Invalid response: missing task_id');+ }++ const taskId = data.task_id;+ log('Video task created with task_id: %s, returning immediately for frontend polling', taskId);++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30+ seconds during server-side polling+ return { inferenceId: taskId };+}diff --git a/packages/model-runtime/src/providers/wenxin/index.test.ts b/packages/model-runtime/src/providers/wenxin/index.test.tsindex ddb13dbc798..b6e36dc370a 100644--- a/packages/model-runtime/src/providers/wenxin/index.test.ts+++ b/packages/model-runtime/src/providers/wenxin/index.test.ts@@ -141,6 +141,25 @@ describe('LobeWenxinAI - Custom Features', () => {});});+ describe('handlePollVideoStatus', () => {+ it('should strip /v2 from baseURL when polling video status', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'processing', task_id: 'task-123' }),+ });++ await params.handlePollVideoStatus!('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://qianfan.baidubce.com/v2',+ provider: 'wenxin',+ });++ const url = (global.fetch as any).mock.calls[0][0];+ expect(url).toBe('https://qianfan.baidubce.com/video/generations?task_id=task-123');+ expect(url).not.toContain('/v2/');+ });+ });+describe('handlePayload', () => {it('should transform payload without enabledSearch', () => {const payload = {diff --git a/packages/model-runtime/src/providers/wenxin/index.ts b/packages/model-runtime/src/providers/wenxin/index.tsindex 81c8ae86e8c..e4e85475051 100644--- a/packages/model-runtime/src/providers/wenxin/index.ts+++ b/packages/model-runtime/src/providers/wenxin/index.ts@@ -4,6 +4,7 @@ import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleimport { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';import { processMultiProviderModelList } from '../../utils/modelParse';import { createWenxinImage } from './createImage';+import { createWenxinVideo } from './createVideo';export interface WenxinModelCard {id: string;@@ -26,9 +27,7 @@ export const params = {},}),...(thinking && {- enable_thinking: thinking.type- ? thinking.type !== 'disabled'- : undefined,+ enable_thinking: thinking.type ? thinking.type !== 'disabled' : undefined,...(thinking?.budget_tokens !== 0 && {thinking_budget: Math.min(Math.max(thinking?.budget_tokens, 100), 16_384),}),@@ -37,6 +36,14 @@ export const params = {},},createImage: createWenxinImage,+ createVideo: createWenxinVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollWenxinVideoStatus } = await import('./createVideo');+ return pollWenxinVideoStatus(inferenceId, {+ apiKey: options.apiKey,+ baseURL: (options.baseURL || '').replace('/v2', ''),+ });+ },debug: {chatCompletion: () => process.env.DEBUG_WENXIN_CHAT_COMPLETION === '1',},diff --git a/packages/model-runtime/src/providers/xai/createVideo.test.ts b/packages/model-runtime/src/providers/xai/createVideo.test.tsnew file mode 100644index 00000000000..7bcb5811cef--- /dev/null+++ b/packages/model-runtime/src/providers/xai/createVideo.test.ts@@ -0,0 +1,293 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import { createXAIVideo, pollXAIVideoStatus, queryXAIVideoStatus } from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createXAIVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://api.x.ai/v1',+ provider: 'xai',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create video with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-request-123' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'A cyberpunk city at night',+ },+ };++ const result = await createXAIVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ 'https://api.x.ai/v1/videos/generations',+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'xai-request-123' });+ });++ it('should include imageUrl as image object', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-image-input' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'Animate this',+ imageUrl: 'https://example.com/image.jpg',+ },+ };++ await createXAIVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.image).toEqual({ url: 'https://example.com/image.jpg' });+ });++ it('should include aspect_ratio parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-aspect' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'Test',+ aspectRatio: '21:9',+ },+ };++ await createXAIVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.aspect_ratio).toBe('21:9');+ });++ it('should include duration parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-duration' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'Test',+ duration: 6,+ },+ };++ await createXAIVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.duration).toBe(6);+ });++ it('should include resolution parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-resolution' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'Test',+ resolution: '4k',+ },+ };++ await createXAIVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.resolution).toBe('4k');+ });++ it('should include size parameter', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ request_id: 'xai-size' }),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: {+ prompt: 'Test',+ size: '1920x1080',+ },+ };++ await createXAIVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.size).toBe('1920x1080');+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 403,+ text: async () => 'Content policy violation',+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: { prompt: 'Test' },+ };++ await expect(createXAIVideo(payload, mockOptions)).rejects.toThrow(+ 'XAI video API error: 403 Content policy violation',+ );+ });++ it('should throw when response missing request_id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const payload: CreateVideoPayload = {+ model: 'grok-2.1-video',+ params: { prompt: 'Test' },+ };++ await expect(createXAIVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing request_id',+ );+ });+});++describe('pollXAIVideoStatus', () => {+ const options = {+ apiKey: 'test-key',+ baseURL: 'https://api.x.ai/v1',+ };++ it('should return success when status is done', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'done',+ video: { url: 'https://cdn.x.ai/video.mp4' },+ }),+ });++ const result = await pollXAIVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.x.ai/video.mp4',+ });+ });++ it('should return failed when status is failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'failed',+ error: { message: 'Content moderation failed' },+ }),+ });++ const result = await pollXAIVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Content moderation failed',+ });+ });++ it('should return pending when status is processing', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ status: 'processing' }),+ });++ const result = await pollXAIVideoStatus('request-123', options);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when done but no video URL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ status: 'done',+ video: {},+ }),+ });++ const result = await pollXAIVideoStatus('request-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no video URL found',+ });+ });+});++describe('queryXAIVideoStatus', () => {+ it('should query status endpoint', async () => {+ const mockResponse = {+ status: 'processing',+ model: 'grok-2.1-video',+ video: { duration: 6 },+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryXAIVideoStatus('request-123', {+ apiKey: 'test-key',+ baseURL: 'https://api.x.ai/v1',+ });++ expect(fetch).toHaveBeenCalledWith(+ 'https://api.x.ai/v1/videos/request-123',+ expect.objectContaining({+ method: 'GET',+ headers: {+ 'Authorization': 'Bearer test-key',+ 'Content-Type': 'application/json',+ },+ }),+ );+ expect(result).toEqual(mockResponse);+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 404,+ text: async () => 'Request not found',+ });++ await expect(+ queryXAIVideoStatus('invalid-request', {+ apiKey: 'test-key',+ baseURL: 'https://api.x.ai/v1',+ }),+ ).rejects.toThrow('XAI status API error: 404 Request not found');+ });+});diff --git a/packages/model-runtime/src/providers/xai/createVideo.ts b/packages/model-runtime/src/providers/xai/createVideo.tsnew file mode 100644index 00000000000..9c7f99782c4--- /dev/null+++ b/packages/model-runtime/src/providers/xai/createVideo.ts@@ -0,0 +1,156 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';++const log = createDebug('lobe-video:xai');++interface XAIVideoStatusResponse {+ error?: {+ code?: string;+ message?: string;+ };+ model?: string;+ status: 'processing' | 'done' | 'failed';+ video?: {+ duration?: number;+ respect_moderation?: boolean;+ url?: string;+ };+}++/**+ * Query the status of a video generation task+ */+export async function queryXAIVideoStatus(+ requestId: string,+ options: { apiKey: string; baseURL: string },+): Promise<XAIVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/videos/${requestId}`;++ log('Querying video status for: %s', requestId);++ const response = await fetch(statusUrl, {+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`XAI status API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as XAIVideoStatusResponse;+ log('Video status response: %O', data);++ return data;+}++/**+ * Poll video status and return standardized result+ */+export async function pollXAIVideoStatus(+ requestId: string,+ options: { apiKey: string; baseURL: string },+): Promise<+ | { status: 'success'; videoUrl: string }+ | { status: 'failed'; error: string }+ | { status: 'pending' }+> {+ const response = await queryXAIVideoStatus(requestId, options);++ if (response.status === 'done') {+ const videoUrl = response.video?.url;+ if (!videoUrl) {+ return { error: 'Task succeeded but no video URL found', status: 'failed' };+ }+ return { status: 'success', videoUrl };+ }++ if (response.status === 'failed') {+ return { error: response.error?.message || 'Video generation failed', status: 'failed' };+ }++ return { status: 'pending' };+}++/**+ * XAI video generation implementation+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createXAIVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, aspectRatio, duration, resolution, size } = params;++ log('Creating video with XAI API - model: %s, params: %O', model, params);++ const baseURL = options.baseURL || 'https://api.x.ai/v1';++ const body: Record<string, unknown> = {+ model,+ prompt,+ };++ if (imageUrl) {+ body.image = { url: imageUrl };+ }++ if (aspectRatio) {+ body.aspect_ratio = aspectRatio;+ }++ if (duration) {+ body.duration = duration;+ }++ if (resolution) {+ body.resolution = resolution;+ }++ if (size) {+ body.size = size;+ }++ log('XAI video API request body: %O', body);++ const response = await fetch(`${baseURL}/videos/generations`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log('XAI video API error: %s %s', response.status, errorText);+ throw new Error(`XAI video API error: ${response.status} ${errorText}`);+ }++ const data = await response.json();+ log('XAI video API response: %O', data);++ if (!data?.request_id) {+ throw new Error('Invalid response: missing request_id');+ }++ const requestId = data.request_id;+ log(+ 'Video task created with request_id: %s, returning immediately for frontend polling',+ requestId,+ );++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30+ seconds during server-side polling+ return { inferenceId: requestId };+}diff --git a/packages/model-runtime/src/providers/xai/index.ts b/packages/model-runtime/src/providers/xai/index.tsindex eeb42b1680e..f0fea9bce8d 100644--- a/packages/model-runtime/src/providers/xai/index.ts+++ b/packages/model-runtime/src/providers/xai/index.ts@@ -4,6 +4,7 @@ import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactorimport type { ChatStreamPayload } from '../../types';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import { createXAIImage } from './createImage';+import { createXAIVideo } from './createVideo';export interface XAIModelCard {id: string;@@ -41,6 +42,14 @@ export const LobeXAI = createOpenAICompatibleRuntime({useResponse: true,},createImage: createXAIImage,+ createVideo: createXAIVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollXAIVideoStatus } = await import('./createVideo');+ return pollXAIVideoStatus(inferenceId, {+ apiKey: options.apiKey,+ baseURL: options.baseURL || '',+ });+ },debug: {chatCompletion: () => process.env.DEBUG_XAI_CHAT_COMPLETION === '1',responses: () => process.env.DEBUG_XAI_RESPONSES === '1',diff --git a/packages/model-runtime/src/providers/zhipu/createVideo.test.ts b/packages/model-runtime/src/providers/zhipu/createVideo.test.tsnew file mode 100644index 00000000000..2c8bd67ba5d--- /dev/null+++ b/packages/model-runtime/src/providers/zhipu/createVideo.test.ts@@ -0,0 +1,245 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type { CreateVideoPayload } from '../../types/video';+import { createZhipuVideo, pollZhipuVideoStatus, queryZhipuVideoStatus } from './createVideo';++vi.mock('debug', () => ({+ default: vi.fn(() => vi.fn()),+}));++describe('createZhipuVideo', () => {+ const mockOptions: CreateVideoOptions = {+ apiKey: 'test-api-key',+ baseURL: 'https://open.bigmodel.cn/api/paas/v4',+ provider: 'zhipu',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should create video with basic prompt', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'zhipu-task-123' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'A robot dancing',+ },+ };++ const result = await createZhipuVideo(payload, mockOptions);++ expect(fetch).toHaveBeenCalledWith(+ 'https://open.bigmodel.cn/api/paas/v4/videos/generations',+ expect.any(Object),+ );+ expect(result).toEqual({ inferenceId: 'zhipu-task-123' });+ });++ it('should include image_url array with first frame', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'task-img2vid' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Animate this image',+ imageUrl: 'https://example.com/first.jpg',+ },+ };++ await createZhipuVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.image_url).toEqual(['https://example.com/first.jpg']);+ });++ it('should include both first and last frame in image_url array', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'task-transformer' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Transform first to last',+ imageUrl: 'https://example.com/first.jpg',+ endImageUrl: 'https://example.com/last.jpg',+ },+ };++ await createZhipuVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.image_url).toEqual([+ 'https://example.com/first.jpg',+ 'https://example.com/last.jpg',+ ]);+ });++ it('should include optional parameters', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ id: 'task-full' }),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: {+ prompt: 'Full options test',+ aspectRatio: '16:9',+ duration: 10,+ generateAudio: true,+ size: '1080p',+ },+ };++ await createZhipuVideo(payload, mockOptions);++ const body = JSON.parse((global.fetch as any).mock.calls[0][1].body);+ expect(body.aspect_ratio).toBe('16:9');+ expect(body.duration).toBe(10);+ expect(body.with_audio).toBe(true);+ expect(body.size).toBe('1080p');+ });++ it('should throw on HTTP error', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: false,+ status: 402,+ text: async () => 'Insufficient credits',+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: { prompt: 'Test' },+ };++ await expect(createZhipuVideo(payload, mockOptions)).rejects.toThrow(+ 'Zhipu video API error: 402 Insufficient credits',+ );+ });++ it('should throw when response missing id', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });++ const payload: CreateVideoPayload = {+ model: 'cogvideox',+ params: { prompt: 'Test' },+ };++ await expect(createZhipuVideo(payload, mockOptions)).rejects.toThrow(+ 'Invalid response: missing task id',+ );+ });+});++describe('pollZhipuVideoStatus', () => {+ const options = {+ apiKey: 'test-key',+ baseURL: 'https://open.bigmodel.cn/api/paas/v4',+ };++ it('should return success when task succeeded', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_status: 'SUCCESS',+ video_result: [{ url: 'https://cdn.zhipu.ai/video.mp4' }],+ }),+ });++ const result = await pollZhipuVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'success',+ videoUrl: 'https://cdn.zhipu.ai/video.mp4',+ });+ });++ it('should return failed when task failed', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ task_status: 'FAIL',+ error: { message: 'Content moderation failed' },+ }),+ });++ const result = await pollZhipuVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Content moderation failed',+ });+ });++ it('should return pending when task in progress', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_status: 'RUNNING' }),+ });++ const result = await pollZhipuVideoStatus('task-123', options);++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return failed when succeeded but no video URL', async () => {+ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => ({ task_status: 'SUCCESS', video_result: [] }),+ });++ const result = await pollZhipuVideoStatus('task-123', options);++ expect(result).toEqual({+ status: 'failed',+ error: 'Task succeeded but no video URL found',+ });+ });+});++describe('queryZhipuVideoStatus', () => {+ it('should query status endpoint correctly', async () => {+ const mockResponse = {+ task_status: 'SUCCESS',+ id: 'task-123',+ request_id: 'req-456',+ };++ global.fetch = vi.fn().mockResolvedValueOnce({+ ok: true,+ json: async () => mockResponse,+ });++ const result = await queryZhipuVideoStatus('task-123', {+ apiKey: 'test-key',+ baseURL: 'https://open.bigmodel.cn/api/paas/v4',+ });++ expect(fetch).toHaveBeenCalledWith(+ 'https://open.bigmodel.cn/api/paas/v4/async-result/task-123',+ expect.objectContaining({+ method: 'GET',+ headers: {+ 'Authorization': 'Bearer test-key',+ 'Content-Type': 'application/json',+ },+ }),+ );+ expect(result).toEqual(mockResponse);+ });+});diff --git a/packages/model-runtime/src/providers/zhipu/createVideo.ts b/packages/model-runtime/src/providers/zhipu/createVideo.tsnew file mode 100644index 00000000000..9d96d60d4ed--- /dev/null+++ b/packages/model-runtime/src/providers/zhipu/createVideo.ts@@ -0,0 +1,155 @@+import createDebug from 'debug';++import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';+import type {+ CreateVideoPayload,+ CreateVideoResponse,+ PollVideoStatusResult,+} from '../../types/video';++const log = createDebug('lobe-video:zhipu');++interface ZhipuVideoStatusResponse {+ error?: {+ code?: string;+ message?: string;+ };+ id?: string;+ request_id?: string;+ task_status?: string;+ video_result?: Array<{+ url?: string;+ cover_image_url?: string;+ watermarked_url?: string;+ }>;+}++/**+ * Query the status of a video generation task+ */+export async function queryZhipuVideoStatus(+ inferenceId: string,+ options: { apiKey: string; baseURL: string },+): Promise<ZhipuVideoStatusResponse> {+ const statusUrl = `${options.baseURL}/async-result/${inferenceId}`;++ log('Querying video status for: %s', inferenceId);++ const response = await fetch(statusUrl, {+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'GET',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Zhipu status API error: ${response.status} ${errorText}`);+ }++ const data = (await response.json()) as ZhipuVideoStatusResponse;+ log('Video status response: %O', data);++ return data;+}++/**+ * Poll video status and return standardized result+ */+export async function pollZhipuVideoStatus(+ inferenceId: string,+ options: { apiKey: string; baseURL: string },+): Promise<PollVideoStatusResult> {+ const response = await queryZhipuVideoStatus(inferenceId, options);++ if (response.task_status === 'SUCCESS') {+ const videoUrl = response.video_result?.[0]?.url;+ if (!videoUrl) {+ return { error: 'Task succeeded but no video URL found', status: 'failed' };+ }+ return { status: 'success', videoUrl };+ }++ if (response.task_status === 'FAIL') {+ return { error: response.error?.message || 'Video generation failed', status: 'failed' };+ }++ return { status: 'pending' };+}++/**+ * Zhipu video generation implementation+ * API docs: https://docs.bigmodel.cn/cn/guide/paid-recommendation/cogvideox+ *+ * Creates a video generation task and returns immediately with inferenceId.+ * The frontend polls the task status using async task polling mechanism.+ */+export async function createZhipuVideo(+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+): Promise<CreateVideoResponse> {+ const { model, params } = payload;+ const { prompt, imageUrl, endImageUrl, aspectRatio, duration, generateAudio, size } = params;++ log('Creating video with Zhipu API - model: %s, params: %O', model, params);++ const baseURL = options.baseURL || 'https://open.bigmodel.cn/api/paas/v4';++ // Build request body based on Zhipu CogVideoX API format+ const body: Record<string, unknown> = {+ model,+ prompt,+ };++ // Zhipu requires image_url as an array: [first_frame, last_frame?]+ // https://docs.bigmodel.cn/cn/guide/paid-recommendation/cogvideox+ const imageUrls: string[] = [];+ if (imageUrl) {+ imageUrls.push(imageUrl);+ }+ if (endImageUrl) {+ imageUrls.push(endImageUrl);+ }+ if (imageUrls.length > 0) {+ body.image_url = imageUrls;+ }++ // Add other optional parameters+ if (aspectRatio) body.aspect_ratio = aspectRatio;+ if (duration) body.duration = duration;+ if (generateAudio !== undefined) body.with_audio = generateAudio;+ if (size) body.size = size;++ log('Zhipu video API request body: %O', body);++ const response = await fetch(`${baseURL}/videos/generations`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${options.apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ log('Zhipu video API error: %s %s', response.status, errorText);+ throw new Error(`Zhipu video API error: ${response.status} ${errorText}`);+ }++ const data = await response.json();+ log('Zhipu video API response: %O', data);++ if (!data?.id) {+ throw new Error('Invalid response: missing task id');+ }++ const inferenceId = data.id;+ log('Video task created with id: %s, returning immediately for frontend polling', inferenceId);++ // Return immediately with inferenceId only+ // Frontend will poll the task status using the async task polling mechanism+ // This avoids blocking the API response for 30+ seconds during server-side polling+ return { inferenceId };+}diff --git a/packages/model-runtime/src/providers/zhipu/index.ts b/packages/model-runtime/src/providers/zhipu/index.tsindex 81d4b23771f..ae0f579fdf3 100644--- a/packages/model-runtime/src/providers/zhipu/index.ts+++ b/packages/model-runtime/src/providers/zhipu/index.ts@@ -9,6 +9,7 @@ import { OpenAIStream } from '../../core/streams/openai';import { convertIterableToStream } from '../../core/streams/protocol';import { getModelMaxOutputs } from '../../utils/getModelMaxOutputs';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';+import { createZhipuVideo } from './createVideo';export interface ZhipuModelCard {description: string;@@ -141,6 +142,14 @@ export const params = {});},},+ createVideo: createZhipuVideo,+ handlePollVideoStatus: async (inferenceId, options) => {+ const { pollZhipuVideoStatus } = await import('./createVideo');+ return pollZhipuVideoStatus(inferenceId, {+ apiKey: options.apiKey,+ baseURL: options.baseURL || '',+ });+ },debug: {chatCompletion: () => process.env.DEBUG_ZHIPU_CHAT_COMPLETION === '1',},diff --git a/packages/model-runtime/src/types/video.ts b/packages/model-runtime/src/types/video.tsindex d06d312d9c8..eec50bde8ab 100644--- a/packages/model-runtime/src/types/video.ts+++ b/packages/model-runtime/src/types/video.ts@@ -1,14 +1,41 @@import type { RuntimeVideoGenParams } from 'model-bank';+export type CreateVideoErrorPayload = {+ error: any;+ errorType: string;+ provider?: string;+};+export type CreateVideoPayload = {callbackUrl?: string;model: string;params: RuntimeVideoGenParams;};-export type CreateVideoResponse = {- inferenceId: string;-};+export type CreateVideoResponse =+ | {+ inferenceId: string;+ /** Provider uses webhook callback instead of polling */+ useWebhook?: boolean;+ }+ | {+ inferenceId: string;+ videoUrl: string;+ };++export type PollVideoStatusResult =+ | {+ headers?: Record<string, string>;+ status: 'success';+ videoUrl: string;+ }+ | {+ error: string;+ status: 'failed';+ }+ | {+ status: 'pending';+ };export type HandleCreateVideoWebhookPayload = {body: unknown;diff --git a/packages/model-runtime/src/utils/createError.ts b/packages/model-runtime/src/utils/createError.tsindex c14414fe275..2f4c0f648b4 100644--- a/packages/model-runtime/src/utils/createError.ts+++ b/packages/model-runtime/src/utils/createError.ts@@ -2,6 +2,7 @@ import type {AgentInitErrorPayload,ChatCompletionErrorPayload,CreateImageErrorPayload,+ CreateVideoErrorPayload,} from '../types';import type { ILobeAgentRuntimeErrorType } from '../types/error';@@ -12,4 +13,5 @@ export const AgentRuntimeError = {error?: any,): AgentInitErrorPayload => ({ error, errorType }),createImage: (error: CreateImageErrorPayload): CreateImageErrorPayload => error,+ createVideo: (error: CreateVideoErrorPayload): CreateVideoErrorPayload => error,};diff --git a/src/locales/default/video.ts b/src/locales/default/video.tsindex 172c92fe41c..5a99dedcf45 100644--- a/src/locales/default/video.ts+++ b/src/locales/default/video.ts@@ -12,6 +12,7 @@ export default {'config.resolution.label': 'Resolution','config.seed.label': 'Seed','config.seed.random': 'Random',+ 'config.size.label': 'Size','generation.actions.copyError': 'Copy Error Message','generation.actions.errorCopied': 'Error Message Copied to Clipboard','generation.actions.errorCopyFailed': 'Failed to Copy Error Message',diff --git a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx b/src/routes/(main)/(create)/video/features/PromptInput/index.tsxindex c89237cf793..f469459528d 100644--- a/src/routes/(main)/(create)/video/features/PromptInput/index.tsx+++ b/src/routes/(main)/(create)/video/features/PromptInput/index.tsx@@ -21,6 +21,7 @@ import {InlineVideoFrames,} from '@/routes/(main)/(create)/features/GenerationInput';import { AspectRatioSelect } from '@/routes/(main)/(create)/image/features/ConfigPanel';+import Select from '@/routes/(main)/(create)/image/features/ConfigPanel/components/Select';import VideoModelItem from '@/routes/(main)/(create)/video/features/ConfigPanel/components/ModelSelect/VideoModelItem';import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';import { useUserStore } from '@/store/user';@@ -51,6 +52,23 @@ const AspectRatioItem = memo(() => {return <AspectRatioSelect options={options} value={value} onChange={(v) => setValue(v as any)} />;});+const SizeItem = memo(() => {+ const { value, setValue, enumValues } = useVideoGenerationConfigParam('size');++ const options = useMemo(+ () =>+ enumValues?.map((size) => ({+ label: size,+ value: size,+ })) ?? [],+ [enumValues],+ );++ if (options.length === 0) return null;++ return <Select options={options} value={value} onChange={setValue} />;+});+const ResolutionItem = memo(() => {const { value, setValue, enumValues } = useVideoGenerationConfigParam('resolution');const options = useMemo(@@ -73,7 +91,31 @@ const ResolutionItem = memo(() => {});const DurationItem = memo(() => {- const { value, setValue, min, max, step } = useVideoGenerationConfigParam('duration');+ const { value, setValue, min, max, step, enumValues } = useVideoGenerationConfigParam('duration');++ const options = useMemo(+ () =>+ enumValues && enumValues.length > 0+ ? enumValues.map((v) => ({+ label: String(v),+ value: v,+ }))+ : [],+ [enumValues],+ );++ if (options.length > 0) {+ return (+ <Segmented+ block+ options={options}+ style={{ width: '100%' }}+ value={value ?? min}+ variant="filled"+ onChange={(v) => setValue(Number(v) as any)}+ />+ );+ }return (<SliderWithInput@@ -143,6 +185,7 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {const isSupportEndImageUrl = useVideoStore(isSupportedParamSelector('endImageUrl'));const isSupportAspectRatio = useVideoStore(isSupportedParamSelector('aspectRatio'));const isSupportResolution = useVideoStore(isSupportedParamSelector('resolution'));+ const isSupportSize = useVideoStore(isSupportedParamSelector('size'));const isSupportDuration = useVideoStore(isSupportedParamSelector('duration'));const isSupportSeed = useVideoStore(isSupportedParamSelector('seed'));const isSupportGenerateAudio = useVideoStore(isSupportedParamSelector('generateAudio'));@@ -269,6 +312,12 @@ const PromptInput = ({ showTitle = false }: PromptInputProps) => {<ResolutionItem /></Flexbox>)}+ {isSupportSize && (+ <Flexbox gap={6}>+ <Text fontSize={12}>{t('config.size.label')}</Text>+ <SizeItem />+ </Flexbox>+ )}{isSupportSeed && (<Flexbox gap={6}><Text fontSize={12}>{t('config.seed.label')}</Text>diff --git a/src/server/routers/async/index.ts b/src/server/routers/async/index.tsindex 9a10e0c4b1a..d32e409657c 100644--- a/src/server/routers/async/index.ts+++ b/src/server/routers/async/index.ts@@ -1,14 +1,16 @@-import { asyncRouter as router,publicProcedure } from '@/libs/trpc/async';+import { asyncRouter as router, publicProcedure } from '@/libs/trpc/async';import { fileRouter } from './file';import { imageRouter } from './image';import { ragEvalRouter } from './ragEval';+import { videoRouter } from './video';export const asyncRouter = router({file: fileRouter,healthcheck: publicProcedure.query(() => "i'm live!"),image: imageRouter,ragEval: ragEvalRouter,+ video: videoRouter,});export type AsyncRouter = typeof asyncRouter;diff --git a/src/server/routers/async/video.ts b/src/server/routers/async/video.tsnew file mode 100644index 00000000000..74f31aa620b--- /dev/null+++ b/src/server/routers/async/video.ts@@ -0,0 +1,293 @@+import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAfterGenerate';+import { AsyncTaskModel } from '@/database/models/asyncTask';+import { GenerationModel } from '@/database/models/generation';+import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { VideoGenerationService } from '@/server/services/generation/video';+import { FileSource } from '@/types/files';+import { sanitizeFileName } from '@/utils/sanitizeFileName';++const log = debug('lobe-video:async');++const videoProcedure = asyncAuthedProcedure.use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),+ generationModel: new GenerationModel(ctx.serverDB, ctx.userId),+ videoService: new VideoGenerationService(ctx.serverDB, ctx.userId),+ },+ });+});++const createVideoInputSchema = z.object({+ asyncTaskCreatedAt: z.date(),+ asyncTaskId: z.string(),+ generationBatchId: z.string(),+ generationId: z.string(),+ generationTopicId: z.string(),+ inferenceId: z.string(),+ model: z.string(),+ prechargeResult: z.any().optional(),+ provider: z.string(),+});++const checkAbortSignal = (signal: AbortSignal) => {+ if (signal.aborted) {+ throw new Error('Operation was aborted');+ }+};++async function pollUntilCompletion(+ modelRuntime: any,+ inferenceId: string,+ signal: AbortSignal,+): Promise<{ headers?: Record<string, string>; videoUrl: string } | null> {+ const maxRetries = 120;+ const pollingInterval = 5000;++ for (let attempt = 0; attempt < maxRetries; attempt++) {+ checkAbortSignal(signal);++ try {+ log('Polling attempt %d/%d for inferenceId: %s', attempt + 1, maxRetries, inferenceId);++ const result = await modelRuntime.handlePollVideoStatus(inferenceId);++ if (result.status === 'success') {+ log('Video generation succeeded for inferenceId: %s', inferenceId);+ return { headers: result.headers, videoUrl: result.videoUrl };+ }++ if (result.status === 'failed') {+ throw new Error(`Video generation failed: ${result.error}`);+ }++ log('Task %s still in progress, waiting...', inferenceId);++ await new Promise<void>((resolve, reject) => {+ const timeoutId = setTimeout(resolve, pollingInterval);+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timeoutId);+ reject(new Error('Operation was aborted'));+ },+ { once: true },+ );+ });+ } catch (error) {+ checkAbortSignal(signal);++ if (error instanceof Error && error.message.includes('failed')) {+ throw error;+ }++ log('Polling attempt %d failed for inferenceId: %s: %O', attempt + 1, inferenceId, error);++ await new Promise<void>((resolve, reject) => {+ const timeoutId = setTimeout(resolve, pollingInterval);+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timeoutId);+ reject(new Error('Operation was aborted'));+ },+ { once: true },+ );+ });+ }+ }++ throw new Error(+ `Video generation timeout after ${maxRetries} attempts (${(maxRetries * pollingInterval) / 1000}s)`,+ );+}++export const videoRouter = router({+ createVideo: videoProcedure.input(createVideoInputSchema).mutation(async ({ input, ctx }) => {+ const {+ asyncTaskCreatedAt,+ asyncTaskId,+ generationBatchId,+ generationId,+ generationTopicId,+ inferenceId,+ model,+ prechargeResult,+ provider,+ } = input;++ log('Starting async video polling: %O', {+ asyncTaskId,+ generationId,+ inferenceId,+ model,+ provider,+ });++ const abortController = new AbortController();+ let timeoutId: ReturnType<typeof setTimeout> | null = null;++ try {+ const pollingPromise = async (signal: AbortSignal) => {+ const asyncTaskModel = ctx.asyncTaskModel;+ const generationModel = ctx.generationModel;+ const videoService = ctx.videoService;++ log('Initializing agent runtime for provider: %s', provider);+ const modelRuntime = await initModelRuntimeFromDB(ctx.serverDB, ctx.userId, provider);++ checkAbortSignal(signal);++ const pollResult = await pollUntilCompletion(modelRuntime, inferenceId, signal);++ if (!pollResult) {+ log('Polling completed but no video URL returned for inferenceId: %s', inferenceId);+ throw new Error('Polling completed but no video URL returned');+ }++ log('Video polling succeeded for task: %s, processing video...', asyncTaskId);++ const processResult = await videoService.processVideoForGeneration(pollResult.videoUrl, {+ headers: pollResult.headers,+ });++ log('Video processed successfully, creating asset and file');++ const batch = await ctx.serverDB.query.generationBatches.findFirst({+ where: (batches, { eq }) => eq(batches.id, generationBatchId),+ });++ await generationModel.createAssetAndFile(+ generationId,+ {+ coverUrl: processResult.coverKey,+ duration: processResult.duration,+ height: processResult.height,+ originalUrl: pollResult.videoUrl,+ thumbnailUrl: processResult.thumbnailKey,+ type: 'video',+ url: processResult.videoKey,+ width: processResult.width,+ },+ {+ fileHash: processResult.fileHash,+ fileType: processResult.mimeType,+ name: `${sanitizeFileName(batch?.prompt ?? '', generationId)}.mp4`,+ size: processResult.fileSize,+ url: processResult.videoKey,+ },+ FileSource.VideoGeneration,+ );++ log('Asset and file created successfully for generation: %s', generationId);++ const duration = Date.now() - asyncTaskCreatedAt.getTime();++ log('Updating task status to Success: %s, duration: %dms', asyncTaskId, duration);+ await asyncTaskModel.update(asyncTaskId, {+ duration,+ status: AsyncTaskStatus.Success,+ });++ if (ENABLE_BUSINESS_FEATURES && prechargeResult) {+ try {+ await chargeAfterGenerate({+ computePriceParams: {+ generateAudio: (batch?.config as any)?.generateAudio,+ },+ latency: duration,+ metadata: {+ asyncTaskId,+ generationBatchId,+ modelId: model,+ topicId: generationTopicId,+ },+ model,+ prechargeResult,+ provider,+ usage: undefined,+ userId: ctx.userId,+ });+ log('Charge completed successfully for asyncTask: %s', asyncTaskId);+ } catch (chargeError) {+ console.error('[video-async] Failed to charge after generate:', chargeError);+ }+ }++ log('Async video generation completed successfully: %s', asyncTaskId);+ return { success: true };+ };++ timeoutId = setTimeout(() => {+ log('Video generation timeout, aborting operation: %s', asyncTaskId);+ abortController.abort();+ }, ASYNC_TASK_TIMEOUT);++ const result = await pollingPromise(abortController.signal);++ if (timeoutId) {+ clearTimeout(timeoutId);+ timeoutId = null;+ }++ return result;+ } catch (error: any) {+ if (timeoutId) {+ clearTimeout(timeoutId);+ }++ log('Async video generation failed: %O', {+ asyncTaskId,+ error: error.message || error,+ generationId,+ inferenceId,+ });++ await ctx.asyncTaskModel.update(asyncTaskId, {+ error: new AsyncTaskError(+ AsyncTaskErrorType.ServerError,+ 'Background polling failed: ' ++ (error instanceof Error ? error.message : 'Unknown error'),+ ),+ status: AsyncTaskStatus.Error,+ });++ log('Task status updated to Error: %s', asyncTaskId);++ if (prechargeResult && ENABLE_BUSINESS_FEATURES) {+ try {+ await chargeAfterGenerate({+ isError: true,+ metadata: {+ asyncTaskId,+ generationBatchId,+ modelId: model,+ topicId: generationTopicId,+ },+ model,+ prechargeResult,+ provider,+ userId: ctx.userId,+ });+ log('Precharge refunded successfully for asyncTask: %s', asyncTaskId);+ } catch (refundError) {+ console.error('[video-async] Failed to refund precharge on error:', refundError);+ }+ }++ return {+ message: `Video generation ${asyncTaskId} failed: ${error instanceof Error ? error.message : 'Unknown error'}`,+ success: false,+ };+ }+ }),+});diff --git a/src/server/routers/lambda/__tests__/video.test.ts b/src/server/routers/lambda/__tests__/video.test.tsnew file mode 100644index 00000000000..b94ef20baca--- /dev/null+++ b/src/server/routers/lambda/__tests__/video.test.ts@@ -0,0 +1,252 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { FileService } from '@/server/services/file';+import { AsyncTaskStatus } from '@/types/asyncTask';++// ---- hoisted mocks (available inside vi.mock factories) ----++const {+ mockAfter,+ mockCreateVideo,+ mockProcessBackgroundVideoPolling,+ mockServerDB,+ mockTransaction,+} = vi.hoisted(() => {+ const mockTransaction = vi.fn();+ const mockServerDB = { transaction: mockTransaction };+ const mockCreateVideo = vi.fn();+ const mockAfter = vi.fn((cb: () => void) => cb());+ const mockProcessBackgroundVideoPolling = vi.fn().mockResolvedValue(undefined);+ return {+ mockAfter,+ mockCreateVideo,+ mockProcessBackgroundVideoPolling,+ mockServerDB,+ mockTransaction,+ };+});++// ---- module-level mocks ----++vi.mock('@/database/models/asyncTask');+vi.mock('@/server/services/file');++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn().mockResolvedValue(mockServerDB),+}));+vi.mock('@/database/server', () => ({+ getServerDB: vi.fn().mockResolvedValue(mockServerDB),+}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn().mockResolvedValue({ createVideo: mockCreateVideo }),+}));+vi.mock('@/business/server/video-generation/chargeBeforeGenerate', () => ({+ chargeBeforeGenerate: vi.fn().mockResolvedValue({ errorBatch: null, prechargeResult: null }),+}));+vi.mock('@/business/server/video-generation/chargeAfterGenerate', () => ({+ chargeAfterGenerate: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/business/server/video-generation/getVideoFreeQuota', () => ({+ getVideoFreeQuota: vi.fn().mockResolvedValue({ remaining: 10 }),+}));+vi.mock('next/server', () => ({ after: (cb: () => void) => mockAfter(cb) }));+vi.mock('@/server/services/generation/videoBackgroundPolling', () => ({+ processBackgroundVideoPolling: mockProcessBackgroundVideoPolling,+}));+vi.mock('@/envs/app', () => ({+ appEnv: { APP_URL: 'https://app.example.com' },+}));+vi.mock('debug', () => ({ default: vi.fn(() => vi.fn()) }));++// ---- helpers ----++const defaultInput = {+ generationTopicId: 'topic-1',+ model: 'test-model',+ params: { prompt: 'a cat dancing' },+ provider: 'volcengine',+};++const txResult = {+ asyncTaskCreatedAt: new Date('2026-01-01'),+ asyncTaskId: 'async-1',+ batch: { id: 'batch-1' },+ generation: { id: 'gen-1' },+};++// Minimal drizzle-like chain mocks+function createInsertChain() {+ return vi.fn().mockReturnValue({+ values: vi.fn().mockReturnValue({+ returning: vi+ .fn()+ .mockResolvedValueOnce([txResult.batch])+ .mockResolvedValueOnce([txResult.generation])+ .mockResolvedValueOnce([+ { id: txResult.asyncTaskId, createdAt: txResult.asyncTaskCreatedAt },+ ]),+ }),+ });+}++const mockDbUpdate = vi.fn().mockReturnValue({+ set: vi.fn().mockReturnValue({+ where: vi.fn().mockResolvedValue(undefined),+ }),+});++function setupMocks() {+ const mockUpdate = vi.fn().mockResolvedValue(undefined);++ vi.mocked(AsyncTaskModel).mockImplementation(() => ({ update: mockUpdate }) as any);+ vi.mocked(FileService).mockImplementation(+ () =>+ ({+ getFullFileUrl: vi.fn().mockResolvedValue(null),+ getKeyFromFullUrl: vi.fn().mockResolvedValue(null),+ }) as any,+ );++ const mockInsert = createInsertChain();+ mockTransaction.mockImplementation(async (cb: any) =>+ cb({ insert: mockInsert, update: mockDbUpdate }),+ );++ return { mockUpdate };+}++// ---- import router AFTER mocks are set up ----++const { videoRouter } = await import('../video');++// ---- tests ----++describe('videoRouter', () => {+ const mockCtx = { userId: 'test-user' };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('createVideo - async strategy routing', () => {+ it('should use webhook path when response contains useWebhook: true', async () => {+ const { mockUpdate } = setupMocks();+ mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-1', useWebhook: true });++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ expect(result.success).toBe(true);+ expect(mockUpdate).toHaveBeenCalledWith('async-1', {+ inferenceId: 'inf-1',+ status: AsyncTaskStatus.Processing,+ });+ // Webhook: should NOT trigger background polling+ expect(mockAfter).not.toHaveBeenCalled();+ });++ it('should use polling path when response contains only inferenceId', async () => {+ const { mockUpdate } = setupMocks();+ mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-2' });++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ expect(result.success).toBe(true);+ expect(mockUpdate).toHaveBeenCalledWith('async-1', {+ inferenceId: 'inf-2',+ status: AsyncTaskStatus.Processing,+ });+ // Polling: should trigger background polling via after()+ expect(mockAfter).toHaveBeenCalled();+ expect(mockProcessBackgroundVideoPolling).toHaveBeenCalled();+ });++ it('should use polling path when response contains videoUrl (no special handling)', async () => {+ const { mockUpdate } = setupMocks();+ mockCreateVideo.mockResolvedValue({+ inferenceId: 'inf-3',+ videoUrl: 'https://cdn.example.com/video.mp4',+ });++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ expect(result.success).toBe(true);+ expect(mockUpdate).toHaveBeenCalledWith('async-1', {+ inferenceId: 'inf-3',+ status: AsyncTaskStatus.Processing,+ });+ // No special videoUrl branch — falls through to polling+ expect(mockAfter).toHaveBeenCalled();+ expect(mockProcessBackgroundVideoPolling).toHaveBeenCalled();+ });++ it('should fall through to polling when useWebhook is false', async () => {+ setupMocks();+ mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-4', useWebhook: false });++ const caller = videoRouter.createCaller(mockCtx);+ await caller.createVideo(defaultInput);++ // useWebhook=false means not webhook, should fall to polling+ expect(mockAfter).toHaveBeenCalled();+ expect(mockProcessBackgroundVideoPolling).toHaveBeenCalled();+ });+ });++ describe('createVideo - error handling', () => {+ it('should set error status when createVideo throws', async () => {+ const { mockUpdate } = setupMocks();+ mockCreateVideo.mockRejectedValue(new Error('API timeout'));++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ // Batch was already created, so still returns success structure+ expect(result.success).toBe(true);+ expect(mockUpdate).toHaveBeenCalledWith(+ 'async-1',+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ });+ });++ describe('createVideo - pre-charge', () => {+ it('should return error batch when pre-charge fails', async () => {+ setupMocks();+ const { chargeBeforeGenerate } =+ await import('@/business/server/video-generation/chargeBeforeGenerate');+ vi.mocked(chargeBeforeGenerate).mockResolvedValueOnce({+ errorBatch: { error: 'insufficient_balance' } as any,+ prechargeResult: undefined,+ });++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ expect(result).toEqual({ error: 'insufficient_balance' });+ // Should not proceed to createVideo+ expect(mockCreateVideo).not.toHaveBeenCalled();+ });+ });++ describe('createVideo - return value', () => {+ it('should return batch and generation data', async () => {+ setupMocks();+ mockCreateVideo.mockResolvedValue({ inferenceId: 'inf-5', useWebhook: true });++ const caller = videoRouter.createCaller(mockCtx);+ const result = await caller.createVideo(defaultInput);++ expect(result).toEqual({+ data: {+ batch: txResult.batch,+ generations: [{ ...txResult.generation, asyncTaskId: 'async-1' }],+ },+ success: true,+ });+ });+ });+});diff --git a/src/server/routers/lambda/video/index.ts b/src/server/routers/lambda/video/index.tsindex 298eb31b89d..a5079fd0658 100644--- a/src/server/routers/lambda/video/index.ts+++ b/src/server/routers/lambda/video/index.ts@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';import debug from 'debug';import { and, eq } from 'drizzle-orm';+import { after } from 'next/server';import { z } from 'zod';import { chargeAfterGenerate } from '@/business/server/video-generation/chargeAfterGenerate';@@ -15,11 +16,13 @@ import {type NewGeneration,type NewGenerationBatch,} from '@/database/schemas';+import { getServerDB } from '@/database/server';import { appEnv } from '@/envs/app';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';+import { processBackgroundVideoPolling } from '@/server/services/generation/videoBackgroundPolling';import {AsyncTaskError,AsyncTaskErrorType,@@ -141,9 +144,10 @@ export const videoRouter = router({// Step 1: Atomically create all database records in a transactionconst {+ asyncTaskCreatedAt,+ asyncTaskId,batch: createdBatch,generation: createdGeneration,- asyncTaskId,} = await serverDB.transaction(async (tx) => {log('Starting database transaction for video generation');@@ -191,6 +195,7 @@ export const videoRouter = router({.where(and(eq(generations.id, generation.id), eq(generations.userId, userId)));return {+ asyncTaskCreatedAt: asyncTask.createdAt,asyncTaskId: asyncTask.id,batch,generation,@@ -215,11 +220,57 @@ export const videoRouter = router({log('Video task submitted successfully, inferenceId: %s', response?.inferenceId);- // Update asyncTask with inferenceId and set status to Processing- await asyncTaskModel.update(asyncTaskId, {- inferenceId: response?.inferenceId,- status: AsyncTaskStatus.Processing,- });+ // Determine async strategy based on response:+ // - useWebhook: provider registered a callback URL, wait for webhook+ // - otherwise: use background polling to check status+ const useWebhook = response && 'useWebhook' in response && response.useWebhook;++ if (useWebhook) {+ // Webhook-based provider (e.g. Volcengine): wait for callback+ log('Webhook-based provider detected, waiting for callback');++ await asyncTaskModel.update(asyncTaskId, {+ inferenceId: response?.inferenceId,+ status: AsyncTaskStatus.Processing,+ });+ } else if (response) {+ // Polling-based provider (e.g. OpenAI Sora): use background polling+ log(+ 'Polling-based provider detected (inferenceId only), using after() for background polling',+ );++ await asyncTaskModel.update(asyncTaskId, {+ inferenceId: response.inferenceId,+ status: AsyncTaskStatus.Processing,+ });++ after(async () => {+ log('After() hook executing background video polling for task: %s', asyncTaskId);++ try {+ const db = await getServerDB();++ await processBackgroundVideoPolling(db, {+ asyncTaskCreatedAt,+ asyncTaskId,+ generationBatchId: createdBatch.id,+ generationId: createdGeneration.id,+ generationTopicId,+ inferenceId: response.inferenceId,+ model,+ prechargeResult,+ provider,+ userId,+ });++ log('Background video polling completed for task: %s', asyncTaskId);+ } catch (error) {+ console.error('[video] Background polling failed:', error);+ }+ });++ log('After() hook registered for background video polling: %s', asyncTaskId);+ }} catch (e) {console.error('Failed to submit video generation task:', e);diff --git a/src/server/services/generation/video.ts b/src/server/services/generation/video.tsindex 8d992b98ffc..f41159d4c14 100644--- a/src/server/services/generation/video.ts+++ b/src/server/services/generation/video.ts@@ -55,14 +55,19 @@ export class VideoGenerationService {/*** Download video, extract metadata, generate cover/thumbnail, upload all to S3*/- async processVideoForGeneration(videoUrl: string): Promise<VideoProcessResult> {+ async processVideoForGeneration(+ videoUrl: string,+ options?: {+ headers?: Record<string, string>;+ },+ ): Promise<VideoProcessResult> {log('Processing video from URL: %s', videoUrl);let tempVideoPath: string | null = null;let tempCoverPath: string | null = null;try {- tempVideoPath = await this.downloadVideo(videoUrl);+ tempVideoPath = await this.downloadVideo(videoUrl, options);const [metadata, videoBuffer] = await Promise.all([this.getVideoMetadata(tempVideoPath),@@ -162,12 +167,18 @@ export class VideoGenerationService {/** Download timeout: 5 minutes */private static DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;- private async downloadVideo(url: string): Promise<string> {+ private async downloadVideo(+ url: string,+ options?: {+ headers?: Record<string, string>;+ },+ ): Promise<string> {const ext = path.extname(new URL(url).pathname).toLowerCase() || '.mp4';const tempVideoPath = path.join(os.tmpdir(), `lobe-video-${nanoid()}${ext}`);log('Downloading video to: %s', tempVideoPath);const response = await fetch(url, {+ headers: options?.headers,signal: AbortSignal.timeout(VideoGenerationService.DOWNLOAD_TIMEOUT_MS),});if (!response.ok) {diff --git a/src/server/services/generation/videoBackgroundPolling.test.ts b/src/server/services/generation/videoBackgroundPolling.test.tsnew file mode 100644index 00000000000..5717c100888--- /dev/null+++ b/src/server/services/generation/videoBackgroundPolling.test.ts@@ -0,0 +1,322 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { GenerationModel } from '@/database/models/generation';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { VideoGenerationService } from '@/server/services/generation/video';+import { processBackgroundVideoPolling } from '@/server/services/generation/videoBackgroundPolling';+import { AsyncTaskError, AsyncTaskStatus } from '@/types/asyncTask';+import { FileSource } from '@/types/files';++vi.mock('@/database/models/asyncTask');+vi.mock('@/database/models/generation');+vi.mock('@/server/services/generation/video');+vi.mock('@/utils/sanitizeFileName', () => ({+ sanitizeFileName: vi.fn((...args) => args.join('-')),+}));++vi.mock('debug', () => ({+ default: () => vi.fn(),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++describe('videoBackgroundPolling', () => {+ const mockAsyncTaskModel = {+ update: vi.fn(),+ };++ const mockGenerationModel = {+ createAssetAndFile: vi.fn(),+ };++ const mockVideoService = {+ processVideoForGeneration: vi.fn(),+ };++ const mockModelRuntime = {+ handlePollVideoStatus: vi.fn(),+ };++ const mockDb = {+ query: {+ generationBatches: {+ findFirst: vi.fn().mockResolvedValue({+ id: 'batch-123',+ prompt: 'test-prompt',+ }),+ },+ },+ } as any as LobeChatDatabase;++ const mockParams = {+ asyncTaskCreatedAt: new Date('2024-01-01T00:00:00Z'),+ asyncTaskId: 'task-123',+ generationBatchId: 'batch-123',+ generationId: 'gen-456',+ generationTopicId: 'topic-789',+ inferenceId: 'inference-abc',+ model: 'test-model',+ prechargeResult: { credits: 10 },+ provider: 'test-provider',+ userId: 'user-xyz',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();++ vi.mocked(AsyncTaskModel).mockImplementation(() => mockAsyncTaskModel as any);+ vi.mocked(GenerationModel).mockImplementation(() => mockGenerationModel as any);+ vi.mocked(VideoGenerationService).mockImplementation(() => mockVideoService as any);+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue(mockModelRuntime as any);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('processBackgroundVideoPolling - success path', () => {+ it('should complete video generation successfully', async () => {+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ headers: { 'Content-Type': 'video/mp4' },+ });++ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key-123',+ duration: 10,+ fileHash: 'hash-abc',+ fileSize: 1024,+ height: 1080,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key-456',+ videoKey: 'video-key-789',+ width: 1920,+ });++ await processBackgroundVideoPolling(mockDb, mockParams);++ expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledWith('inference-abc');++ expect(mockVideoService.processVideoForGeneration).toHaveBeenCalledWith(+ 'https://example.com/video.mp4',+ { headers: { 'Content-Type': 'video/mp4' } },+ );++ expect(mockGenerationModel.createAssetAndFile).toHaveBeenCalledWith(+ 'gen-456',+ expect.objectContaining({+ coverUrl: 'cover-key-123',+ duration: 10,+ height: 1080,+ originalUrl: 'https://example.com/video.mp4',+ thumbnailUrl: 'thumb-key-456',+ type: 'video',+ url: 'video-key-789',+ width: 1920,+ }),+ expect.objectContaining({+ fileHash: 'hash-abc',+ fileType: 'video/mp4',+ name: 'test-prompt-gen-456.mp4',+ size: 1024,+ url: 'video-key-789',+ }),+ FileSource.VideoGeneration,+ );++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith('task-123', {+ duration: expect.any(Number),+ status: AsyncTaskStatus.Success,+ });+ });+ });++ describe('processBackgroundVideoPolling - polling behavior', () => {+ it('should retry polling multiple times until success', async () => {+ mockModelRuntime.handlePollVideoStatus+ .mockResolvedValueOnce({ status: 'processing' })+ .mockResolvedValueOnce({ status: 'processing' })+ .mockResolvedValueOnce({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });++ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key',+ duration: 10,+ fileHash: 'hash',+ fileSize: 1024,+ height: 1080,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key',+ videoKey: 'video-key',+ width: 1920,+ });++ const pollPromise = processBackgroundVideoPolling(mockDb, mockParams);++ await vi.advanceTimersByTimeAsync(10000);++ await pollPromise;++ expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledTimes(3);+ });+ });++ describe('processBackgroundVideoPolling - error handling', () => {+ it('should handle polling failure with error message', async () => {+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'failed',+ error: 'Model API error',+ });++ await processBackgroundVideoPolling(mockDb, mockParams);++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith('task-123', {+ error: expect.any(AsyncTaskError),+ status: AsyncTaskStatus.Error,+ });++ const errorCall = mockAsyncTaskModel.update.mock.calls[0][1];+ expect(errorCall.error).toBeInstanceOf(AsyncTaskError);+ expect(errorCall.error?.name).toBe('ServerError');+ });++ it('should handle model runtime initialization error', async () => {+ vi.mocked(initModelRuntimeFromDB).mockRejectedValue(new Error('Runtime init failed'));++ await processBackgroundVideoPolling(mockDb, mockParams);++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith('task-123', {+ error: expect.any(AsyncTaskError),+ status: AsyncTaskStatus.Error,+ });+ });++ it('should handle video processing error', async () => {+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });++ mockVideoService.processVideoForGeneration.mockRejectedValue(+ new Error('Video processing failed'),+ );++ await processBackgroundVideoPolling(mockDb, mockParams);++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith('task-123', {+ error: expect.any(AsyncTaskError),+ status: AsyncTaskStatus.Error,+ });+ });++ it('should handle asset creation error', async () => {+ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });++ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key',+ duration: 10,+ fileHash: 'hash',+ fileSize: 1024,+ height: 1080,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key',+ videoKey: 'video-key',+ width: 1920,+ });++ mockGenerationModel.createAssetAndFile.mockRejectedValue(new Error('DB error'));++ await processBackgroundVideoPolling(mockDb, mockParams);++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith('task-123', {+ error: expect.any(AsyncTaskError),+ status: AsyncTaskStatus.Error,+ });+ });+ });++ describe('polling edge cases', () => {+ it('should handle network errors during polling gracefully', async () => {+ mockModelRuntime.handlePollVideoStatus+ .mockRejectedValueOnce(new Error('Network error'))+ .mockResolvedValueOnce({ status: 'processing' })+ .mockResolvedValueOnce({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });++ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key',+ duration: 10,+ fileHash: 'hash',+ fileSize: 1024,+ height: 1080,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key',+ videoKey: 'video-key',+ width: 1920,+ });++ mockGenerationModel.createAssetAndFile.mockResolvedValue(undefined);++ const pollPromise = processBackgroundVideoPolling(mockDb, mockParams);+ await vi.advanceTimersByTimeAsync(10000);+ await pollPromise;++ expect(mockModelRuntime.handlePollVideoStatus).toHaveBeenCalledTimes(3);+ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith(+ 'task-123',+ expect.objectContaining({ status: AsyncTaskStatus.Success }),+ );+ });+ });++ describe('async task duration calculation', () => {+ it('should calculate correct duration from start time', async () => {+ const startTime = new Date('2024-01-01T00:00:00Z');+ const endTime = new Date('2024-01-01T00:05:00Z');++ mockModelRuntime.handlePollVideoStatus.mockResolvedValue({+ status: 'success',+ videoUrl: 'https://example.com/video.mp4',+ });++ mockVideoService.processVideoForGeneration.mockResolvedValue({+ coverKey: 'cover-key',+ duration: 10,+ fileHash: 'hash',+ fileSize: 1024,+ height: 1080,+ mimeType: 'video/mp4',+ thumbnailKey: 'thumb-key',+ videoKey: 'video-key',+ width: 1920,+ });++ mockGenerationModel.createAssetAndFile.mockResolvedValue(undefined);++ vi.setSystemTime(endTime);++ await processBackgroundVideoPolling(mockDb, { ...mockParams, asyncTaskCreatedAt: startTime });++ expect(mockAsyncTaskModel.update).toHaveBeenCalledWith(+ 'task-123',+ expect.objectContaining({+ duration: expect.any(Number),+ status: AsyncTaskStatus.Success,+ }),+ );+ });+ });+});diff --git a/src/server/services/generation/videoBackgroundPolling.ts b/src/server/services/generation/videoBackgroundPolling.tsnew file mode 100644index 00000000000..d8d960d8821--- /dev/null+++ b/src/server/services/generation/videoBackgroundPolling.ts@@ -0,0 +1,160 @@+import debug from 'debug';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { GenerationModel } from '@/database/models/generation';+import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { VideoGenerationService } from '@/server/services/generation/video';+import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';+import { FileSource } from '@/types/files';+import type { VideoGenerationAsset } from '@/types/generation';+import { sanitizeFileName } from '@/utils/sanitizeFileName';++const log = debug('lobe-video:background-polling');++interface BackgroundPollingParams {+ asyncTaskCreatedAt: Date;+ asyncTaskId: string;+ generationBatchId: string;+ generationId: string;+ generationTopicId: string;+ inferenceId: string;+ model: string;+ prechargeResult?: any;+ provider: string;+ userId: string;+}++export async function processBackgroundVideoPolling(+ db: LobeChatDatabase,+ params: BackgroundPollingParams,+): Promise<void> {+ const {+ asyncTaskCreatedAt,+ asyncTaskId,+ generationBatchId,+ generationId,+ generationTopicId,+ inferenceId,+ model,+ prechargeResult,+ provider,+ userId,+ } = params;++ log(+ 'Starting background video polling for task: %s (provider: %s, inferenceId: %s)',+ asyncTaskId,+ provider,+ inferenceId,+ );++ try {+ const asyncTaskModel = new AsyncTaskModel(db, userId);+ const videoService = new VideoGenerationService(db, userId);+ const generationModel = new GenerationModel(db, userId);++ const modelRuntime = await initModelRuntimeFromDB(db, userId, provider);+ const pollResult = await pollUntilCompletion(modelRuntime, inferenceId);++ if (!pollResult) {+ throw new Error('Polling completed but no video URL returned');+ }++ log('Video polling succeeded for task: %s, processing video...', asyncTaskId);++ const processResult = await videoService.processVideoForGeneration(pollResult.videoUrl, {+ headers: pollResult.headers,+ });++ const asset: VideoGenerationAsset = {+ coverUrl: processResult.coverKey,+ duration: processResult.duration,+ height: processResult.height,+ originalUrl: pollResult.videoUrl,+ thumbnailUrl: processResult.thumbnailKey,+ type: 'video',+ url: processResult.videoKey,+ width: processResult.width,+ };++ const batch = await db.query.generationBatches.findFirst({+ where: (batches, { eq }) => eq(batches.id, generationBatchId),+ });++ await generationModel.createAssetAndFile(+ generationId,+ asset,+ {+ fileHash: processResult.fileHash,+ fileType: processResult.mimeType,+ name: `${sanitizeFileName(batch?.prompt ?? '', generationId)}.mp4`,+ size: processResult.fileSize,+ url: processResult.videoKey,+ },+ FileSource.VideoGeneration,+ );++ const duration = Date.now() - asyncTaskCreatedAt.getTime();++ await asyncTaskModel.update(asyncTaskId, {+ duration,+ status: AsyncTaskStatus.Success,+ });++ log('Video processing completed successfully for task: %s', asyncTaskId);+ } catch (error) {+ log('Background video polling error for task: %s', asyncTaskId, error);++ const asyncTaskModel = new AsyncTaskModel(db, userId);+ await asyncTaskModel.update(asyncTaskId, {+ error: new AsyncTaskError(+ AsyncTaskErrorType.ServerError,+ 'Background polling failed: ' + (error instanceof Error ? error.message : 'Unknown error'),+ ),+ status: AsyncTaskStatus.Error,+ });+ }+}++async function pollUntilCompletion(+ modelRuntime: any,+ inferenceId: string,+): Promise<{ headers?: Record<string, string>; videoUrl: string } | null> {+ const maxRetries = 120;+ const pollingInterval = 5000;++ for (let attempt = 0; attempt < maxRetries; attempt++) {+ try {+ log('Polling attempt %d/%d for task: %s', attempt + 1, maxRetries, inferenceId);++ const result = await modelRuntime.handlePollVideoStatus(inferenceId);++ if (result.status === 'success') {+ log('Video generation succeeded for task: %s', inferenceId);+ return { headers: result.headers, videoUrl: result.videoUrl };+ }++ if (result.status === 'failed') {+ throw new Error(`Video generation failed: ${result.error}`);+ }++ log('Task %s still in progress', inferenceId);+ await sleep(pollingInterval);+ } catch (error) {+ if (error instanceof Error && error.message.includes('failed')) {+ throw error;+ }+ log('Polling attempt %d failed for task: %s: %O', attempt + 1, inferenceId, error);+ await sleep(pollingInterval);+ }+ }++ throw new Error(+ `Video generation timeout after ${maxRetries} attempts (${(maxRetries * pollingInterval) / 1000}s)`,+ );+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}