feat(plugins): generate video with Gemini Omni on Vertex AI channels (#8142)

This commit is contained in:
feitianbubu authored and GitHub committed 2026-11-01 14:04:56 +08:00
1 parent ea343c4a81
commit d0abbf6e0d
7 files changed
+339 -38

No files matched your search

+2
View File
@@ -647,6 +647,8 @@ func TestProxyTaskMediaReadsArtifactFromJSONContentPath(t *testing.T) {
{name: "written to storage", method: http.MethodGet, reply: `{"done":true,"response":{"videos":[{"gcsUri":"gs://bucket/video.mp4"}]}}`, status: http.StatusGone, code: "artifact_gone"},
{name: "operation failed", method: http.MethodGet, reply: `{"done":true,"error":{"code":3,"message":"bad request"}}`, status: http.StatusBadGateway, code: "artifact_upstream_error"},
{name: "operation running", method: http.MethodGet, reply: `{"name":"op"}`, status: http.StatusConflict, code: "artifact_not_ready"},
{name: "interaction completed", method: http.MethodGet, reply: `{"id":"int","status":"completed","response":{"videos":[{"bytesBase64Encoded":"` + inline + `"}]}}`, status: http.StatusOK, body: "inline-video"},
{name: "interaction running", method: http.MethodGet, reply: `{"id":"int","status":"in_progress"}`, status: http.StatusConflict, code: "artifact_not_ready"},
{name: "operation expired", method: http.MethodGet, replyStatus: http.StatusNotFound, reply: `{"error":{"code":404}}`, status: http.StatusGone, code: "artifact_gone"},
{name: "reply too large", method: http.MethodGet, reply: `{"done":true,"response":{"videos":[{"bytesBase64Encoded":"` + strings.Repeat("A", 3<<20) + `"}]}}`, status: http.StatusBadGateway, code: "artifact_request_rejected"},
} {
+2 -1
View File
@@ -373,7 +373,8 @@ func writeTaskMediaContentPath(c *gin.Context, body io.Reader, descriptor *relay
message: "Artifact upstream returned an error",
}
}
if operation.Get("done").Type != gjson.True {
// An interaction reports completion through status, not done.
if operation.Get("done").Type != gjson.True && operation.Get("status").String() != "completed" {
return &taskMediaProxyError{
status: http.StatusConflict, code: "artifact_not_ready",
message: "Task artifacts are not ready",
+1 -1
View File
@@ -440,7 +440,7 @@ The host treats every 2xx upstream status (`200`, `201 Created`, `202 Accepted`,
contentPath: ["response", "videos", 0, "bytesBase64Encoded"], mimeType: "video/mp4"}
```
The path follows the rules of a JSON change path: string keys and non-negative integer indices, at most 32 segments. The host reads a 200 reply as a long-running operation: an `error` member answers 502 `artifact_upstream_error`, a `done` other than `true` answers 409 `artifact_not_ready`, and a value at `contentPath` that is not a non-empty string answers 410 `artifact_gone`. Otherwise it decodes the string as base64 (standard or URL-safe) and serves the bytes with `mimeType` (default `video/mp4`) as `Content-Type`; a HEAD client gets the headers only. The reply may not exceed four thirds of `MAX_FILE_DOWNLOAD_MB` plus 1 MiB (502 `artifact_request_rejected`), and the client's range and validator headers are not sent with such a request. Other statuses keep the usual mapping. The whole reply is held in memory while the artifact is served. Other hooks ignore `contentPath` and `mimeType`.
The path follows the rules of a JSON change path: string keys and non-negative integer indices, at most 32 segments. The host reads a 200 reply as a long-running operation: an `error` member answers 502 `artifact_upstream_error`, a reply that is neither `done: true` nor an interaction with `status: "completed"` answers 409 `artifact_not_ready`, and a value at `contentPath` that is not a non-empty string answers 410 `artifact_gone`. Otherwise it decodes the string as base64 (standard or URL-safe) and serves the bytes with `mimeType` (default `video/mp4`) as `Content-Type`; a HEAD client gets the headers only. The reply may not exceed four thirds of `MAX_FILE_DOWNLOAD_MB` plus 1 MiB (502 `artifact_request_rejected`), and the client's range and validator headers are not sent with such a request. Other statuses keep the usual mapping. The whole reply is held in memory while the artifact is served. Other hooks ignore `contentPath` and `mimeType`.
## Origin tasks
+163 -35
View File
@@ -1,30 +1,42 @@
export const meta = {
apiVersion: 1,
key: "vertex-ai",
name: "Google Veo (Vertex AI)",
name: "Google Veo & Gemini Omni (Vertex AI)",
icon: "VertexAI.Color",
description: {
en: "Google Veo video generation on Vertex AI (text-to-video and image-to-video)",
zh: "Google Veo 视频生成(文生视频、图生视频),Vertex AI 版本",
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.2.0",
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"],
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.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.
// Requested video duration in seconds. Veo allows 4, 6, 8; Gemini Omni allows integers from 3 to 10.
seconds: {
type: "number",
unit: "second",
description: { en: "Video generation unit price", zh: "视频生成单价" },
},
// Requested video output resolution.
// Requested video output resolution. 360p is Gemini Omni only.
resolution: {
enum: ["720p", "1080p", "4k"],
enumLabels: { "720p": { en: "720p", zh: "720p" }, "1080p": { en: "1080p", zh: "1080p" }, "4k": { en: "4k", zh: "4k" } },
enum: ["360p", "720p", "1080p", "4k"],
enumLabels: {
"360p": { en: "360p", zh: "360p" },
"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.
@@ -38,6 +50,7 @@ export const meta = {
{ 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 } },
{ label: "8s 360p audio (Gemini Omni)", facts: { seconds: 8, resolution: "360p", generate_audio: true } },
],
// 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
@@ -83,6 +96,115 @@ function requestHeaders(ctx) {
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;
}
const RESOLUTIONS = meta.usageSchema.resolution.enum;
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;
}
function omniDuration(req) {
const n = req.duration === undefined || req.duration === "" ? 8 : Number(req.duration);
if (!Number.isInteger(n) || n < 3 || n > 10) throw new Error("seconds must be an integer from 3 to 10");
return n;
}
// inputImage is the first frame'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 };
}
function omniSubmitRequest(ctx, req, model) {
const input = [];
if (trimmed(req.prompt)) input.push({ type: "text", text: req.prompt });
const image = (req.images || [])[0];
if (image) {
const frame = inputImage(ctx, image);
input.push({ type: "image", mime_type: frame.mime, data: frame.data });
}
if (!input.length) throw new Error("prompt is required");
const task = image ? "image_to_video" : "text_to_video";
return {
url: interactionsURL(ctx),
method: "POST",
headers: requestHeaders(ctx),
body: {
model: model,
input: input,
response_format: [{ type: "video", aspect_ratio: aspect(req.size), resolution: omniResolution(req), duration: omniDuration(req) + "s" }],
generation_config: { video_config: { task: task } },
background: true,
store: true,
},
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)) return { status: "FAILURE", progress: "100%", 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 = [];
@@ -264,6 +386,7 @@ export function buildSubmitRequest(ctx) {
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);
@@ -271,31 +394,9 @@ export function buildSubmitRequest(ctx) {
metadata.sampleCount = 1;
const instance = { prompt: req.prompt };
const image = (req.images || [])[0];
if (image && typeof image === "object" && !Array.isArray(image) && image.__fileRef) {
let mime = String(image.mimeType || "").toLowerCase();
if (mime !== "image/jpeg" && mime !== "image/png") {
const files = ctx.files || [];
for (const file of files) {
if (file.ref === image.__fileRef || file.field === "input_reference") {
mime = String(file.mimeType || "").toLowerCase();
break;
}
}
}
if (mime !== "image/jpeg" && mime !== "image/png") throw new Error("input image must be image/jpeg or image/png");
instance.image = { bytesBase64Encoded: image, mimeType: mime };
} else if (image) {
const text = String(image);
const comma = text.indexOf(",");
let mime = "";
let 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");
instance.image = { bytesBase64Encoded: data, mimeType: mime };
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.
@@ -309,12 +410,18 @@ export function buildSubmitRequest(ctx) {
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 { seconds: omniDuration(req), resolution: omniResolution(req), generate_audio: true };
return {
seconds: duration(req),
resolution: String(metadata.resolution || resolution(req.size) || "720p").toLowerCase(),
@@ -325,9 +432,11 @@ export function extractUsageOnComplete() {
return null;
}
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
@@ -343,12 +452,29 @@ export function parseTaskResult(ctx, body) {
// 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)) {
@@ -497,14 +623,16 @@ protocols.openai_video = {
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 (n !== 4 && n !== 6 && n !== 8) throw new Error("seconds must be one of 4, 6, or 8");
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 (providedResolution !== undefined && providedResolution !== "") {
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");
}
+150 -1
View File
@@ -51,7 +51,7 @@ func TestVertexAIResponsesProtocol(t *testing.T) {
require.True(t, exists, key)
assert.NotEmpty(t, schema.Description, key)
}
assert.Equal(t, []string{"720p", "1080p", "4k"}, plugin.Meta.UsageSchema["resolution"].Enum)
assert.Equal(t, []string{"360p", "720p", "1080p", "4k"}, plugin.Meta.UsageSchema["resolution"].Enum)
assert.Equal(t, "boolean", plugin.Meta.UsageSchema["generate_audio"].Type)
})
@@ -331,3 +331,152 @@ func TestVertexAIDeliversInlineVideoByFetchingTheOperationAgain(t *testing.T) {
assert.Equal(t, v1[0].Route.Decode, v1beta1[0].Route.Decode)
assert.Equal(t, v1[0].Route.Render, v1beta1[0].Route.Render)
}
// Gemini Omni submits a background interaction on the global endpoint.
func TestVertexAIOmniBuildSubmitRequest(t *testing.T) {
plugin := loadVertexAIPlugin(t)
const omni = "gemini-omni-1.1-flash-preview"
call := func(args map[string]any) (map[string]any, error) {
t.Helper()
value, err := plugin.Engine.Call(t.Context(), "buildSubmitRequest", args)
if err != nil {
return nil, err
}
return decodePluginValue(t, value), nil
}
descriptor, err := call(map[string]any{
"model": "gemini-omni-1.1-flash", "upstreamModel": omni,
"authHeader": "Bearer token", "auth": map[string]any{"authHeader": "Bearer token", "projectId": "my-project"},
"requestBody": map[string]any{"prompt": "a cat on the beach", "duration": 6, "size": "720x1280", "metadata": map[string]any{"resolution": "360p"}},
})
require.NoError(t, err)
assert.Equal(t, "https://aiplatform.googleapis.com/v1beta1/projects/my-project/locations/global/interactions", descriptor["url"])
assert.Equal(t, "POST", descriptor["method"])
assert.Equal(t, "text_to_video", descriptor["action"])
assert.Equal(t, map[string]any{"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer token", "x-goog-user-project": "my-project"}, descriptor["headers"])
assert.Equal(t, map[string]any{
"model": omni,
"input": []any{map[string]any{"type": "text", "text": "a cat on the beach"}},
"response_format": []any{map[string]any{"type": "video", "aspect_ratio": "9:16", "resolution": "360p", "duration": "6s"}},
"generation_config": map[string]any{"video_config": map[string]any{"task": "text_to_video"}},
"background": true,
"store": true,
}, descriptor["body"])
descriptor, err = call(map[string]any{
"upstreamModel": omni, "baseUrl": "https://vertex.example/",
"authHeader": "Bearer token",
"auth": map[string]any{"authHeader": "Bearer token", "projectId": "my-project"},
"files": []any{map[string]any{"ref": "request_file:input_reference", "field": "input_reference", "mimeType": "image/png"}},
"requestBody": map[string]any{"prompt": "animate", "images": []any{map[string]any{"__fileRef": "request_file:input_reference", "encoding": "base64"}}},
})
require.NoError(t, err)
assert.Equal(t, "https://vertex.example/v1beta1/projects/my-project/locations/global/interactions", descriptor["url"])
assert.Equal(t, "image_to_video", descriptor["action"])
input := descriptor["body"].(map[string]any)["input"].([]any)
require.Len(t, input, 2)
assert.Equal(t, map[string]any{"type": "image", "mime_type": "image/png", "data": map[string]any{"__fileRef": "request_file:input_reference", "encoding": "base64"}}, input[1])
_, err = call(map[string]any{"upstreamModel": omni, "authHeader": "Bearer t", "auth": map[string]any{"authHeader": "Bearer t", "projectId": "p"}, "requestBody": map[string]any{"prompt": "x", "duration": 12}})
assert.ErrorContains(t, err, "3 to 10")
_, err = call(map[string]any{"upstreamModel": omni, "authHeader": "Bearer t", "auth": map[string]any{"authHeader": "Bearer t", "projectId": "p"}, "requestBody": map[string]any{"prompt": "x", "resolution": "2k"}})
assert.ErrorContains(t, err, "resolution must be one of 360p")
_, err = call(map[string]any{"upstreamModel": omni, "upstream": map[string]any{"kind": "new_api"}, "authHeader": "Bearer t", "auth": map[string]any{}, "requestBody": map[string]any{"prompt": "x"}})
assert.ErrorContains(t, err, "New API gateway")
}
func TestVertexAIOmniQueryAndParse(t *testing.T) {
plugin := loadVertexAIPlugin(t)
const omni = "gemini-omni-1.1-flash-preview"
call := func(hook string, args ...any) map[string]any {
t.Helper()
value, err := plugin.Engine.Call(t.Context(), hook, args...)
require.NoError(t, err)
return decodePluginValue(t, value)
}
queryCtx := map[string]any{"taskId": "int_1", "model": "gemini-omni-1.1-flash", "upstreamModel": omni, "authHeader": "Bearer token", "auth": map[string]any{"authHeader": "Bearer token", "projectId": "p1"}}
descriptor := call("buildQueryRequest", queryCtx)
assert.Equal(t, "https://aiplatform.googleapis.com/v1beta1/projects/p1/locations/global/interactions/int_1", descriptor["url"])
assert.Equal(t, "GET", descriptor["method"])
submitted := call("parseSubmitResponse", queryCtx, map[string]any{"body": map[string]any{"id": "int_1", "status": "in_progress"}})
assert.Equal(t, "int_1", submitted["taskId"])
// The stored interaction keeps the inline video's media type only, so the
// artifact is served by fetching the interaction again and reading the
// model_output step.
redacted := map[string]any{"id": "int_1", "object": "interaction", "status": "completed", "steps": []any{
map[string]any{"type": "thought", "summary": []any{}},
map[string]any{"type": "model_output", "content": []any{map[string]any{"type": "video", "mime_type": "video/mp4"}}},
}}
inline := map[string]any{"id": "int_1", "object": "interaction", "status": "completed", "steps": []any{
map[string]any{"type": "model_output", "content": []any{map[string]any{"type": "video", "mime_type": "video/mp4", "data": "AAAA"}}},
}}
stored := map[string]any{"id": "int_1", "object": "interaction", "status": "completed", "steps": []any{
map[string]any{"type": "model_output", "content": []any{map[string]any{"type": "video", "mime_type": "video/mp4", "uri": "gs://b/v.mp4"}}},
}}
for _, tc := range []struct {
name string
body map[string]any
want map[string]any
}{
{"running", map[string]any{"id": "int_1", "status": "in_progress"}, map[string]any{"status": "IN_PROGRESS", "progress": "50%"}},
{"completed inline", inline, map[string]any{"status": "SUCCESS", "progress": "100%"}},
{"completed uri", stored, map[string]any{"status": "SUCCESS", "progress": "100%", "remoteUrl": "gs://b/v.mp4"}},
{"completed without video", map[string]any{"id": "int_1", "status": "completed", "steps": []any{}}, map[string]any{"status": "FAILURE", "progress": "100%", "reason": "interaction completed without a video"}},
{"failed", map[string]any{"id": "int_1", "status": "failed"}, map[string]any{"status": "FAILURE", "progress": "100%", "reason": "failed"}},
{"error", map[string]any{"error": map[string]any{"message": "quota exceeded"}}, map[string]any{"status": "FAILURE", "progress": "100%", "reason": "quota exceeded"}},
{"unrecognized", map[string]any{"foo": "bar"}, map[string]any{"status": "UNKNOWN", "reason": "unrecognized interaction state"}},
} {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, call("parseTaskResult", queryCtx, tc.body))
})
}
artifacts, err := plugin.Engine.Call(t.Context(), "listArtifacts", map[string]any{"status": "SUCCESS", "data": redacted})
require.NoError(t, err)
assert.Equal(t, []any{map[string]any{"key": "video", "type": "video", "mimeType": "video/mp4"}}, artifacts)
artifacts, err = plugin.Engine.Call(t.Context(), "listArtifacts", map[string]any{"status": "SUCCESS", "data": stored})
require.NoError(t, err)
assert.Empty(t, artifacts)
assert.Equal(t, map[string]any{
"url": "https://aiplatform.googleapis.com/v1beta1/projects/p1/locations/global/interactions/int_1",
"method": "GET",
"headers": map[string]any{"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer token", "x-goog-user-project": "p1"},
"responseType": "json",
"contentPath": []any{"steps", float64(1), "content", float64(0), "data"},
"mimeType": "video/mp4",
}, call("buildContentRequest", map[string]any{
"artifactKey": "video", "upstreamTaskId": "int_1", "data": redacted, "authHeader": "Bearer token",
"auth": map[string]any{"authHeader": "Bearer token", "projectId": "p1"}, "clientRequest": map[string]any{"method": "GET"},
}))
}
// The OpenAI video decoder leaves Gemini Omni's duration and resolution to the
// request builder, which allows what Veo does not.
func TestVertexAIOmniUsageAndVideoDecoder(t *testing.T) {
plugin := loadVertexAIPlugin(t)
const omni = "gemini-omni-1.1-flash-preview"
usage, err := plugin.Engine.Call(t.Context(), "extractUsage", map[string]any{"upstreamModel": omni, "requestBody": map[string]any{"prompt": "x", "size": "1920x1080"}})
require.NoError(t, err)
assert.Equal(t, map[string]any{"seconds": float64(8), "resolution": "1080p", "generate_audio": true}, decodePluginValue(t, usage))
decoded, err := plugin.Engine.CallPath(t.Context(), "protocols", []string{"openai_video", "decodeRequest"}, map[string]any{
"model": "omni-alias", "upstreamModel": omni,
"body": map[string]any{"kind": "json", "value": map[string]any{"model": "omni-alias", "prompt": "a cat", "seconds": "3", "resolution": "360p"}},
})
require.NoError(t, err)
requestBody := decodePluginValue(t, decoded)["requestBody"].(map[string]any)
assert.Equal(t, "omni-alias", requestBody["model"])
assert.Equal(t, float64(3), requestBody["duration"])
assert.Equal(t, "360p", requestBody["resolution"])
}
func loadVertexAIPlugin(t *testing.T) *jsplugin.LoadedPlugin {
t.Helper()
source, err := builtinplugins.Source("vertex-ai")
require.NoError(t, err)
plugin, err := jsplugin.NewRegistry().RegisterFactory(source, jsplugin.Options{Key: "vertex-ai"})
require.NoError(t, err)
return plugin
}
+11
View File
@@ -664,6 +664,17 @@ func redactVideoResponseBody(body []byte) []byte {
}
}
}
if steps, ok := m["steps"].([]any); ok {
for _, step := range steps {
sm, _ := step.(map[string]any)
parts, _ := sm["content"].([]any)
for _, part := range parts {
if pm, ok := part.(map[string]any); ok && pm["type"] == "video" {
delete(pm, "data")
}
}
}
}
b, err := common.Marshal(m)
if err != nil {
return body
+10
View File
@@ -173,6 +173,16 @@ func TestRedactVideoResponseBodyPreservesPollingPayloadShape(t *testing.T) {
assert.Equal(t, "https://media.example/video.mp4", video["uri"])
}
func TestRedactVideoResponseBodyDropsInteractionInlineVideo(t *testing.T) {
body := []byte(`{"id":"int_1","status":"completed","steps":[{"type":"model_output","content":[{"type":"video","mime_type":"video/mp4","data":"` + strings.Repeat("a", 1024) + `"},{"type":"text","text":"done"}]}]}`)
var stored map[string]any
require.NoError(t, common.Unmarshal(redactVideoResponseBody(body), &stored))
content := stored["steps"].([]any)[0].(map[string]any)["content"].([]any)
assert.Equal(t, map[string]any{"type": "video", "mime_type": "video/mp4"}, content[0])
assert.Equal(t, "done", content[1].(map[string]any)["text"])
}
func seedTaskPollingChannel(t *testing.T, id int, disableSleep bool) {
t.Helper()
ch := &model.Channel{