// Gemini Omni bills tokens: input, text output (including thinking) and video // output (with audio). A second of output video is billed at these rates // (cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing). const OMNI_VIDEO_TOKENS_PER_SECOND = { "360p": 1931, "720p": 5792, "1080p": 8688, "4k": 17376 }; const RESOLUTIONS = Object.keys(OMNI_VIDEO_TOKENS_PER_SECOND); const OMNI_USAGE_SCHEMA = { // Input tokens (reported on completion). input_tokens: { type: "number", unit: "token", description: { en: "Input token unit price", zh: "输入 Token 单价" }, }, // Text output tokens, including thinking (reported on completion). output_tokens: { type: "number", unit: "token", description: { en: "Text output token unit price", zh: "文本输出 Token 单价" }, }, // Video output tokens (estimated at submit, reported on completion). video_tokens: { type: "number", unit: "token", description: { en: "Video output token unit price", zh: "视频输出 Token 单价" }, }, }; // Input and text output are only known on completion, which reports them. function omniUsageFacts(seconds, resolution) { return { input_tokens: 0, output_tokens: 0, video_tokens: seconds * OMNI_VIDEO_TOKENS_PER_SECOND[resolution] }; } export const meta = { apiVersion: 1, key: "vertex-ai", name: "Google Veo & Gemini Omni (Vertex AI)", icon: "VertexAI.Color", description: { en: "Google Veo and Gemini Omni Flash video generation on Vertex AI (text-to-video and image-to-video)", zh: "Google Veo 与 Gemini Omni Flash 视频生成(文生视频、图生视频),Vertex AI 版本", }, version: "1.3.1", channelTypes: [41], author: { name: "QuantumNous" }, models: [ "veo-3.0-generate-001", "veo-3.0-fast-generate-001", "veo-3.1-generate-preview", "veo-3.1-fast-generate-preview", "gemini-omni-1.2-flash", "gemini-omni-1.1-flash-preview", "gemini-omni-flash-preview", ], fetchMode: "per_task", auth: { type: "oauth2_jwt" }, upstreams: ["vendor", "new_api"], usageSchema: { // Requested video duration in seconds. Allowed values: 4, 6, 8. seconds: { type: "number", unit: "second", description: { en: "Video generation unit price", zh: "视频生成单价" }, }, // Requested video output resolution. resolution: { enum: ["720p", "1080p", "4k"], enumLabels: { "720p": { en: "720p", zh: "720p" }, "1080p": { en: "1080p", zh: "1080p" }, "4k": { en: "4k", zh: "4k" } }, description: { en: "Output video resolution", zh: "输出视频分辨率" }, }, // Whether audio is generated. Default true. Audio and muted tiers have different prices. generate_audio: { type: "boolean", description: { en: "Whether audio is generated", zh: "是否生成音频" }, }, }, usageExamples: [ { label: "8s 720p audio", facts: { seconds: 8, resolution: "720p", generate_audio: true } }, { label: "8s 720p muted", facts: { seconds: 8, resolution: "720p", generate_audio: false } }, { label: "8s 1080p audio", facts: { seconds: 8, resolution: "1080p", generate_audio: true } }, { label: "8s 4k audio", facts: { seconds: 8, resolution: "4k", generate_audio: true } }, ], usageProfiles: [ { models: ["gemini-omni-1.2-flash", "gemini-omni-1.1-flash-preview", "gemini-omni-flash-preview"], schema: OMNI_USAGE_SCHEMA, examples: [ { label: "3s 360p", facts: omniUsageFacts(3, "360p") }, { label: "8s 720p", facts: omniUsageFacts(8, "720p") }, { label: "8s 1080p", facts: omniUsageFacts(8, "1080p") }, { label: "10s 4k", facts: omniUsageFacts(10, "4k") }, ], }, ], // Vertex AI request and response bodies, for clients and for a downstream New // API gateway, at both API versions Vertex serves them (google-genai defaults // to v1beta1); the gateway also serves each under /vertex-ai. The model // segment carries the method: predictLongRunning submits and // fetchPredictOperation polls. The gateway runs every request in its own // channel's project; the operation names it returns echo the path's project // and location and end with the gateway task id. routes: [ { method: "POST", path: "/v1/projects/:project/locations/:location/publishers/google/models/:model", type: "dynamic", decode: "modelMethod", render: "operation", }, { method: "POST", path: "/v1beta1/projects/:project/locations/:location/publishers/google/models/:model", type: "dynamic", decode: "modelMethod", render: "operation", }, ], protocols: [{ name: "openai_responses", supports: ["stream", "sync", "background"] }, "openai_video"], }; function trimmed(value) { return String(value || "").trim(); } function plainObject(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : null; } // On a New API channel the same plugin answers on another gateway, which // serves the Vertex AI wire format under /vertex-ai, the form every gateway // release serves, takes its own token as a Bearer header and runs the request // in its own project. function viaGateway(ctx) { return Boolean(ctx.upstream && ctx.upstream.kind === "new_api"); } function requestHeaders(ctx) { const headers = { "Content-Type": "application/json", Accept: "application/json", Authorization: ctx.authHeader }; if (!viaGateway(ctx)) headers["x-goog-user-project"] = ctx.auth.projectId; return headers; } function omniModel(ctx) { return trimmed(ctx.upstreamModel || ctx.model).startsWith("gemini-omni-"); } // Gemini Omni runs through the Interactions API, which Vertex serves on the // global endpoint only, and returns the video inline in the interaction. function interactionsURL(ctx, interactionId) { if (viaGateway(ctx)) throw new Error("Gemini Omni is not available through a New API gateway"); const base = trimmed(ctx.baseUrl).replace(/\/$/, "") || "https://aiplatform.googleapis.com"; const url = base + "/v1beta1/projects/" + ctx.auth.projectId + "/locations/global/interactions"; return interactionId ? url + "/" + encodeURIComponent(interactionId) : url; } function omniResolution(req) { const metadata = req.metadata || {}; const value = String(req.resolution || metadata.resolution || resolution(req.size)).toLowerCase(); if (!RESOLUTIONS.includes(value)) throw new Error("resolution must be one of " + RESOLUTIONS.join(", ")); return value; } // Omni 1.2 generates up to 15 seconds; 1.1 and first/last-frame interpolation // stop at 10, which Vertex itself rejects. function omniDuration(req) { const n = req.duration === undefined || req.duration === "" ? 8 : Number(req.duration); if (!Number.isInteger(n) || n < 3 || n > 15) throw new Error("seconds must be an integer from 3 to 15"); return n; } // inputImage is an input image's media type and base64 bytes: an uploaded // file placeholder, a data URL or bare base64. function inputImage(ctx, image) { let mime = ""; let data = image; if (plainObject(image) && image.__fileRef) { mime = String(image.mimeType || "").toLowerCase(); if (mime !== "image/jpeg" && mime !== "image/png") { for (const file of ctx.files || []) { if (file.ref === image.__fileRef || file.field === "input_reference") { mime = String(file.mimeType || "").toLowerCase(); break; } } } } else { const text = String(image); const comma = text.indexOf(","); data = text; if (text.startsWith("data:")) { mime = text.slice(5, comma).split(";")[0].toLowerCase(); data = text.slice(comma + 1); } else if (text.startsWith("iVBORw0KGgo")) mime = "image/png"; else if (text.startsWith("/9j/")) mime = "image/jpeg"; } if (mime !== "image/jpeg" && mime !== "image/png") throw new Error("input image must be image/jpeg or image/png"); return { mime: mime, data: data }; } // Images keep the client's order: two are the first and last frame, more are // subject references. The task hint limits the image count, so it is only sent // for the single-image and text-only forms. function omniSubmitRequest(ctx, req, model) { const input = []; const images = req.images || []; for (const image of images) { const frame = inputImage(ctx, image); input.push({ type: "image", mime_type: frame.mime, data: frame.data }); } if (trimmed(req.prompt)) input.push({ type: "text", text: req.prompt }); if (!input.length) throw new Error("prompt is required"); const body = { model: model, input: input, response_format: [{ type: "video", aspect_ratio: aspect(req.size), resolution: omniResolution(req), duration: omniDuration(req) + "s" }], background: true, store: true, }; const task = images.length ? "image_to_video" : "text_to_video"; if (images.length < 2) body.generation_config = { video_config: { task: task } }; return { url: interactionsURL(ctx), method: "POST", headers: requestHeaders(ctx), body: body, action: task }; } function isInteraction(body) { return plainObject(body) !== null && (body.object === "interaction" || Array.isArray(body.steps)); } // omniVideo locates the video of a finished interaction: the model_output // step holds it inline (data) or at a Cloud Storage uri. Like an inline Veo // video, the stored interaction keeps its media type only, so the path // addresses the bytes for a download that fetches the interaction again. function omniVideo(body) { const steps = Array.isArray(body.steps) ? body.steps : []; for (let i = 0; i < steps.length; i++) { const step = steps[i]; if (!plainObject(step) || step.type !== "model_output" || !Array.isArray(step.content)) continue; for (let j = 0; j < step.content.length; j++) { const part = step.content[j]; if (!plainObject(part) || part.type !== "video") continue; return { path: ["steps", i, "content", j, "data"], mimeType: trimmed(part.mime_type) || "video/mp4", uri: trimmed(part.uri) }; } } return null; } function omniTaskResult(body) { body = plainObject(body) || {}; if (plainObject(body.error) && body.error.message) return { status: "FAILURE", progress: "100%", reason: body.error.message }; const status = trimmed(body.status).toLowerCase(); if (status === "in_progress" || status === "queued") return { status: "IN_PROGRESS", progress: "50%" }; if (["failed", "cancelled", "canceled", "expired", "incomplete"].includes(status)) { const error = plainObject((body.errors || [])[0]) || {}; const reason = [trimmed(error.code), trimmed(error.message)].filter(Boolean).join(": "); return { status: "FAILURE", progress: "100%", reason: reason || status }; } if (status !== "completed") return { status: "UNKNOWN", reason: "unrecognized interaction state" }; const video = omniVideo(body); if (!video) return { status: "FAILURE", progress: "100%", reason: "interaction completed without a video" }; const result = { status: "SUCCESS", progress: "100%" }; if (video.uri) result.remoteUrl = video.uri; return result; } function responsesInput(req) { const texts = [], images = []; const input = req.input; if (typeof input === "string") texts.push(input); else if (Array.isArray(input)) { for (const item of input) { if (typeof item === "string") { texts.push(item); continue; } if (!item || typeof item !== "object" || Array.isArray(item)) continue; const content = item.content === undefined ? [item] : Array.isArray(item.content) ? item.content : [item.content]; for (const part of content) { if (typeof part === "string") { texts.push(part); continue; } if (!part || typeof part !== "object" || Array.isArray(part)) continue; if (["input_text", "text"].includes(part.type) && typeof part.text === "string") texts.push(part.text); if (["input_image", "image_url"].includes(part.type)) { let image = part.image_url; if (image && typeof image === "object") image = image.url; if (trimmed(image)) images.push(trimmed(image)); } } } } return { prompt: texts .filter(function (text) { return trimmed(text); }) .join("\n"), images: images, }; } function validImageInput(value) { value = trimmed(value); if (!value) return false; if (value.startsWith("data:")) { const comma = value.indexOf(","); return comma >= 0 && Boolean(value.slice(comma + 1)); } return /^[A-Za-z0-9+/]+={0,2}$/.test(value); } function sizeParts(size) { const p = String(size || "") .toLowerCase() .split("x"); return p.length === 2 ? [Number(p[0]), Number(p[1])] : null; } function resolution(size) { const p = sizeParts(size); if (!p) return "720p"; const m = Math.max(p[0], p[1]); return m >= 3840 ? "4k" : m >= 1920 ? "1080p" : "720p"; } function aspect(size) { const p = sizeParts(size); return !p || p[0] <= 0 || p[1] <= 0 ? "16:9" : p[1] > p[0] ? "9:16" : "16:9"; } function duration(req) { let n = Number(req.duration); if (!Number.isFinite(n) || n <= 0) n = 8; return n; } // The channel's region field, read as the built-in Vertex AI channel reads it: // a plain region, or a JSON map of model to region with a default, keyed by // the model the client asked for, before the channel's model mapping. function region(ctx, model) { const other = String(ctx.channelOther || "").trim(); if (other.startsWith("{")) { try { const regions = JSON.parse(other); return String(regions[model] || regions.default || "global"); } catch (e) {} } return other || "global"; } function apiBase(baseUrl, project, location) { const base = String(baseUrl || "").replace(/\/$/, ""); if (base) return base + (base.endsWith("/v1") ? "" : "/v1") + "/projects/" + project + "/locations/" + location; return "https://" + (location === "global" ? "" : location + "-") + "aiplatform.googleapis.com/v1/projects/" + project + "/locations/" + location; } function modelURL(ctx, project, location, model, action) { return apiBase(ctx.baseUrl + (viaGateway(ctx) ? "/vertex-ai" : ""), project, location) + "/publishers/google/models/" + model + ":" + action; } function decodeTaskId(value) { return utils.base64URLDecode(value); } function operationPart(name, marker) { const start = name.indexOf(marker); if (start < 0) return ""; return name.slice(start + marker.length).split("/")[0]; } // firstVideo is the first video of a finished operation: written to Cloud // Storage (gcsUri) or returned inline (bytesBase64Encoded). function firstVideo(operation) { return plainObject((((plainObject(operation) || {}).response || {}).videos || [])[0]) || {}; } // fetchOperation reads a long-running operation by name, for the poller and // for a video download. function fetchOperation(ctx, name) { const project = operationPart(name, "projects/"), location = operationPart(name, "locations/"), model = operationPart(name, "models/"); if (!project || !model) throw new Error("cannot extract project or model from operation name"); return { url: modelURL(ctx, project, location || "us-central1", model, "fetchPredictOperation"), method: "POST", headers: requestHeaders(ctx), body: { operationName: name }, }; } export const native = { modelMethod: function (ctx) { const segment = String((ctx.params || {}).model || ""); const separator = segment.lastIndexOf(":"); const method = separator > 0 ? segment.slice(separator + 1) : ""; if (!ctx.body || ctx.body.kind !== "json") throw new Error("JSON body required"); const body = plainObject(ctx.body.value); if (!body) throw new Error("request body must be an object"); if (method === "fetchPredictOperation") { const name = String(body.operationName || ""); const marker = name.lastIndexOf("/operations/"); if (marker < 0) throw new Error("operationName must name an operation"); return { kind: "query", taskIds: [name.slice(marker + "/operations/".length)] }; } if (method !== "predictLongRunning") throw new Error("the path must name models/{model}:predictLongRunning or :fetchPredictOperation"); const model = segment.slice(0, separator); const instances = Array.isArray(body.instances) ? body.instances : []; const instance = plainObject(instances[0]); if (instances.length !== 1 || !instance) throw new Error("instances must hold exactly one instance"); // buildSubmitRequest sends only the prompt and the first frame. for (const key of Object.keys(instance)) { if (key !== "prompt" && key !== "image") throw new Error("instances[0]." + key + " is not supported"); } const metadata = Object.assign({}, plainObject(body.parameters) || {}); const requestBody = { model: model, prompt: instance.prompt, metadata: metadata }; if (metadata.durationSeconds !== undefined) { requestBody.duration = metadata.durationSeconds; delete metadata.durationSeconds; if ([4, 6, 8].indexOf(Number(requestBody.duration)) < 0) throw new Error("durationSeconds must be one of 4, 6, or 8"); } if (metadata.resolution !== undefined && ["720p", "1080p", "4k"].indexOf(String(metadata.resolution).toLowerCase()) < 0) throw new Error("resolution must be one of 720p, 1080p, or 4k"); if (instance.image !== undefined) { const image = plainObject(instance.image) || {}; const mime = trimmed(image.mimeType).toLowerCase(); if (!trimmed(image.bytesBase64Encoded)) throw new Error("instances[0].image must carry bytesBase64Encoded"); if (mime !== "image/jpeg" && mime !== "image/png") throw new Error("input image must be image/jpeg or image/png"); requestBody.images = ["data:" + mime + ";base64," + image.bytesBase64Encoded]; } return { kind: "submit", model: model, action: requestBody.images ? "image_to_video" : "text_to_video", requestBody: requestBody }; }, // Submission renders one task and fetchPredictOperation a list of one. The // poller can fail a task whose operation was still running; that operation // is rendered done with the failure. operation: function (ctx, tasks) { const task = Array.isArray(tasks) ? tasks[0] : tasks; const params = ctx.params || {}; const data = plainObject(task.data) || {}; const named = /\/models\/([^/]+)\/operations\//.exec(String(data.name || "")); const model = named ? named[1] : String(params.model || "").split(":")[0]; const output = Object.assign({}, data, { name: "projects/" + params.project + "/locations/" + params.location + "/publishers/google/models/" + model + "/operations/" + task.task_id, }); if (task.status === "FAILURE" && !(plainObject(data.error) && data.error.message)) { output.done = true; output.error = { message: task.fail_reason || "task failed" }; delete output.response; } return output; }, error: function (ctx, error) { return { error: { code: error.httpStatus, message: error.message } }; }, }; export function buildSubmitRequest(ctx) { if (ctx.authError) throw new Error(ctx.authError); const req = ctx.requestBody || {}, metadata = Object.assign({}, req.metadata || {}), model = ctx.upstreamModel || "veo-3.0-generate-001"; if (omniModel(ctx)) return omniSubmitRequest(ctx, req, model); if (Number(req.duration) > 0) metadata.durationSeconds = Number(req.duration); if (!metadata.resolution && req.size) metadata.resolution = resolution(req.size); if (!metadata.aspectRatio && req.size) metadata.aspectRatio = aspect(req.size); if (metadata.resolution) metadata.resolution = String(metadata.resolution).toLowerCase(); metadata.sampleCount = 1; const instance = { prompt: req.prompt }; const image = (req.images || [])[0]; if (image) { const frame = inputImage(ctx, image); instance.image = { bytesBase64Encoded: frame.data, mimeType: frame.mime }; } return { // A gateway runs the request in its own project, so the path names none. url: modelURL(ctx, viaGateway(ctx) ? "-" : ctx.auth.projectId, region(ctx, ctx.model || model), model, "predictLongRunning"), method: "POST", headers: requestHeaders(ctx), body: { instances: [instance], parameters: metadata }, action: image ? "image_to_video" : "text_to_video", }; } export function parseSubmitResponse(ctx, resp) { const body = resp.body || {}; if (omniModel(ctx)) { const id = trimmed(body.id); if (!id) throw new Error("missing interaction id"); return { taskId: id, taskData: body }; } if (!String(body.name || "").trim()) throw new Error("missing operation name"); return { taskId: utils.base64URL(body.name), taskData: body }; } export function extractUsage(ctx) { const req = ctx.requestBody || {}; const metadata = req.metadata || {}; if (omniModel(ctx)) return omniUsageFacts(omniDuration(req), omniResolution(req)); return { seconds: duration(req), resolution: String(metadata.resolution || resolution(req.size) || "720p").toLowerCase(), generate_audio: metadata.generateAudio !== false, }; } // Facts Vertex does not report are omitted so the host keeps the submit estimate. export function extractUsageOnComplete(ctx, _result, body) { if (!ctx || !omniModel(ctx)) return null; const usage = plainObject(body && body.usage); if (!usage) return null; const facts = {}; const inputTokens = Number(usage.total_input_tokens); if (Number.isFinite(inputTokens)) facts.input_tokens = inputTokens; let textTokens = Number(usage.total_thought_tokens); let videoTokens = NaN; for (const item of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) { const entry = plainObject(item) || {}; const tokens = Number(entry.tokens) || 0; const modality = trimmed(entry.modality).toLowerCase(); if (modality === "video" || modality === "audio") videoTokens = (videoTokens || 0) + tokens; else textTokens = (textTokens || 0) + tokens; } if (Number.isFinite(textTokens)) facts.output_tokens = textTokens; if (Number.isFinite(videoTokens)) facts.video_tokens = videoTokens; return facts; } export function buildQueryRequest(ctx) { if (omniModel(ctx)) return { url: interactionsURL(ctx, ctx.taskId), method: "GET", headers: requestHeaders(ctx) }; return fetchOperation(ctx, decodeTaskId(ctx.taskId)); } export function parseTaskResult(ctx, body) { if (omniModel(ctx)) return omniTaskResult(body); if (body.error && body.error.message) return { status: "FAILURE", progress: "100%", reason: body.error.message }; // Google long-running operations omit `done` (proto3 default) while still // running, so a missing key means in-progress; only a non-operation shape is // unrecognized. if (!body || typeof body !== "object" || !String(body.name || "").trim()) return { status: "UNKNOWN", reason: "unrecognized operation state" }; if (body.done !== true) return { status: "IN_PROGRESS", progress: "50%" }; const result = { status: "SUCCESS", progress: "100%" }; const gcsUri = trimmed(firstVideo(body).gcsUri); if (gcsUri) result.remoteUrl = gcsUri; return result; } // A video written to Cloud Storage stays there. An inline video is too large // for the stored operation, which keeps its media type only, so a download // fetches the operation again. export function listArtifacts(task) { if (isInteraction(task.data)) { const omni = omniVideo(task.data); if (task.status !== "SUCCESS" || !omni || omni.uri) return []; return [{ key: "video", type: "video", mimeType: omni.mimeType }]; } const video = firstVideo(task.data); if (task.status !== "SUCCESS" || !Object.keys(video).length || trimmed(video.gcsUri)) return []; return [{ key: "video", type: "video", mimeType: trimmed(video.mimeType) || "video/mp4" }]; } export function buildContentRequest(ctx) { if (ctx.artifactKey !== "video") throw new Error("artifact_not_found"); if (isInteraction(ctx.data)) { const omni = omniVideo(ctx.data); if (!omni) throw new Error("artifact_not_found"); return { url: interactionsURL(ctx, ctx.upstreamTaskId), method: "GET", headers: requestHeaders(ctx), responseType: "json", contentPath: omni.path, mimeType: omni.mimeType, }; } // Another gateway serves the video as the artifact of its task, the last // segment of the operation name. if (viaGateway(ctx)) { const taskID = decodeTaskId(ctx.upstreamTaskId).split("/").pop(); return { url: ctx.baseUrl + "/v1/tasks/" + encodeURIComponent(taskID) + "/artifacts/video/content", method: ctx.clientRequest.method, headers: { Authorization: "Bearer " + ctx.apiKey }, }; } return Object.assign(fetchOperation(ctx, decodeTaskId(ctx.upstreamTaskId)), { responseType: "json", contentPath: ["response", "videos", 0, "bytesBase64Encoded"], mimeType: trimmed(firstVideo(ctx.data).mimeType) || "video/mp4", }); } function completionMessage(ctx, task) { const request = (ctx && ctx.requestBody) || {}; const model = trimmed(request.model) || trimmed((task.properties || {}).origin_model_name) || "veo-3.0-generate-001"; const status = String(task.status || "SUCCESS").toUpperCase(); return ( "Video generation for " + model + " completed (" + duration(request) + " seconds, status " + status + "). Retrieve the video through the native /v1/videos task flow." ); } export const protocols = { openai_responses: { decodeRequest: function (ctx) { if (!ctx.body || ctx.body.kind !== "json") throw new Error("JSON body required"); const req = ctx.body.value; if (!req || typeof req !== "object" || Array.isArray(req)) throw new Error("request body must be an object"); const model = trimmed(req.model); if (!model) throw new Error("model is required"); if (req.input !== undefined && typeof req.input !== "string" && !Array.isArray(req.input)) throw new Error("input must be a string or array"); if (req.images !== undefined && !Array.isArray(req.images)) throw new Error("images must be an array"); if (req.metadata !== undefined && (!req.metadata || typeof req.metadata !== "object" || Array.isArray(req.metadata))) throw new Error("metadata must be an object"); const input = responsesInput(req); const prompt = input.prompt || trimmed(req.prompt); const images = []; for (const image of [req.image, req.input_reference].concat(req.images || [], input.images)) { if (trimmed(image) && !images.includes(trimmed(image))) images.push(trimmed(image)); } if (!prompt && images.length === 0) throw new Error("input is required"); if (!images.every(validImageInput)) throw new Error("input image must be a data URL or base64 value"); const metadata = Object.assign({}, req.metadata || {}); if (Object.prototype.hasOwnProperty.call(req, "resolution")) metadata.resolution = req.resolution; const requestBody = { model: model, prompt: prompt, metadata: metadata }; if (images.length) requestBody.images = images; if (Object.prototype.hasOwnProperty.call(req, "seconds")) requestBody.duration = req.seconds; else if (Object.prototype.hasOwnProperty.call(req, "duration")) requestBody.duration = req.duration; if (Object.prototype.hasOwnProperty.call(req, "size")) requestBody.size = req.size; return { kind: "submit", model: model, action: images.length ? "image_to_video" : "text_to_video", requestBody: requestBody }; }, renderEvents: function (ctx, task, previousState) { const status = String(task.status || "UNKNOWN").toUpperCase(); const value = Number(String(task.progress || "").replace("%", "")); const progress = Number.isFinite(value) && value >= 0 && value <= 100 ? value : null; const state = { status: status, progress: progress }; if (status === "SUCCESS") { const events = previousState && previousState.status === status ? [] : [{ type: "output", data: completionMessage(ctx, task) }]; return { events: events, state: state, done: true }; } if (status === "FAILURE") return { events: [{ type: "error", code: "task_failed", message: task.fail_reason || "task failed" }], state: state, done: true }; if (previousState && previousState.status === status && previousState.progress === progress) return { events: [], state: state, done: false }; const event = { type: "progress", message: status.toLowerCase() }; if (progress !== null) event.progress = progress; return { events: [event], state: state, done: false }; }, renderFinal: function (ctx, task) { return { output: [ { type: "message", status: "completed", role: "assistant", content: [{ type: "output_text", text: completionMessage(ctx, task), annotations: [], logprobs: [] }], }, ], metadata: { vendor: "vertex", artifact_mode: "native_videos" }, }; }, }, }; const legacyRenderers = { openai_video: function (task) { const model = (task.properties || {}).origin_model_name || "veo-3.0-generate-001"; const statuses = { NOT_START: "queued", SUBMITTED: "queued", QUEUED: "queued", IN_PROGRESS: "in_progress", SUCCESS: "completed", FAILURE: "failed" }; const out = { id: task.task_id, object: "video", model, status: statuses[task.status] || "unknown", progress: Number(String(task.progress || "0").replace("%", "")), created_at: task.created_at, }; if (Number(task.updated_at) > 0) out.completed_at = Number(task.updated_at); return out; }, }; protocols.openai_video = { decodeRequest: function (ctx) { if (!ctx.body || (ctx.body.kind !== "json" && ctx.body.kind !== "multipart")) throw new Error("JSON or multipart body required"); let req; let hasInputReferenceFile = false; if (ctx.body.kind === "json") { if (!ctx.body.value || Array.isArray(ctx.body.value)) throw new Error("JSON object required"); req = Object.assign({}, ctx.body.value); } else { const first = function (name) { const values = (ctx.body.fields || {})[name] || []; if (values.length > 1) throw new Error(name + " must be provided once"); return values[0]; }; req = {}; const fields = ctx.body.fields || {}; for (const name of Object.keys(fields)) { req[name] = first(name); } for (const file of ctx.body.files || []) { if (file.field !== "input_reference") throw new Error("unexpected file field: " + file.field); if (hasInputReferenceFile) throw new Error("input_reference must be provided once"); const mime = String(file.mimeType || "").toLowerCase(); if (mime !== "image/jpeg" && mime !== "image/png") throw new Error("input_reference must be image/jpeg or image/png"); hasInputReferenceFile = true; } if (req.metadata !== undefined) { let parsed; try { parsed = JSON.parse(req.metadata); } catch { throw new Error("metadata must be a JSON object string"); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("metadata must be a JSON object string"); req.metadata = parsed; } if (req.seconds !== undefined) req.seconds = Number(req.seconds); else if (req.duration !== undefined) req.seconds = Number(req.duration); } // Gemini Omni's duration and resolution are checked where the request is built. const omni = omniModel(ctx); const seconds = req.seconds === undefined ? req.duration : req.seconds; if (seconds !== undefined) { const n = Number(seconds); if (!omni && n !== 4 && n !== 6 && n !== 8) throw new Error("seconds must be one of 4, 6, or 8"); req.duration = n; } const providedResolution = req.resolution !== undefined ? req.resolution : req.metadata && req.metadata.resolution; if (!omni && providedResolution !== undefined && providedResolution !== "") { const value = String(providedResolution).toLowerCase(); if (value !== "720p" && value !== "1080p" && value !== "4k") throw new Error("resolution must be one of 720p, 1080p, or 4k"); } if (hasInputReferenceFile) { req.images = [{ __fileRef: "request_file:input_reference", encoding: "base64", maxBytes: 20971520 }]; } return { kind: "submit", model: ctx.model, action: hasInputReferenceFile || req.input_reference || req.image ? "image_to_video" : "text_to_video", requestBody: Object.assign({}, req, { model: ctx.model }), }; }, render: function (ctx, task) { return legacyRenderers.openai_video(task); }, };