Compare commits
11 Commits
6ca7feb1a0
...
f3f1fdafbd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3f1fdafbd | ||
|
|
712d4350a0 | ||
|
|
e2f8a253a7 | ||
|
|
7a837c2180 | ||
|
|
94d6a9008c | ||
|
|
1b281a76dc | ||
|
|
2489ce54f2 | ||
|
|
86c196ce51 | ||
|
|
a0a144f506 | ||
|
|
cef15871ac | ||
|
|
9ae24394fe |
@ -159,12 +159,15 @@ export function LocalAiImagePipelineSections({
|
||||
},
|
||||
{
|
||||
label:
|
||||
rmbgConfig.apiKey ||
|
||||
rmbgConfig.provider === "vip98k"
|
||||
? "服务商 Key 已配置"
|
||||
: rmbgConfig.apiKey ||
|
||||
rmbgConfig.photoroomApiKey ||
|
||||
rmbgConfig.aosApiKey
|
||||
? "Key 已配置"
|
||||
: "Key 待配置",
|
||||
tone:
|
||||
rmbgConfig.provider === "vip98k" ||
|
||||
rmbgConfig.apiKey ||
|
||||
rmbgConfig.photoroomApiKey ||
|
||||
rmbgConfig.aosApiKey
|
||||
@ -179,7 +182,26 @@ export function LocalAiImagePipelineSections({
|
||||
{/* 服务提供商选择 */}
|
||||
<div className="space-y-3">
|
||||
<Label>抠图服务提供商</Label>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
|
||||
<div
|
||||
className={`relative flex cursor-pointer items-center gap-3 rounded-lg border p-4 transition-all hover:bg-accent ${
|
||||
rmbgConfig.provider === "vip98k"
|
||||
? "border-primary bg-accent ring-1 ring-primary"
|
||||
: ""
|
||||
}`}
|
||||
onClick={() => setRmbgConfig({ ...rmbgConfig, provider: "vip98k" })}
|
||||
>
|
||||
<div
|
||||
className={`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-primary ${
|
||||
rmbgConfig.provider === "vip98k"
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-transparent"
|
||||
}`}
|
||||
>
|
||||
{rmbgConfig.provider === "vip98k" && <Check className="h-3 w-3" />}
|
||||
</div>
|
||||
<p className="font-medium text-sm leading-none">VIP98K 统一服务</p>
|
||||
</div>
|
||||
<div
|
||||
className={`relative flex cursor-pointer items-center gap-3 rounded-lg border p-4 transition-all hover:bg-accent ${
|
||||
rmbgConfig.provider === "rmbg"
|
||||
@ -266,6 +288,13 @@ export function LocalAiImagePipelineSections({
|
||||
|
||||
<Separator />
|
||||
|
||||
{rmbgConfig.provider === "vip98k" && (
|
||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||
使用 VIP98K 的 remove-background 模型。API Key 从“AI 模型设置”中的
|
||||
VIP98K 服务商读取,不会在此重复保存。
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* RMBG 配置 */}
|
||||
{rmbgConfig.provider === "rmbg" && (
|
||||
<>
|
||||
@ -471,7 +500,7 @@ export function LocalAiImagePipelineSections({
|
||||
<LocalAiSectionShell
|
||||
description={
|
||||
<>
|
||||
配置图片变清晰API,用于画图标注功能中的图片增强处理。支持主API和备用API切换。
|
||||
配置图片变清晰服务,用于画图标注功能中的图片增强处理。
|
||||
</>
|
||||
}
|
||||
expanded={isLocalAiSectionExpanded("enhance")}
|
||||
@ -481,17 +510,21 @@ export function LocalAiImagePipelineSections({
|
||||
<LocalAiSectionSummary
|
||||
items={[
|
||||
{
|
||||
label: enhanceConfig.useBackupApi
|
||||
label: enhanceConfig.provider === "vip98k"
|
||||
? "VIP98K"
|
||||
: enhanceConfig.useBackupApi
|
||||
? "备用 Real-ESRGAN"
|
||||
: "主 API",
|
||||
tone: "neutral",
|
||||
},
|
||||
{
|
||||
label:
|
||||
enhanceConfig.provider === "vip98k" ||
|
||||
enhanceConfig.apiKey || enhanceConfig.backupApiKey
|
||||
? "Key 已配置"
|
||||
: "Key 待配置",
|
||||
tone:
|
||||
enhanceConfig.provider === "vip98k" ||
|
||||
enhanceConfig.apiKey || enhanceConfig.backupApiKey
|
||||
? "enabled"
|
||||
: "warning",
|
||||
@ -501,6 +534,13 @@ export function LocalAiImagePipelineSections({
|
||||
}
|
||||
title="变清晰API配置"
|
||||
>
|
||||
{enhanceConfig.provider === "vip98k" ? (
|
||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||
使用 VIP98K 的 enhance 模型,默认 4 倍增强。API Key 从“AI 模型设置”中的
|
||||
VIP98K 服务商读取。
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* API切换开关 */}
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
@ -749,6 +789,8 @@ export function LocalAiImagePipelineSections({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button onClick={handleSaveEnhanceConfig}>
|
||||
<Save className="mr-2 h-4 w-4" /> 保存配置
|
||||
@ -2324,7 +2366,7 @@ export function LocalAiImagePipelineSections({
|
||||
<LocalAiSectionShell
|
||||
description={
|
||||
<>
|
||||
配置阿里云Dashscope图像拓展API,用于画图标注功能中的图像智能扩展处理
|
||||
配置图像拓展服务,用于画图标注功能中的图像智能扩展处理
|
||||
</>
|
||||
}
|
||||
expanded={isLocalAiSectionExpanded("extend")}
|
||||
@ -2334,8 +2376,14 @@ export function LocalAiImagePipelineSections({
|
||||
<LocalAiSectionSummary
|
||||
items={[
|
||||
{
|
||||
label: extendConfig.apiKey ? "Key 已配置" : "Key 待配置",
|
||||
tone: extendConfig.apiKey ? "enabled" : "warning",
|
||||
label:
|
||||
extendConfig.provider === "vip98k" || extendConfig.apiKey
|
||||
? "Key 已配置"
|
||||
: "Key 待配置",
|
||||
tone:
|
||||
extendConfig.provider === "vip98k" || extendConfig.apiKey
|
||||
? "enabled"
|
||||
: "warning",
|
||||
},
|
||||
{
|
||||
label: `${extendConfig.xScale}x / ${extendConfig.yScale}x`,
|
||||
@ -2346,6 +2394,12 @@ export function LocalAiImagePipelineSections({
|
||||
}
|
||||
title="图像拓展API配置"
|
||||
>
|
||||
{extendConfig.provider === "vip98k" ? (
|
||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||
使用 VIP98K 的 image-expansion 模型。API Key 从“AI 模型设置”中的
|
||||
VIP98K 服务商读取,仅在这里维护扩展比例。
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="extendApiKey">API密钥 *</Label>
|
||||
<Input
|
||||
@ -2362,6 +2416,7 @@ export function LocalAiImagePipelineSections({
|
||||
sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="extendXScale">X轴放大倍数 *</Label>
|
||||
|
||||
@ -249,7 +249,7 @@ export type EnhanceProKeyRow = {
|
||||
};
|
||||
|
||||
export type RmbgConfig = {
|
||||
provider: "rmbg" | "photoroom" | "aoscdn";
|
||||
provider: "vip98k" | "rmbg" | "photoroom" | "aoscdn";
|
||||
apiUrl: string;
|
||||
apiKey: string;
|
||||
photoroomApiKey: string;
|
||||
@ -261,6 +261,7 @@ export type RmbgConfig = {
|
||||
};
|
||||
|
||||
export type EnhanceConfig = {
|
||||
provider: "vip98k" | "legacy";
|
||||
apiUrl: string;
|
||||
apiKey: string;
|
||||
type: string;
|
||||
@ -273,6 +274,7 @@ export type EnhanceConfig = {
|
||||
};
|
||||
|
||||
export type ExtendConfig = {
|
||||
provider: "vip98k" | "dashscope";
|
||||
apiKey: string;
|
||||
xScale: string;
|
||||
yScale: string;
|
||||
|
||||
@ -2559,7 +2559,7 @@ export function AdminSettingsClient() {
|
||||
|
||||
// 抠图API配置状态
|
||||
const [rmbgConfig, setRmbgConfig] = useState({
|
||||
provider: "rmbg" as "rmbg" | "photoroom" | "aoscdn", // 抠图服务提供商
|
||||
provider: "vip98k" as "vip98k" | "rmbg" | "photoroom" | "aoscdn", // 抠图服务提供商
|
||||
apiUrl: "",
|
||||
apiKey: "",
|
||||
// PhotoRoom 配置
|
||||
@ -2574,6 +2574,7 @@ export function AdminSettingsClient() {
|
||||
|
||||
// 变清晰API配置状态
|
||||
const [enhanceConfig, setEnhanceConfig] = useState({
|
||||
provider: "vip98k" as "vip98k" | "legacy",
|
||||
apiUrl: "",
|
||||
apiKey: "",
|
||||
type: "clean", // "clean" | "face"
|
||||
@ -2603,6 +2604,7 @@ export function AdminSettingsClient() {
|
||||
|
||||
// 图像拓展API配置状态
|
||||
const [extendConfig, setExtendConfig] = useState({
|
||||
provider: "vip98k" as "vip98k" | "dashscope",
|
||||
apiKey: "",
|
||||
xScale: "1.5", // X轴放大倍数
|
||||
yScale: "1.5", // Y轴放大倍数
|
||||
@ -2767,7 +2769,7 @@ export function AdminSettingsClient() {
|
||||
useEffect(() => {
|
||||
if (rmbgConfigData?.setting?.value) {
|
||||
const config = rmbgConfigData.setting.value as {
|
||||
provider?: "rmbg" | "photoroom" | "aoscdn";
|
||||
provider?: "vip98k" | "rmbg" | "photoroom" | "aoscdn";
|
||||
apiUrl?: string;
|
||||
apiKey?: string;
|
||||
photoroomApiKey?: string;
|
||||
@ -2778,7 +2780,7 @@ export function AdminSettingsClient() {
|
||||
aosFormat?: "png" | "jpg";
|
||||
};
|
||||
setRmbgConfig({
|
||||
provider: config.provider || "rmbg",
|
||||
provider: config.provider || "vip98k",
|
||||
apiUrl: config.apiUrl || "",
|
||||
apiKey: config.apiKey || "",
|
||||
photoroomApiKey: config.photoroomApiKey || "",
|
||||
@ -2804,6 +2806,7 @@ export function AdminSettingsClient() {
|
||||
useEffect(() => {
|
||||
if (enhanceConfigData?.setting?.value) {
|
||||
const config = enhanceConfigData.setting.value as {
|
||||
provider?: "vip98k" | "legacy";
|
||||
apiUrl?: string;
|
||||
apiKey?: string;
|
||||
type?: string;
|
||||
@ -2815,6 +2818,7 @@ export function AdminSettingsClient() {
|
||||
backupModel?: string;
|
||||
};
|
||||
setEnhanceConfig({
|
||||
provider: config.provider === "vip98k" ? "vip98k" : "legacy",
|
||||
apiUrl: config.apiUrl || "",
|
||||
apiKey: config.apiKey || "",
|
||||
type: config.type || "clean",
|
||||
@ -2919,11 +2923,13 @@ export function AdminSettingsClient() {
|
||||
useEffect(() => {
|
||||
if (extendConfigData?.setting?.value) {
|
||||
const config = extendConfigData.setting.value as {
|
||||
provider?: "vip98k" | "dashscope";
|
||||
apiKey?: string;
|
||||
xScale?: number;
|
||||
yScale?: number;
|
||||
};
|
||||
setExtendConfig({
|
||||
provider: config.provider === "vip98k" ? "vip98k" : "dashscope",
|
||||
apiKey: config.apiKey || "",
|
||||
xScale: config.xScale ? String(config.xScale) : "1.5",
|
||||
yScale: config.yScale ? String(config.yScale) : "1.5",
|
||||
@ -5109,7 +5115,9 @@ export function AdminSettingsClient() {
|
||||
const handleSaveEnhanceConfig = async () => {
|
||||
try {
|
||||
// 如果启用了备用API,验证备用API配置
|
||||
if (enhanceConfig.useBackupApi) {
|
||||
if (enhanceConfig.provider === "vip98k") {
|
||||
// VIP98K credentials are read from AiProvider and never duplicated here.
|
||||
} else if (enhanceConfig.useBackupApi) {
|
||||
if (!enhanceConfig.backupApiUrl.trim()) {
|
||||
toast.error("请输入备用API地址");
|
||||
return;
|
||||
@ -5136,6 +5144,7 @@ export function AdminSettingsClient() {
|
||||
body: JSON.stringify({
|
||||
key: "enhance_api_config",
|
||||
value: {
|
||||
provider: enhanceConfig.provider,
|
||||
apiUrl: enhanceConfig.apiUrl.trim(),
|
||||
apiKey: enhanceConfig.apiKey.trim(),
|
||||
type: enhanceConfig.type,
|
||||
@ -5512,7 +5521,7 @@ export function AdminSettingsClient() {
|
||||
// --- 图像拓展API配置逻辑 ---
|
||||
const handleSaveExtendConfig = async () => {
|
||||
try {
|
||||
if (!extendConfig.apiKey.trim()) {
|
||||
if (extendConfig.provider !== "vip98k" && !extendConfig.apiKey.trim()) {
|
||||
toast.error("请输入API密钥");
|
||||
return;
|
||||
}
|
||||
@ -5536,6 +5545,7 @@ export function AdminSettingsClient() {
|
||||
body: JSON.stringify({
|
||||
key: "extend_api_config",
|
||||
value: {
|
||||
provider: extendConfig.provider,
|
||||
apiKey: extendConfig.apiKey.trim(),
|
||||
xScale,
|
||||
yScale,
|
||||
@ -7681,7 +7691,7 @@ export function AdminSettingsClient() {
|
||||
if (
|
||||
!options?.skipConfirm &&
|
||||
!confirm(
|
||||
"将从 VIP98K 模型目录同步全部模型,并按图片、视频、3D 世界、文本、图片工具、OCR、音频工具分类。图片模型会配置比例、1K/2K/4K 和多参考图能力。\n\n继续吗?"
|
||||
"将同步 VIP98K 当前可用目录,停用服务商已关闭的模型,并排除纯文生图和纯文生视频模型。图片编辑、图生视频、参考媒体、多模态、3D 与工具模型会保留;你此前手动删除的模型不会恢复。\n\n继续吗?"
|
||||
)
|
||||
) {
|
||||
return;
|
||||
@ -7700,8 +7710,9 @@ export function AdminSettingsClient() {
|
||||
const totalSynced =
|
||||
Number(data.addedCount || 0) + Number(data.updatedCount || 0);
|
||||
const totalCatalog = Number(data.counts?.total || totalSynced);
|
||||
const totalDisabled = Number(data.disabledCount || 0);
|
||||
toast.success(
|
||||
`已同步 ${totalSynced} 个 VIP98K 模型(目录共 ${totalCatalog} 个)`
|
||||
`已同步 ${totalSynced} 个 VIP98K 模型,停用 ${totalDisabled} 个旧模型(可用目录 ${totalCatalog} 个)`
|
||||
);
|
||||
mutateModels();
|
||||
if (data.errors?.length) {
|
||||
|
||||
@ -75,6 +75,7 @@ export async function POST(request: Request) {
|
||||
body.modelIds.map((item: unknown) => String(item || "").trim()).filter(Boolean),
|
||||
)
|
||||
: null;
|
||||
const preserveDeletedModels = body?.preserveDeletedModels !== false;
|
||||
if (!providerId) {
|
||||
return NextResponse.json({ error: "Provider ID is required" }, { status: 400 });
|
||||
}
|
||||
@ -91,14 +92,38 @@ export async function POST(request: Request) {
|
||||
baseURL: provider.baseUrl,
|
||||
apiKey: provider.apiKey,
|
||||
});
|
||||
const existingModels = await db.query.aiModel.findMany({
|
||||
where: eq(aiModel.providerId, providerId),
|
||||
});
|
||||
const existingModelIds = new Set(existingModels.map((model) => model.modelId));
|
||||
const preserveExistingCatalog =
|
||||
requestedModelIds === null &&
|
||||
preserveDeletedModels &&
|
||||
existingModels.length > 0;
|
||||
const presets = requestedModelIds
|
||||
? catalogPresets.filter((preset) => requestedModelIds.has(preset.modelId))
|
||||
: catalogPresets;
|
||||
: preserveExistingCatalog
|
||||
? catalogPresets.filter((preset) => existingModelIds.has(preset.modelId))
|
||||
: catalogPresets;
|
||||
|
||||
const addedModels: AiModel[] = [];
|
||||
const updatedModels: AiModel[] = [];
|
||||
const disabledModels: AiModel[] = [];
|
||||
const errors: Array<{ modelId: string; error: string }> = [];
|
||||
|
||||
if (requestedModelIds === null) {
|
||||
const catalogModelIds = new Set(catalogPresets.map((preset) => preset.modelId));
|
||||
for (const existing of existingModels) {
|
||||
if (catalogModelIds.has(existing.modelId)) continue;
|
||||
const [disabled] = await db
|
||||
.update(aiModel)
|
||||
.set({ isEnabled: false, isHidden: true, updatedAt: new Date() })
|
||||
.where(eq(aiModel.id, existing.id))
|
||||
.returning();
|
||||
if (disabled) disabledModels.push(disabled);
|
||||
}
|
||||
}
|
||||
|
||||
for (const preset of presets) {
|
||||
try {
|
||||
const existing = await db.query.aiModel.findFirst({
|
||||
@ -113,7 +138,8 @@ export async function POST(request: Request) {
|
||||
description: preset.description,
|
||||
supportsVision: preset.supportsVision,
|
||||
supportsImageGen: preset.supportsImageGen,
|
||||
isEnabled: true,
|
||||
isEnabled:
|
||||
requestedModelIds !== null ? true : (existing?.isEnabled ?? true),
|
||||
isHidden: preset.isHidden,
|
||||
sortOrder: preset.sortOrder,
|
||||
capabilities: preset.capabilities,
|
||||
@ -161,8 +187,10 @@ export async function POST(request: Request) {
|
||||
success: true,
|
||||
addedCount: addedModels.length,
|
||||
updatedCount: updatedModels.length,
|
||||
disabledCount: disabledModels.length,
|
||||
addedModels,
|
||||
updatedModels,
|
||||
disabledModelIds: disabledModels.map((model) => model.modelId),
|
||||
errors: errors.length > 0 ? errors : undefined,
|
||||
counts: {
|
||||
requested: presets.length,
|
||||
|
||||
@ -1956,7 +1956,7 @@ export async function POST(request: Request) {
|
||||
(item) =>
|
||||
!item.model.isSubModel &&
|
||||
item.model.isEnabled &&
|
||||
["zhipu", "alibaba", "openai", "custom", "local"].includes(item.provider.type),
|
||||
["zhipu", "alibaba", "openai", "custom", "local", "vip98k"].includes(item.provider.type),
|
||||
);
|
||||
const configuredDetailAgentConfig =
|
||||
currentSiteSettings?.canvasDetailAgentModelId &&
|
||||
|
||||
@ -204,7 +204,7 @@ export async function POST(request: Request) {
|
||||
(item) =>
|
||||
!item.model.isSubModel &&
|
||||
item.model.isEnabled &&
|
||||
["zhipu", "alibaba", "openai", "custom", "local"].includes(item.provider.type),
|
||||
["zhipu", "alibaba", "openai", "custom", "local", "vip98k"].includes(item.provider.type),
|
||||
);
|
||||
const configuredDetailAgentConfig =
|
||||
currentSiteSettings?.canvasDetailAgentModelId &&
|
||||
|
||||
@ -9,9 +9,11 @@ import { auth } from "@/app/(auth)/auth";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
import { db } from "@/lib/db";
|
||||
import { generatedImage } from "@/lib/db/schema";
|
||||
import { executeConfiguredVip98kTask } from "@/lib/ai/vip98k-runtime";
|
||||
|
||||
// 变清晰API配置类型
|
||||
type EnhanceApiConfig = {
|
||||
provider?: "vip98k" | "aoscdn";
|
||||
apiUrl?: string;
|
||||
apiKey?: string;
|
||||
type?: string; // "clean" | "face"
|
||||
@ -317,6 +319,102 @@ async function processWithRealESRGANBase64(
|
||||
};
|
||||
}
|
||||
|
||||
async function processWithVip98kEnhance(params: {
|
||||
userId: string;
|
||||
imageBase64: string;
|
||||
prompt: string;
|
||||
chatId: string | null;
|
||||
messageId: string | null;
|
||||
sourceImageUrl: string | null;
|
||||
scaleFactor: number;
|
||||
}) {
|
||||
const startedAt = Date.now();
|
||||
const result = await executeConfiguredVip98kTask({
|
||||
modelId: "enhance",
|
||||
kind: "image-tool",
|
||||
prompt: `${params.prompt || "Enhance image clarity"}. Upscale ${params.scaleFactor}x while preserving composition, color and texture.`,
|
||||
imageUrls: [`data:image/jpeg;base64,${params.imageBase64}`],
|
||||
imageParams: { scaleFactor: params.scaleFactor },
|
||||
});
|
||||
const outputUrl = result.outputUrls[0];
|
||||
if (!outputUrl) throw new Error("VIP98K 变清晰未返回图片");
|
||||
|
||||
const response = await fetch(outputUrl, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`VIP98K 变清晰结果下载失败(HTTP ${response.status})`);
|
||||
}
|
||||
const outputBuffer = Buffer.from(await response.arrayBuffer());
|
||||
const outputBase64 = outputBuffer.toString("base64");
|
||||
const uploaded = await uploadBase64ToS3(outputBase64, "image/png");
|
||||
const [savedImage] = await db
|
||||
.insert(generatedImage)
|
||||
.values({
|
||||
userId: params.userId,
|
||||
chatId: params.chatId,
|
||||
messageId: params.messageId,
|
||||
thumbnailUrl: uploaded.thumbnail,
|
||||
originalUrl: uploaded.original,
|
||||
imageSize: `${params.scaleFactor}x放大`,
|
||||
prompt: params.prompt,
|
||||
modelId: "enhance",
|
||||
})
|
||||
.returning();
|
||||
|
||||
try {
|
||||
const sourceAssets = params.sourceImageUrl
|
||||
? await getMediaAssetsByUserAndUrls({
|
||||
userId: params.userId,
|
||||
urls: [params.sourceImageUrl],
|
||||
})
|
||||
: [];
|
||||
const media = await upsertMediaAsset({
|
||||
userId: params.userId,
|
||||
chatId: params.chatId,
|
||||
mediaType: "image",
|
||||
sourceType: "edited",
|
||||
status: "ready",
|
||||
originalUrl: uploaded.original,
|
||||
previewUrl: uploaded.original,
|
||||
thumbnailUrl: uploaded.thumbnail,
|
||||
displayName: params.prompt.slice(0, 80),
|
||||
prompt: params.prompt,
|
||||
modelId: "enhance",
|
||||
sourceMessageId: params.messageId,
|
||||
sourceTable: "GeneratedImage",
|
||||
sourceRowId: savedImage?.id || null,
|
||||
primaryParentAssetId: sourceAssets[0]?.id ?? null,
|
||||
metadata: { provider: "vip98k", scaleFactor: params.scaleFactor },
|
||||
});
|
||||
if (media) {
|
||||
for (const sourceAsset of sourceAssets) {
|
||||
await createMediaAssetRelation({
|
||||
userId: params.userId,
|
||||
chatId: params.chatId,
|
||||
fromAssetId: sourceAsset.id,
|
||||
toAssetId: media.id,
|
||||
relationType: "edited_from",
|
||||
sourceMessageId: params.messageId,
|
||||
metadata: { prompt: params.prompt, provider: "vip98k" },
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[Enhance-VIP98K] MediaAsset registration failed", error);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
image_base64: outputBase64,
|
||||
thumbnail_url: uploaded.thumbnail,
|
||||
original_url: uploaded.original,
|
||||
processing_time: (Date.now() - startedAt) / 1000,
|
||||
api_type: "vip98k",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询获取任务结果(根据官方示例)
|
||||
*/
|
||||
@ -563,6 +661,12 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
const config = enhanceConfig.value as EnhanceApiConfig;
|
||||
if (config.provider === "vip98k") {
|
||||
return NextResponse.json(
|
||||
{ error: "VIP98K 变清晰任务在 POST 请求内完成,无需 taskId 轮询" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (config.useBackupApi) {
|
||||
return NextResponse.json(
|
||||
{ error: "当前启用了Real-ESRGAN备用模式,不支持 taskId 轮询" },
|
||||
@ -651,12 +755,15 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const config = enhanceConfig.value as EnhanceApiConfig;
|
||||
const useVip98k = config.provider === "vip98k";
|
||||
|
||||
// 检查是否使用备用API
|
||||
const useBackupApi = config.useBackupApi === true;
|
||||
const useBackupApi = !useVip98k && config.useBackupApi === true;
|
||||
console.log(`[Enhance API] 使用${useBackupApi ? "备用API (Real-ESRGAN)" : "主API"}`);
|
||||
|
||||
if (useBackupApi) {
|
||||
if (useVip98k) {
|
||||
// VIP98K 密钥只从 AiProvider 读取。
|
||||
} else if (useBackupApi) {
|
||||
// 验证备用API配置
|
||||
if (!config.backupApiUrl || !config.backupApiKey) {
|
||||
return NextResponse.json(
|
||||
@ -757,6 +864,31 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
if (useVip98k) {
|
||||
try {
|
||||
const scaleFactor = requestedScaleFactor || 4;
|
||||
const payload = await processWithVip98kEnhance({
|
||||
userId,
|
||||
imageBase64,
|
||||
prompt: prompt || "图片变清晰处理",
|
||||
chatId,
|
||||
messageId,
|
||||
sourceImageUrl,
|
||||
scaleFactor,
|
||||
});
|
||||
return NextResponse.json(payload);
|
||||
} catch (error) {
|
||||
console.error("[Enhance-VIP98K] Processing failed", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "VIP98K 变清晰处理失败",
|
||||
detail: error instanceof Error ? error.message : "未知错误",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 备用API处理路径 (Real-ESRGAN) ==========
|
||||
if (useBackupApi) {
|
||||
console.log("[Enhance API] 使用Real-ESRGAN备用API处理(URL方式)...");
|
||||
|
||||
@ -1222,7 +1222,7 @@ type EnabledModelWithProvider = Awaited<
|
||||
>[number];
|
||||
|
||||
function isAgentGenerateTextProviderType(providerType: string): boolean {
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local"].includes(providerType);
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local", "vip98k"].includes(providerType);
|
||||
}
|
||||
|
||||
function isLikelyVisionCapableModel(item: EnabledModelWithProvider) {
|
||||
|
||||
@ -4,16 +4,21 @@ import {
|
||||
getSystemSetting,
|
||||
upsertMediaAsset,
|
||||
} from "@/lib/db/queries";
|
||||
import { executeConfiguredVip98kTask } from "@/lib/ai/vip98k-runtime";
|
||||
import { db } from "@/lib/db";
|
||||
import { generatedImage } from "@/lib/db/schema";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
|
||||
type ExtendConfig = {
|
||||
provider?: "vip98k" | "dashscope";
|
||||
apiKey?: string;
|
||||
xScale?: number;
|
||||
yScale?: number;
|
||||
};
|
||||
|
||||
const VIP98K_EXPANSION_FALLBACK_MODEL = "google/nano-banana-pro/edit";
|
||||
const VIP98K_SOURCE_DOWNLOAD_TIMEOUT_MS = 120_000;
|
||||
|
||||
export interface ExecuteExtendJobParams {
|
||||
userId: string;
|
||||
imageUrl?: string | null;
|
||||
@ -121,12 +126,130 @@ async function uploadImageToS3ForAPI(imageBase64: string): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
function isTemporaryVip98kExpansionError(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error || "");
|
||||
return /HTTP\s+(?:429|5\d\d)|temporar(?:y|ily)|timeout|timed out|unavailable/i.test(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
async function createVip98kExpansionCanvas(
|
||||
imageUrl: string,
|
||||
xScale: number,
|
||||
yScale: number,
|
||||
) {
|
||||
const response = await fetch(imageUrl, {
|
||||
cache: "no-store",
|
||||
redirect: "follow",
|
||||
signal: AbortSignal.timeout(VIP98K_SOURCE_DOWNLOAD_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new ExtendServiceError(
|
||||
"下载待拓展图片失败",
|
||||
502,
|
||||
`${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const sourceBuffer = Buffer.from(await response.arrayBuffer());
|
||||
const sharp = await import("sharp");
|
||||
const image = sharp.default(sourceBuffer, { failOn: "none" });
|
||||
const metadata = await image.metadata();
|
||||
const width = Number(metadata.width || 0);
|
||||
const height = Number(metadata.height || 0);
|
||||
if (!width || !height) {
|
||||
throw new ExtendServiceError("无法识别待拓展图片尺寸", 422);
|
||||
}
|
||||
|
||||
const targetWidth = Math.max(width, Math.round(width * xScale));
|
||||
const targetHeight = Math.max(height, Math.round(height * yScale));
|
||||
const left = Math.floor((targetWidth - width) / 2);
|
||||
const top = Math.floor((targetHeight - height) / 2);
|
||||
const canvas = await image
|
||||
.ensureAlpha()
|
||||
.extend({
|
||||
left,
|
||||
right: targetWidth - width - left,
|
||||
top,
|
||||
bottom: targetHeight - height - top,
|
||||
background: { r: 0, g: 0, b: 0, alpha: 0 },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
const arrayBuffer = canvas.buffer.slice(
|
||||
canvas.byteOffset,
|
||||
canvas.byteOffset + canvas.byteLength,
|
||||
) as ArrayBuffer;
|
||||
const uploaded = await uploadFile(
|
||||
`extend-vip98k-canvas-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`,
|
||||
arrayBuffer,
|
||||
);
|
||||
return {
|
||||
imageUrl: uploaded.url,
|
||||
width,
|
||||
height,
|
||||
targetWidth,
|
||||
targetHeight,
|
||||
};
|
||||
}
|
||||
|
||||
async function extendImageWithVip98kEditFallback(
|
||||
imageUrl: string,
|
||||
xScale: number,
|
||||
yScale: number,
|
||||
) {
|
||||
const canvas = await createVip98kExpansionCanvas(imageUrl, xScale, yScale);
|
||||
const result = await executeConfiguredVip98kTask({
|
||||
modelId: VIP98K_EXPANSION_FALLBACK_MODEL,
|
||||
kind: "image",
|
||||
prompt: [
|
||||
"Outpaint only the transparent regions of this image.",
|
||||
"Keep every original pixel, subject, scale, position, perspective, lighting and style unchanged.",
|
||||
`Complete the ${canvas.targetWidth}x${canvas.targetHeight} canvas naturally from the centered ${canvas.width}x${canvas.height} source.`,
|
||||
"Do not crop, zoom, move, replace or redraw the original content.",
|
||||
].join(" "),
|
||||
imageUrls: [canvas.imageUrl],
|
||||
});
|
||||
const outputUrl = result.outputUrls[0];
|
||||
if (!outputUrl) {
|
||||
throw new ExtendServiceError("VIP98K 生成式扩图未返回图片", 502);
|
||||
}
|
||||
return outputUrl;
|
||||
}
|
||||
|
||||
async function extendImage(
|
||||
imageUrl: string,
|
||||
apiKey: string,
|
||||
config: ExtendConfig,
|
||||
xScale: number,
|
||||
yScale: number,
|
||||
): Promise<string> {
|
||||
if (config.provider === "vip98k") {
|
||||
try {
|
||||
const result = await executeConfiguredVip98kTask({
|
||||
modelId: "image-expansion",
|
||||
kind: "image-tool",
|
||||
prompt: `Expand the image canvas naturally to ${xScale}x width and ${yScale}x height. Preserve the original subject, perspective, lighting and style.`,
|
||||
imageUrls: [imageUrl],
|
||||
imageParams: { xScale, yScale },
|
||||
});
|
||||
const outputUrl = result.outputUrls[0];
|
||||
if (!outputUrl) {
|
||||
throw new ExtendServiceError("VIP98K 图像拓展未返回图片", 502);
|
||||
}
|
||||
return outputUrl;
|
||||
} catch (error) {
|
||||
if (!isTemporaryVip98kExpansionError(error)) throw error;
|
||||
console.warn(
|
||||
"[Extend Service] VIP98K expansion tool is temporarily unavailable; using VIP98K generative outpainting fallback",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return extendImageWithVip98kEditFallback(imageUrl, xScale, yScale);
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.apiKey) {
|
||||
throw new ExtendServiceError("图像拓展API密钥未配置", 400);
|
||||
}
|
||||
const requestBody = {
|
||||
model: "image-out-painting",
|
||||
input: {
|
||||
@ -147,7 +270,7 @@ async function extendImage(
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
"X-DashScope-Async": "enable",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
@ -170,7 +293,7 @@ async function extendImage(
|
||||
for (let attempt = 0; attempt < 60; attempt += 1) {
|
||||
const statusResponse = await fetch(taskStatusUrl, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
});
|
||||
const result = await statusResponse.json();
|
||||
@ -207,7 +330,7 @@ async function getValidatedExtendConfig(): Promise<ExtendConfig> {
|
||||
}
|
||||
|
||||
const config = extendConfig.value as ExtendConfig;
|
||||
if (!config.apiKey) {
|
||||
if (config.provider !== "vip98k" && !config.apiKey) {
|
||||
throw new ExtendServiceError("图像拓展API密钥未配置", 400);
|
||||
}
|
||||
return config;
|
||||
@ -243,7 +366,7 @@ export async function executeExtendJob(
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const extendedImageUrl = await extendImage(inputImageUrl, config.apiKey!, xScale, yScale);
|
||||
const extendedImageUrl = await extendImage(inputImageUrl, config, xScale, yScale);
|
||||
const imageResponse = await fetch(extendedImageUrl);
|
||||
if (!imageResponse.ok) {
|
||||
throw new ExtendServiceError(
|
||||
@ -277,7 +400,7 @@ export async function executeExtendJob(
|
||||
thumbnailUrl: uploadResult.thumbnail,
|
||||
originalUrl: uploadResult.original,
|
||||
prompt,
|
||||
modelId: "extend-1.0",
|
||||
modelId: config.provider === "vip98k" ? "image-expansion" : "extend-1.0",
|
||||
imageSize: "2K",
|
||||
})
|
||||
.returning();
|
||||
@ -301,7 +424,7 @@ export async function executeExtendJob(
|
||||
thumbnailUrl: uploadResult.thumbnail,
|
||||
displayName: prompt.slice(0, 80),
|
||||
prompt,
|
||||
modelId: "extend-1.0",
|
||||
modelId: config.provider === "vip98k" ? "image-expansion" : "extend-1.0",
|
||||
sourceMessageId: messageId,
|
||||
sourceTable: "GeneratedImage",
|
||||
sourceRowId: generatedImageId,
|
||||
|
||||
@ -611,7 +611,7 @@ export async function optimizePromptWithLLM(params: {
|
||||
const allModels = await getEnabledAiModelsWithProvider();
|
||||
const agentModel = await getAgentAiModelWithProvider();
|
||||
const isReasoningCompatibleProvider = (providerType: string) =>
|
||||
["zhipu", "alibaba", "openai", "custom", "local", "volcano-multimodal", "volcano-vision"].includes(providerType);
|
||||
["zhipu", "alibaba", "openai", "custom", "local", "vip98k", "volcano-multimodal", "volcano-vision"].includes(providerType);
|
||||
const normalizedPreferredModelId = String(preferredModelId || "").trim();
|
||||
const preferredOptimizerModel = normalizedPreferredModelId
|
||||
? allModels.find(
|
||||
|
||||
@ -3,10 +3,17 @@ import "server-only";
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import sharp from "sharp";
|
||||
import { createOpenAIImage } from "@/lib/ai/providers/openai-image";
|
||||
import {
|
||||
resolveVip98kTaskInvocation,
|
||||
type Vip98kTaskInvocation,
|
||||
} from "@/lib/ai/vip98k-task-invocation";
|
||||
import { VIP98K_BASE_URL, normalizeVip98kBaseUrl } from "@/lib/ai/vip98k-models";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { createDeferredUploadedImage } from "@/lib/storage/image-archive";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
|
||||
const logger = createLogger("vip98k-provider");
|
||||
|
||||
interface Vip98kConfig {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
@ -30,6 +37,8 @@ type Vip98kModelRuntimeConfig = {
|
||||
imageGenConfig?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
type Vip98kInvocation = Vip98kTaskInvocation;
|
||||
|
||||
type UploadedImage = {
|
||||
thumbnail: string;
|
||||
original: string;
|
||||
@ -75,6 +84,23 @@ function getVip98kMetadata(config: Vip98kModelRuntimeConfig) {
|
||||
return capabilitiesVip98k || imageConfigVip98k || {};
|
||||
}
|
||||
|
||||
function getVip98kInvocation(config: Vip98kModelRuntimeConfig): Vip98kInvocation | null {
|
||||
const metadata = getVip98kMetadata(config);
|
||||
const invocation = toRecord(metadata.invocation);
|
||||
if (!invocation) return null;
|
||||
const path = String(invocation.path || "").trim();
|
||||
if (!path.startsWith("/")) return null;
|
||||
return {
|
||||
kind: String(invocation.kind || "task").trim().toLowerCase(),
|
||||
method: String(invocation.method || "POST").trim().toUpperCase(),
|
||||
path,
|
||||
contentType: String(invocation.contentType || "application/json").trim(),
|
||||
requestExample: { ...(toRecord(invocation.requestExample) || {}) },
|
||||
resultMethod: String(invocation.resultMethod || "GET").trim().toUpperCase(),
|
||||
resultPath: String(invocation.resultPath || "").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function inferKind(modelId: string, config: Vip98kModelRuntimeConfig) {
|
||||
const capabilities = config.capabilities;
|
||||
const metadata = getVip98kMetadata(config);
|
||||
@ -85,6 +111,9 @@ function inferKind(modelId: string, config: Vip98kModelRuntimeConfig) {
|
||||
getStringField(metadata, "modelType");
|
||||
if (configuredKind.includes("world")) return "world";
|
||||
if (configuredKind.includes("video")) return "video";
|
||||
if (configuredKind.includes("model-3d") || configuredKind === "3d") {
|
||||
return "model-3d";
|
||||
}
|
||||
if (configuredKind.includes("image-tool")) return "image-tool";
|
||||
if (configuredKind.includes("image")) return "image";
|
||||
if (configuredKind.includes("audio")) return "audio";
|
||||
@ -105,6 +134,25 @@ function inferKind(modelId: string, config: Vip98kModelRuntimeConfig) {
|
||||
return "chat";
|
||||
}
|
||||
|
||||
const VIP98K_OPENAI_IMAGE_ALIASES = new Set([
|
||||
"nano-banana-2",
|
||||
"nano-banana-pro",
|
||||
"gpt-image-2-vip",
|
||||
]);
|
||||
|
||||
function resolveVip98kReferenceModelId(modelId: string) {
|
||||
switch (modelId.trim().toLowerCase()) {
|
||||
case "nano-banana-2":
|
||||
return "google/nano-banana-2/reference-to-image";
|
||||
case "nano-banana-pro":
|
||||
return "google/nano-banana-pro/edit";
|
||||
case "gpt-image-2-vip":
|
||||
return "openai/gpt-image-2/edit";
|
||||
default:
|
||||
return modelId;
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@ -369,14 +417,19 @@ function getConfiguredPollSeconds(config: Vip98kModelRuntimeConfig, key: string,
|
||||
async function submitTask(params: {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
path?: string | null;
|
||||
method?: string | null;
|
||||
contentType?: string | null;
|
||||
body: Record<string, unknown>;
|
||||
}) {
|
||||
const baseURL = normalizeVip98kBaseUrl(params.baseURL);
|
||||
const response = await fetch(`${baseURL}/api/external/task/generate`, {
|
||||
method: "POST",
|
||||
const path = String(params.path || "/api/external/task/generate").trim();
|
||||
if (!path.startsWith("/")) throw new Error("VIP98K invocation path is invalid");
|
||||
const response = await fetch(`${baseURL}${path}`, {
|
||||
method: String(params.method || "POST").toUpperCase(),
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"Content-Type": params.contentType || "application/json",
|
||||
},
|
||||
body: JSON.stringify(params.body),
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
@ -393,6 +446,131 @@ async function submitTask(params: {
|
||||
};
|
||||
}
|
||||
|
||||
export type Vip98kExternalTaskSubmission = {
|
||||
taskId: string;
|
||||
resultPath: string;
|
||||
outputUrls: string[];
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
export type Vip98kExternalTaskStatus = {
|
||||
taskId: string;
|
||||
status: string;
|
||||
done: boolean;
|
||||
failed: boolean;
|
||||
outputUrls: string[];
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
export async function submitVip98kExternalTask(params: {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
modelId: string;
|
||||
kind: string;
|
||||
prompt?: string;
|
||||
imageUrls?: string[];
|
||||
videoUrls?: string[];
|
||||
videoParams?: Record<string, unknown>;
|
||||
imageParams?: Record<string, unknown>;
|
||||
modelConfig?: Vip98kModelRuntimeConfig;
|
||||
}): Promise<Vip98kExternalTaskSubmission> {
|
||||
const [imageUrls, videoUrls] = await Promise.all([
|
||||
Promise.all((params.imageUrls || []).map(ensurePublicMediaUrl)),
|
||||
Promise.all((params.videoUrls || []).map(ensurePublicMediaUrl)),
|
||||
]);
|
||||
const taskParams: Vip98kTaskParams = {
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
modelId: params.modelId,
|
||||
kind: params.kind,
|
||||
prompt: String(params.prompt || "Process media").trim() || "Process media",
|
||||
imageUrls,
|
||||
videoUrls,
|
||||
videoParams: params.videoParams,
|
||||
imageParams: params.imageParams,
|
||||
modelConfig: params.modelConfig || {},
|
||||
};
|
||||
const invocation = resolveVip98kTaskInvocation(
|
||||
taskParams.modelId,
|
||||
getVip98kInvocation(taskParams.modelConfig)
|
||||
);
|
||||
const body = buildTaskBody(taskParams, invocation);
|
||||
const imageBindingKeys = [
|
||||
"images",
|
||||
"imageUrls",
|
||||
"referenceImages",
|
||||
"reference_images",
|
||||
"image",
|
||||
"imageUrl",
|
||||
"image_url",
|
||||
"video_clips",
|
||||
].filter((key) => key in body);
|
||||
logger.info("task submit audit", {
|
||||
modelId: taskParams.modelId,
|
||||
kind: taskParams.kind,
|
||||
invocationKind: invocation?.kind || "task",
|
||||
invocationPath: invocation?.path || "/api/external/task",
|
||||
imageCount: imageUrls.length,
|
||||
videoCount: videoUrls.length,
|
||||
imageBindingKeys,
|
||||
bodyKeys: Object.keys(body).sort(),
|
||||
});
|
||||
const submitted = await submitTask({
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
path: invocation?.path,
|
||||
method: invocation?.method,
|
||||
contentType: invocation?.contentType,
|
||||
body,
|
||||
});
|
||||
const resultPath = submitted.resultPath || invocation?.resultPath || "";
|
||||
return {
|
||||
taskId: submitted.taskId,
|
||||
resultPath: submitted.taskId
|
||||
? resultPath.replaceAll("{task_id}", encodeURIComponent(submitted.taskId))
|
||||
: resultPath,
|
||||
outputUrls: submitted.outputs,
|
||||
payload: submitted.payload,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getVip98kExternalTaskStatus(params: {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
taskId: string;
|
||||
resultPath?: string | null;
|
||||
}): Promise<Vip98kExternalTaskStatus> {
|
||||
const baseURL = normalizeVip98kBaseUrl(params.baseURL);
|
||||
const resultUrl = params.resultPath
|
||||
? params.resultPath.startsWith("http")
|
||||
? params.resultPath
|
||||
: `${baseURL}${params.resultPath.startsWith("/") ? "" : "/"}${params.resultPath}`
|
||||
: `${baseURL}/api/external/task/result?taskId=${encodeURIComponent(params.taskId)}`;
|
||||
const response = await fetch(resultUrl, {
|
||||
cache: "no-store",
|
||||
headers: { Authorization: `Bearer ${params.apiKey}` },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
});
|
||||
const payload = await parseJsonResponse(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(`${extractErrorMessage(payload)} (HTTP ${response.status})`);
|
||||
}
|
||||
const status = extractStatus(payload);
|
||||
const outputUrls = collectOutputUrls(payload);
|
||||
const failed = ["failed", "error", "timeout", "canceled", "cancelled"].includes(status);
|
||||
const done =
|
||||
["succeeded", "success", "completed", "done", "finished"].includes(status) ||
|
||||
(extractDone(payload) && outputUrls.length > 0);
|
||||
return {
|
||||
taskId: params.taskId,
|
||||
status,
|
||||
done,
|
||||
failed,
|
||||
outputUrls,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForTask(params: {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
@ -457,15 +635,16 @@ function normalizeDuration(value: unknown) {
|
||||
return Math.round(numeric);
|
||||
}
|
||||
|
||||
function buildTaskBody(params: Vip98kTaskParams) {
|
||||
function buildTaskBody(params: Vip98kTaskParams, invocation: Vip98kInvocation | null) {
|
||||
const videoParams = params.videoParams || {};
|
||||
const imageParams = params.imageParams || {};
|
||||
const promptTitle = params.prompt.split(/\s+/).slice(0, 8).join(" ").slice(0, 80);
|
||||
const body: Record<string, unknown> = {
|
||||
model: params.modelId,
|
||||
displayName: promptTitle || params.modelId,
|
||||
prompt: params.prompt,
|
||||
};
|
||||
const body: Record<string, unknown> = { ...(invocation?.requestExample || {}) };
|
||||
if (invocation?.kind !== "tool" || "model" in body) body.model = params.modelId;
|
||||
if ("displayName" in body || invocation?.kind !== "tool") {
|
||||
body.displayName = promptTitle || params.modelId;
|
||||
}
|
||||
if ("prompt" in body || !invocation) body.prompt = params.prompt;
|
||||
|
||||
const aspectRatio =
|
||||
normalizeRatio(videoParams.ratio) ||
|
||||
@ -476,54 +655,75 @@ function buildTaskBody(params: Vip98kTaskParams) {
|
||||
const negativePrompt = String(videoParams.negativePrompt || imageParams.negativePrompt || "").trim();
|
||||
|
||||
if (aspectRatio) {
|
||||
body.ratio = aspectRatio;
|
||||
body.aspectRatio = aspectRatio;
|
||||
body.aspect_ratio = aspectRatio;
|
||||
if ("ratio" in body || !invocation) body.ratio = aspectRatio;
|
||||
if ("aspectRatio" in body || !invocation) body.aspectRatio = aspectRatio;
|
||||
if ("aspect_ratio" in body || !invocation) body.aspect_ratio = aspectRatio;
|
||||
}
|
||||
if (duration) body.duration = duration;
|
||||
if (duration && ("duration" in body || !invocation)) body.duration = duration;
|
||||
if (resolution) {
|
||||
body.resolution = resolution;
|
||||
body.imageSize = resolution;
|
||||
body.image_size = resolution;
|
||||
if ("resolution" in body || !invocation) body.resolution = resolution;
|
||||
if ("imageSize" in body || !invocation) body.imageSize = resolution;
|
||||
if ("image_size" in body || !invocation) body.image_size = resolution;
|
||||
if ("size" in body && typeof body.size === "string") body.size = resolution;
|
||||
}
|
||||
if (negativePrompt) {
|
||||
body.negativePrompt = negativePrompt;
|
||||
body.negative_prompt = negativePrompt;
|
||||
if ("negativePrompt" in body || !invocation) body.negativePrompt = negativePrompt;
|
||||
if ("negative_prompt" in body || !invocation) body.negative_prompt = negativePrompt;
|
||||
}
|
||||
if (typeof videoParams.generateAudio === "boolean") {
|
||||
body.generateAudio = videoParams.generateAudio;
|
||||
body.generate_audio = videoParams.generateAudio;
|
||||
if ("generateAudio" in body || !invocation) body.generateAudio = videoParams.generateAudio;
|
||||
if ("generate_audio" in body || !invocation) body.generate_audio = videoParams.generateAudio;
|
||||
}
|
||||
|
||||
if (params.imageUrls.length > 0) {
|
||||
body.images = params.imageUrls;
|
||||
body.imageUrls = params.imageUrls;
|
||||
body.referenceImages = params.imageUrls;
|
||||
body.reference_images = params.imageUrls;
|
||||
body.image = params.imageUrls[0];
|
||||
body.imageUrl = params.imageUrls[0];
|
||||
body.image_url = params.imageUrls[0];
|
||||
body.firstFrameImage = params.imageUrls[0];
|
||||
body.first_frame_image = params.imageUrls[0];
|
||||
body.firstFrameImageUrl = params.imageUrls[0];
|
||||
body.first_frame_image_url = params.imageUrls[0];
|
||||
let hasImageBinding = false;
|
||||
const setImageField = (key: string, value: unknown) => {
|
||||
if (key in body || !invocation) {
|
||||
body[key] = value;
|
||||
hasImageBinding = true;
|
||||
}
|
||||
};
|
||||
setImageField("images", params.imageUrls);
|
||||
setImageField("imageUrls", params.imageUrls);
|
||||
setImageField("referenceImages", params.imageUrls);
|
||||
setImageField("reference_images", params.imageUrls);
|
||||
setImageField("image", params.imageUrls[0]);
|
||||
setImageField("imageUrl", params.imageUrls[0]);
|
||||
setImageField("image_url", params.imageUrls[0]);
|
||||
setImageField("firstFrameImage", params.imageUrls[0]);
|
||||
setImageField("first_frame_image", params.imageUrls[0]);
|
||||
setImageField("firstFrameImageUrl", params.imageUrls[0]);
|
||||
setImageField("first_frame_image_url", params.imageUrls[0]);
|
||||
if (Array.isArray(body.video_clips)) {
|
||||
const template = toRecord(body.video_clips[0]) || {};
|
||||
body.video_clips = params.imageUrls.map((url) => ({ ...template, url }));
|
||||
hasImageBinding = true;
|
||||
}
|
||||
if (params.imageUrls[1]) {
|
||||
body.lastFrameImage = params.imageUrls[1];
|
||||
body.last_frame_image = params.imageUrls[1];
|
||||
body.endImageUrl = params.imageUrls[1];
|
||||
body.end_image_url = params.imageUrls[1];
|
||||
setImageField("lastFrameImage", params.imageUrls[1]);
|
||||
setImageField("last_frame_image", params.imageUrls[1]);
|
||||
setImageField("endImageUrl", params.imageUrls[1]);
|
||||
setImageField("end_image_url", params.imageUrls[1]);
|
||||
}
|
||||
if (
|
||||
!hasImageBinding &&
|
||||
(params.kind === "image" || params.kind === "image-tool")
|
||||
) {
|
||||
body.images = params.imageUrls;
|
||||
}
|
||||
}
|
||||
|
||||
if (params.videoUrls.length > 0) {
|
||||
body.videos = params.videoUrls;
|
||||
body.videoUrls = params.videoUrls;
|
||||
body.referenceVideos = params.videoUrls;
|
||||
if ("videos" in body || !invocation) body.videos = params.videoUrls;
|
||||
if ("videoUrls" in body || !invocation) body.videoUrls = params.videoUrls;
|
||||
if ("referenceVideos" in body || !invocation) body.referenceVideos = params.videoUrls;
|
||||
if ("video" in body) body.video = params.videoUrls[0];
|
||||
if ("video_url" in body) body.video_url = params.videoUrls[0];
|
||||
}
|
||||
|
||||
if (params.kind === "world") {
|
||||
if (params.kind === "world" && ("mode" in body || !invocation)) {
|
||||
body.mode = "world-generation";
|
||||
} else if (params.kind === "video") {
|
||||
} else if (params.kind === "video" && ("mode" in body || !invocation)) {
|
||||
body.mode = params.imageUrls.length > 0 ? "image-to-video" : "text-to-video";
|
||||
}
|
||||
|
||||
@ -545,23 +745,67 @@ function formatWorldMarkdown(urls: string[]) {
|
||||
return urls.map((url, index) => `[查看 3D 世界 ${index + 1}](${url})`).join("\n\n");
|
||||
}
|
||||
|
||||
async function runTask(params: Vip98kTaskParams) {
|
||||
const body = buildTaskBody(params);
|
||||
const submitted = await submitTask({
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
body,
|
||||
export type Vip98kExternalTaskResult = {
|
||||
taskId: string;
|
||||
outputUrls: string[];
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
export async function executeVip98kExternalTask(params: {
|
||||
apiKey: string;
|
||||
baseURL?: string | null;
|
||||
modelId: string;
|
||||
kind: string;
|
||||
prompt?: string;
|
||||
imageUrls?: string[];
|
||||
videoUrls?: string[];
|
||||
videoParams?: Record<string, unknown>;
|
||||
imageParams?: Record<string, unknown>;
|
||||
modelConfig?: Vip98kModelRuntimeConfig;
|
||||
}): Promise<Vip98kExternalTaskResult> {
|
||||
const submitted = await submitVip98kExternalTask({
|
||||
...params,
|
||||
});
|
||||
|
||||
const outputUrls = submitted.outputs.length
|
||||
? submitted.outputs
|
||||
: await waitForTask({
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
taskId: submitted.taskId,
|
||||
resultPath: submitted.resultPath,
|
||||
modelConfig: params.modelConfig,
|
||||
}).then((result) => result.outputs);
|
||||
if (submitted.outputUrls.length > 0) {
|
||||
return {
|
||||
taskId: submitted.taskId,
|
||||
outputUrls: submitted.outputUrls,
|
||||
payload: submitted.payload,
|
||||
};
|
||||
}
|
||||
if (!submitted.taskId) {
|
||||
throw new Error("VIP98K task submission returned neither a task ID nor output URLs");
|
||||
}
|
||||
|
||||
const completed = await waitForTask({
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
taskId: submitted.taskId,
|
||||
resultPath: submitted.resultPath,
|
||||
modelConfig: params.modelConfig || {},
|
||||
});
|
||||
return {
|
||||
taskId: submitted.taskId,
|
||||
outputUrls: completed.outputs,
|
||||
payload: completed.payload,
|
||||
};
|
||||
}
|
||||
|
||||
async function runTask(params: Vip98kTaskParams) {
|
||||
const completed = await executeVip98kExternalTask({
|
||||
apiKey: params.apiKey,
|
||||
baseURL: params.baseURL,
|
||||
modelId: params.modelId,
|
||||
kind: params.kind,
|
||||
prompt: params.prompt,
|
||||
imageUrls: params.imageUrls,
|
||||
videoUrls: params.videoUrls,
|
||||
videoParams: params.videoParams,
|
||||
imageParams: params.imageParams,
|
||||
modelConfig: params.modelConfig,
|
||||
});
|
||||
const outputUrls = completed.outputUrls;
|
||||
|
||||
if (params.kind === "video") {
|
||||
const videoUrl =
|
||||
@ -580,7 +824,7 @@ async function runTask(params: Vip98kTaskParams) {
|
||||
return formatImageMarkdown(archived, imageSize);
|
||||
}
|
||||
|
||||
if (params.kind === "world") {
|
||||
if (params.kind === "world" || params.kind === "model-3d") {
|
||||
return formatWorldMarkdown(outputUrls);
|
||||
}
|
||||
|
||||
@ -605,10 +849,6 @@ export function createVip98k({ apiKey, baseURL }: Vip98kConfig) {
|
||||
const modelConfig = parseRuntimeConfig(defaultModelConfig);
|
||||
const kind = inferKind(modelId, modelConfig);
|
||||
|
||||
if (kind === "image") {
|
||||
return openAIImageProvider.chat(modelId) as any;
|
||||
}
|
||||
|
||||
if (kind === "chat") {
|
||||
return openAITextProvider.chat(modelId) as any;
|
||||
}
|
||||
@ -633,14 +873,25 @@ export function createVip98k({ apiKey, baseURL }: Vip98kConfig) {
|
||||
if (!activeModelId) throw new Error("VIP98K model ID is not configured");
|
||||
const activeKind = inferKind(activeModelId, runtimeConfig);
|
||||
const { prompt, imageUrls, videoUrls } = extractPromptAndMedia(options.messages);
|
||||
if (
|
||||
activeKind === "image" &&
|
||||
imageUrls.length === 0 &&
|
||||
VIP98K_OPENAI_IMAGE_ALIASES.has(activeModelId.toLowerCase())
|
||||
) {
|
||||
return openAIImageProvider.chat(activeModelId).doGenerate(options as any);
|
||||
}
|
||||
const [publicImageUrls, publicVideoUrls] = await Promise.all([
|
||||
Promise.all(imageUrls.map(ensurePublicMediaUrl)),
|
||||
Promise.all(videoUrls.map(ensurePublicMediaUrl)),
|
||||
]);
|
||||
const taskModelId =
|
||||
activeKind === "image" && publicImageUrls.length > 0
|
||||
? resolveVip98kReferenceModelId(activeModelId)
|
||||
: activeModelId;
|
||||
const text = await runTask({
|
||||
apiKey,
|
||||
baseURL: rootBaseURL,
|
||||
modelId: activeModelId,
|
||||
modelId: taskModelId,
|
||||
kind: activeKind,
|
||||
prompt,
|
||||
imageUrls: publicImageUrls,
|
||||
|
||||
@ -4,6 +4,7 @@ import {
|
||||
getSystemSetting,
|
||||
upsertMediaAsset,
|
||||
} from "@/lib/db/queries";
|
||||
import { executeConfiguredVip98kTask } from "@/lib/ai/vip98k-runtime";
|
||||
import { db } from "@/lib/db";
|
||||
import { generatedImage } from "@/lib/db/schema";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
@ -11,7 +12,7 @@ import { uploadFile } from "@/lib/storage/service";
|
||||
|
||||
const logger = createLogger("rmbg-service");
|
||||
|
||||
export type RmbgProvider = "rmbg" | "photoroom" | "aoscdn";
|
||||
export type RmbgProvider = "vip98k" | "rmbg" | "photoroom" | "aoscdn";
|
||||
|
||||
type RmbgConfig = {
|
||||
provider?: RmbgProvider;
|
||||
@ -268,6 +269,44 @@ async function processWithRMBG(
|
||||
}
|
||||
}
|
||||
|
||||
async function processWithVip98k(
|
||||
imageBuffer: Buffer,
|
||||
): Promise<{ success: boolean; imageBuffer?: Buffer; processing_time?: number; error?: string }> {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const result = await executeConfiguredVip98kTask({
|
||||
modelId: "remove-background",
|
||||
kind: "image-tool",
|
||||
prompt: "Remove the image background and return a transparent PNG.",
|
||||
imageUrls: [`data:image/png;base64,${imageBuffer.toString("base64")}`],
|
||||
});
|
||||
const outputUrl = result.outputUrls[0];
|
||||
if (!outputUrl) {
|
||||
return { success: false, error: "VIP98K 抠图未返回图片" };
|
||||
}
|
||||
const response = await fetch(outputUrl, {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false,
|
||||
error: `VIP98K 抠图结果下载失败(HTTP ${response.status})`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
imageBuffer: Buffer.from(await response.arrayBuffer()),
|
||||
processing_time: (Date.now() - startedAt) / 1000,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "VIP98K 抠图失败",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function processWithPhotoRoom(
|
||||
imageBuffer: Buffer,
|
||||
apiKey: string
|
||||
@ -492,7 +531,9 @@ async function getValidatedRmbgConfig(): Promise<{ provider: RmbgProvider; confi
|
||||
}
|
||||
|
||||
function getModelId(provider: RmbgProvider) {
|
||||
return provider === "photoroom"
|
||||
return provider === "vip98k"
|
||||
? "remove-background"
|
||||
: provider === "photoroom"
|
||||
? "photoroom-hd"
|
||||
: provider === "aoscdn"
|
||||
? "aos-segmentation"
|
||||
@ -583,7 +624,19 @@ export async function executeRmbgJob(
|
||||
let resultBase64: string;
|
||||
let processingTime: number;
|
||||
|
||||
if (provider === "photoroom") {
|
||||
if (provider === "vip98k") {
|
||||
const result = await processWithVip98k(imageBuffer);
|
||||
if (!result.success || !result.imageBuffer) {
|
||||
logger.warn("job_provider_failed", {
|
||||
provider,
|
||||
reasonLength: result.error?.length ?? 0,
|
||||
});
|
||||
throw new RmbgServiceError("抠图处理失败", 500, result.error);
|
||||
}
|
||||
resultBuffer = result.imageBuffer;
|
||||
resultBase64 = resultBuffer.toString("base64");
|
||||
processingTime = result.processing_time || 0;
|
||||
} else if (provider === "photoroom") {
|
||||
const result = await processWithPhotoRoom(imageBuffer, config.photoroomApiKey!);
|
||||
if (!result.success || !result.imageBuffer) {
|
||||
logger.warn("job_provider_failed", {
|
||||
|
||||
@ -1717,7 +1717,7 @@ type VisionSummaryModel = Awaited<
|
||||
>[number];
|
||||
|
||||
function isAnalyzerGenerateTextProviderType(providerType: string): boolean {
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local"].includes(providerType);
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local", "vip98k"].includes(providerType);
|
||||
}
|
||||
|
||||
function getAnalyzerModelIncompatibleReason(params: {
|
||||
|
||||
@ -1,5 +1,3 @@
|
||||
import "server-only";
|
||||
|
||||
export const VIP98K_BASE_URL = "https://api.vip98k.com";
|
||||
|
||||
export type Vip98kCatalogModelType =
|
||||
@ -12,6 +10,16 @@ export type Vip98kCatalogModelType =
|
||||
| "world"
|
||||
| string;
|
||||
|
||||
export interface Vip98kInvocationContract {
|
||||
kind?: "chat" | "task" | "tool" | string;
|
||||
method?: string;
|
||||
path?: string;
|
||||
content_type?: string;
|
||||
request_example?: Record<string, unknown>;
|
||||
result_method?: string;
|
||||
result_path?: string;
|
||||
}
|
||||
|
||||
export interface Vip98kCatalogModel {
|
||||
modelId?: string;
|
||||
id?: string;
|
||||
@ -49,6 +57,24 @@ export interface Vip98kCatalogModel {
|
||||
pricing?: unknown;
|
||||
price?: unknown;
|
||||
status?: string;
|
||||
available?: boolean;
|
||||
isAvailable?: boolean;
|
||||
enabled?: boolean;
|
||||
isEnabled?: boolean;
|
||||
is_active?: boolean;
|
||||
invocation?: Vip98kInvocationContract;
|
||||
taskTypes?: unknown;
|
||||
task_types?: unknown;
|
||||
releasedAt?: unknown;
|
||||
released_at?: unknown;
|
||||
releaseDate?: unknown;
|
||||
release_date?: unknown;
|
||||
releaseYear?: unknown;
|
||||
release_year?: unknown;
|
||||
publishedAt?: unknown;
|
||||
published_at?: unknown;
|
||||
launchDate?: unknown;
|
||||
launch_date?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@ -86,12 +112,87 @@ const TYPE_SORT_ORDER: Record<string, number> = {
|
||||
image: 100,
|
||||
video: 200,
|
||||
world: 300,
|
||||
model_3d: 320,
|
||||
model: 400,
|
||||
image_tool: 800,
|
||||
audio: 900,
|
||||
document_tool: 950,
|
||||
};
|
||||
|
||||
const IMAGE_TOOL_MODEL_IDS = new Set([
|
||||
"background-generator",
|
||||
"clothing-segmentation",
|
||||
"colorize",
|
||||
"compress",
|
||||
"enhance",
|
||||
"face-swap-image",
|
||||
"head-cutout",
|
||||
"id-photo",
|
||||
"image-expansion",
|
||||
"image-upscaler",
|
||||
"photo-cleanup",
|
||||
"remove-background",
|
||||
"remove-object",
|
||||
"remove-watermark",
|
||||
"smart-crop",
|
||||
"youchuan/v8.1/remove-background",
|
||||
]);
|
||||
|
||||
const VIDEO_CAPABILITY_KEYS = new Set([
|
||||
"audio-to-video",
|
||||
"first-frame-to-video",
|
||||
"image-to-video",
|
||||
"reference-to-video",
|
||||
"start-end-frame-to-video",
|
||||
"text-to-video",
|
||||
"video-extend",
|
||||
"video-to-video",
|
||||
]);
|
||||
|
||||
const IMAGE_CAPABILITY_KEYS = new Set([
|
||||
"image-to-image",
|
||||
"reference-to-image",
|
||||
"text-to-image",
|
||||
]);
|
||||
|
||||
const IMAGE_TOOL_OPERATION_BY_MODEL_ID: Record<string, string> = {
|
||||
"background-generator": "background-generation",
|
||||
"clothing-segmentation": "segmentation",
|
||||
colorize: "colorize",
|
||||
compress: "compress",
|
||||
enhance: "enhance",
|
||||
"face-swap-image": "face-swap",
|
||||
"head-cutout": "remove-background",
|
||||
"id-photo": "id-photo",
|
||||
"image-expansion": "extend",
|
||||
"image-upscaler": "enhance",
|
||||
"photo-cleanup": "cleanup",
|
||||
"remove-background": "remove-background",
|
||||
"remove-object": "remove-object",
|
||||
"remove-watermark": "remove-watermark",
|
||||
"smart-crop": "smart-crop",
|
||||
"youchuan/v8.1/remove-background": "remove-background",
|
||||
};
|
||||
|
||||
// The VIP98K catalog currently has no release-date field. Unknown image models stay
|
||||
// available to backend routing but remain hidden until their 2026+ release is verified.
|
||||
const VERIFIED_2026_IMAGE_MODEL_PATTERNS = [
|
||||
/^nano-banana-2(?:$|[-/])/,
|
||||
/^gpt-image-2(?:$|[-/])/,
|
||||
/^alibaba\/wan-2\.(?:6|7)(?:$|[-/])/,
|
||||
/^black-forest-labs\/flux-2(?:$|[-/])/,
|
||||
/^bytedance\/seedream-v5(?:$|[.\-/])/,
|
||||
/^google\/nano-banana-2(?:$|[-/])/,
|
||||
/^hidream-o1-1\.5(?:$|[-/])/,
|
||||
/^ideogram\/v4(?:$|[-/])/,
|
||||
/^krea-2(?:$|[-/])/,
|
||||
/^microsoft\/mai-image-2\.5(?:$|[-/])/,
|
||||
/^nvidia\/cosmos-3(?:$|[-/])/,
|
||||
/^openai\/gpt-image-2(?:$|[-/])/,
|
||||
/^qwen\/qwen-image-2\.0(?:$|[-/])/,
|
||||
/^youchuan\/v8\.1(?:$|[-/])/,
|
||||
];
|
||||
|
||||
function toRecord(value: unknown): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
return value as Record<string, unknown>;
|
||||
@ -132,6 +233,167 @@ function normalizeCatalogType(model: Vip98kCatalogModel): Vip98kCatalogModelType
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function getReleaseYear(model: Vip98kCatalogModel): number | null {
|
||||
const candidates = [
|
||||
model.releaseYear,
|
||||
model.release_year,
|
||||
model.releasedAt,
|
||||
model.released_at,
|
||||
model.releaseDate,
|
||||
model.release_date,
|
||||
model.publishedAt,
|
||||
model.published_at,
|
||||
model.launchDate,
|
||||
model.launch_date,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const match = String(candidate || "").match(/(?:19|20)\d{2}/);
|
||||
if (match) return Number(match[0]);
|
||||
}
|
||||
|
||||
const datedModelId = getModelId(model).match(/(?:^|[^\d])((?:19|20)\d{2})\d{4}(?:[^\d]|$)/);
|
||||
return datedModelId?.[1] ? Number(datedModelId[1]) : null;
|
||||
}
|
||||
|
||||
export function isVip98kImageModelVisible(model: Vip98kCatalogModel) {
|
||||
const releaseYear = getReleaseYear(model);
|
||||
if (releaseYear !== null) return releaseYear >= 2026;
|
||||
const modelId = getModelId(model).toLowerCase();
|
||||
return VERIFIED_2026_IMAGE_MODEL_PATTERNS.some((pattern) => pattern.test(modelId));
|
||||
}
|
||||
|
||||
function resolvePresetType(model: Vip98kCatalogModel): Vip98kCatalogModelType {
|
||||
const catalogType = normalizeCatalogType(model);
|
||||
const modelId = getModelId(model).toLowerCase();
|
||||
const capabilities = getCapabilities(model);
|
||||
|
||||
if (
|
||||
capabilities.includes("image-to-3d") ||
|
||||
capabilities.includes("text-to-3d")
|
||||
) {
|
||||
return "model_3d";
|
||||
}
|
||||
|
||||
if (catalogType === "world") return "world";
|
||||
|
||||
if (catalogType === "image_tool" || IMAGE_TOOL_MODEL_IDS.has(modelId)) {
|
||||
return "image_tool";
|
||||
}
|
||||
|
||||
if (
|
||||
catalogType === "video" ||
|
||||
capabilities.some(
|
||||
(capability) =>
|
||||
VIDEO_CAPABILITY_KEYS.has(capability) ||
|
||||
capability.endsWith("-to-video") ||
|
||||
capability.startsWith("video-"),
|
||||
)
|
||||
) {
|
||||
return "video";
|
||||
}
|
||||
|
||||
if (
|
||||
catalogType === "image" ||
|
||||
capabilities.some(
|
||||
(capability) =>
|
||||
IMAGE_CAPABILITY_KEYS.has(capability) || capability.endsWith("-to-image"),
|
||||
)
|
||||
) {
|
||||
return "image";
|
||||
}
|
||||
|
||||
return catalogType;
|
||||
}
|
||||
|
||||
const UNAVAILABLE_STATUS_TOKENS = [
|
||||
"disabled",
|
||||
"unavailable",
|
||||
"closed",
|
||||
"offline",
|
||||
"deprecated",
|
||||
"removed",
|
||||
"retired",
|
||||
"suspended",
|
||||
] as const;
|
||||
|
||||
function getInvocationRequestKeys(model: Vip98kCatalogModel) {
|
||||
const invocation = toRecord(model.invocation);
|
||||
return Object.keys(toRecord(invocation?.request_example) || {}).map((key) =>
|
||||
key.trim().toLowerCase().replace(/_/g, "-"),
|
||||
);
|
||||
}
|
||||
|
||||
function hasMediaReferenceInput(
|
||||
model: Vip98kCatalogModel,
|
||||
type: Vip98kCatalogModelType,
|
||||
) {
|
||||
const capabilities = getCapabilities(model);
|
||||
const inputModes = getInputModes(model).map((mode) => mode.replace(/_/g, "-"));
|
||||
const requestKeys = getInvocationRequestKeys(model);
|
||||
const modelId = getModelId(model).toLowerCase();
|
||||
const mediaInputModes = new Set([
|
||||
"image",
|
||||
"images",
|
||||
"url",
|
||||
"file",
|
||||
"video",
|
||||
"audio",
|
||||
"base64",
|
||||
]);
|
||||
const hasMediaCapability = capabilities.some((capability) => {
|
||||
if (capability.startsWith("text-to-")) return false;
|
||||
if (type === "image") {
|
||||
return capability.endsWith("-to-image") || capability.includes("image-edit");
|
||||
}
|
||||
return (
|
||||
capability.endsWith("-to-video") ||
|
||||
capability.startsWith("video-") ||
|
||||
capability.includes("video-edit")
|
||||
);
|
||||
});
|
||||
const hasMediaRequestField = requestKeys.some((key) =>
|
||||
/(?:image|video|audio|reference|first-?frame|last-?frame|file|url)/.test(key),
|
||||
);
|
||||
const hasMediaModelPath =
|
||||
type === "image"
|
||||
? /(?:image-to-image|reference-to-image|\/edit(?:$|[\/-]))/.test(modelId)
|
||||
: /(?:image-to-video|video-to-video|reference-to-video|first-frame|start-end|video-edit|video-extend)/.test(
|
||||
modelId,
|
||||
);
|
||||
|
||||
return (
|
||||
hasMediaCapability ||
|
||||
inputModes.some((mode) => mediaInputModes.has(mode)) ||
|
||||
hasMediaRequestField ||
|
||||
hasMediaModelPath
|
||||
);
|
||||
}
|
||||
|
||||
export function isVip98kCatalogModelAvailable(model: Vip98kCatalogModel) {
|
||||
const status = String(model.status || "").trim().toLowerCase();
|
||||
if (UNAVAILABLE_STATUS_TOKENS.some((token) => status.includes(token))) {
|
||||
return false;
|
||||
}
|
||||
return !(
|
||||
model.available === false ||
|
||||
model.isAvailable === false ||
|
||||
model.enabled === false ||
|
||||
model.isEnabled === false ||
|
||||
model.is_active === false
|
||||
);
|
||||
}
|
||||
|
||||
export function isVip98kCatalogModelEligible(model: Vip98kCatalogModel) {
|
||||
if (!getModelId(model) || !isVip98kCatalogModelAvailable(model)) return false;
|
||||
const type = resolvePresetType(model);
|
||||
if (type !== "image" && type !== "video") return true;
|
||||
return hasMediaReferenceInput(model, type);
|
||||
}
|
||||
|
||||
export function filterVip98kCatalogModels(models: Vip98kCatalogModel[]) {
|
||||
return models.filter(isVip98kCatalogModelEligible);
|
||||
}
|
||||
|
||||
function normalizeImageSize(value: string): string | null {
|
||||
const normalized = value.trim().toUpperCase();
|
||||
if (normalized === "1K" || normalized === "2K" || normalized === "4K") {
|
||||
@ -226,9 +488,24 @@ function getBillingMode(model: Vip98kCatalogModel) {
|
||||
}
|
||||
|
||||
function getVip98kMetadata(model: Vip98kCatalogModel, type: string) {
|
||||
const invocation = toRecord(model.invocation);
|
||||
return {
|
||||
modelType: type,
|
||||
taskApi: "external-task",
|
||||
taskApi:
|
||||
String(invocation?.kind || "").toLowerCase() === "tool"
|
||||
? "external-tool"
|
||||
: "external-task",
|
||||
invocation: invocation
|
||||
? {
|
||||
kind: String(invocation.kind || ""),
|
||||
method: String(invocation.method || "POST"),
|
||||
path: String(invocation.path || ""),
|
||||
contentType: String(invocation.content_type || "application/json"),
|
||||
requestExample: toRecord(invocation.request_example) || {},
|
||||
resultMethod: String(invocation.result_method || "GET"),
|
||||
resultPath: String(invocation.result_path || ""),
|
||||
}
|
||||
: null,
|
||||
supportsAsync: Boolean(model.supportsAsync ?? model.supports_async ?? true),
|
||||
pollIntervalSeconds: parseNumber(
|
||||
model.pollIntervalSeconds || model.poll_interval_seconds,
|
||||
@ -277,7 +554,7 @@ function createImagePreset(
|
||||
type: "image",
|
||||
supportsVision: supportsReferenceImages,
|
||||
supportsImageGen: true,
|
||||
isHidden: false,
|
||||
isHidden: !isVip98kImageModelVisible(model),
|
||||
capabilities: {
|
||||
provider: "vip98k",
|
||||
kind: "image",
|
||||
@ -447,18 +724,72 @@ function createWorldPreset(
|
||||
};
|
||||
}
|
||||
|
||||
function createThreeDPreset(
|
||||
model: Vip98kCatalogModel,
|
||||
index: number,
|
||||
): Vip98kModelPreset {
|
||||
const modelId = getModelId(model);
|
||||
const displayName = getDisplayName(model, modelId);
|
||||
const catalogCapabilities = getCapabilities(model);
|
||||
const supportsImageInput = catalogCapabilities.includes("image-to-3d");
|
||||
const supportedModes = [
|
||||
...(catalogCapabilities.includes("text-to-3d") ? ["text-to-3d"] : []),
|
||||
...(supportsImageInput ? ["image-to-3d"] : []),
|
||||
];
|
||||
|
||||
return {
|
||||
modelId,
|
||||
displayName,
|
||||
description: model.description || `VIP98K 3D model (${modelId})`,
|
||||
type: "model_3d",
|
||||
supportsVision: supportsImageInput,
|
||||
supportsImageGen: false,
|
||||
// Keep the dedicated Tripo 3D integration as the only frontend 3D route.
|
||||
isHidden: true,
|
||||
capabilities: {
|
||||
provider: "vip98k",
|
||||
kind: "model-3d",
|
||||
mediaType: "model-3d",
|
||||
modelType: "model-3d",
|
||||
outputType: "3d",
|
||||
supportedModes,
|
||||
maxReferenceImages: supportsImageInput ? 1 : 0,
|
||||
vip98k: getVip98kMetadata(model, "model_3d"),
|
||||
},
|
||||
defaultParams: {
|
||||
provider: "vip98k",
|
||||
kind: "model-3d",
|
||||
endpoint: modelId,
|
||||
taskApi: "external-task",
|
||||
supportedModes,
|
||||
},
|
||||
imageGenConfig: null,
|
||||
sortOrder: TYPE_SORT_ORDER.model_3d + index,
|
||||
};
|
||||
}
|
||||
|
||||
function createChatPreset(
|
||||
model: Vip98kCatalogModel,
|
||||
index: number,
|
||||
): Vip98kModelPreset {
|
||||
const modelId = getModelId(model);
|
||||
const displayName = getDisplayName(model, modelId);
|
||||
const catalogCapabilities = getCapabilities(model);
|
||||
const inputModes = getInputModes(model);
|
||||
const supportsVision =
|
||||
catalogCapabilities.some((capability) =>
|
||||
["vision", "multimodal", "image-input", "image-understanding"].includes(
|
||||
capability,
|
||||
),
|
||||
) ||
|
||||
inputModes.some((mode) => ["image", "url", "file"].includes(mode)) ||
|
||||
/^(?:gpt-|claude-|qwen)/i.test(modelId);
|
||||
return {
|
||||
modelId,
|
||||
displayName,
|
||||
description: model.description || `VIP98K text model (${modelId})`,
|
||||
type: "model",
|
||||
supportsVision: false,
|
||||
supportsVision,
|
||||
supportsImageGen: false,
|
||||
isHidden: false,
|
||||
capabilities: {
|
||||
@ -468,6 +799,8 @@ function createChatPreset(
|
||||
modelType: "model",
|
||||
outputType: "text",
|
||||
apiFormat: "openai-compatible",
|
||||
inputModes,
|
||||
supportedModes: supportsVision ? ["text", "vision"] : ["text"],
|
||||
vip98k: getVip98kMetadata(model, "model"),
|
||||
},
|
||||
defaultParams: {
|
||||
@ -491,6 +824,7 @@ function createToolPreset(
|
||||
const inputModes = getInputModes(model);
|
||||
const outputModes = getOutputModes(model);
|
||||
const isImageTool = type === "image_tool";
|
||||
const toolOperation = IMAGE_TOOL_OPERATION_BY_MODEL_ID[modelId.toLowerCase()] || type;
|
||||
|
||||
return {
|
||||
modelId,
|
||||
@ -509,12 +843,14 @@ function createToolPreset(
|
||||
inputModes,
|
||||
outputModes,
|
||||
supportedModes: getCapabilities(model),
|
||||
toolOperation,
|
||||
vip98k: getVip98kMetadata(model, type),
|
||||
},
|
||||
defaultParams: {
|
||||
provider: "vip98k",
|
||||
kind: type.replace(/_/g, "-"),
|
||||
endpoint: modelId,
|
||||
toolOperation,
|
||||
taskApi: type === "audio" ? "openai-compatible" : "external-task",
|
||||
},
|
||||
imageGenConfig: null,
|
||||
@ -525,14 +861,15 @@ function createToolPreset(
|
||||
export function buildVip98kModelPresets(
|
||||
models: Vip98kCatalogModel[],
|
||||
): Vip98kModelPreset[] {
|
||||
return models
|
||||
return filterVip98kCatalogModels(models)
|
||||
.map((model, index) => {
|
||||
const modelId = getModelId(model);
|
||||
if (!modelId) return null;
|
||||
const type = normalizeCatalogType(model);
|
||||
const type = resolvePresetType(model);
|
||||
if (type === "image") return createImagePreset(model, index);
|
||||
if (type === "video") return createVideoPreset(model, index);
|
||||
if (type === "world") return createWorldPreset(model, index);
|
||||
if (type === "model_3d") return createThreeDPreset(model, index);
|
||||
if (type === "model") return createChatPreset(model, index);
|
||||
return createToolPreset(model, type, index);
|
||||
})
|
||||
@ -568,6 +905,17 @@ function extractCatalogModels(payload: unknown): Vip98kCatalogModel[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
function extractPublicCatalogModels(payload: unknown): Vip98kCatalogModel[] {
|
||||
const record = toRecord(payload);
|
||||
const data = toRecord(record?.data);
|
||||
const sections = Array.isArray(data?.sections) ? data.sections : [];
|
||||
return sections.flatMap((section) => {
|
||||
const sectionRecord = toRecord(section);
|
||||
const models = Array.isArray(sectionRecord?.models) ? sectionRecord.models : [];
|
||||
return models.filter((model): model is Vip98kCatalogModel => Boolean(toRecord(model)));
|
||||
});
|
||||
}
|
||||
|
||||
async function parseJsonResponse(response: Response) {
|
||||
const text = await response.text();
|
||||
if (!text.trim()) return null;
|
||||
@ -598,23 +946,58 @@ export async function fetchVip98kCatalog(params: {
|
||||
apiKey: string;
|
||||
}): Promise<Vip98kCatalogModel[]> {
|
||||
const baseURL = normalizeVip98kBaseUrl(params.baseURL);
|
||||
const response = await fetch(`${baseURL}/api/external/task/models`, {
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
});
|
||||
const payload = await parseJsonResponse(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(`${extractErrorMessage(payload)} (HTTP ${response.status})`);
|
||||
const [authorizedResponse, publicResponse] = await Promise.all([
|
||||
fetch(`${baseURL}/api/external/task/models`, {
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
}),
|
||||
fetch(`${baseURL}/api/v1/public/models`, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
}),
|
||||
]);
|
||||
const [authorizedPayload, publicPayload] = await Promise.all([
|
||||
parseJsonResponse(authorizedResponse),
|
||||
parseJsonResponse(publicResponse),
|
||||
]);
|
||||
if (!authorizedResponse.ok) {
|
||||
throw new Error(
|
||||
`${extractErrorMessage(authorizedPayload)} (HTTP ${authorizedResponse.status})`,
|
||||
);
|
||||
}
|
||||
const models = extractCatalogModels(payload);
|
||||
if (models.length === 0) {
|
||||
if (!publicResponse.ok) {
|
||||
throw new Error(
|
||||
`VIP98K public invocation catalog failed (HTTP ${publicResponse.status})`,
|
||||
);
|
||||
}
|
||||
const authorizedModels = extractCatalogModels(authorizedPayload);
|
||||
const publicModels = extractPublicCatalogModels(publicPayload);
|
||||
if (authorizedModels.length === 0) {
|
||||
throw new Error("VIP98K model catalog is empty or has an unsupported response shape");
|
||||
}
|
||||
return models;
|
||||
if (publicModels.length === 0) {
|
||||
throw new Error("VIP98K public invocation catalog is empty");
|
||||
}
|
||||
|
||||
const publicById = new Map(
|
||||
publicModels.map((model) => [getModelId(model).toLowerCase(), model]),
|
||||
);
|
||||
return authorizedModels.map((model) => {
|
||||
const publicModel = publicById.get(getModelId(model).toLowerCase());
|
||||
if (!publicModel) return model;
|
||||
return {
|
||||
...publicModel,
|
||||
...model,
|
||||
invocation: publicModel.invocation,
|
||||
taskTypes: model.taskTypes || model.task_types || publicModel.taskTypes || publicModel.task_types,
|
||||
capabilities: model.capabilities || publicModel.capabilities,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchVip98kModelPresets(params: {
|
||||
|
||||
165
lib/ai/vip98k-runtime.ts
Normal file
165
lib/ai/vip98k-runtime.ts
Normal file
@ -0,0 +1,165 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import {
|
||||
executeVip98kExternalTask,
|
||||
getVip98kExternalTaskStatus,
|
||||
submitVip98kExternalTask,
|
||||
} from "@/lib/ai/providers/vip98k";
|
||||
import { db } from "@/lib/db";
|
||||
import { getAiProvidersByType } from "@/lib/db/queries";
|
||||
import { aiModel } from "@/lib/db/schema";
|
||||
|
||||
export type Vip98kRuntimeProvider = {
|
||||
id: string;
|
||||
name: string;
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
};
|
||||
|
||||
let providerCursor = 0;
|
||||
|
||||
export async function getVip98kRuntimeProviders(): Promise<Vip98kRuntimeProvider[]> {
|
||||
const providers = await getAiProvidersByType({
|
||||
type: "vip98k",
|
||||
enabledOnly: true,
|
||||
});
|
||||
return providers
|
||||
.map((provider) => ({
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
apiKey: String(provider.apiKey || "").trim(),
|
||||
baseUrl: String(provider.baseUrl || "").trim(),
|
||||
}))
|
||||
.filter((provider) => Boolean(provider.apiKey && provider.baseUrl));
|
||||
}
|
||||
|
||||
export async function getVip98kRuntimeProvider(
|
||||
preferredProviderId?: string | null,
|
||||
): Promise<Vip98kRuntimeProvider> {
|
||||
const providers = await getVip98kRuntimeProviders();
|
||||
const preferredId = String(preferredProviderId || "").trim();
|
||||
if (preferredId) {
|
||||
const matched = providers.find((provider) => provider.id === preferredId);
|
||||
if (matched) return matched;
|
||||
}
|
||||
if (providers.length === 0) {
|
||||
throw new Error("VIP98K 服务商未配置或未启用");
|
||||
}
|
||||
const selected = providers[providerCursor % providers.length]!;
|
||||
providerCursor = (providerCursor + 1) % providers.length;
|
||||
return selected;
|
||||
}
|
||||
|
||||
export async function executeConfiguredVip98kTask(params: {
|
||||
modelId: string;
|
||||
kind: string;
|
||||
prompt?: string;
|
||||
imageUrls?: string[];
|
||||
videoUrls?: string[];
|
||||
imageParams?: Record<string, unknown>;
|
||||
videoParams?: Record<string, unknown>;
|
||||
preferredProviderId?: string | null;
|
||||
}) {
|
||||
const provider = await getVip98kRuntimeProvider(params.preferredProviderId);
|
||||
const model = await db.query.aiModel.findFirst({
|
||||
where: and(
|
||||
eq(aiModel.providerId, provider.id),
|
||||
eq(aiModel.modelId, params.modelId),
|
||||
eq(aiModel.isEnabled, true),
|
||||
),
|
||||
});
|
||||
if (!model) {
|
||||
throw new Error(`VIP98K 模型未同步或未启用:${params.modelId}`);
|
||||
}
|
||||
|
||||
const result = await executeVip98kExternalTask({
|
||||
apiKey: provider.apiKey,
|
||||
baseURL: provider.baseUrl,
|
||||
modelId: params.modelId,
|
||||
kind: params.kind,
|
||||
prompt: params.prompt,
|
||||
imageUrls: params.imageUrls,
|
||||
videoUrls: params.videoUrls,
|
||||
imageParams: params.imageParams,
|
||||
videoParams: params.videoParams,
|
||||
modelConfig: {
|
||||
capabilities:
|
||||
model.capabilities && typeof model.capabilities === "object"
|
||||
? (model.capabilities as Record<string, unknown>)
|
||||
: null,
|
||||
imageGenConfig:
|
||||
model.imageGenConfig && typeof model.imageGenConfig === "object"
|
||||
? (model.imageGenConfig as Record<string, unknown>)
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...result,
|
||||
providerId: provider.id,
|
||||
providerName: provider.name,
|
||||
};
|
||||
}
|
||||
|
||||
export async function submitConfiguredVip98kTask(params: {
|
||||
modelId: string;
|
||||
kind: string;
|
||||
prompt?: string;
|
||||
imageUrls?: string[];
|
||||
videoUrls?: string[];
|
||||
imageParams?: Record<string, unknown>;
|
||||
videoParams?: Record<string, unknown>;
|
||||
preferredProviderId?: string | null;
|
||||
}) {
|
||||
const provider = await getVip98kRuntimeProvider(params.preferredProviderId);
|
||||
const model = await db.query.aiModel.findFirst({
|
||||
where: and(
|
||||
eq(aiModel.providerId, provider.id),
|
||||
eq(aiModel.modelId, params.modelId),
|
||||
eq(aiModel.isEnabled, true),
|
||||
),
|
||||
});
|
||||
if (!model) {
|
||||
throw new Error(`VIP98K 模型未同步或未启用:${params.modelId}`);
|
||||
}
|
||||
|
||||
const result = await submitVip98kExternalTask({
|
||||
apiKey: provider.apiKey,
|
||||
baseURL: provider.baseUrl,
|
||||
modelId: params.modelId,
|
||||
kind: params.kind,
|
||||
prompt: params.prompt,
|
||||
imageUrls: params.imageUrls,
|
||||
videoUrls: params.videoUrls,
|
||||
imageParams: params.imageParams,
|
||||
videoParams: params.videoParams,
|
||||
modelConfig: {
|
||||
capabilities:
|
||||
model.capabilities && typeof model.capabilities === "object"
|
||||
? (model.capabilities as Record<string, unknown>)
|
||||
: null,
|
||||
imageGenConfig:
|
||||
model.imageGenConfig && typeof model.imageGenConfig === "object"
|
||||
? (model.imageGenConfig as Record<string, unknown>)
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
return { ...result, providerId: provider.id, providerName: provider.name };
|
||||
}
|
||||
|
||||
export async function getConfiguredVip98kTaskStatus(params: {
|
||||
taskId: string;
|
||||
preferredProviderId?: string | null;
|
||||
resultPath?: string | null;
|
||||
}) {
|
||||
const provider = await getVip98kRuntimeProvider(params.preferredProviderId);
|
||||
const result = await getVip98kExternalTaskStatus({
|
||||
apiKey: provider.apiKey,
|
||||
baseURL: provider.baseUrl,
|
||||
taskId: params.taskId,
|
||||
resultPath: params.resultPath,
|
||||
});
|
||||
return { ...result, providerId: provider.id, providerName: provider.name };
|
||||
}
|
||||
67
lib/ai/vip98k-task-invocation.ts
Normal file
67
lib/ai/vip98k-task-invocation.ts
Normal file
@ -0,0 +1,67 @@
|
||||
export type Vip98kTaskInvocation = {
|
||||
kind: string;
|
||||
method: string;
|
||||
path: string;
|
||||
contentType: string;
|
||||
requestExample: Record<string, unknown>;
|
||||
resultMethod: string;
|
||||
resultPath: string;
|
||||
};
|
||||
|
||||
type KnownImageInput = "images" | "video_clips";
|
||||
|
||||
const KNOWN_IMAGE_TOOL_INPUTS: Record<string, KnownImageInput> = {
|
||||
"google/nano-banana-2/reference-to-image": "video_clips",
|
||||
"google/nano-banana-pro/edit": "images",
|
||||
"openai/gpt-image-2/edit": "images",
|
||||
};
|
||||
|
||||
function getInvocationToolId(invocation: Vip98kTaskInvocation | null) {
|
||||
if (!invocation || invocation.kind !== "tool") return null;
|
||||
const query = invocation.path.split("?", 2)[1] || "";
|
||||
return new URLSearchParams(query).get("tool_id");
|
||||
}
|
||||
|
||||
function createKnownImageToolInvocation(
|
||||
modelId: string,
|
||||
imageInput: KnownImageInput
|
||||
): Vip98kTaskInvocation {
|
||||
const encodedModelId = encodeURIComponent(modelId);
|
||||
const requestExample =
|
||||
imageInput === "video_clips"
|
||||
? {
|
||||
prompt: "",
|
||||
video_clips: [{ fps: 1, url: "", ends: 0, start: 0 }],
|
||||
}
|
||||
: { prompt: "", images: [""] };
|
||||
|
||||
return {
|
||||
kind: "tool",
|
||||
method: "POST",
|
||||
path: `/api/external/tools/generate?tool_id=${encodedModelId}`,
|
||||
contentType: "application/json",
|
||||
requestExample,
|
||||
resultMethod: "GET",
|
||||
resultPath: `/api/external/tools/result?tool_id=${encodedModelId}&taskId={task_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A frontend alias may resolve to a different VIP98K tool at runtime. In that
|
||||
* case the selected model's invocation cannot be reused because its endpoint
|
||||
* and reference-image field belong to the alias rather than the resolved tool.
|
||||
*/
|
||||
export function resolveVip98kTaskInvocation(
|
||||
modelId: string,
|
||||
configuredInvocation: Vip98kTaskInvocation | null
|
||||
) {
|
||||
const normalizedModelId = modelId.trim().toLowerCase();
|
||||
const knownImageInput = KNOWN_IMAGE_TOOL_INPUTS[normalizedModelId];
|
||||
if (!knownImageInput) return configuredInvocation;
|
||||
|
||||
if (getInvocationToolId(configuredInvocation)?.toLowerCase() === normalizedModelId) {
|
||||
return configuredInvocation;
|
||||
}
|
||||
|
||||
return createKnownImageToolInvocation(modelId, knownImageInput);
|
||||
}
|
||||
@ -182,7 +182,7 @@ type EnabledModelWithProvider = Awaited<
|
||||
>[number];
|
||||
|
||||
function isAgentGenerateTextProviderType(providerType: string): boolean {
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local"].includes(providerType);
|
||||
return ["zhipu", "alibaba", "openai", "custom", "local", "vip98k"].includes(providerType);
|
||||
}
|
||||
|
||||
function isAgentGenerateTextCompatibleModel(item: EnabledModelWithProvider) {
|
||||
|
||||
@ -42,10 +42,17 @@ function providerToWorldLabsConfig(
|
||||
export async function getWorldLabsProviderConfigs(): Promise<
|
||||
WorldLabsProviderConfig[]
|
||||
> {
|
||||
const providers = await getAiProvidersByType({
|
||||
const legacyProviders = await getAiProvidersByType({
|
||||
type: "worldlabs-3d",
|
||||
enabledOnly: true,
|
||||
});
|
||||
const providers =
|
||||
legacyProviders.length > 0
|
||||
? legacyProviders
|
||||
: await getAiProvidersByType({
|
||||
type: "vip98k",
|
||||
enabledOnly: true,
|
||||
});
|
||||
|
||||
const normalizedProviders = providers
|
||||
.map((provider) => providerToWorldLabsConfig(provider))
|
||||
@ -105,7 +112,7 @@ export async function getWorldLabsProviderConfig(
|
||||
return worldLabsProvider;
|
||||
}
|
||||
|
||||
throw new Error("未配置 World Labs API,请在系统设置-本地AI新增 World Labs 提供商");
|
||||
throw new Error("未配置 3D 世界服务,请启用 VIP98K 服务商并同步 world-generation 模型");
|
||||
}
|
||||
|
||||
export async function reportWorldLabsProviderRuntimeFailure(
|
||||
|
||||
@ -54,7 +54,9 @@
|
||||
"test": "export PLAYWRIGHT=True && pnpm exec playwright test",
|
||||
"storage:configure-upload-cors": "pnpm exec tsx scripts/storage/configure-direct-upload-cors.ts",
|
||||
"storage:configure-upload-lifecycle": "pnpm exec tsx scripts/storage/configure-multipart-lifecycle.ts",
|
||||
"verify:ruxa-models": "pnpm exec tsx scripts/verify-ruxa-image-models.ts"
|
||||
"verify:ruxa-models": "pnpm exec tsx scripts/verify-ruxa-image-models.ts",
|
||||
"providers:consolidate": "pnpm exec tsx scripts/consolidate-ai-providers.ts",
|
||||
"providers:test-vip98k": "pnpm exec tsx scripts/test-vip98k-capability.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/gateway": "^1.0.15",
|
||||
|
||||
@ -46,12 +46,14 @@ export default defineConfig({
|
||||
/routes\/video-mark-prompt\.test\.ts/,
|
||||
/routes\/video-subtitle-erase-tools\.test\.ts/,
|
||||
/routes\/home-sidebar-auth\.test\.ts/,
|
||||
/routes\/model-classification\.test\.ts/,
|
||||
/routes\/openclaw-client-errors\.test\.ts/,
|
||||
/routes\/openclaw-config\.test\.ts/,
|
||||
/routes\/openclaw-durable-task-state\.test\.ts/,
|
||||
/routes\/openclaw-request-state\.test\.ts/,
|
||||
/routes\/openclaw-video-attachments\.test\.ts/,
|
||||
/routes\/openapi-access-key\.test\.ts/,
|
||||
/routes\/vip98k-reference-routing\.test\.ts/,
|
||||
],
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
|
||||
501
scripts/consolidate-ai-providers.ts
Normal file
501
scripts/consolidate-ai-providers.ts
Normal file
@ -0,0 +1,501 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import dotenv from "dotenv";
|
||||
import postgres from "postgres";
|
||||
import {
|
||||
buildVip98kModelPresets,
|
||||
fetchVip98kModelPresets,
|
||||
type Vip98kCatalogModel,
|
||||
type Vip98kModelPreset,
|
||||
} from "../lib/ai/vip98k-models";
|
||||
|
||||
dotenv.config({ path: ".env.local" });
|
||||
dotenv.config();
|
||||
|
||||
const KEEP_PROVIDER_TYPES = new Set([
|
||||
"vip98k",
|
||||
"fal-image",
|
||||
"fal-video",
|
||||
"tripo-3d",
|
||||
"kittycad-cad",
|
||||
]);
|
||||
const REQUIRED_CAPABILITY_MODELS = [
|
||||
"nano-banana-2",
|
||||
"remove-background",
|
||||
"enhance",
|
||||
"image-expansion",
|
||||
"world-generation",
|
||||
"tencent/hunyuan3d-pro/text-to-3d",
|
||||
"tencent/hunyuan3d-pro/image-to-3d",
|
||||
] as const;
|
||||
const PROTECTED_SYSTEM_SETTING_KEYS = new Set([
|
||||
"realtime_canvas_config",
|
||||
]);
|
||||
|
||||
type ProviderRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
isEnabled: boolean;
|
||||
};
|
||||
|
||||
type ModelRow = {
|
||||
id: string;
|
||||
providerId: string;
|
||||
modelId: string;
|
||||
displayName: string;
|
||||
supportsVision: boolean;
|
||||
supportsImageGen: boolean;
|
||||
isHidden: boolean;
|
||||
capabilities: unknown;
|
||||
imageGenConfig: unknown;
|
||||
};
|
||||
|
||||
function hasFlag(name: string) {
|
||||
return process.argv.includes(name);
|
||||
}
|
||||
|
||||
function getArgValue(name: string) {
|
||||
const prefix = `${name}=`;
|
||||
return process.argv.find((item) => item.startsWith(prefix))?.slice(prefix.length) || "";
|
||||
}
|
||||
|
||||
function stableHash(value: unknown) {
|
||||
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
}
|
||||
|
||||
function toJsonValue(value: unknown): postgres.JSONValue {
|
||||
return JSON.parse(JSON.stringify(value)) as postgres.JSONValue;
|
||||
}
|
||||
|
||||
function sortById<T extends { id: string }>(rows: T[]) {
|
||||
return [...rows].sort((left, right) => left.id.localeCompare(right.id));
|
||||
}
|
||||
|
||||
function isExplicitlyUnavailable(model: Vip98kCatalogModel) {
|
||||
return ["disabled", "unavailable", "offline", "removed"].includes(
|
||||
String(model.status || "").trim().toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadPresets(apiKey: string): Promise<Vip98kModelPreset[]> {
|
||||
const catalogPath = getArgValue("--catalog") || process.env.VIP98K_CATALOG_FILE || "";
|
||||
if (catalogPath) {
|
||||
const payload = JSON.parse(await readFile(catalogPath, "utf8")) as {
|
||||
data?: { models?: Vip98kCatalogModel[] } | Vip98kCatalogModel[];
|
||||
models?: Vip98kCatalogModel[];
|
||||
};
|
||||
const dataModels = Array.isArray(payload.data) ? payload.data : payload.data?.models;
|
||||
const models = (dataModels || payload.models || []).filter(
|
||||
(model) => !isExplicitlyUnavailable(model),
|
||||
);
|
||||
if (models.length === 0) throw new Error("VIP98K catalog file contains no models");
|
||||
return buildVip98kModelPresets(models);
|
||||
}
|
||||
return fetchVip98kModelPresets({
|
||||
baseURL: process.env.VIP98K_BASE_URL || "https://api.vip98k.com",
|
||||
apiKey,
|
||||
});
|
||||
}
|
||||
|
||||
function classifyOldModel(model: ModelRow, providerType: string) {
|
||||
const serialized = JSON.stringify({
|
||||
capabilities: model.capabilities,
|
||||
imageGenConfig: model.imageGenConfig,
|
||||
}).toLowerCase();
|
||||
if (providerType.includes("video") || serialized.includes("video")) return "video";
|
||||
if (
|
||||
providerType.includes("3d") ||
|
||||
serialized.includes("model-3d") ||
|
||||
serialized.includes("text-to-3d") ||
|
||||
serialized.includes("image-to-3d")
|
||||
) {
|
||||
return "model-3d";
|
||||
}
|
||||
if (providerType.includes("world") || serialized.includes("world-generation")) return "world";
|
||||
if (model.supportsImageGen || providerType.includes("image")) return "image";
|
||||
return "chat";
|
||||
}
|
||||
|
||||
function chooseTargetModelId(kind: string, presets: Vip98kModelPreset[]) {
|
||||
const preferred: Record<string, string[]> = {
|
||||
chat: ["gpt-5.4-mini", "gpt-5.4", "claude-sonnet-4-6"],
|
||||
image: ["nano-banana-2", "nano-banana-pro", "gpt-image-2-vip"],
|
||||
video: ["google/veo-3.1-fast", "google/veo-3.1", "veo-3.1-fast"],
|
||||
world: ["world-generation"],
|
||||
"model-3d": [
|
||||
"tencent/hunyuan3d-pro/image-to-3d",
|
||||
"tencent/hunyuan3d-pro/text-to-3d",
|
||||
],
|
||||
};
|
||||
const candidates = preferred[kind] || preferred.chat;
|
||||
const selected = candidates.find((modelId) => presets.some((preset) => preset.modelId === modelId));
|
||||
if (selected) return selected;
|
||||
const fallbackType = kind === "model-3d" ? "model_3d" : kind === "chat" ? "model" : kind;
|
||||
return presets.find((preset) => preset.type === fallbackType)?.modelId || "";
|
||||
}
|
||||
|
||||
function rewriteSettingValue(params: {
|
||||
value: unknown;
|
||||
oldProviders: Map<string, ProviderRow>;
|
||||
oldModels: Map<string, ModelRow>;
|
||||
targetProviderId: string;
|
||||
targetModelByKind: Record<string, { id: string; modelId: string }>;
|
||||
key?: string;
|
||||
}): unknown {
|
||||
const { value, oldProviders, oldModels, targetProviderId, targetModelByKind } = params;
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => rewriteSettingValue({ ...params, value: item }));
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, nested]) => [
|
||||
key,
|
||||
rewriteSettingValue({ ...params, value: nested, key }),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (typeof value !== "string") return value;
|
||||
|
||||
const oldProvider = oldProviders.get(value);
|
||||
if (oldProvider) {
|
||||
if (/type/i.test(params.key || "")) return "vip98k";
|
||||
if (/name/i.test(params.key || "")) return "VIP98K";
|
||||
return targetProviderId;
|
||||
}
|
||||
const oldModel = oldModels.get(value);
|
||||
if (oldModel) {
|
||||
const provider = oldProviders.get(oldModel.providerId);
|
||||
const kind = classifyOldModel(oldModel, provider?.type || "");
|
||||
// A value found in oldModels is a database UUID, regardless of the JSON key name.
|
||||
return targetModelByKind[kind]?.id || targetModelByKind.chat.id;
|
||||
}
|
||||
if (/providerType/i.test(params.key || "")) {
|
||||
const oldTypes = new Set(Array.from(oldProviders.values()).map((provider) => provider.type));
|
||||
if (oldTypes.has(value)) return "vip98k";
|
||||
}
|
||||
for (const [kind, target] of Object.entries(targetModelByKind)) {
|
||||
const oldRuntimeModel = Array.from(oldModels.values()).find((model) => {
|
||||
const provider = oldProviders.get(model.providerId);
|
||||
return (
|
||||
model.modelId === value && classifyOldModel(model, provider?.type || "") === kind
|
||||
);
|
||||
});
|
||||
if (oldRuntimeModel) return target.modelId;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function summarizePresets(presets: Vip98kModelPreset[]) {
|
||||
return presets.reduce<Record<string, number>>((summary, preset) => {
|
||||
const type = String(preset.type || "model");
|
||||
summary[type] = (summary[type] || 0) + 1;
|
||||
return summary;
|
||||
}, {});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const apply = hasFlag("--apply");
|
||||
const stage = hasFlag("--stage");
|
||||
if (apply && stage) throw new Error("Use either --stage or --apply, not both");
|
||||
const databaseUrl = process.env.POSTGRES_URL || "";
|
||||
const apiKey = process.env.VIP98K_API_KEY || "";
|
||||
if (!databaseUrl) throw new Error("POSTGRES_URL is required");
|
||||
if (!apiKey) throw new Error("VIP98K_API_KEY is required and must not be passed on the command line");
|
||||
|
||||
const presets = await loadPresets(apiKey);
|
||||
const modelIds = new Set(presets.map((preset) => preset.modelId));
|
||||
const missingRequired = REQUIRED_CAPABILITY_MODELS.filter((modelId) => !modelIds.has(modelId));
|
||||
const hasVideo = presets.some((preset) => preset.type === "video");
|
||||
const hasChat = presets.some((preset) => preset.type === "model");
|
||||
if (missingRequired.length > 0 || !hasVideo || !hasChat) {
|
||||
throw new Error(
|
||||
`VIP98K capability coverage incomplete: ${[
|
||||
...missingRequired,
|
||||
...(!hasVideo ? ["video"] : []),
|
||||
...(!hasChat ? ["multimodal/chat"] : []),
|
||||
].join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const sql = postgres(databaseUrl, { prepare: false, max: 1 });
|
||||
try {
|
||||
const providers = await sql<ProviderRow[]>`select * from "AiProvider" order by "createdAt"`;
|
||||
const models = await sql<ModelRow[]>`select * from "AiModel" order by "createdAt"`;
|
||||
const falProviders = providers.filter((provider) =>
|
||||
["fal-image", "fal-video"].includes(provider.type),
|
||||
);
|
||||
const falProviderIds = new Set(falProviders.map((provider) => provider.id));
|
||||
const falFingerprintBefore = stableHash({
|
||||
providers: sortById(falProviders),
|
||||
models: sortById(models.filter((model) => falProviderIds.has(model.providerId))),
|
||||
});
|
||||
const protectedSettingsBefore = await sql<{ key: string; value: unknown }[]>`
|
||||
select key, value from "SystemSettings"
|
||||
where key = any(${Array.from(PROTECTED_SYSTEM_SETTING_KEYS)}::text[])
|
||||
order by key
|
||||
`;
|
||||
const protectedSettingsFingerprintBefore = stableHash(protectedSettingsBefore);
|
||||
const removableProviders = providers.filter(
|
||||
(provider) => !KEEP_PROVIDER_TYPES.has(provider.type),
|
||||
);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
mode: apply ? "apply" : stage ? "stage" : "dry-run",
|
||||
vip98kModels: presets.length,
|
||||
vip98kByType: summarizePresets(presets),
|
||||
falProvidersProtected: falProviders.length,
|
||||
falModelsProtected: models.filter((model) => falProviderIds.has(model.providerId)).length,
|
||||
providersToRemove: removableProviders.length,
|
||||
modelsToRemove: models.filter((model) =>
|
||||
removableProviders.some((provider) => provider.id === model.providerId),
|
||||
).length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
if (!apply && !stage) {
|
||||
console.log(
|
||||
"Dry run complete. Re-run with --stage to add VIP98K without deleting existing providers.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await sql.begin(async (tx) => {
|
||||
const existingVipProviders = providers.filter((provider) => provider.type === "vip98k");
|
||||
let targetProviderId = existingVipProviders[0]?.id || "";
|
||||
if (targetProviderId) {
|
||||
await tx`
|
||||
update "AiProvider"
|
||||
set name = 'VIP98K', "baseUrl" = 'https://api.vip98k.com', "apiKey" = ${apiKey},
|
||||
"isEnabled" = true, "updatedAt" = now()
|
||||
where id = ${targetProviderId}::uuid
|
||||
`;
|
||||
} else {
|
||||
const [created] = await tx<{ id: string }[]>`
|
||||
insert into "AiProvider" (name, type, "baseUrl", "apiKey", "isEnabled")
|
||||
values ('VIP98K', 'vip98k', 'https://api.vip98k.com', ${apiKey}, true)
|
||||
returning id
|
||||
`;
|
||||
targetProviderId = created?.id || "";
|
||||
}
|
||||
if (!targetProviderId) throw new Error("Failed to create VIP98K provider");
|
||||
|
||||
const modelDbIds = new Map<string, string>();
|
||||
for (const preset of presets) {
|
||||
const existing = await tx<{ id: string }[]>`
|
||||
select id from "AiModel"
|
||||
where "providerId" = ${targetProviderId}::uuid and "modelId" = ${preset.modelId}
|
||||
order by "createdAt" limit 1
|
||||
`;
|
||||
const capabilitiesJson = tx.json(toJsonValue(preset.capabilities));
|
||||
const defaultParamsJson = tx.json(toJsonValue(preset.defaultParams));
|
||||
const imageGenConfigJson = preset.imageGenConfig
|
||||
? tx.json(toJsonValue(preset.imageGenConfig))
|
||||
: null;
|
||||
if (existing[0]) {
|
||||
await tx`
|
||||
update "AiModel" set
|
||||
"displayName" = ${preset.displayName}, description = ${preset.description},
|
||||
"supportsVision" = ${preset.supportsVision}, "supportsImageGen" = ${preset.supportsImageGen},
|
||||
"isEnabled" = true, "isHidden" = ${preset.isHidden}, "sortOrder" = ${preset.sortOrder},
|
||||
capabilities = ${capabilitiesJson}, "defaultParams" = ${defaultParamsJson},
|
||||
"imageGenConfig" = ${imageGenConfigJson}, "updatedAt" = now()
|
||||
where id = ${existing[0].id}::uuid
|
||||
`;
|
||||
modelDbIds.set(preset.modelId, existing[0].id);
|
||||
} else {
|
||||
const [created] = await tx<{ id: string }[]>`
|
||||
insert into "AiModel" (
|
||||
"providerId", "modelId", "displayName", description, "supportsVision",
|
||||
"supportsImageGen", "isEnabled", "isHidden", "sortOrder", capabilities,
|
||||
"defaultParams", "imageGenConfig", "isDefault", "isDefaultTextEditModel"
|
||||
) values (
|
||||
${targetProviderId}::uuid, ${preset.modelId}, ${preset.displayName}, ${preset.description},
|
||||
${preset.supportsVision}, ${preset.supportsImageGen}, true, ${preset.isHidden},
|
||||
${preset.sortOrder}, ${capabilitiesJson}, ${defaultParamsJson},
|
||||
${imageGenConfigJson}, false, false
|
||||
) returning id
|
||||
`;
|
||||
if (!created) throw new Error(`Failed to create VIP98K model ${preset.modelId}`);
|
||||
modelDbIds.set(preset.modelId, created.id);
|
||||
}
|
||||
}
|
||||
|
||||
const targetModelByKind = Object.fromEntries(
|
||||
["chat", "image", "video", "world", "model-3d"].map((kind) => {
|
||||
const modelId = chooseTargetModelId(kind, presets);
|
||||
const id = modelDbIds.get(modelId) || "";
|
||||
if (!id) throw new Error(`No VIP98K target model for ${kind}`);
|
||||
return [kind, { id, modelId }];
|
||||
}),
|
||||
) as Record<string, { id: string; modelId: string }>;
|
||||
|
||||
if (stage) return;
|
||||
|
||||
await tx`
|
||||
update "AiModel" set "isDefault" = false, "isDefaultTextEditModel" = false
|
||||
where "providerId" = ${targetProviderId}::uuid
|
||||
`;
|
||||
await tx`
|
||||
update "AiModel" set "isDefault" = true
|
||||
where id = ${targetModelByKind.chat.id}::uuid
|
||||
`;
|
||||
await tx`
|
||||
update "AiModel" set "isDefaultTextEditModel" = true,
|
||||
"fallbackModelId1" = 'nano-banana-pro', "fallbackModelId2" = 'gpt-image-2-vip'
|
||||
where id = ${targetModelByKind.image.id}::uuid
|
||||
`;
|
||||
|
||||
const duplicateVipProviders = existingVipProviders.slice(1);
|
||||
const replaceableProviders = [...removableProviders, ...duplicateVipProviders];
|
||||
const oldProviderMap = new Map(
|
||||
replaceableProviders.map((provider) => [provider.id, provider]),
|
||||
);
|
||||
const oldModels = models.filter((model) => oldProviderMap.has(model.providerId));
|
||||
const oldModelMap = new Map(oldModels.map((model) => [model.id, model]));
|
||||
|
||||
if (oldModelMap.size > 0) {
|
||||
for (const presetType of ["image", "video", "text"] as const) {
|
||||
const target = presetType === "video"
|
||||
? targetModelByKind.video
|
||||
: presetType === "image"
|
||||
? targetModelByKind.image
|
||||
: targetModelByKind.chat;
|
||||
await tx`
|
||||
update "AgentPreset" set "defaultModelId" = ${target.id}::uuid, "updatedAt" = now()
|
||||
where type = ${presetType}
|
||||
and "defaultModelId" = any(${Array.from(oldModelMap.keys())}::uuid[])
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const settings = await tx<{ id: string; key: string; value: unknown }[]>`
|
||||
select id, key, value from "SystemSettings"
|
||||
`;
|
||||
for (const setting of settings) {
|
||||
if (PROTECTED_SYSTEM_SETTING_KEYS.has(setting.key)) continue;
|
||||
let nextValue = rewriteSettingValue({
|
||||
value: setting.value,
|
||||
oldProviders: oldProviderMap,
|
||||
oldModels: oldModelMap,
|
||||
targetProviderId,
|
||||
targetModelByKind,
|
||||
});
|
||||
if (setting.key === "rmbg_api_config") nextValue = { provider: "vip98k" };
|
||||
if (setting.key === "enhance_api_config") {
|
||||
nextValue = { provider: "vip98k", type: "clean", scaleFactor: 4 };
|
||||
}
|
||||
if (setting.key === "extend_api_config") {
|
||||
nextValue = { provider: "vip98k", xScale: 1.5, yScale: 1.5 };
|
||||
}
|
||||
if (setting.key === "worldlabs_key_pool_config") {
|
||||
nextValue = { baseUrl: "https://api.vip98k.com", providers: [] };
|
||||
}
|
||||
if (JSON.stringify(nextValue) !== JSON.stringify(setting.value)) {
|
||||
await tx`
|
||||
update "SystemSettings" set value = ${JSON.stringify(nextValue)}::jsonb, "updatedAt" = now()
|
||||
where id = ${setting.id}::uuid
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const removableProviderIds = removableProviders.map((provider) => provider.id);
|
||||
const duplicateVipProviderIds = duplicateVipProviders.map((provider) => provider.id);
|
||||
const deleteIds = [...removableProviderIds, ...duplicateVipProviderIds];
|
||||
if (deleteIds.length > 0) {
|
||||
await tx`delete from "AiProvider" where id = any(${deleteIds}::uuid[])`;
|
||||
}
|
||||
});
|
||||
|
||||
const remainingProviders = await sql<ProviderRow[]>`select * from "AiProvider" order by "createdAt"`;
|
||||
const remainingModels = await sql<ModelRow[]>`select * from "AiModel" order by "createdAt"`;
|
||||
const remainingFalProviders = remainingProviders.filter((provider) =>
|
||||
["fal-image", "fal-video"].includes(provider.type),
|
||||
);
|
||||
const remainingFalIds = new Set(remainingFalProviders.map((provider) => provider.id));
|
||||
const falFingerprintAfter = stableHash({
|
||||
providers: sortById(remainingFalProviders),
|
||||
models: sortById(
|
||||
remainingModels.filter((model) => remainingFalIds.has(model.providerId)),
|
||||
),
|
||||
});
|
||||
if (falFingerprintAfter !== falFingerprintBefore) {
|
||||
throw new Error("FAL provider/model fingerprint changed; restore the verified database backup");
|
||||
}
|
||||
const protectedSettingsAfter = await sql<{ key: string; value: unknown }[]>`
|
||||
select key, value from "SystemSettings"
|
||||
where key = any(${Array.from(PROTECTED_SYSTEM_SETTING_KEYS)}::text[])
|
||||
order by key
|
||||
`;
|
||||
if (stableHash(protectedSettingsAfter) !== protectedSettingsFingerprintBefore) {
|
||||
throw new Error("Realtime canvas configuration changed; restore the verified database backup");
|
||||
}
|
||||
const vipProviderIds = new Set(
|
||||
remainingProviders
|
||||
.filter((provider) => provider.type === "vip98k")
|
||||
.map((provider) => provider.id),
|
||||
);
|
||||
const invalidVipModels = remainingModels.filter((model) => {
|
||||
if (!vipProviderIds.has(model.providerId)) return false;
|
||||
if (
|
||||
!model.capabilities ||
|
||||
typeof model.capabilities !== "object" ||
|
||||
Array.isArray(model.capabilities)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const capabilities = model.capabilities as Record<string, unknown>;
|
||||
const kind = String(capabilities?.kind || "").trim().toLowerCase();
|
||||
if (["video", "model-3d", "world", "chat"].includes(kind)) {
|
||||
if (model.supportsImageGen) return true;
|
||||
}
|
||||
return ["image-tool", "model-3d"].includes(kind) && !model.isHidden;
|
||||
});
|
||||
if (invalidVipModels.length > 0) {
|
||||
throw new Error(
|
||||
`VIP98K model classification invalid: ${invalidVipModels
|
||||
.slice(0, 10)
|
||||
.map((model) => model.modelId)
|
||||
.join(", ")}`,
|
||||
);
|
||||
}
|
||||
const invalidTypes = remainingProviders.filter(
|
||||
(provider) => !KEEP_PROVIDER_TYPES.has(provider.type),
|
||||
);
|
||||
if (apply && invalidTypes.length > 0) {
|
||||
throw new Error(`Unexpected provider types remain: ${invalidTypes.map((item) => item.type).join(", ")}`);
|
||||
}
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
success: true,
|
||||
mode: apply ? "apply" : "stage",
|
||||
providerTypes: Array.from(new Set(remainingProviders.map((provider) => provider.type))).sort(),
|
||||
vip98kModels: remainingModels.filter((model) =>
|
||||
remainingProviders.some(
|
||||
(provider) => provider.id === model.providerId && provider.type === "vip98k",
|
||||
),
|
||||
).length,
|
||||
falFingerprintUnchanged: true,
|
||||
realtimeCanvasConfigUnchanged: true,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
await sql.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exit(1);
|
||||
});
|
||||
566
scripts/test-vip98k-capability.ts
Normal file
566
scripts/test-vip98k-capability.ts
Normal file
@ -0,0 +1,566 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import dotenv from "dotenv";
|
||||
import sharp from "sharp";
|
||||
|
||||
dotenv.config({ path: ".env.local" });
|
||||
dotenv.config();
|
||||
|
||||
const VIP98K_BASE_URL = "https://api.vip98k.com";
|
||||
|
||||
type Vip98kCatalogModel = {
|
||||
id?: string;
|
||||
modelId?: string;
|
||||
model_id?: string;
|
||||
slug?: string;
|
||||
name?: string;
|
||||
displayName?: string;
|
||||
display_name?: string;
|
||||
invocation?: Vip98kInvocation;
|
||||
};
|
||||
|
||||
type Vip98kInvocation = {
|
||||
kind?: string;
|
||||
method?: string;
|
||||
path?: string;
|
||||
content_type?: string;
|
||||
request_example?: Record<string, unknown>;
|
||||
result_method?: string;
|
||||
result_path?: string;
|
||||
};
|
||||
|
||||
const CAPABILITIES = [
|
||||
"chat",
|
||||
"multimodal",
|
||||
"image",
|
||||
"multi-image-edit",
|
||||
"rmbg",
|
||||
"enhance",
|
||||
"extend",
|
||||
"video",
|
||||
"world",
|
||||
"text-to-3d",
|
||||
"image-to-3d",
|
||||
] as const;
|
||||
|
||||
type Capability = (typeof CAPABILITIES)[number];
|
||||
type LedgerEntry = {
|
||||
runId: string;
|
||||
capability: Capability;
|
||||
modelId: string;
|
||||
status: "started" | "success" | "failure" | "skipped";
|
||||
startedAt: string;
|
||||
finishedAt?: string;
|
||||
durationMs?: number;
|
||||
outputCount?: number;
|
||||
outputDigest?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
const DEFAULT_MODEL_IDS: Record<Capability, string[]> = {
|
||||
chat: ["gpt-5.4-mini", "gpt-5.4", "claude-sonnet-4-6"],
|
||||
multimodal: ["gpt-5.4-mini", "gpt-5.4", "claude-sonnet-4-6"],
|
||||
image: ["nano-banana-2", "nano-banana-pro", "gpt-image-2-vip"],
|
||||
"multi-image-edit": [
|
||||
"google/nano-banana-pro/edit",
|
||||
"google/nano-banana-2/edit",
|
||||
"openai/gpt-image-2/edit",
|
||||
],
|
||||
rmbg: ["remove-background"],
|
||||
enhance: ["enhance", "image-upscaler"],
|
||||
extend: ["image-expansion"],
|
||||
video: [
|
||||
"bytedance/seedance-v1-pro-fast/text-to-video",
|
||||
"veo-3.1-fast",
|
||||
"google/veo3.1-fast/text-to-video",
|
||||
],
|
||||
world: ["world-generation"],
|
||||
"text-to-3d": [
|
||||
"tencent/hunyuan3d-pro/text-to-3d",
|
||||
"tencent/hunyuan3d-rapid/text-to-3d",
|
||||
],
|
||||
"image-to-3d": [
|
||||
"tencent/hunyuan3d-pro/image-to-3d",
|
||||
"tencent/hunyuan3d-rapid/image-to-3d",
|
||||
],
|
||||
};
|
||||
|
||||
function getArgValue(name: string) {
|
||||
const prefix = `${name}=`;
|
||||
return process.argv.find((item) => item.startsWith(prefix))?.slice(prefix.length) || "";
|
||||
}
|
||||
|
||||
function hasFlag(name: string) {
|
||||
return process.argv.includes(name);
|
||||
}
|
||||
|
||||
function getModelId(model: Vip98kCatalogModel) {
|
||||
return String(model.id || model.modelId || model.model_id || model.slug || model.name || "").trim();
|
||||
}
|
||||
|
||||
function normalizeVip98kBaseUrl(baseUrl?: string | null) {
|
||||
const normalized = String(baseUrl || VIP98K_BASE_URL).trim().replace(/\/+$/, "");
|
||||
if (!normalized) return VIP98K_BASE_URL;
|
||||
return normalized.replace(/\/v1$/i, "").replace(/\/api\/external\/task$/i, "");
|
||||
}
|
||||
|
||||
async function fetchVip98kCatalog(params: { baseURL: string; apiKey: string }) {
|
||||
const baseUrl = normalizeVip98kBaseUrl(params.baseURL);
|
||||
const [authorizedPayload, publicPayload] = await Promise.all([
|
||||
parseResponse(
|
||||
await fetch(`${baseUrl}/api/external/task/models`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
}),
|
||||
),
|
||||
parseResponse(
|
||||
await fetch(`${baseUrl}/api/v1/public/models`, {
|
||||
headers: { Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
}),
|
||||
),
|
||||
]);
|
||||
const record =
|
||||
authorizedPayload && typeof authorizedPayload === "object"
|
||||
? (authorizedPayload as Record<string, any>)
|
||||
: {};
|
||||
const data = record.data;
|
||||
const authorized =
|
||||
(Array.isArray(data?.models) && data.models) ||
|
||||
(Array.isArray(data?.items) && data.items) ||
|
||||
(Array.isArray(data) && data) ||
|
||||
(Array.isArray(record.models) && record.models) ||
|
||||
[];
|
||||
const publicRecord =
|
||||
publicPayload && typeof publicPayload === "object"
|
||||
? (publicPayload as Record<string, any>)
|
||||
: {};
|
||||
const publicModels = (Array.isArray(publicRecord.data?.sections)
|
||||
? publicRecord.data.sections
|
||||
: []
|
||||
).flatMap((section: any) => (Array.isArray(section?.models) ? section.models : []));
|
||||
if (authorized.length === 0) throw new Error("VIP98K authorized model catalog is empty");
|
||||
if (publicModels.length === 0) throw new Error("VIP98K public invocation catalog is empty");
|
||||
const publicById = new Map<string, Vip98kCatalogModel>(
|
||||
publicModels.map((model: Vip98kCatalogModel) => [
|
||||
getModelId(model).toLowerCase(),
|
||||
model,
|
||||
]),
|
||||
);
|
||||
return authorized.map((model: Vip98kCatalogModel) => ({
|
||||
...(publicById.get(getModelId(model).toLowerCase()) || {}),
|
||||
...model,
|
||||
invocation: publicById.get(getModelId(model).toLowerCase())?.invocation,
|
||||
})) as Vip98kCatalogModel[];
|
||||
}
|
||||
|
||||
function sanitizeError(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]").slice(0, 2000);
|
||||
}
|
||||
|
||||
function digestOutputs(outputs: string[]) {
|
||||
return createHash("sha256").update(outputs.join("\n")).digest("hex");
|
||||
}
|
||||
|
||||
async function readLedger(path: string): Promise<LedgerEntry[]> {
|
||||
const content = await readFile(path, "utf8").catch(() => "");
|
||||
return content
|
||||
.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.flatMap((line) => {
|
||||
try {
|
||||
return [JSON.parse(line) as LedgerEntry];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function writeLedger(path: string, entry: LedgerEntry) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await appendFile(path, `${JSON.stringify(entry)}\n`, "utf8");
|
||||
}
|
||||
|
||||
async function parseResponse(response: Response) {
|
||||
const text = await response.text();
|
||||
let payload: unknown = text;
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
// Keep the response body for a useful provider error.
|
||||
}
|
||||
if (!response.ok) {
|
||||
const record = payload && typeof payload === "object" ? (payload as Record<string, any>) : {};
|
||||
const message =
|
||||
record.error?.message || record.error || record.message || text || `HTTP ${response.status}`;
|
||||
throw new Error(`${String(message)} (HTTP ${response.status})`);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function collectUrls(value: unknown, urls = new Set<string>()) {
|
||||
if (!value) return urls;
|
||||
if (typeof value === "string") {
|
||||
for (const match of value.match(/https?:\/\/[^\s"'<>()[\]{}]+/g) || []) {
|
||||
urls.add(match.replace(/[),.;]+$/g, ""));
|
||||
}
|
||||
if (/^data:[^;]+;base64,/i.test(value)) urls.add(value);
|
||||
return urls;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => collectUrls(item, urls));
|
||||
return urls;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
Object.values(value as Record<string, unknown>).forEach((item) => collectUrls(item, urls));
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
function extractTaskId(payload: unknown) {
|
||||
const root = payload && typeof payload === "object" ? (payload as Record<string, any>) : {};
|
||||
const data = root.data && typeof root.data === "object" ? root.data : root;
|
||||
return String(data.taskId || data.task_id || data.id || data.requestId || "").trim();
|
||||
}
|
||||
|
||||
function extractResultPath(payload: unknown) {
|
||||
const root = payload && typeof payload === "object" ? (payload as Record<string, any>) : {};
|
||||
const data = root.data && typeof root.data === "object" ? root.data : root;
|
||||
return String(data.resultPath || data.result_path || "").trim();
|
||||
}
|
||||
|
||||
function extractStatus(payload: unknown) {
|
||||
const root = payload && typeof payload === "object" ? (payload as Record<string, any>) : {};
|
||||
const data = root.data && typeof root.data === "object" ? root.data : root;
|
||||
return String(data.status || data.state || data.taskStatus || "").trim().toLowerCase();
|
||||
}
|
||||
|
||||
async function makeReferencePng(color: string, label: string) {
|
||||
return sharp({
|
||||
create: { width: 96, height: 96, channels: 4, background: color },
|
||||
})
|
||||
.composite([
|
||||
{
|
||||
input: Buffer.from(
|
||||
`<svg width="96" height="96"><text x="48" y="58" text-anchor="middle" font-size="30" fill="white">${label}</text></svg>`,
|
||||
),
|
||||
},
|
||||
])
|
||||
.png()
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
async function runOpenAIImage(params: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
modelId: string;
|
||||
multiImage: boolean;
|
||||
}) {
|
||||
const endpoint = `${params.baseUrl}/v1/images/${params.multiImage ? "edits" : "generations"}`;
|
||||
if (!params.multiImage) {
|
||||
const payload = await parseResponse(
|
||||
await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: params.modelId,
|
||||
prompt: "A small blue ceramic cup on a white studio background",
|
||||
size: "1024x1024",
|
||||
response_format: "url",
|
||||
}),
|
||||
signal: AbortSignal.timeout(900_000),
|
||||
}),
|
||||
);
|
||||
const outputs = Array.from(collectUrls(payload));
|
||||
if (outputs.length === 0) throw new Error("Image generation returned no image output");
|
||||
return outputs;
|
||||
}
|
||||
|
||||
const [left, right] = await Promise.all([
|
||||
makeReferencePng("#2563eb", "A"),
|
||||
makeReferencePng("#dc2626", "B"),
|
||||
]);
|
||||
const form = new FormData();
|
||||
form.append("model", params.modelId);
|
||||
form.append("prompt", "Combine both references into one clean side-by-side product comparison image");
|
||||
form.append("size", "1024x1024");
|
||||
form.append("response_format", "url");
|
||||
form.append("image[]", new Blob([left], { type: "image/png" }), "reference-a.png");
|
||||
form.append("image[]", new Blob([right], { type: "image/png" }), "reference-b.png");
|
||||
const payload = await parseResponse(
|
||||
await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${params.apiKey}` },
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(900_000),
|
||||
}),
|
||||
);
|
||||
const outputs = Array.from(collectUrls(payload));
|
||||
if (outputs.length === 0) throw new Error("Multi-image edit returned no image output");
|
||||
return outputs;
|
||||
}
|
||||
|
||||
async function runChat(params: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
modelId: string;
|
||||
multimodal: boolean;
|
||||
}) {
|
||||
const content = params.multimodal
|
||||
? [
|
||||
{ type: "text", text: "Reply with the dominant color in one English word." },
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: { url: "https://dummyimage.com/96x96/2563eb/ffffff.png&text=A" },
|
||||
},
|
||||
]
|
||||
: "Reply with exactly: vip98k-ok";
|
||||
const payload = await parseResponse(
|
||||
await fetch(`${params.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: params.modelId,
|
||||
messages: [{ role: "user", content }],
|
||||
max_tokens: 64,
|
||||
}),
|
||||
signal: AbortSignal.timeout(180_000),
|
||||
}),
|
||||
);
|
||||
const text = JSON.stringify(payload);
|
||||
if (!text || text === "{}") throw new Error("Chat request returned no content");
|
||||
return [text.slice(0, 500)];
|
||||
}
|
||||
|
||||
async function runExternalTask(params: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
modelId: string;
|
||||
capability: Capability;
|
||||
invocation: Vip98kInvocation;
|
||||
}) {
|
||||
const imageUrl = "https://dummyimage.com/512x512/2563eb/ffffff.png&text=VIP98K";
|
||||
const secondImageUrl = "https://dummyimage.com/512x512/dc2626/ffffff.png&text=REFERENCE";
|
||||
const body: Record<string, unknown> = JSON.parse(
|
||||
JSON.stringify(params.invocation.request_example || {}),
|
||||
);
|
||||
if ("model" in body) body.model = params.modelId;
|
||||
if ("displayName" in body) body.displayName = `provider-smoke-${params.capability}`;
|
||||
if ("prompt" in body) body.prompt = "Create a minimal test result with one simple object";
|
||||
if (
|
||||
["multi-image-edit", "rmbg", "enhance", "extend", "image-to-3d"].includes(
|
||||
params.capability,
|
||||
)
|
||||
) {
|
||||
const images =
|
||||
params.capability === "multi-image-edit" ? [imageUrl, secondImageUrl] : [imageUrl];
|
||||
if ("image" in body) body.image = imageUrl;
|
||||
if ("imageUrl" in body) body.imageUrl = imageUrl;
|
||||
if ("image_url" in body) body.image_url = imageUrl;
|
||||
if ("images" in body) body.images = images;
|
||||
if ("imageUrls" in body) body.imageUrls = images;
|
||||
if ("referenceImages" in body) body.referenceImages = images;
|
||||
if ("reference_images" in body) body.reference_images = images;
|
||||
if (Array.isArray(body.video_clips)) {
|
||||
const template =
|
||||
body.video_clips[0] && typeof body.video_clips[0] === "object"
|
||||
? (body.video_clips[0] as Record<string, unknown>)
|
||||
: {};
|
||||
body.video_clips = images.map((url) => ({ ...template, url }));
|
||||
}
|
||||
if (
|
||||
params.capability === "multi-image-edit" &&
|
||||
!Array.isArray(body.images) &&
|
||||
!Array.isArray(body.referenceImages) &&
|
||||
!Array.isArray(body.reference_images) &&
|
||||
!Array.isArray(body.video_clips)
|
||||
) {
|
||||
throw new Error(`${params.modelId} official invocation does not expose multi-image input`);
|
||||
}
|
||||
}
|
||||
if (params.capability === "extend") {
|
||||
if ("aspectRatio" in body) body.aspectRatio = "16:9";
|
||||
if ("aspect_ratio" in body) body.aspect_ratio = "16:9";
|
||||
if ("ratio" in body) body.ratio = "16:9";
|
||||
}
|
||||
if (params.capability === "world" && "mode" in body) body.mode = "world-generation";
|
||||
|
||||
const path = String(params.invocation.path || "").trim();
|
||||
if (!path.startsWith("/")) throw new Error(`${params.modelId} has no valid invocation path`);
|
||||
|
||||
const submitted = await parseResponse(
|
||||
await fetch(`${params.baseUrl}${path}`, {
|
||||
method: String(params.invocation.method || "POST").toUpperCase(),
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.apiKey}`,
|
||||
"Content-Type": params.invocation.content_type || "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(180_000),
|
||||
}),
|
||||
);
|
||||
const inputUrls = new Set([imageUrl, secondImageUrl]);
|
||||
const immediate = Array.from(collectUrls(submitted)).filter((url) => !inputUrls.has(url));
|
||||
if (immediate.length > 0) return immediate;
|
||||
const taskId = extractTaskId(submitted);
|
||||
if (!taskId) throw new Error("External task returned neither output nor task ID");
|
||||
const resultPath =
|
||||
extractResultPath(submitted) ||
|
||||
String(params.invocation.result_path || "").replaceAll(
|
||||
"{task_id}",
|
||||
encodeURIComponent(taskId),
|
||||
);
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < 1_200_000) {
|
||||
await new Promise((resolvePromise) => setTimeout(resolvePromise, 5000));
|
||||
const resultUrl = resultPath
|
||||
? resultPath.startsWith("http")
|
||||
? resultPath
|
||||
: `${params.baseUrl}${resultPath.startsWith("/") ? "" : "/"}${resultPath}`
|
||||
: `${params.baseUrl}/api/external/task/result?taskId=${encodeURIComponent(taskId)}`;
|
||||
const payload = await parseResponse(
|
||||
await fetch(resultUrl, {
|
||||
headers: { Authorization: `Bearer ${params.apiKey}` },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
}),
|
||||
);
|
||||
const status = extractStatus(payload);
|
||||
const outputs = Array.from(collectUrls(payload)).filter((url) => !inputUrls.has(url));
|
||||
if (["failed", "error", "timeout", "canceled", "cancelled"].includes(status)) {
|
||||
throw new Error(`External task failed with status ${status}`);
|
||||
}
|
||||
if (
|
||||
["succeeded", "success", "completed", "done", "finished"].includes(status) ||
|
||||
outputs.length > 0
|
||||
) {
|
||||
if (outputs.length === 0) throw new Error("External task completed without output URL");
|
||||
return outputs;
|
||||
}
|
||||
}
|
||||
throw new Error("External task did not complete within 20 minutes");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const capabilityArg = getArgValue("--capability");
|
||||
if (!CAPABILITIES.includes(capabilityArg as Capability)) {
|
||||
throw new Error(`Pass exactly one --capability=${CAPABILITIES.join("|")}`);
|
||||
}
|
||||
const capability = capabilityArg as Capability;
|
||||
const apiKey = String(process.env.VIP98K_API_KEY || "").trim();
|
||||
if (!apiKey) throw new Error("VIP98K_API_KEY is required and must remain server-side");
|
||||
const baseUrl = normalizeVip98kBaseUrl(process.env.VIP98K_BASE_URL || VIP98K_BASE_URL);
|
||||
const catalog = await fetchVip98kCatalog({ baseURL: baseUrl, apiKey });
|
||||
const availableModelIds = new Set(catalog.map(getModelId));
|
||||
const explicitModelId = getArgValue("--model");
|
||||
const modelId =
|
||||
explicitModelId || DEFAULT_MODEL_IDS[capability].find((candidate) => availableModelIds.has(candidate));
|
||||
if (!modelId || !availableModelIds.has(modelId)) {
|
||||
throw new Error(`No catalog model is available for ${capability}; pass --model=<catalog-id>`);
|
||||
}
|
||||
const selectedModel = catalog.find((model) => getModelId(model) === modelId);
|
||||
if (
|
||||
!["chat", "multimodal", "image"].includes(capability) &&
|
||||
!selectedModel?.invocation?.path
|
||||
) {
|
||||
throw new Error(`${modelId} is missing its official invocation contract`);
|
||||
}
|
||||
|
||||
const ledgerPath = resolve(
|
||||
getArgValue("--ledger") ||
|
||||
process.env.VIP98K_TEST_LEDGER ||
|
||||
".local/vip98k-capability-tests.jsonl",
|
||||
);
|
||||
const ledger = await readLedger(ledgerPath);
|
||||
if (
|
||||
!hasFlag("--force") &&
|
||||
ledger.some(
|
||||
(entry) =>
|
||||
entry.capability === capability && entry.modelId === modelId && entry.status === "success",
|
||||
)
|
||||
) {
|
||||
console.log(JSON.stringify({ skipped: true, capability, modelId, ledgerPath }, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const startedAt = new Date();
|
||||
await writeLedger(ledgerPath, {
|
||||
runId,
|
||||
capability,
|
||||
modelId,
|
||||
status: "started",
|
||||
startedAt: startedAt.toISOString(),
|
||||
});
|
||||
|
||||
try {
|
||||
let outputs: string[];
|
||||
if (capability === "chat" || capability === "multimodal") {
|
||||
outputs = await runChat({
|
||||
baseUrl,
|
||||
apiKey,
|
||||
modelId,
|
||||
multimodal: capability === "multimodal",
|
||||
});
|
||||
} else if (capability === "image") {
|
||||
outputs = await runOpenAIImage({
|
||||
baseUrl,
|
||||
apiKey,
|
||||
modelId,
|
||||
multiImage: false,
|
||||
});
|
||||
} else {
|
||||
outputs = await runExternalTask({
|
||||
baseUrl,
|
||||
apiKey,
|
||||
modelId,
|
||||
capability,
|
||||
invocation: selectedModel!.invocation!,
|
||||
});
|
||||
}
|
||||
const finishedAt = new Date();
|
||||
const entry: LedgerEntry = {
|
||||
runId,
|
||||
capability,
|
||||
modelId,
|
||||
status: "success",
|
||||
startedAt: startedAt.toISOString(),
|
||||
finishedAt: finishedAt.toISOString(),
|
||||
durationMs: finishedAt.getTime() - startedAt.getTime(),
|
||||
outputCount: outputs.length,
|
||||
outputDigest: digestOutputs(outputs),
|
||||
};
|
||||
await writeLedger(ledgerPath, entry);
|
||||
console.log(JSON.stringify({ ...entry, ledgerPath }, null, 2));
|
||||
} catch (error) {
|
||||
const finishedAt = new Date();
|
||||
const entry: LedgerEntry = {
|
||||
runId,
|
||||
capability,
|
||||
modelId,
|
||||
status: "failure",
|
||||
startedAt: startedAt.toISOString(),
|
||||
finishedAt: finishedAt.toISOString(),
|
||||
durationMs: finishedAt.getTime() - startedAt.getTime(),
|
||||
error: sanitizeError(error),
|
||||
};
|
||||
await writeLedger(ledgerPath, entry);
|
||||
console.error(JSON.stringify({ ...entry, ledgerPath }, null, 2));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(sanitizeError(error));
|
||||
process.exit(1);
|
||||
});
|
||||
@ -9,6 +9,11 @@ import {
|
||||
isImageGenerationModelDescriptor,
|
||||
isVideoModelDescriptor,
|
||||
} from "@/lib/ai/model-classification";
|
||||
import {
|
||||
buildVip98kModelPresets,
|
||||
isVip98kCatalogModelEligible,
|
||||
isVip98kImageModelVisible,
|
||||
} from "@/lib/ai/vip98k-models";
|
||||
|
||||
const atlasHunyuan3D = {
|
||||
model: "tencent/hunyuan3d-pro/text-to-3d",
|
||||
@ -188,4 +193,163 @@ test.describe("AI model media classification", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("normalizes VIP98K media and tool types before they reach the frontend", () => {
|
||||
const presets = buildVip98kModelPresets([
|
||||
{
|
||||
modelId: "mislabelled-video",
|
||||
displayName: "Mislabelled video",
|
||||
type: "image",
|
||||
capabilities: ["text_to_video", "image_to_video"],
|
||||
inputModes: ["text", "image"],
|
||||
},
|
||||
{
|
||||
modelId: "enhance",
|
||||
displayName: "Enhance",
|
||||
type: "image",
|
||||
capabilities: ["image_processing"],
|
||||
},
|
||||
{
|
||||
modelId: "image-expansion",
|
||||
displayName: "Extend",
|
||||
type: "image_tool",
|
||||
capabilities: ["outpainting"],
|
||||
},
|
||||
{
|
||||
modelId: "remove-background",
|
||||
displayName: "Remove background",
|
||||
type: "image_tool",
|
||||
capabilities: ["image_processing"],
|
||||
},
|
||||
{
|
||||
modelId: "multimodal-model",
|
||||
displayName: "Multimodal model",
|
||||
type: "model",
|
||||
capabilities: ["multimodal"],
|
||||
inputModes: ["text", "image"],
|
||||
},
|
||||
{
|
||||
modelId: "tencent/hunyuan3d-pro/text-to-3d",
|
||||
displayName: "Hunyuan 3D",
|
||||
type: "image",
|
||||
capabilities: ["text-to-3d"],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(presets.find((item) => item.modelId === "mislabelled-video")).toMatchObject({
|
||||
type: "video",
|
||||
supportsImageGen: false,
|
||||
});
|
||||
expect(presets.find((item) => item.modelId === "enhance")).toMatchObject({
|
||||
type: "image_tool",
|
||||
isHidden: true,
|
||||
capabilities: { toolOperation: "enhance" },
|
||||
});
|
||||
expect(presets.find((item) => item.modelId === "image-expansion")).toMatchObject({
|
||||
type: "image_tool",
|
||||
capabilities: { toolOperation: "extend" },
|
||||
});
|
||||
expect(presets.find((item) => item.modelId === "remove-background")).toMatchObject({
|
||||
type: "image_tool",
|
||||
capabilities: { toolOperation: "remove-background" },
|
||||
});
|
||||
expect(presets.find((item) => item.modelId === "multimodal-model")).toMatchObject({
|
||||
type: "model",
|
||||
supportsVision: true,
|
||||
supportsImageGen: false,
|
||||
});
|
||||
expect(
|
||||
presets.find((item) => item.modelId === "tencent/hunyuan3d-pro/text-to-3d"),
|
||||
).toMatchObject({
|
||||
type: "model_3d",
|
||||
supportsImageGen: false,
|
||||
isHidden: true,
|
||||
capabilities: { kind: "model-3d" },
|
||||
});
|
||||
});
|
||||
|
||||
test("only shows VIP98K image models verified as released in 2026 or later", () => {
|
||||
const models = [
|
||||
{
|
||||
modelId: "black-forest-labs/flux-dev",
|
||||
displayName: "Flux Dev",
|
||||
type: "image",
|
||||
capabilities: ["text_to_image"],
|
||||
},
|
||||
{
|
||||
modelId: "google/nano-banana-2/text-to-image",
|
||||
displayName: "Nano Banana 2",
|
||||
type: "image",
|
||||
capabilities: ["text_to_image"],
|
||||
},
|
||||
{
|
||||
modelId: "future-image-with-date",
|
||||
displayName: "Future image",
|
||||
type: "image",
|
||||
capabilities: ["text_to_image"],
|
||||
releasedAt: "2027-02-01",
|
||||
},
|
||||
{
|
||||
modelId: "old-image-with-date",
|
||||
displayName: "Old image",
|
||||
type: "image",
|
||||
capabilities: ["text_to_image"],
|
||||
releasedAt: "2025-12-15",
|
||||
},
|
||||
];
|
||||
|
||||
expect(isVip98kImageModelVisible(models[0])).toBe(false);
|
||||
expect(isVip98kImageModelVisible(models[1])).toBe(true);
|
||||
expect(isVip98kImageModelVisible(models[2])).toBe(true);
|
||||
expect(isVip98kImageModelVisible(models[3])).toBe(false);
|
||||
});
|
||||
|
||||
test("excludes pure text image/video models but keeps reference and 3D models", () => {
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "openai/gpt-image-2/text-to-image",
|
||||
type: "image",
|
||||
capabilities: ["text-to-image"],
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "google/veo/text-to-video",
|
||||
type: "video",
|
||||
capabilities: ["text-to-video"],
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "google/nano-banana-2/edit",
|
||||
type: "image",
|
||||
capabilities: ["text-to-image", "image-to-image"],
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "bytedance/seedance/image-to-video",
|
||||
type: "video",
|
||||
capabilities: ["text-to-video", "image-to-video"],
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "tencent/hunyuan3d-pro/text-to-3d",
|
||||
type: "image",
|
||||
capabilities: ["text-to-3d"],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("excludes catalog models explicitly marked unavailable", () => {
|
||||
expect(
|
||||
isVip98kCatalogModelEligible({
|
||||
modelId: "google/nano-banana-2/edit",
|
||||
type: "image",
|
||||
capabilities: ["image-to-image"],
|
||||
status: "closed",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
62
tests/routes/vip98k-reference-routing.test.ts
Normal file
62
tests/routes/vip98k-reference-routing.test.ts
Normal file
@ -0,0 +1,62 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import {
|
||||
resolveVip98kTaskInvocation,
|
||||
type Vip98kTaskInvocation,
|
||||
} from "@/lib/ai/vip98k-task-invocation";
|
||||
|
||||
const textToImageInvocation: Vip98kTaskInvocation = {
|
||||
kind: "tool",
|
||||
method: "POST",
|
||||
path: "/api/external/tools/generate?tool_id=google%2Fnano-banana-2%2Ftext-to-image",
|
||||
contentType: "application/json",
|
||||
requestExample: { prompt: "Generate an image" },
|
||||
resultMethod: "GET",
|
||||
resultPath:
|
||||
"/api/external/tools/result?tool_id=google%2Fnano-banana-2%2Ftext-to-image&taskId={task_id}",
|
||||
};
|
||||
|
||||
test.describe("VIP98K reference-image routing", () => {
|
||||
test("replaces a text-to-image alias invocation with the resolved reference tool", () => {
|
||||
const invocation = resolveVip98kTaskInvocation(
|
||||
"google/nano-banana-2/reference-to-image",
|
||||
textToImageInvocation
|
||||
);
|
||||
|
||||
expect(invocation?.path).toContain(
|
||||
"tool_id=google%2Fnano-banana-2%2Freference-to-image"
|
||||
);
|
||||
expect(invocation?.resultPath).toContain(
|
||||
"tool_id=google%2Fnano-banana-2%2Freference-to-image"
|
||||
);
|
||||
expect(invocation?.requestExample).toMatchObject({
|
||||
prompt: "",
|
||||
video_clips: [{ fps: 1, url: "", ends: 0, start: 0 }],
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the catalog invocation when it already targets the resolved tool", () => {
|
||||
const catalogInvocation: Vip98kTaskInvocation = {
|
||||
...textToImageInvocation,
|
||||
path: "/api/external/tools/generate?tool_id=google%2Fnano-banana-2%2Freference-to-image",
|
||||
resultPath:
|
||||
"/api/external/tools/result?tool_id=google%2Fnano-banana-2%2Freference-to-image&taskId={task_id}",
|
||||
requestExample: {
|
||||
prompt: "Catalog prompt",
|
||||
video_clips: [{ fps: 2, url: "catalog", ends: 1, start: 0 }],
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveVip98kTaskInvocation(
|
||||
"google/nano-banana-2/reference-to-image",
|
||||
catalogInvocation
|
||||
)
|
||||
).toBe(catalogInvocation);
|
||||
});
|
||||
|
||||
test("does not rewrite unrelated tools", () => {
|
||||
expect(
|
||||
resolveVip98kTaskInvocation("other/image-model", textToImageInvocation)
|
||||
).toBe(textToImageInvocation);
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user