feat: add VIDEO model type support (generation, UI, admin)
This commit is contained in:
1 parent
e8c94f4222
commit
c04ec83a63
13 files changed
+306
-10
No files matched your search
Generated
+1
-1
@@ -56,7 +56,7 @@
|
||||
"prettier-plugin-tailwindcss": "^0.6.12",
|
||||
"tailwindcss": "^4.1.8",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript": "^5.8.3"
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
|
||||
+1
-1
@@ -63,6 +63,6 @@
|
||||
"prettier-plugin-tailwindcss": "^0.6.12",
|
||||
"tailwindcss": "^4.1.8",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript": "^5.8.3"
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,7 @@ export default function AdminModelMappingsPage() {
|
||||
<option value="chat">Chat</option>
|
||||
<option value="image">Image</option>
|
||||
<option value="audio">Audio</option>
|
||||
<option value="video">Video</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,7 @@ function parseRawKeys(input: string): string[] {
|
||||
function inferModelType(modelId: string, _providerId: string): ModelType {
|
||||
const id = modelId.toLowerCase();
|
||||
if (/^tts-/.test(id) || /^eleven[_-]/.test(id) || id.includes("whisper")) return "audio";
|
||||
if (/sora|kling|runway|luma|wan|hailuo|minimax-video|cogvideo|pika/.test(id) || (id.includes("video") && !id.includes("video-llava"))) return "video";
|
||||
if (/^dall-e-/.test(id) || /^gpt-image-/.test(id) || id.includes("-image") || id.includes("image-")) return "image";
|
||||
return "chat";
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { ModelType } from "@/types/provider";
|
||||
function inferModelType(modelId: string): ModelType {
|
||||
const id = modelId.toLowerCase();
|
||||
if (/^tts-/.test(id) || /^eleven[_-]/.test(id) || id.includes("whisper")) return "audio";
|
||||
if (/sora|kling|runway|luma|wan|hailuo|minimax-video|cogvideo|pika/.test(id) || (id.includes("video") && !id.includes("video-llava"))) return "video";
|
||||
if (/^dall-e-/.test(id) || /^gpt-image-/.test(id) || id.includes("-image") || id.includes("image-")) return "image";
|
||||
return "chat";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getSession } from "@/lib/auth-helpers";
|
||||
import { db } from "@/lib/db";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { checkRateLimit } from "@/server/services/rate-limiter";
|
||||
import { resolveModelRouteCandidates } from "@/server/services/model-router";
|
||||
import { logUsage } from "@/server/services/usage-logger";
|
||||
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
|
||||
|
||||
const schema = z.object({
|
||||
model: z.string().min(1),
|
||||
prompt: z.string().trim().min(1).max(4000),
|
||||
duration: z.number().int().min(1).max(60).optional(),
|
||||
resolution: z.enum(["480p", "720p", "1080p"]).optional(),
|
||||
aspect_ratio: z.enum(["16:9", "9:16", "1:1", "4:3", "3:4"]).optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const payload = parsed.data;
|
||||
|
||||
const [apiKeys, subscription] = await Promise.all([
|
||||
db.userApiKey.findMany({
|
||||
where: { userId: session.user.id },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
|
||||
}),
|
||||
db.subscription.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
include: { plan: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
|
||||
const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
|
||||
if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
|
||||
|
||||
const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
|
||||
if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
|
||||
|
||||
const limits = {
|
||||
dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
|
||||
dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
|
||||
dailyCostCents: apiKey.softCostLimitCents ?? null,
|
||||
};
|
||||
const rateLimit = await checkRateLimit(apiKey.id, limits);
|
||||
if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
|
||||
|
||||
const routes = await resolveModelRouteCandidates(payload.model);
|
||||
if (routes.length === 0) return modelNotFound(payload.model).toResponse();
|
||||
|
||||
const startedAt = Date.now();
|
||||
let lastApiError: ApiError | null = null;
|
||||
|
||||
for (const route of routes) {
|
||||
if (!route.adapter.videoGeneration) continue;
|
||||
|
||||
try {
|
||||
const result = await route.adapter.videoGeneration(
|
||||
{
|
||||
prompt: payload.prompt,
|
||||
model: payload.model,
|
||||
duration: payload.duration,
|
||||
resolution: payload.resolution,
|
||||
aspect_ratio: payload.aspect_ratio,
|
||||
},
|
||||
route.ctx,
|
||||
);
|
||||
|
||||
const latencyMs = Date.now() - startedAt;
|
||||
|
||||
logUsage({
|
||||
userId: session.user.id,
|
||||
userApiKeyId: apiKey.id,
|
||||
providerId: route.providerId,
|
||||
providerApiKeyId: route.providerApiKeyId,
|
||||
logicalModelId: route.logicalModelId,
|
||||
providerModelId: route.providerModelId,
|
||||
statusCode: 200,
|
||||
tokensIn: 0,
|
||||
tokensOut: 0,
|
||||
latencyMs,
|
||||
streamed: false,
|
||||
promptText: payload.prompt,
|
||||
loggingMode: "preview",
|
||||
}).catch((err) => logger.error(err, "Failed to log video generation usage"));
|
||||
|
||||
return NextResponse.json({
|
||||
providerId: route.providerId,
|
||||
model: payload.model,
|
||||
videos: result.data.map((d) => ({
|
||||
url: d.url,
|
||||
b64: d.b64,
|
||||
revised_prompt: d.revised_prompt,
|
||||
})),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
lastApiError = error;
|
||||
if (error.statusCode === 429 || error.statusCode >= 500) continue;
|
||||
return error.toResponse();
|
||||
}
|
||||
logger.error(error, "Unhandled video generation error");
|
||||
}
|
||||
}
|
||||
|
||||
if (lastApiError) return lastApiError.toResponse();
|
||||
return internalError().toResponse();
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
ArrowUp, Check, ChevronDown, Edit2, EyeOff, Globe, Image as ImageIcon,
|
||||
LayoutDashboard, Mic, Palette, MessageSquare, Phone, Plus, Settings,
|
||||
Smartphone, Sparkles, Square, Star, Trash2, Users, X,
|
||||
LayoutDashboard, Mic, Palette, MessageSquare, Phone, Play, Plus, Settings,
|
||||
Smartphone, Sparkles, Square, Star, Trash2, Users, Video, X,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ModelMenuItem } from "./ModelMenuItem";
|
||||
@@ -275,6 +275,8 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
<Palette className="h-3.5 w-3.5 text-violet-400" />
|
||||
) : e.currentModelType === "audio" ? (
|
||||
<Mic className="h-3.5 w-3.5 text-emerald-400" />
|
||||
) : e.currentModelType === "video" ? (
|
||||
<Video className="h-3.5 w-3.5 text-rose-400" />
|
||||
) : (
|
||||
<Sparkles className="h-3.5 w-3.5 text-blue-400" />
|
||||
)}
|
||||
@@ -482,6 +484,36 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{e.currentModelType === "video" && (
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-muted-foreground">Aspect Ratio</label>
|
||||
<select value={e.videoAspectRatio} onChange={(ev) => { e.setVideoAspectRatio(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
|
||||
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
|
||||
<option value="16:9">16:9 (Landscape)</option>
|
||||
<option value="9:16">9:16 (Portrait)</option>
|
||||
<option value="1:1">1:1 (Square)</option>
|
||||
<option value="4:3">4:3</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-muted-foreground">Resolution</label>
|
||||
<select value={e.videoResolution} onChange={(ev) => { e.setVideoResolution(ev.target.value); setTimeout(e.saveChatSettings, 0); }}
|
||||
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30">
|
||||
<option value="1080p">1080p</option>
|
||||
<option value="720p">720p</option>
|
||||
<option value="480p">480p</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-muted-foreground">Duration (sec)</label>
|
||||
<input type="number" min={1} max={60} value={e.videoDuration ?? ""} placeholder="Auto"
|
||||
onChange={(ev) => { e.setVideoDuration(ev.target.value ? Number(ev.target.value) : undefined); setTimeout(e.saveChatSettings, 0); }}
|
||||
className="w-full rounded-lg border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-sm outline-none focus:border-blue-500/30" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -492,22 +524,25 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
<div className="flex h-full flex-col items-center justify-center px-4">
|
||||
<div className={cn(
|
||||
"mb-6 rounded-2xl p-4",
|
||||
e.currentModelType === "image" ? "bg-violet-500/10" : e.currentModelType === "audio" ? "bg-emerald-500/10" : "bg-blue-500/10",
|
||||
e.currentModelType === "image" ? "bg-violet-500/10" : e.currentModelType === "audio" ? "bg-emerald-500/10" : e.currentModelType === "video" ? "bg-rose-500/10" : "bg-blue-500/10",
|
||||
)}>
|
||||
{e.currentModelType === "image" ? <Palette className="h-8 w-8 text-violet-400" />
|
||||
: e.currentModelType === "audio" ? <Mic className="h-8 w-8 text-emerald-400" />
|
||||
: e.currentModelType === "video" ? <Video className="h-8 w-8 text-rose-400" />
|
||||
: <Sparkles className="h-8 w-8 text-blue-400" />}
|
||||
</div>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{e.incognito ? "Incognito Chat"
|
||||
: e.currentModelType === "image" ? "Generate Images"
|
||||
: e.currentModelType === "audio" ? "Text to Speech"
|
||||
: e.currentModelType === "video" ? "Generate Videos"
|
||||
: "Start a conversation"}
|
||||
</h2>
|
||||
<p className="mt-2 max-w-md text-center text-sm text-muted-foreground">
|
||||
{e.incognito ? "Messages in this session won't be saved. Close or switch to normal mode to clear."
|
||||
: e.currentModelType === "image" ? "Describe the image you want to create and the model will generate it for you."
|
||||
: e.currentModelType === "audio" ? "Enter text and the model will convert it to natural-sounding speech."
|
||||
: e.currentModelType === "video" ? "Describe the video you want to create and the model will generate it for you."
|
||||
: "Send a message to begin. Your conversation will be saved automatically."}
|
||||
</p>
|
||||
</div>
|
||||
@@ -524,6 +559,7 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
<div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-white/[0.06]">
|
||||
{e.currentModelType === "image" ? <Palette className="h-3.5 w-3.5 text-violet-400" />
|
||||
: e.currentModelType === "audio" ? <Mic className="h-3.5 w-3.5 text-emerald-400" />
|
||||
: e.currentModelType === "video" ? <Video className="h-3.5 w-3.5 text-rose-400" />
|
||||
: <Sparkles className="h-3.5 w-3.5 text-blue-400" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -540,6 +576,10 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="h-2 w-2 animate-pulse rounded-full bg-emerald-400" />Generating audio...
|
||||
</div>
|
||||
) : e.currentModelType === "video" ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="h-2 w-2 animate-pulse rounded-full bg-rose-400" />Generating video...
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="h-2 w-2 animate-pulse rounded-full bg-blue-400" />
|
||||
@@ -606,6 +646,7 @@ export function ClassicChatUI({ engine, onToggleMode }: { engine: ChatEngine; on
|
||||
e.pendingImages.length ? "Add a message about these images..."
|
||||
: e.currentModelType === "image" ? "Describe the image you want to generate..."
|
||||
: e.currentModelType === "audio" ? "Enter text to convert to speech..."
|
||||
: e.currentModelType === "video" ? "Describe the video you want to generate..."
|
||||
: "Send a message..."
|
||||
}
|
||||
className="px-4 py-3 pr-32"
|
||||
|
||||
@@ -45,7 +45,31 @@ export function MessageBubble({ msg, variant = "classic" }: { msg: ChatMessage;
|
||||
"min-w-0",
|
||||
isMessenger ? "max-w-[80%] rounded-2xl rounded-bl-md bg-[hsl(220,16%,12%)] px-4 py-3" : "flex-1",
|
||||
)}>
|
||||
{msg.generatedImages?.length ? (
|
||||
{msg.generatedVideos?.length ? (
|
||||
<div className="space-y-3">
|
||||
{msg.content && msg.content !== "Generated video" && (
|
||||
<p className="text-sm text-muted-foreground italic">{msg.content}</p>
|
||||
)}
|
||||
{msg.generatedVideos.map((v, i) => (
|
||||
<div key={i}>
|
||||
<video
|
||||
controls
|
||||
className="max-w-full rounded-lg"
|
||||
style={{ maxHeight: "400px" }}
|
||||
src={v.url || (v.b64 ? `data:${v.contentType || "video/mp4"};base64,${v.b64}` : undefined)}
|
||||
/>
|
||||
<div className="mt-1 flex gap-2">
|
||||
{v.url && (
|
||||
<a href={v.url} download className="text-xs text-muted-foreground hover:text-foreground">Download</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{msg.generatedVideos[0]?.revised_prompt && (
|
||||
<p className="text-xs text-muted-foreground/60 italic">{msg.generatedVideos[0].revised_prompt}</p>
|
||||
)}
|
||||
</div>
|
||||
) : msg.generatedImages?.length ? (
|
||||
<div className="space-y-3">
|
||||
{msg.content && msg.content !== "Generated image" && (
|
||||
<p className="text-sm text-muted-foreground italic">{msg.content}</p>
|
||||
|
||||
@@ -39,6 +39,9 @@ export function ModelMenuItem({
|
||||
{m.modelType === "audio" && (
|
||||
<span className="shrink-0 rounded bg-emerald-500/15 px-1.5 py-0.5 text-[10px] font-medium text-emerald-400">TTS</span>
|
||||
)}
|
||||
{m.modelType === "video" && (
|
||||
<span className="shrink-0 rounded bg-rose-500/15 px-1.5 py-0.5 text-[10px] font-medium text-rose-400">VID</span>
|
||||
)}
|
||||
</button>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">{m.providerId}</span>
|
||||
<button
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type ModelType = "chat" | "image" | "audio";
|
||||
export type ModelType = "chat" | "image" | "audio" | "video";
|
||||
|
||||
export interface ModelOption {
|
||||
id: string;
|
||||
@@ -17,6 +17,7 @@ export interface ChatMessage {
|
||||
content: string;
|
||||
images?: ImagePart[];
|
||||
generatedImages?: Array<{ b64_json?: string; url?: string; revised_prompt?: string }>;
|
||||
generatedVideos?: Array<{ url?: string; b64?: string; revised_prompt?: string; contentType?: string }>;
|
||||
audioB64?: string;
|
||||
audioContentType?: string;
|
||||
model?: string;
|
||||
|
||||
@@ -114,6 +114,14 @@ export interface ChatEngine {
|
||||
imageN: number;
|
||||
setImageN: (v: number) => void;
|
||||
|
||||
// Advanced settings — video
|
||||
videoDuration: number | undefined;
|
||||
setVideoDuration: (v: number | undefined) => void;
|
||||
videoResolution: string;
|
||||
setVideoResolution: (v: string) => void;
|
||||
videoAspectRatio: string;
|
||||
setVideoAspectRatio: (v: string) => void;
|
||||
|
||||
// Call settings
|
||||
callSettings: CallSettings;
|
||||
setCallSettings: (v: CallSettings) => void;
|
||||
@@ -189,6 +197,9 @@ export function useChatEngine(): ChatEngine {
|
||||
const [imageSize, setImageSize] = useState("1024x1024");
|
||||
const [imageQuality, setImageQuality] = useState("auto");
|
||||
const [imageStyle, setImageStyle] = useState("vivid");
|
||||
const [videoDuration, setVideoDuration] = useState<number | undefined>();
|
||||
const [videoResolution, setVideoResolution] = useState("1080p");
|
||||
const [videoAspectRatio, setVideoAspectRatio] = useState("16:9");
|
||||
const [imageN, setImageN] = useState(1);
|
||||
|
||||
const currentMessages = incognito ? incognitoHistory : messages;
|
||||
@@ -229,6 +240,9 @@ export function useChatEngine(): ChatEngine {
|
||||
if (typeof cs.imageQuality === "string") setImageQuality(cs.imageQuality);
|
||||
if (typeof cs.imageStyle === "string") setImageStyle(cs.imageStyle);
|
||||
if (typeof cs.imageN === "number") setImageN(cs.imageN);
|
||||
if (typeof cs.videoDuration === "number") setVideoDuration(cs.videoDuration);
|
||||
if (typeof cs.videoResolution === "string") setVideoResolution(cs.videoResolution);
|
||||
if (typeof cs.videoAspectRatio === "string") setVideoAspectRatio(cs.videoAspectRatio);
|
||||
if (cs.callSettings && typeof cs.callSettings === "object") {
|
||||
const c = cs.callSettings as Record<string, unknown>;
|
||||
setCallSettings((prev) => ({
|
||||
@@ -283,6 +297,9 @@ export function useChatEngine(): ChatEngine {
|
||||
chatSettings.imageSize = imageSize;
|
||||
chatSettings.imageQuality = imageQuality;
|
||||
chatSettings.imageStyle = imageStyle;
|
||||
if (videoDuration !== undefined) chatSettings.videoDuration = videoDuration;
|
||||
chatSettings.videoResolution = videoResolution;
|
||||
chatSettings.videoAspectRatio = videoAspectRatio;
|
||||
chatSettings.imageN = imageN;
|
||||
chatSettings.callSettings = callSettings;
|
||||
fetch("/api/chat/preferences", {
|
||||
@@ -290,7 +307,7 @@ export function useChatEngine(): ChatEngine {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ chatSettings }),
|
||||
}).catch(() => {});
|
||||
}, [systemPrompt, temperature, maxTokens, topP, frequencyPenalty, presencePenalty, audioVoice, audioSpeed, elevenVoiceId, elevenStability, elevenSimilarityBoost, elevenStyle, imageSize, imageQuality, imageStyle, imageN, callSettings]);
|
||||
}, [systemPrompt, temperature, maxTokens, topP, frequencyPenalty, presencePenalty, audioVoice, audioSpeed, elevenVoiceId, elevenStability, elevenSimilarityBoost, elevenStyle, imageSize, imageQuality, imageStyle, imageN, videoDuration, videoResolution, videoAspectRatio, callSettings]);
|
||||
|
||||
// Load ElevenLabs voices
|
||||
useEffect(() => {
|
||||
@@ -561,6 +578,42 @@ export function useChatEngine(): ChatEngine {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleVideoGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages, convId: string | null) {
|
||||
try {
|
||||
const res = await fetch("/api/chat/generate-video", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
model, prompt: userContent,
|
||||
duration: videoDuration, resolution: videoResolution, aspect_ratio: videoAspectRatio,
|
||||
}),
|
||||
signal: abort.signal,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => null);
|
||||
toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Video generation failed");
|
||||
msgSetter((prev) => prev.slice(0, -1));
|
||||
setInput(userContent);
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: "assistant", content: data.videos?.[0]?.revised_prompt || "Generated video",
|
||||
generatedVideos: data.videos, providerId: data.providerId, model,
|
||||
};
|
||||
msgSetter((prev) => [...prev, assistantMsg]);
|
||||
if (convId) {
|
||||
await fetch(`/api/chat/conversations/${convId}/save`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ messages: [{ role: "user", content: userContent }, { role: "assistant", content: assistantMsg.content, model, providerId: data.providerId, generatedVideos: data.videos }] }),
|
||||
}).catch(() => {});
|
||||
loadConversations();
|
||||
}
|
||||
} catch (err) {
|
||||
if ((err as Error).name !== "AbortError") { toast.error("Video generation failed"); msgSetter((prev) => prev.slice(0, -1)); setInput(userContent); }
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(e?: FormEvent) {
|
||||
e?.preventDefault();
|
||||
console.log("[handleSubmit]", { input: input.trim(), model, submitting, pendingImages: pendingImages.length });
|
||||
@@ -577,7 +630,7 @@ export function useChatEngine(): ChatEngine {
|
||||
const abort = new AbortController();
|
||||
abortRef.current = abort;
|
||||
|
||||
if (currentModelType === "image" || currentModelType === "audio") {
|
||||
if (currentModelType === "image" || currentModelType === "audio" || currentModelType === "video") {
|
||||
const msgSetter = incognito ? setIncognitoHistory : setMessages;
|
||||
const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages };
|
||||
msgSetter((prev) => [...prev, userMsg]);
|
||||
@@ -592,6 +645,7 @@ export function useChatEngine(): ChatEngine {
|
||||
}
|
||||
|
||||
if (currentModelType === "image") await handleImageGeneration(userContent, abort, msgSetter, convId);
|
||||
else if (currentModelType === "video") await handleVideoGeneration(userContent, abort, msgSetter, convId);
|
||||
else await handleAudioGeneration(userContent, abort, msgSetter, convId);
|
||||
|
||||
setStreamingText("");
|
||||
@@ -751,6 +805,7 @@ export function useChatEngine(): ChatEngine {
|
||||
elevenSimilarityBoost, setElevenSimilarityBoost, elevenStyle, setElevenStyle,
|
||||
elevenSpeed, setElevenSpeed, elevenVoices,
|
||||
imageSize, setImageSize, imageQuality, setImageQuality, imageStyle, setImageStyle, imageN, setImageN,
|
||||
videoDuration, setVideoDuration, videoResolution, setVideoResolution, videoAspectRatio, setVideoAspectRatio,
|
||||
callSettings, setCallSettings,
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
AudioSpeechRequest,
|
||||
ImageGenerationRequest,
|
||||
ImageGenerationResponse,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResponse,
|
||||
ProviderAdapter,
|
||||
ProviderKeyContext,
|
||||
ProviderKeyMetadata,
|
||||
@@ -266,6 +268,36 @@ export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
|
||||
return response.arrayBuffer();
|
||||
}
|
||||
|
||||
async videoGeneration(req: VideoGenerationRequest, ctx: ProviderKeyContext): Promise<VideoGenerationResponse> {
|
||||
const body: Record<string, unknown> = {
|
||||
model: ctx.providerModelId,
|
||||
prompt: req.prompt,
|
||||
};
|
||||
if (req.duration !== undefined) body.duration = req.duration;
|
||||
if (req.resolution !== undefined) body.resolution = req.resolution;
|
||||
if (req.aspect_ratio !== undefined) body.aspect_ratio = req.aspect_ratio;
|
||||
|
||||
const response = await fetch(`${ctx.providerBaseUrl}/v1/video/generations`, {
|
||||
method: "POST",
|
||||
headers: this.buildHeaders(ctx),
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(ctx.timeout),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => "Unknown error");
|
||||
logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider video generation error");
|
||||
let userMessage = `Video generation failed (${response.status})`;
|
||||
try {
|
||||
const parsed = JSON.parse(errorText) as { error?: { message?: string } };
|
||||
if (parsed?.error?.message) userMessage = parsed.error.message;
|
||||
} catch { /* use default message */ }
|
||||
throw new ApiError(response.status, userMessage, "server_error", "provider_error");
|
||||
}
|
||||
|
||||
return (await response.json()) as VideoGenerationResponse;
|
||||
}
|
||||
|
||||
async validateApiKey(key: string): Promise<ProviderKeyMetadata> {
|
||||
try {
|
||||
const response = await fetch(`${this.defaultBaseUrl}/v1/models`, {
|
||||
|
||||
+14
-1
@@ -1,7 +1,7 @@
|
||||
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "./unified-request";
|
||||
import type { UnifiedChatResponse, UnifiedCompletionResponse, UnifiedEmbeddingResponse } from "./unified-response";
|
||||
|
||||
export type ModelType = "chat" | "image" | "audio";
|
||||
export type ModelType = "chat" | "image" | "audio" | "video";
|
||||
|
||||
export interface ImageGenerationRequest {
|
||||
prompt: string;
|
||||
@@ -31,6 +31,18 @@ export interface AudioSpeechRequest {
|
||||
style?: number;
|
||||
}
|
||||
|
||||
export interface VideoGenerationRequest {
|
||||
model: string;
|
||||
prompt: string;
|
||||
duration?: number;
|
||||
resolution?: string;
|
||||
aspect_ratio?: string;
|
||||
}
|
||||
|
||||
export interface VideoGenerationResponse {
|
||||
data: Array<{ url?: string; b64?: string; revised_prompt?: string }>;
|
||||
}
|
||||
|
||||
export interface ProviderKeyContext {
|
||||
decryptedKey: string;
|
||||
providerModelId: string;
|
||||
@@ -67,5 +79,6 @@ export interface ProviderAdapter {
|
||||
embeddings?(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise<UnifiedEmbeddingResponse>;
|
||||
imageGeneration?(req: ImageGenerationRequest, ctx: ProviderKeyContext): Promise<ImageGenerationResponse>;
|
||||
audioSpeech?(req: AudioSpeechRequest, ctx: ProviderKeyContext): Promise<ArrayBuffer>;
|
||||
videoGeneration?(req: VideoGenerationRequest, ctx: ProviderKeyContext): Promise<VideoGenerationResponse>;
|
||||
listModels?(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]>;
|
||||
}
|
||||
Reference in new issue
Block a user