mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(media-generation): add gemini-omni-1.1-flash video model and redesign settings UI (#383)
* feat(settings): redesign image and video generation settings with tabs, card switch, and 2-box model selector * fix(settings): remove model type checkmark, remove search inputs, and fix select box scrolling in add model dialog * refactor(settings): remove display name input from add model dialog * feat(media-generation): add gemini-omni-1.1-flash as default video model via google interactions api * feat(media-generation): forward video parameters to gemini-omni-1.1-flash via system instructions and prompt
This commit is contained in:
@@ -2,6 +2,15 @@ import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { mediaGenerationService, BUILTIN_MEDIA_PROVIDERS } from './media-generation'
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import * as aiModule from 'ai'
|
||||
|
||||
vi.mock('ai', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('ai')>()
|
||||
return {
|
||||
...actual,
|
||||
generateText: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('MediaGenerationService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -10,6 +19,7 @@ describe('MediaGenerationService', () => {
|
||||
const originalEnv = process.env
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
process.env = { ...originalEnv }
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
@@ -24,6 +34,7 @@ describe('MediaGenerationService', () => {
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
vi.clearAllMocks()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
@@ -56,7 +67,7 @@ describe('MediaGenerationService', () => {
|
||||
|
||||
expect(openai?.apiKeyConfigured).toBe(true)
|
||||
expect(openai?.status).toBe('configured_custom')
|
||||
expect(openai?.customApiKeyOrEnv).toBe('••••••••')
|
||||
expect(openai?.customApiKeyOrEnv).toBe('sk-literal-key')
|
||||
|
||||
// 2. Set custom ENV var name
|
||||
process.env.MY_CUSTOM_OPENAI_ENV = 'sk-resolved-custom-env'
|
||||
@@ -66,7 +77,7 @@ describe('MediaGenerationService', () => {
|
||||
|
||||
expect(openai?.apiKeyConfigured).toBe(true)
|
||||
expect(openai?.status).toBe('configured_custom')
|
||||
expect(openai?.customApiKeyOrEnv).toBe('••••••••')
|
||||
expect(openai?.customApiKeyOrEnv).toBe('MY_CUSTOM_OPENAI_ENV')
|
||||
expect(mediaGenerationService.resolveApiKey('openai', 'MY_CUSTOM_OPENAI_ENV')).toBe(
|
||||
'sk-resolved-custom-env',
|
||||
)
|
||||
@@ -209,4 +220,117 @@ describe('MediaGenerationService', () => {
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('should include gemini-omni-1.1-flash as the default video model in Google curated models', () => {
|
||||
const googleVideoModels = mediaGenerationService.getCuratedModels('google', 'video')
|
||||
expect(googleVideoModels.length).toBeGreaterThan(0)
|
||||
expect(googleVideoModels[0].modelId).toBe('gemini-omni-1.1-flash')
|
||||
expect(googleVideoModels[0].name).toBe('Gemini Omni 1.1 Flash')
|
||||
expect(googleVideoModels[0].type).toBe('video')
|
||||
})
|
||||
|
||||
it('should generate video via interactions API for gemini-omni-1.1-flash in text_to_video mode', async () => {
|
||||
const mockGenerateText = vi.mocked(aiModule.generateText).mockResolvedValue({
|
||||
files: [
|
||||
{
|
||||
mediaType: 'video/mp4',
|
||||
uint8Array: new Uint8Array([10, 20, 30, 40]),
|
||||
base64: Buffer.from([10, 20, 30, 40]).toString('base64'),
|
||||
},
|
||||
],
|
||||
warnings: [],
|
||||
} as unknown as Awaited<ReturnType<typeof aiModule.generateText>>)
|
||||
|
||||
const result = await mediaGenerationService.generateVideo({
|
||||
provider: 'google',
|
||||
modelId: 'gemini-omni-1.1-flash',
|
||||
apiKey: 'test-gemini-key',
|
||||
mode: 'text_to_video',
|
||||
prompt: 'A cinematic drone shot over rolling hills',
|
||||
aspectRatio: '16:9',
|
||||
resolution: '1280x720',
|
||||
duration: 5,
|
||||
fps: 24,
|
||||
generateAudio: true,
|
||||
seed: 42,
|
||||
})
|
||||
|
||||
expect(mockGenerateText).toHaveBeenCalledTimes(1)
|
||||
const callArgs = mockGenerateText.mock.calls[0][0]
|
||||
expect(callArgs.seed).toBe(42)
|
||||
expect(callArgs.system).toContain('Aspect ratio: 16:9')
|
||||
expect(callArgs.system).toContain('Resolution: 720p (1280x720)')
|
||||
expect(callArgs.system).toContain('Duration: 5 seconds')
|
||||
expect(callArgs.system).toContain('Frame rate: 24 fps')
|
||||
expect(callArgs.system).toContain('Audio: generate synchronized audio')
|
||||
const messages = callArgs.messages as Array<{
|
||||
role: string
|
||||
content: Array<{ type: string; text?: string }>
|
||||
}>
|
||||
expect(messages[0].content[0].text).toContain(
|
||||
'[Video parameters: Aspect ratio: 16:9, Resolution: 720p (1280x720), Duration: 5 seconds, Frame rate: 24 fps, Audio: generate synchronized audio]',
|
||||
)
|
||||
expect(callArgs.providerOptions).toEqual({
|
||||
google: {
|
||||
responseModalities: ['video'],
|
||||
store: false,
|
||||
},
|
||||
})
|
||||
expect(result.mimeType).toBe('video/mp4')
|
||||
expect(result.buffer).toEqual(Buffer.from([10, 20, 30, 40]))
|
||||
})
|
||||
|
||||
it('should generate video via interactions API for gemini-omni-1.1-flash in image_to_video mode', async () => {
|
||||
const fakeImageBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
const mockGenerateText = vi.mocked(aiModule.generateText).mockResolvedValue({
|
||||
files: [
|
||||
{
|
||||
mediaType: 'video/mp4',
|
||||
uint8Array: new Uint8Array([50, 60, 70, 80]),
|
||||
base64: Buffer.from([50, 60, 70, 80]).toString('base64'),
|
||||
},
|
||||
],
|
||||
warnings: [],
|
||||
} as unknown as Awaited<ReturnType<typeof aiModule.generateText>>)
|
||||
|
||||
const result = await mediaGenerationService.generateVideo({
|
||||
provider: 'google',
|
||||
modelId: 'gemini-omni-1.1-flash',
|
||||
apiKey: 'test-gemini-key',
|
||||
mode: 'image_to_video',
|
||||
prompt: 'Make the character wave',
|
||||
image: fakeImageBuffer,
|
||||
})
|
||||
|
||||
expect(mockGenerateText).toHaveBeenCalledTimes(1)
|
||||
const callArgs = mockGenerateText.mock.calls[0][0]
|
||||
const messages = callArgs.messages as Array<{
|
||||
role: string
|
||||
content: Array<{ type: string; mediaType?: string; data?: Buffer }>
|
||||
}>
|
||||
expect(messages).toBeDefined()
|
||||
expect(messages[0].content).toHaveLength(2)
|
||||
expect(messages[0].content[0].type).toBe('text')
|
||||
expect(messages[0].content[1].type).toBe('file')
|
||||
expect(messages[0].content[1].mediaType).toBe('image/png')
|
||||
expect(messages[0].content[1].data).toEqual(fakeImageBuffer)
|
||||
expect(result.buffer).toEqual(Buffer.from([50, 60, 70, 80]))
|
||||
})
|
||||
|
||||
it('should throw an error if interactions API returns no video file', async () => {
|
||||
vi.mocked(aiModule.generateText).mockResolvedValue({
|
||||
files: [],
|
||||
warnings: [],
|
||||
} as unknown as Awaited<ReturnType<typeof aiModule.generateText>>)
|
||||
|
||||
await expect(
|
||||
mediaGenerationService.generateVideo({
|
||||
provider: 'google',
|
||||
modelId: 'gemini-omni-1.1-flash',
|
||||
apiKey: 'test-gemini-key',
|
||||
mode: 'text_to_video',
|
||||
prompt: 'A video that fails to generate',
|
||||
}),
|
||||
).rejects.toThrow('No video binary data returned by Gemini Omni Flash')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,7 +9,11 @@ import {
|
||||
} from '@shumai/dtos'
|
||||
import { ulid } from 'ulid'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { generateImage as aiGenerateImage, experimental_generateVideo as aiGenerateVideo } from 'ai'
|
||||
import {
|
||||
generateImage as aiGenerateImage,
|
||||
experimental_generateVideo as aiGenerateVideo,
|
||||
generateText as aiGenerateText,
|
||||
} from 'ai'
|
||||
import { createOpenAI } from '@ai-sdk/openai'
|
||||
import { createGoogleGenerativeAI } from '@ai-sdk/google'
|
||||
import { createGoogleVertex } from '@ai-sdk/google-vertex'
|
||||
@@ -72,6 +76,7 @@ export const BUILTIN_MEDIA_PROVIDERS: Record<string, BuiltinMediaProviderDef> =
|
||||
name: 'Gemini 3.1 Flash Image Preview',
|
||||
type: 'image',
|
||||
},
|
||||
{ modelId: 'gemini-omni-1.1-flash', name: 'Gemini Omni 1.1 Flash', type: 'video' },
|
||||
{ modelId: 'veo-3.1-generate', name: 'Veo 3.1', type: 'video' },
|
||||
{ modelId: 'veo-3.1-generate-preview', name: 'Veo 3.1 Preview', type: 'video' },
|
||||
{ modelId: 'veo-3.1-fast-generate-preview', name: 'Veo 3.1 Fast Preview', type: 'video' },
|
||||
@@ -437,7 +442,7 @@ export class MediaGenerationService {
|
||||
defaultEnvKey: def.defaultEnvKey,
|
||||
apiKeyConfigured: !!resolvedKey,
|
||||
status,
|
||||
customApiKeyOrEnv: customKey ? '••••••••' : undefined,
|
||||
customApiKeyOrEnv: customKey || undefined,
|
||||
supportedTypes: def.supportedTypes,
|
||||
}
|
||||
})
|
||||
@@ -770,6 +775,10 @@ export class MediaGenerationService {
|
||||
mimeType: string
|
||||
warnings?: unknown
|
||||
}> {
|
||||
if (params.provider === 'google' && params.modelId === 'gemini-omni-1.1-flash') {
|
||||
return this.generateGoogleInteractionsVideo(params)
|
||||
}
|
||||
|
||||
const model = this.getVideoModel(params.provider, params.modelId, params.apiKey)
|
||||
|
||||
type GenerateVideoOptions = Parameters<typeof aiGenerateVideo>[0]
|
||||
@@ -838,6 +847,182 @@ export class MediaGenerationService {
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
private async generateGoogleInteractionsVideo(params: GenerateVideoServiceParams): Promise<{
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
warnings?: unknown
|
||||
}> {
|
||||
const google = createGoogleGenerativeAI({ apiKey: params.apiKey })
|
||||
// AI SDK provider interactions method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const model = google.interactions(params.modelId as any)
|
||||
|
||||
const content: Array<
|
||||
| { type: 'text'; text: string }
|
||||
| { type: 'file'; data: Buffer | Uint8Array; mediaType: string }
|
||||
> = []
|
||||
|
||||
const specs: string[] = []
|
||||
if (params.aspectRatio) {
|
||||
specs.push(`- Aspect ratio: ${params.aspectRatio}`)
|
||||
}
|
||||
if (params.resolution) {
|
||||
const resolutionMap: Record<string, string> = {
|
||||
'640x360': '360p',
|
||||
'1280x720': '720p',
|
||||
'1920x1080': '1080p',
|
||||
'3840x2160': '4K',
|
||||
}
|
||||
const resName = resolutionMap[params.resolution] || params.resolution
|
||||
specs.push(`- Resolution: ${resName} (${params.resolution})`)
|
||||
}
|
||||
if (params.duration) {
|
||||
specs.push(`- Duration: ${params.duration} seconds`)
|
||||
}
|
||||
if (params.fps) {
|
||||
specs.push(`- Frame rate: ${params.fps} fps`)
|
||||
}
|
||||
if (params.generateAudio !== undefined) {
|
||||
specs.push(
|
||||
`- Audio: ${params.generateAudio ? 'generate synchronized audio' : 'silent / no audio'}`,
|
||||
)
|
||||
}
|
||||
|
||||
const systemInstruction =
|
||||
specs.length > 0
|
||||
? `You are generating a video with Gemini Omni Flash. Follow the user request and strictly adhere to these video generation specifications:\n${specs.join('\n')}`
|
||||
: undefined
|
||||
|
||||
let userPrompt = params.prompt?.trim() || ''
|
||||
if (specs.length > 0) {
|
||||
const specLine = `[Video parameters: ${specs.map((s) => s.replace(/^- /, '')).join(', ')}]`
|
||||
userPrompt = userPrompt ? `${userPrompt}\n\n${specLine}` : specLine
|
||||
}
|
||||
|
||||
if (userPrompt) {
|
||||
content.push({ type: 'text', text: userPrompt })
|
||||
}
|
||||
|
||||
const addImagePart = (input?: string | Uint8Array | Buffer) => {
|
||||
if (!input) return
|
||||
const normalized = this.normalizeMediaInput(input)
|
||||
content.push({
|
||||
type: 'file',
|
||||
data: normalized.buffer,
|
||||
mediaType: normalized.mimeType,
|
||||
})
|
||||
}
|
||||
|
||||
if (params.mode === 'image_to_video' && params.image) {
|
||||
addImagePart(params.image)
|
||||
} else if (params.mode === 'first_last_frame') {
|
||||
if (params.firstFrame) addImagePart(params.firstFrame)
|
||||
if (params.lastFrame) addImagePart(params.lastFrame)
|
||||
} else if (params.mode === 'reference_to_video' && params.inputReferences) {
|
||||
for (const ref of params.inputReferences) {
|
||||
addImagePart(ref)
|
||||
}
|
||||
}
|
||||
|
||||
if (content.length === 0) {
|
||||
content.push({ type: 'text', text: 'Generate video' })
|
||||
}
|
||||
|
||||
const result = await aiGenerateText({
|
||||
model,
|
||||
system: systemInstruction,
|
||||
messages: [{ role: 'user', content }],
|
||||
providerOptions: {
|
||||
google: {
|
||||
responseModalities: ['video'],
|
||||
store: false,
|
||||
},
|
||||
},
|
||||
seed: params.seed,
|
||||
})
|
||||
|
||||
const videoFile = result.files.find((f) => f.mediaType.startsWith('video/'))
|
||||
if (!videoFile) {
|
||||
throw new Error('No video binary data returned by Gemini Omni Flash')
|
||||
}
|
||||
|
||||
let buffer: Buffer
|
||||
if (videoFile.uint8Array) {
|
||||
buffer = Buffer.from(videoFile.uint8Array)
|
||||
} else if (videoFile.base64) {
|
||||
if (videoFile.base64.startsWith('http://') || videoFile.base64.startsWith('https://')) {
|
||||
const res = await fetch(videoFile.base64)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to download video from ${videoFile.base64}: ${res.statusText}`)
|
||||
}
|
||||
buffer = Buffer.from(await res.arrayBuffer())
|
||||
} else if (videoFile.base64.startsWith('data:')) {
|
||||
const match = videoFile.base64.match(/^data:([^;]+);base64,(.*)$/)
|
||||
buffer = match ? Buffer.from(match[2], 'base64') : Buffer.from(videoFile.base64, 'base64')
|
||||
} else {
|
||||
buffer = Buffer.from(videoFile.base64, 'base64')
|
||||
}
|
||||
} else {
|
||||
throw new Error('Video file returned by Gemini Omni Flash has no binary content')
|
||||
}
|
||||
|
||||
return {
|
||||
buffer,
|
||||
mimeType: videoFile.mediaType || 'video/mp4',
|
||||
warnings: result.warnings,
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeMediaInput(input: string | Uint8Array | Buffer): {
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
} {
|
||||
if (typeof input === 'string') {
|
||||
if (input.startsWith('data:')) {
|
||||
const match = input.match(/^data:([^;]+);base64,(.*)$/)
|
||||
if (match) {
|
||||
return {
|
||||
buffer: Buffer.from(match[2], 'base64'),
|
||||
mimeType: match[1],
|
||||
}
|
||||
}
|
||||
}
|
||||
const buf = Buffer.from(input, 'base64')
|
||||
return { buffer: buf, mimeType: this.detectImageMimeType(buf) }
|
||||
}
|
||||
|
||||
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input)
|
||||
return { buffer: buf, mimeType: this.detectImageMimeType(buf) }
|
||||
}
|
||||
|
||||
private detectImageMimeType(buffer: Buffer): string {
|
||||
if (buffer.length >= 4) {
|
||||
if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {
|
||||
return 'image/png'
|
||||
}
|
||||
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
|
||||
return 'image/jpeg'
|
||||
}
|
||||
if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38) {
|
||||
return 'image/gif'
|
||||
}
|
||||
if (
|
||||
buffer[0] === 0x52 &&
|
||||
buffer[1] === 0x49 &&
|
||||
buffer[2] === 0x46 &&
|
||||
buffer[3] === 0x46 &&
|
||||
buffer.length >= 12 &&
|
||||
buffer[8] === 0x57 &&
|
||||
buffer[9] === 0x45 &&
|
||||
buffer[10] === 0x42 &&
|
||||
buffer[11] === 0x50
|
||||
) {
|
||||
return 'image/webp'
|
||||
}
|
||||
}
|
||||
return 'image/png'
|
||||
}
|
||||
}
|
||||
|
||||
export const mediaGenerationService = new MediaGenerationService()
|
||||
|
||||
Reference in New Issue
Block a user