feat(models): 统一模型规格价格与路由
This commit is contained in:
1 parent
bcfb87c98c
commit
c34f1ea476
36 files changed
+3404
-421
No files matched your search
@@ -3,9 +3,9 @@ import { ConfigProvider, Switch } from "antd";
|
||||
|
||||
import { type CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { buildImageResolutionOptions, formatImageResolutionSize, imageRatioForSize, imageResolutionChoices, imageResolutionOption, imageSizeForResolution, supportsImageResolutionPresets, type ImageResolutionChoice } from "@/lib/image-resolution-tiers";
|
||||
import { normalizeImageValue, type ImageCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { modelCapabilityConfigFor, normalizeImageValue, type ImageCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { mergedImageCapabilityConfig } from "@/lib/model-selection";
|
||||
import { type AiConfig } from "@/stores/use-config-store";
|
||||
import { modelOptionName, resolveModelChannel, type AiConfig } from "@/stores/use-config-store";
|
||||
|
||||
const qualityOptions = [
|
||||
{ value: "auto", label: "自动" },
|
||||
@@ -74,7 +74,8 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
|
||||
: imageAspectOptions(profile);
|
||||
const selectedAspect = availableAspects.find((item) => imageOptionValue(profile, item) === activeSize || item.value === activeSize) || availableAspects.find((item) => item.label === activeRatio);
|
||||
const dimensions = readSizeDimensions(activeSize, selectedAspect || aspectOptions[0]);
|
||||
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
|
||||
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
|
||||
const priceTiers = imageModelPriceTiers(config);
|
||||
const selectAspect = (value: string) => {
|
||||
const option = availableAspects.find((item) => item.value === value);
|
||||
onConfigChange("size", option ? imageOptionValue(profile, option) : "auto");
|
||||
@@ -110,8 +111,8 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
|
||||
{profile.quality.supported ? <div className="space-y-2">
|
||||
<SettingTitle color={theme.node.muted}>{isGrokResolutionQuality(profile) ? "分辨率" : "质量"}</SettingTitle>
|
||||
<div className={`grid gap-1.5 ${activeQualityOptions.length <= 2 ? "grid-cols-2" : "grid-cols-4"}`}>
|
||||
{activeQualityOptions.map((item) => (
|
||||
<OptionPill key={item.value} selected={quality === item.value} theme={theme} onClick={() => onConfigChange("quality", item.value)}>
|
||||
{activeQualityOptions.map((item) => (
|
||||
<OptionPill key={item.value} selected={quality === item.value} disabled={!hasPriceTierForImageSelection(priceTiers, item.value, activeSize)} theme={theme} onClick={() => onConfigChange("quality", item.value)}>
|
||||
{item.label}
|
||||
</OptionPill>
|
||||
))}
|
||||
@@ -262,12 +263,27 @@ export function imageSizeLabel(size: string) {
|
||||
return resolutionLabel !== size ? resolutionLabel : aspectOptions.find((item) => (item.size || item.value) === size || item.value === size)?.label || size;
|
||||
}
|
||||
|
||||
function OptionPill({ selected, theme, onClick, children }: { selected: boolean; theme: CanvasTheme; onClick: () => void; children: ReactNode }) {
|
||||
function imageModelPriceTiers(config: AiConfig) {
|
||||
const channel = resolveModelChannel(config, config.model || config.imageModel);
|
||||
const cost = channel.modelCosts?.find((item) => item.model === modelOptionName(config.model || config.imageModel));
|
||||
return cost?.logicalPriceTiers || [];
|
||||
}
|
||||
|
||||
function hasPriceTierForImageSelection(tiers: ReturnType<typeof imageModelPriceTiers>, quality: string, size: string) {
|
||||
if (!tiers.length) return true;
|
||||
return tiers.some((tier) => {
|
||||
const selector = tier.selector || {};
|
||||
return (!selector.quality || selector.quality === "*" || selector.quality === quality.toLowerCase()) && (!selector.size || selector.size === "*" || selector.size === size.toLowerCase());
|
||||
});
|
||||
}
|
||||
|
||||
function OptionPill({ selected, disabled = false, theme, onClick, children }: { selected: boolean; disabled?: boolean; theme: CanvasTheme; onClick: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="h-8 cursor-pointer rounded-full px-2 text-xs transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1"
|
||||
style={{ background: selected ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }}
|
||||
className="h-8 cursor-pointer rounded-full px-2 text-xs transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
style={{ background: selected ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }}
|
||||
disabled={disabled}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onClick={onClick}
|
||||
>
|
||||
|
||||
@@ -4,12 +4,14 @@ import { Popover } from "antd";
|
||||
|
||||
import { canvasThemes, type CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { modelCapabilityConfigFor, videoDurationOptions } from "@/lib/model-capabilities";
|
||||
import { compatibleModelInGroup, configuredModelDisplayName, groupModelsByDisplayName, modelCompatibilityError, resolveCompatibleModel, type ModelRequirements } from "@/lib/model-selection";
|
||||
import { compatibleModelInGroup, configuredModelDisplayName, groupModelsByDisplayName, modelCompatibilityError, modelRequestOptions, resolveCompatibleModel, type ModelRequirements } from "@/lib/model-selection";
|
||||
import { normalizeVideoResolution } from "@/lib/video-generation-options";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { modelDisplayName, modelIcon, modelOptionName, PUBLIC_MODEL_CATALOG_ID, resolveModelChannel, selectableModelsByCapability, type AiConfig, type ModelCapability } from "@/stores/use-config-store";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
import { ModelLogo } from "@/components/model-logo";
|
||||
import { quoteLogicalModel, type LogicalModelQuote, type ModelRequestIntent } from "@/services/api/logical-models";
|
||||
|
||||
type ModelPickerProps = {
|
||||
config: AiConfig;
|
||||
@@ -53,12 +55,31 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
|
||||
return channelGroups;
|
||||
}, [config, options]);
|
||||
const storedCurrent = value?.trim() || "";
|
||||
const resolvedCurrent = resolveCompatibleModel(config, storedCurrent, requirements) || storedCurrent;
|
||||
// 参数档位会在选中模型后由调用方归一到其能力配置,不能因为旧模型留下的参数而禁止切换。
|
||||
const selectionRequirements = requirements ? { ...requirements, videoSeconds: undefined, imageSize: undefined, options: undefined } : undefined;
|
||||
const resolvedCurrent = resolveCompatibleModel(config, storedCurrent, selectionRequirements) || storedCurrent;
|
||||
// 旧画布可能保存过已下架或前端历史内置模型;它们不能重新进入当前可选目录。
|
||||
const current = options.includes(resolvedCurrent) ? resolvedCurrent : "";
|
||||
const currentPrice = modelMenuPrice(config, current);
|
||||
const currentPrice = modelMenuPrice(config, current, capability);
|
||||
const quoteRequest = useMemo(() => modelQuoteRequest(config, current, capability, requirements), [capability, config, current, requirements]);
|
||||
const [routeQuote, setRouteQuote] = useState<LogicalModelQuote | undefined>();
|
||||
const creationVariant = variant === "creation";
|
||||
|
||||
useEffect(() => {
|
||||
if (!showSelectedPrice || !creditsEnabled || !quoteRequest) {
|
||||
setRouteQuote(undefined);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setRouteQuote(undefined);
|
||||
quoteLogicalModel(quoteRequest.logicalModelID, quoteRequest.intent, controller.signal)
|
||||
.then((payload) => setRouteQuote(payload.quote))
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setRouteQuote(undefined);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [creditsEnabled, quoteRequest, showSelectedPrice]);
|
||||
|
||||
useEffect(() => {
|
||||
const closeOtherPicker = (event: Event) => {
|
||||
if ((event as CustomEvent<string>).detail !== pickerId) setOpen(false);
|
||||
@@ -141,26 +162,28 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
|
||||
<div className="grid min-w-0 gap-1">
|
||||
{group.models.map((modelGroup) => {
|
||||
const selected = modelGroup.models.includes(current);
|
||||
const compatibleModel = compatibleModelInGroup(config, modelGroup.models, requirements, selected ? current : undefined);
|
||||
const model = compatibleModel || modelGroup.models[0];
|
||||
const displayModel = model;
|
||||
const incompatibleReason = compatibleModel ? "" : modelCompatibilityError(config, modelGroup.models[0], requirements) || "当前输入不符合该模型能力,切换后将重置参数";
|
||||
const model = compatibleModelInGroup(config, modelGroup.models, selectionRequirements, selected ? current : undefined);
|
||||
const displayModel = model || (selected ? current : modelGroup.models[0]);
|
||||
const disabledReason = model ? "" : modelCompatibilityError(config, modelGroup.models[0], selectionRequirements) || "当前输入不符合该模型能力";
|
||||
return (
|
||||
<button
|
||||
key={modelGroup.key}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
title={incompatibleReason || pickerModelOptionLabel(config, displayModel, showConfiguredModelName)}
|
||||
className="canvas-model-picker-option"
|
||||
style={{ background: "transparent", color: theme.node.text }}
|
||||
aria-disabled={Boolean(disabledReason)}
|
||||
disabled={Boolean(disabledReason)}
|
||||
title={disabledReason || pickerModelOptionLabel(config, displayModel, showConfiguredModelName)}
|
||||
className="canvas-model-picker-option disabled:cursor-not-allowed disabled:opacity-45"
|
||||
style={{ background: selected ? theme.toolbar.activeBg : "transparent", color: theme.node.text }}
|
||||
onClick={() => {
|
||||
if (!model) return;
|
||||
onChange(model);
|
||||
setOpen(false);
|
||||
window.requestAnimationFrame(() => triggerRef.current?.focus());
|
||||
}}
|
||||
>
|
||||
<ModelLabel config={config} model={displayModel} capability={capability} theme={theme} creationVariant={creationVariant} showConfiguredModelName={showConfiguredModelName} showPrice={creditsEnabled} disabledReason={incompatibleReason} />
|
||||
<ModelLabel config={config} model={displayModel} capability={capability} theme={theme} creationVariant={creationVariant} showConfiguredModelName={showConfiguredModelName} showPrice={creditsEnabled} disabledReason={disabledReason} />
|
||||
{selected ? <Check className="canvas-model-picker-option-check" style={{ color: theme.node.activeStroke }} /> : null}
|
||||
</button>
|
||||
);
|
||||
@@ -206,7 +229,7 @@ export function ModelPicker({ config, value, onChange, capability, className, fu
|
||||
<ModelIcon config={config} model={current} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate">{current ? (creationVariant ? pickerModelDisplayName(config, current, showConfiguredModelName) : pickerModelOptionLabel(config, current, showConfiguredModelName)) : placeholder}</span>
|
||||
{showSelectedPrice && creditsEnabled ? <ModelPrice price={currentPrice} compact /> : null}
|
||||
{showSelectedPrice && creditsEnabled ? <ModelPrice price={currentPrice} quote={routeQuote} compact /> : null}
|
||||
</span>
|
||||
<ChevronDown className={cn("canvas-model-picker-chevron", open && "is-open")} aria-hidden="true" />
|
||||
</button>
|
||||
@@ -257,7 +280,7 @@ function ModelLabel({
|
||||
{capabilitySummary}
|
||||
</span>
|
||||
</span>
|
||||
{showPrice ? <ModelPrice price={modelMenuPrice(config, model)} /> : null}
|
||||
{showPrice ? <ModelPrice price={modelMenuPrice(config, model, capability, true)} /> : null}
|
||||
{!creationVariant && meta.time ? (
|
||||
<span className="shrink-0 rounded-full px-1.5 py-0.5 text-[var(--fs-tiny)] tabular-nums" style={{ background: theme.toolbar.itemHover, color: theme.node.muted }}>
|
||||
{meta.time}
|
||||
@@ -326,17 +349,24 @@ function formatDurationSummary(profile: NonNullable<ReturnType<typeof modelCapab
|
||||
return `${profile.duration.min || values[0]}-${profile.duration.max || values[values.length - 1]}s`;
|
||||
}
|
||||
|
||||
type ModelMenuPrice = { value: number; unit: "次" | "秒" | "百万 Token" };
|
||||
type ModelMenuPrice =
|
||||
| { kind: "tiers"; label: string; compactLabel: string; title: string }
|
||||
| { kind: "estimate" }
|
||||
| { kind: "fixed"; value: number; unit: "次" | "秒" | "百万 Token" };
|
||||
|
||||
function modelMenuPrice(config: AiConfig, model: string): ModelMenuPrice | null | undefined {
|
||||
function modelMenuPrice(config: AiConfig, model: string, capability?: ModelCapability, summary = false): ModelMenuPrice | null | undefined {
|
||||
if (!model) return undefined;
|
||||
const channel = resolveModelChannel(config, model);
|
||||
const cost = channel.modelCosts?.find((item) => item.model === modelOptionName(model));
|
||||
if (!cost) return channel.scope === "system" ? null : undefined;
|
||||
if (cost.billingMode === "token") {
|
||||
return { value: (cost.outputTokenPriceMicrocredits || 0) / 1_000_000, unit: "百万 Token" };
|
||||
if (cost.pricePolicy === "channel") {
|
||||
const tiers = cost.logicalPriceTiers || [];
|
||||
if (!tiers.length) return null;
|
||||
const matched = summary ? tiers : priceTiersForCurrentSelection(tiers, capability, config);
|
||||
return channelTierPriceSummary(matched.length ? matched : tiers, tiers);
|
||||
}
|
||||
return { value: cost.unitPriceMicrocredits / 1_000_000, unit: cost.billingMode === "per_second" ? "秒" : "次" };
|
||||
if (cost.billingMode === "token") return { kind: "estimate" };
|
||||
return { kind: "fixed", value: cost.unitPriceMicrocredits / 1_000_000, unit: cost.billingMode === "per_second" ? "秒" : "次" };
|
||||
}
|
||||
|
||||
function pickerModelDisplayName(config: AiConfig, model: string, showConfiguredModelName: boolean) {
|
||||
@@ -349,9 +379,131 @@ function pickerModelOptionLabel(config: AiConfig, model: string, showConfiguredM
|
||||
return channel.scope === "system" ? displayName : `${displayName}(${channel.name})`;
|
||||
}
|
||||
|
||||
function ModelPrice({ price, compact = false }: { price: ModelMenuPrice | null | undefined; compact?: boolean }) {
|
||||
function priceTiersForCurrentSelection(
|
||||
tiers: NonNullable<NonNullable<AiConfig["channels"][number]["modelCosts"]>[number]["logicalPriceTiers"]>,
|
||||
capability: ModelCapability | undefined,
|
||||
config: AiConfig,
|
||||
) {
|
||||
const requested: Record<string, string> = {};
|
||||
if (capability === "video") {
|
||||
const resolution = normalizeTierResolution(config.vquality);
|
||||
if (resolution !== "*") requested.vquality = resolution;
|
||||
const seconds = Math.max(0, Math.floor(Number(config.videoSeconds) || 0));
|
||||
if (seconds > 0) requested.videoSeconds = String(seconds);
|
||||
}
|
||||
if (capability === "image") {
|
||||
if (config.quality && config.quality !== "auto") requested.quality = config.quality.toLowerCase();
|
||||
if (config.size && config.size !== "auto") requested.size = config.size.toLowerCase();
|
||||
}
|
||||
let bestScore = -1;
|
||||
let matched: typeof tiers = [];
|
||||
for (const tier of tiers) {
|
||||
const selector = tier.selector || {};
|
||||
const conditions = Object.entries(selector).filter(([, value]) => value && value !== "*");
|
||||
if (conditions.some(([key, value]) => requested[key] !== value)) continue;
|
||||
const score = conditions.length;
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
matched = [tier];
|
||||
} else if (score === bestScore) {
|
||||
matched.push(tier);
|
||||
}
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
|
||||
function normalizeTierResolution(value: string) {
|
||||
const raw = String(value || "").trim();
|
||||
if (!raw || raw === "*") return "*";
|
||||
return `${normalizeVideoResolution(raw)}p`;
|
||||
}
|
||||
|
||||
function channelTierPriceSummary(
|
||||
visibleTiers: NonNullable<NonNullable<AiConfig["channels"][number]["modelCosts"]>[number]["logicalPriceTiers"]>,
|
||||
allTiers: NonNullable<NonNullable<AiConfig["channels"][number]["modelCosts"]>[number]["logicalPriceTiers"]>,
|
||||
): Extract<ModelMenuPrice, { kind: "tiers" }> {
|
||||
const fixedRequestValues = visibleTiers
|
||||
.filter((tier) => tier.billingMode === "fixed_request")
|
||||
.map((tier) => tier.unitPriceMicrocredits / 1_000_000)
|
||||
.filter((value) => value > 0);
|
||||
const perSecondValues = visibleTiers
|
||||
.filter((tier) => tier.billingMode === "per_second")
|
||||
.map((tier) => tier.unitPriceMicrocredits / 1_000_000)
|
||||
.filter((value) => value > 0);
|
||||
const hasTokenTier = visibleTiers.some((tier) => tier.billingMode === "token");
|
||||
const label = fixedRequestValues.length
|
||||
? formatPriceRange(fixedRequestValues, "积分")
|
||||
: perSecondValues.length
|
||||
? formatPriceRange(perSecondValues, "积分/秒")
|
||||
: hasTokenTier
|
||||
? "按量预估"
|
||||
: "未配置";
|
||||
return {
|
||||
kind: "tiers",
|
||||
label,
|
||||
compactLabel: label,
|
||||
title: `系统规格价格:${allTiers.map((tier) => `${tierSpecificationLabel(tier)} ${tierPriceLabel(tier)}`).join(";")}`,
|
||||
};
|
||||
}
|
||||
|
||||
function formatPriceRange(values: number[], suffix: string) {
|
||||
const unique = Array.from(new Set(values)).sort((left, right) => left - right);
|
||||
const format = (value: number) => value.toLocaleString("zh-CN", { maximumFractionDigits: 3 });
|
||||
return unique.length === 1 ? `${format(unique[0])} ${suffix}` : `${format(unique[0])}-${format(unique[unique.length - 1])} ${suffix}`;
|
||||
}
|
||||
|
||||
function tierResolutionLabel(value: string) {
|
||||
const normalized = normalizeTierResolution(value);
|
||||
return normalized === "*" ? "全部分辨率" : normalized.toUpperCase();
|
||||
}
|
||||
|
||||
function tierDurationLabel(seconds: number) {
|
||||
return seconds > 0 ? `${seconds} 秒` : "全部时长";
|
||||
}
|
||||
|
||||
function tierSpecificationLabel(tier: NonNullable<NonNullable<AiConfig["channels"][number]["modelCosts"]>[number]["logicalPriceTiers"]>[number]) {
|
||||
const selector = tier.selector || {};
|
||||
const operationLabels: Record<string, string> = { text_to_image: "文生图", image_to_image: "图生图", text_to_video: "文生视频", image_to_video: "图生视频", video_to_video: "视频生视频" };
|
||||
const operation = selector.operation && selector.operation !== "*" ? (operationLabels[selector.operation] || selector.operation) : "";
|
||||
const details = [
|
||||
operation,
|
||||
selector.quality && selector.quality !== "*" ? selector.quality.toUpperCase() : "",
|
||||
selector.size && selector.size !== "*" ? selector.size : "",
|
||||
tier.resolution !== "*" ? tierResolutionLabel(tier.resolution) : "",
|
||||
tier.videoSeconds ? tierDurationLabel(tier.videoSeconds) : "",
|
||||
].filter(Boolean);
|
||||
return details.length ? details.join(" / ") : "默认规格";
|
||||
}
|
||||
|
||||
function tierPriceLabel(tier: NonNullable<NonNullable<AiConfig["channels"][number]["modelCosts"]>[number]["logicalPriceTiers"]>[number]) {
|
||||
if (tier.billingMode === "token") return "按量预估";
|
||||
return `${formatPriceRange([tier.unitPriceMicrocredits / 1_000_000], tier.billingMode === "per_second" ? "积分/秒" : "积分")}`;
|
||||
}
|
||||
|
||||
function ModelPrice({ price, quote, compact = false }: { price: ModelMenuPrice | null | undefined; quote?: LogicalModelQuote; compact?: boolean }) {
|
||||
if (quote) {
|
||||
const amount = (quote.amountMicrocredits / 1_000_000).toLocaleString("zh-CN", { maximumFractionDigits: 3 });
|
||||
const label = quote.estimated ? `预计 ${amount}` : `${amount}`;
|
||||
return (
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5 text-[var(--fs-tiny)] font-bold tabular-nums text-amber-600 dark:text-amber-300" title={`${quote.estimated ? "预计" : "本次"}消耗 ${amount} 积分`}>
|
||||
<Coins className="size-3" />
|
||||
{compact ? label : `${label} 积分`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (price === undefined) return null;
|
||||
if (price === null) return compact ? null : <span className="shrink-0 text-[var(--fs-tiny)] text-foreground/40">未配置</span>;
|
||||
if (price.kind === "tiers") {
|
||||
return (
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5 text-[var(--fs-tiny)] font-bold tabular-nums text-amber-600 dark:text-amber-300" title={price.title}>
|
||||
<Coins className="size-3" />
|
||||
{compact ? price.compactLabel : price.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (price.kind === "estimate") {
|
||||
return <span className="shrink-0 text-[var(--fs-tiny)] font-medium text-amber-600 dark:text-amber-300">按量预估</span>;
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex shrink-0 items-center gap-0.5 text-[var(--fs-tiny)] font-bold tabular-nums text-amber-600 dark:text-amber-300" title={`每${price.unit}消耗 ${price.value.toLocaleString("zh-CN", { maximumFractionDigits: 6 })} 积分`}>
|
||||
<Coins className="size-3" />
|
||||
@@ -360,6 +512,31 @@ function ModelPrice({ price, compact = false }: { price: ModelMenuPrice | null |
|
||||
);
|
||||
}
|
||||
|
||||
function modelQuoteRequest(config: AiConfig, value: string, capability?: ModelCapability, requirements?: ModelRequirements): { logicalModelID: string; intent: ModelRequestIntent } | undefined {
|
||||
if (!capability || !value) return undefined;
|
||||
const channel = resolveModelChannel(config, value);
|
||||
if (channel.scope !== "system") return undefined;
|
||||
const cost = channel.modelCosts?.find((item) => item.model === modelOptionName(value));
|
||||
if (!cost?.logicalModelId) return undefined;
|
||||
const input = requirements?.input;
|
||||
const intent: ModelRequestIntent = {
|
||||
capability,
|
||||
operation: requirements?.videoOperation,
|
||||
inputs: {
|
||||
image: (input?.imageCount || 0) + (input?.characterCount || 0),
|
||||
video: input?.videoCount || 0,
|
||||
audio: input?.audioCount || 0,
|
||||
},
|
||||
options: {
|
||||
...modelRequestOptions(config, capability),
|
||||
...(requirements?.options || {}),
|
||||
...(requirements?.videoSeconds ? { videoSeconds: Number(requirements.videoSeconds) } : {}),
|
||||
...(requirements?.imageSize ? { size: requirements.imageSize } : {}),
|
||||
},
|
||||
};
|
||||
return { logicalModelID: cost.logicalModelId, intent };
|
||||
}
|
||||
|
||||
function modelMenuMeta(model: string, capability?: ModelCapability): { description: string; time?: string } {
|
||||
const name = modelOptionName(model).toLowerCase();
|
||||
if (capability === "image") {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { boolConfig, isSeedanceFastModel, isSeedanceVideoConfig, normalizeSeedan
|
||||
import { type CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { normalizeVideoDuration, normalizeVideoResolution, VIDEO_DURATION_MIN } from "@/lib/video-generation-options";
|
||||
import { modelCapabilityConfigFor, videoDurationOptions, type VideoCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { modelOptionName, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { modelOptionName, resolveModelChannel, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
|
||||
const sizeOptions = [
|
||||
{ value: "1280x720", label: "横屏", width: 1280, height: 720 },
|
||||
@@ -27,11 +27,12 @@ type VideoSettingsPanelProps = {
|
||||
|
||||
export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle = true, className = "w-[292px] space-y-3" }: VideoSettingsPanelProps) {
|
||||
const profile = modelCapabilityConfigFor(config, config.model).video!;
|
||||
const priceTiers = modelPriceTiers(config);
|
||||
if (resolveModelRequestConfig(config, config.model).interfaceType === "volcengine-jimeng-video") {
|
||||
return <JiMengVideoSettingsPanel config={config} profile={profile} onConfigChange={onConfigChange} theme={theme} showTitle={showTitle} className={className} />;
|
||||
return <JiMengVideoSettingsPanel config={config} profile={profile} priceTiers={priceTiers} onConfigChange={onConfigChange} theme={theme} showTitle={showTitle} className={className} />;
|
||||
}
|
||||
if (isSeedanceVideoConfig(config)) {
|
||||
return <SeedanceVideoSettingsPanel config={config} profile={profile} onConfigChange={onConfigChange} theme={theme} showTitle={showTitle} className={className} />;
|
||||
return <SeedanceVideoSettingsPanel config={config} profile={profile} priceTiers={priceTiers} onConfigChange={onConfigChange} theme={theme} showTitle={showTitle} className={className} />;
|
||||
}
|
||||
|
||||
const seconds = normalizeVideoDuration(config.videoSeconds);
|
||||
@@ -53,7 +54,7 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
|
||||
{configuredResolutions.length ? <SettingGroup title="分辨率" color={theme.node.muted}>
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{configuredResolutions.map((item) => (
|
||||
<OptionPill key={item.value} selected={resolution === item.value} theme={theme} onClick={() => onConfigChange("vquality", item.value)}>
|
||||
<OptionPill key={item.value} selected={resolution === item.value} disabled={!hasPriceTierForVideoSelection(priceTiers, item.value, Number(seconds))} theme={theme} onClick={() => onConfigChange("vquality", item.value)}>
|
||||
{item.label}
|
||||
</OptionPill>
|
||||
))}
|
||||
@@ -82,7 +83,7 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
|
||||
</div>
|
||||
</SettingGroup>
|
||||
<SettingGroup title="秒数" color={theme.node.muted}>
|
||||
<VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
<VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} disabled={(value) => !hasPriceTierForVideoSelection(priceTiers, resolution, value)} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
</SettingGroup>
|
||||
{profile.generateAudio.supported || profile.watermark.supported ? <SettingGroup title="输出" color={theme.node.muted}><div className="grid grid-cols-2 gap-3 rounded-md px-2" style={{ background: theme.toolbar.itemHover }}>{profile.generateAudio.supported ? <SwitchRow label="生成声音" checked={generateAudio} theme={theme} onChange={(checked) => onConfigChange("videoGenerateAudio", String(checked))} /> : null}{profile.watermark.supported ? <SwitchRow label="添加水印" checked={watermark} theme={theme} onChange={(checked) => onConfigChange("videoWatermark", String(checked))} /> : null}</div></SettingGroup> : null}
|
||||
</div>
|
||||
@@ -90,7 +91,7 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
|
||||
);
|
||||
}
|
||||
|
||||
function JiMengVideoSettingsPanel({ config, profile, onConfigChange, theme, showTitle, className }: VideoSettingsPanelProps & { profile: VideoCapabilityConfig }) {
|
||||
function JiMengVideoSettingsPanel({ config, profile, priceTiers, onConfigChange, theme, showTitle, className }: VideoSettingsPanelProps & { profile: VideoCapabilityConfig; priceTiers: ReturnType<typeof modelPriceTiers> }) {
|
||||
const seconds = normalizeVideoDuration(config.videoSeconds);
|
||||
return (
|
||||
<ImageSettingsTheme theme={theme}>
|
||||
@@ -102,14 +103,14 @@ function JiMengVideoSettingsPanel({ config, profile, onConfigChange, theme, show
|
||||
</div>
|
||||
</SettingGroup>
|
||||
<SettingGroup title="秒数" color={theme.node.muted}>
|
||||
<VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
<VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} disabled={(value) => !hasPriceTierForVideoSelection(priceTiers, "*", value)} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
</SettingGroup>
|
||||
</div>
|
||||
</ImageSettingsTheme>
|
||||
);
|
||||
}
|
||||
|
||||
function SeedanceVideoSettingsPanel({ config, profile, onConfigChange, theme, showTitle, className }: VideoSettingsPanelProps & { profile: VideoCapabilityConfig }) {
|
||||
function SeedanceVideoSettingsPanel({ config, profile, priceTiers, onConfigChange, theme, showTitle, className }: VideoSettingsPanelProps & { profile: VideoCapabilityConfig; priceTiers: ReturnType<typeof modelPriceTiers> }) {
|
||||
const model = modelOptionName(config.model || config.videoModel);
|
||||
const resolution = normalizeSeedanceResolution(config.vquality, model);
|
||||
const ratio = normalizeSeedanceRatio(config.size);
|
||||
@@ -125,7 +126,7 @@ function SeedanceVideoSettingsPanel({ config, profile, onConfigChange, theme, sh
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{profile.resolutions.map((value) => {
|
||||
const item = { value, label: value.toUpperCase() };
|
||||
const disabled = item.value === "1080p" && isSeedanceFastModel(model);
|
||||
const disabled = (item.value === "1080p" && isSeedanceFastModel(model)) || !hasPriceTierForVideoSelection(priceTiers, item.value, duration);
|
||||
return (
|
||||
<OptionPill key={item.value} selected={resolution === item.value} disabled={disabled} theme={theme} onClick={() => onConfigChange("vquality", item.value)}>
|
||||
{item.label}
|
||||
@@ -158,7 +159,7 @@ function SeedanceVideoSettingsPanel({ config, profile, onConfigChange, theme, sh
|
||||
</div>
|
||||
</SettingGroup>
|
||||
<SettingGroup title="时长" color={theme.node.muted}>
|
||||
<VideoDurationControl profile={profile} value={duration} theme={theme} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
<VideoDurationControl profile={profile} value={duration} theme={theme} disabled={(value) => !hasPriceTierForVideoSelection(priceTiers, resolution, value)} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
|
||||
</SettingGroup>
|
||||
<SettingGroup title="输出" color={theme.node.muted}>
|
||||
<div className="grid grid-cols-2 gap-3 rounded-md px-2" style={{ background: theme.toolbar.itemHover }}>
|
||||
@@ -256,21 +257,44 @@ function DurationInput({ value, min, max, theme, onChange }: { value: number; mi
|
||||
);
|
||||
}
|
||||
|
||||
function VideoDurationControl({ profile, value, theme, onChange }: { profile: VideoCapabilityConfig; value: number; theme: CanvasTheme; onChange: (value: number) => void }) {
|
||||
function VideoDurationControl({ profile, value, theme, disabled, onChange }: { profile: VideoCapabilityConfig; value: number; theme: CanvasTheme; disabled?: (value: number) => boolean; onChange: (value: number) => void }) {
|
||||
if (profile.duration.selection === "range") {
|
||||
const min = profile.duration.min || VIDEO_DURATION_MIN;
|
||||
const max = Math.max(min, profile.duration.max || min);
|
||||
const step = Math.max(1, profile.duration.step || 1);
|
||||
const normalized = normalizeDurationValue(value, profile.duration.default, min, max, step);
|
||||
return <DurationRangeControl value={normalized} min={min} max={max} step={step} theme={theme} onChange={onChange} />;
|
||||
return <DurationRangeControl value={normalized} min={min} max={max} step={step} theme={theme} onChange={(next) => { if (!disabled?.(next)) onChange(next); }} />;
|
||||
}
|
||||
|
||||
const options = videoDurationOptions(profile);
|
||||
return <div className="grid gap-1.5" style={{ gridTemplateColumns: `repeat(${Math.min(options.length, 4)}, minmax(0, 1fr))` }}>
|
||||
{options.map((option) => <OptionPill key={option} selected={normalizedNumber(value) === option} theme={theme} onClick={() => onChange(option)}>{option}s</OptionPill>)}
|
||||
{options.map((option) => <OptionPill key={option} selected={normalizedNumber(value) === option} disabled={disabled?.(option)} theme={theme} onClick={() => onChange(option)}>{option}s</OptionPill>)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function modelPriceTiers(config: AiConfig) {
|
||||
const channel = resolveModelChannel(config, config.model);
|
||||
const cost = channel.modelCosts?.find((item) => item.model === modelOptionName(config.model));
|
||||
return cost?.logicalPriceTiers || [];
|
||||
}
|
||||
|
||||
function hasPriceTierForVideoSelection(tiers: ReturnType<typeof modelPriceTiers>, resolution: string, seconds: number) {
|
||||
if (!tiers.length) return true;
|
||||
const normalizedResolution = normalizeTierResolution(resolution);
|
||||
return tiers.some((tier) => {
|
||||
const selector = tier.selector || {};
|
||||
const tierResolution = selector.vquality || tier.resolution;
|
||||
const tierSeconds = selector.videoSeconds ? Number(selector.videoSeconds) : tier.videoSeconds;
|
||||
return (tierResolution === "*" || !tierResolution || normalizeTierResolution(tierResolution) === normalizedResolution) && (!tierSeconds || tierSeconds === seconds);
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTierResolution(value: string) {
|
||||
const normalized = normalizeVideoResolution(value);
|
||||
if (/^\d+$/.test(normalized)) return `${normalized}p`;
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
|
||||
function DurationRangeControl({ value, min, max, step, theme, onChange }: { value: number; min: number; max: number; step: number; theme: CanvasTheme; onChange: (value: number) => void }) {
|
||||
return <div className="space-y-1.5">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
|
||||
@@ -145,7 +145,10 @@ function logicalModelCompatibilityError(spec: NonNullable<NonNullable<AiConfig["
|
||||
}
|
||||
|
||||
function logicalOptionMatches(name: string, constraint: { values?: unknown[]; min?: number; max?: number; step?: number }, value: unknown) {
|
||||
if (constraint.values?.length) return constraint.values.some((candidate) => logicalOptionValueMatches(name, candidate, value));
|
||||
if (constraint.values?.length) {
|
||||
const requested = normalizeLogicalOptionValue(name, value);
|
||||
return constraint.values.some((candidate) => normalizeLogicalOptionValue(name, candidate) === requested);
|
||||
}
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric)) return false;
|
||||
if (constraint.min !== undefined && numeric < constraint.min) return false;
|
||||
@@ -154,11 +157,15 @@ function logicalOptionMatches(name: string, constraint: { values?: unknown[]; mi
|
||||
return true;
|
||||
}
|
||||
|
||||
function logicalOptionValueMatches(name: string, candidate: unknown, value: unknown) {
|
||||
const left = String(candidate).trim().toLowerCase();
|
||||
const right = String(value).trim().toLowerCase();
|
||||
if (name === "vquality" || name === "resolution") return left.replace(/p$/, "") === right.replace(/p$/, "");
|
||||
return left === right;
|
||||
function normalizeLogicalOptionValue(name: string, value: unknown) {
|
||||
const normalized = String(value).trim().toLowerCase();
|
||||
if (name !== "vquality" && name !== "resolution") return normalized;
|
||||
if (normalized === "low") return "480p";
|
||||
if (["auto", "medium", "high"].includes(normalized)) return "720p";
|
||||
if (normalized === "2k") return "1440p";
|
||||
if (normalized === "4k") return "2160p";
|
||||
const resolution = normalized.replace(/p$/i, "");
|
||||
return resolution ? `${resolution}p` : "";
|
||||
}
|
||||
|
||||
function logicalOptionError(name: string) {
|
||||
|
||||
@@ -81,6 +81,9 @@ function managedModelChannels(models: PublicLogicalModel[]) {
|
||||
scope: "system",
|
||||
enabled: true,
|
||||
models: availableModels.map((item) => item.id),
|
||||
modelAliases: Object.fromEntries(
|
||||
availableModels.flatMap((item) => (item.legacyModelIds || []).map((legacyID) => [legacyID, item.id])),
|
||||
),
|
||||
modelCosts: availableModels.map((item) => ({
|
||||
model: item.id,
|
||||
displayName: item.name,
|
||||
@@ -97,6 +100,7 @@ function managedModelChannels(models: PublicLogicalModel[]) {
|
||||
logicalModelId: item.id,
|
||||
logicalCapabilitySpec: item.capabilitySpec,
|
||||
logicalCapabilityProfiles: item.capabilityProfiles,
|
||||
logicalPriceTiers: item.priceTiers,
|
||||
defaultOptions: item.defaultOptions,
|
||||
})),
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { App, Button, Drawer, Form, Input, InputNumber, Popconfirm, Segmented, Select, Space, Switch } from "antd";
|
||||
import { App, Button, Drawer, Form, Input, InputNumber, Popconfirm, Segmented, Select, Space, Switch, type FormInstance } from "antd";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import { FlaskConical, Plus, RefreshCw, Search, Trash2 } from "lucide-react";
|
||||
import { FlaskConical, Plus, RefreshCw, Search, Trash2, X } from "lucide-react";
|
||||
|
||||
import { PaginationBar } from "@/components/layout/workspace-page";
|
||||
import { ModelIcon } from "@/components/model-picker";
|
||||
@@ -9,7 +9,7 @@ import { ModelCapabilityEditor } from "@/components/model-capability-editor";
|
||||
import { CapabilityCardPicker, ProtocolCardPicker, type ModelCapabilityChoice } from "@/components/model-protocol-picker";
|
||||
import { defaultModelCapabilityConfig, normalizeModelCapabilityConfig, type ModelCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { MODEL_PROTOCOLS, modelProtocolCapability, modelProtocolDefinition, modelProtocolLabel, modelProtocolSupportsTokenBilling, type ModelProtocol } from "@/lib/model-protocols";
|
||||
import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, testAdminChannelModel, updateAdminChannelModel, type ChannelModel } from "@/services/api/wallet";
|
||||
import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, testAdminChannelModel, updateAdminChannelModel, type ChannelModel, type ChannelModelPriceTier } from "@/services/api/wallet";
|
||||
import type { ModelChannel } from "@/stores/use-config-store";
|
||||
import { AdminPageFrame } from "./admin-shell";
|
||||
import { AdminDataTable, AdminFilterChip, AdminStatusBadge } from "./admin-ui";
|
||||
@@ -18,16 +18,29 @@ type EditableCapability = ModelCapabilityChoice;
|
||||
|
||||
type FormValues = {
|
||||
modelKey: string;
|
||||
providerModelKey?: string;
|
||||
displayName?: string;
|
||||
capability: EditableCapability;
|
||||
protocol: ModelProtocol;
|
||||
priceTiers: PriceTierFormValues[];
|
||||
enabled: boolean;
|
||||
capabilityConfig?: ModelCapabilityConfig;
|
||||
};
|
||||
|
||||
type PriceTierFormValues = {
|
||||
operation: string;
|
||||
quality: string;
|
||||
size: string;
|
||||
resolution: string;
|
||||
videoSeconds: number;
|
||||
providerModelKey?: string;
|
||||
billingMode: ChannelModel["billingMode"];
|
||||
unitPrice: number;
|
||||
inputTokenPrice: number;
|
||||
outputTokenPrice: number;
|
||||
cachedTokenPrice: number;
|
||||
priceConfigured: boolean;
|
||||
enabled: boolean;
|
||||
capabilityConfig?: ModelCapabilityConfig;
|
||||
};
|
||||
|
||||
export function ChannelModelManager({ channel, onClose, onChanged }: { channel: ModelChannel; onClose: () => void; onChanged: () => void | Promise<void> }) {
|
||||
@@ -45,10 +58,11 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
const billingMode = Form.useWatch("billingMode", form) || "fixed_request";
|
||||
const modelCapability = Form.useWatch("capability", form);
|
||||
const modelProtocol = Form.useWatch("protocol", form);
|
||||
const modelKey = Form.useWatch("modelKey", form) || "";
|
||||
const providerModelKey = Form.useWatch("providerModelKey", form) || "";
|
||||
const capabilityConfig = Form.useWatch("capabilityConfig", form);
|
||||
|
||||
const reload = async () => {
|
||||
if (!channel) return;
|
||||
@@ -93,14 +107,11 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
setEditing(null);
|
||||
form.setFieldsValue({
|
||||
modelKey: "",
|
||||
providerModelKey: "",
|
||||
displayName: "",
|
||||
capability: "text",
|
||||
protocol: "chat-completion",
|
||||
billingMode: "fixed_request",
|
||||
unitPrice: 0,
|
||||
inputTokenPrice: 0,
|
||||
outputTokenPrice: 0,
|
||||
cachedTokenPrice: 0,
|
||||
priceTiers: [defaultPriceTier()],
|
||||
enabled: true,
|
||||
capabilityConfig: defaultModelCapabilityConfig("chat-completion", ""),
|
||||
});
|
||||
@@ -111,37 +122,48 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
setEditing(item);
|
||||
form.setFieldsValue({
|
||||
modelKey: item.modelKey,
|
||||
providerModelKey: item.providerModelKey || item.modelKey,
|
||||
displayName: item.displayName,
|
||||
capability: item.capability || undefined,
|
||||
protocol: item.protocol,
|
||||
billingMode: item.billingMode,
|
||||
unitPrice: item.unitPriceMicrocredits / 1_000_000,
|
||||
inputTokenPrice: item.inputTokenPriceMicrocredits / 1_000_000,
|
||||
outputTokenPrice: item.outputTokenPriceMicrocredits / 1_000_000,
|
||||
cachedTokenPrice: item.cachedTokenPriceMicrocredits / 1_000_000,
|
||||
priceTiers: item.priceTiers?.length ? item.priceTiers.map(priceTierToForm) : [legacyPriceTierToForm(item)],
|
||||
enabled: item.enabled,
|
||||
capabilityConfig: item.capability === "text" || item.capability === "image" || item.capability === "video" ? normalizeModelCapabilityConfig(item.capabilityConfig || defaultModelCapabilityConfig(item.protocol, item.modelKey)) : undefined,
|
||||
capabilityConfig: item.capability === "text" || item.capability === "image" || item.capability === "video"
|
||||
? normalizeModelCapabilityConfig(item.capabilityConfig, item.protocol, item.providerModelKey || item.modelKey, channel.apiFormat)
|
||||
: undefined,
|
||||
});
|
||||
setEditorOpen(true);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
const values = await form.validateFields();
|
||||
const upstreamModel = values.providerModelKey?.trim() || values.modelKey.trim();
|
||||
const capabilityConfig = values.capability === "text" || values.capability === "image" || values.capability === "video"
|
||||
? normalizeModelCapabilityConfig(values.capabilityConfig, values.protocol, upstreamModel, channel.apiFormat)
|
||||
: undefined;
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
modelKey: values.modelKey.trim(),
|
||||
providerModelKey: upstreamModel,
|
||||
displayName: values.displayName?.trim() || values.modelKey.trim(),
|
||||
capability: values.capability,
|
||||
protocol: values.protocol,
|
||||
billingMode: values.billingMode,
|
||||
unitPriceMicrocredits: Math.round(values.unitPrice * 1_000_000),
|
||||
inputTokenPriceMicrocredits: Math.round((values.inputTokenPrice || 0) * 1_000_000),
|
||||
outputTokenPriceMicrocredits: Math.round((values.outputTokenPrice || 0) * 1_000_000),
|
||||
cachedTokenPriceMicrocredits: Math.round((values.cachedTokenPrice || 0) * 1_000_000),
|
||||
priceConfigured: true,
|
||||
priceTiers: values.priceTiers.map((tier) => ({
|
||||
selector: skuSelectorFromForm(values.capability, tier),
|
||||
resolution: values.capability === "video" ? (tier.resolution || "*") : "*",
|
||||
videoSeconds: values.capability === "video" ? Number(tier.videoSeconds || 0) : 0,
|
||||
providerModelKey: tier.providerModelKey?.trim() || upstreamModel,
|
||||
billingMode: tier.billingMode,
|
||||
unitPriceMicrocredits: Math.round((tier.unitPrice || 0) * 1_000_000),
|
||||
inputTokenPriceMicrocredits: Math.round((tier.inputTokenPrice || 0) * 1_000_000),
|
||||
outputTokenPriceMicrocredits: Math.round((tier.outputTokenPrice || 0) * 1_000_000),
|
||||
cachedTokenPriceMicrocredits: Math.round((tier.cachedTokenPrice || 0) * 1_000_000),
|
||||
priceConfigured: tier.priceConfigured !== false,
|
||||
enabled: tier.enabled !== false,
|
||||
})),
|
||||
enabled: values.enabled !== false,
|
||||
capabilityConfig: values.capability === "text" || values.capability === "image" || values.capability === "video" ? normalizeModelCapabilityConfig(values.capabilityConfig!) : undefined,
|
||||
capabilityConfig,
|
||||
};
|
||||
if (editing) await updateAdminChannelModel(channel.id, editing.id, payload);
|
||||
else await createAdminChannelModel(channel.id, payload);
|
||||
@@ -158,14 +180,19 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
};
|
||||
|
||||
const testModel = async () => {
|
||||
const values = await form.validateFields(["modelKey", "capability", "protocol", ...(modelCapability === "text" || modelCapability === "image" || modelCapability === "video" ? ["capabilityConfig"] : [])]);
|
||||
const values = await form.validateFields(["modelKey", "providerModelKey", "capability", "protocol", ...(modelCapability === "text" || modelCapability === "image" || modelCapability === "video" ? ["capabilityConfig"] : [])]);
|
||||
const upstreamModel = values.providerModelKey?.trim() || values.modelKey.trim();
|
||||
const capabilityConfig = values.capability === "text" || values.capability === "image" || values.capability === "video"
|
||||
? normalizeModelCapabilityConfig(values.capabilityConfig, values.protocol, upstreamModel, channel.apiFormat)
|
||||
: undefined;
|
||||
setTesting(true);
|
||||
try {
|
||||
const result = await testAdminChannelModel(channel.id, {
|
||||
modelKey: values.modelKey.trim(),
|
||||
providerModelKey: upstreamModel,
|
||||
capability: values.capability,
|
||||
protocol: values.protocol,
|
||||
capabilityConfig: values.capabilityConfig ? normalizeModelCapabilityConfig(values.capabilityConfig) : undefined,
|
||||
capabilityConfig,
|
||||
});
|
||||
message.success(`模型测试通过,耗时 ${(result.durationMs / 1000).toFixed(2)} 秒`);
|
||||
} catch (error) {
|
||||
@@ -203,6 +230,16 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
form.setFieldValue("protocol", nextProtocol);
|
||||
form.setFieldValue("capabilityConfig", changed.capability === "text" || changed.capability === "image" || changed.capability === "video" ? defaultModelCapabilityConfig(nextProtocol, form.getFieldValue("modelKey")) : undefined);
|
||||
}
|
||||
const nextTiers = (form.getFieldValue("priceTiers") || []).map((tier: PriceTierFormValues) => ({
|
||||
...tier,
|
||||
operation: tier.operation || "*",
|
||||
quality: changed.capability === "image" ? tier.quality || "*" : "*",
|
||||
size: changed.capability === "image" ? tier.size || "*" : "*",
|
||||
resolution: changed.capability === "video" ? tier.resolution || "*" : "*",
|
||||
videoSeconds: changed.capability === "video" ? tier.videoSeconds || 0 : 0,
|
||||
billingMode: tier.billingMode === "per_second" && changed.capability !== "video" ? "fixed_request" : tier.billingMode,
|
||||
}));
|
||||
form.setFieldValue("priceTiers", nextTiers);
|
||||
};
|
||||
|
||||
const columns: ColumnsType<ChannelModel> = [
|
||||
@@ -216,6 +253,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{item.displayName || item.modelKey}</div>
|
||||
<div className="admin-monospace truncate text-xs text-foreground/45">{item.modelKey}</div>
|
||||
{item.providerModelKey && item.providerModelKey !== item.modelKey ? <div className="admin-monospace truncate text-xs text-foreground/35">上游:{item.providerModelKey}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
@@ -235,7 +273,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
<AdminStatusBadge label="待配置" tone="warning" />
|
||||
),
|
||||
},
|
||||
{ title: "计费", width: 220, render: (_, item) => (item.priceConfigured ? billingSummary(item) : <AdminStatusBadge label="未配置价格" tone="warning" />) },
|
||||
{ title: "规格价格", width: 280, render: (_, item) => (item.priceConfigured ? billingSummary(item) : <AdminStatusBadge label="未配置价格" tone="warning" />) },
|
||||
{ title: "版本", dataIndex: "priceVersion", width: 75, render: (value) => `v${value}` },
|
||||
{ title: "状态", dataIndex: "enabled", width: 85, render: (enabled) => <AdminStatusBadge label={enabled ? "启用" : "停用"} tone={enabled ? "success" : "neutral"} /> },
|
||||
{
|
||||
@@ -256,7 +294,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
|
||||
const filteredItems = items.filter((item) => {
|
||||
const query = keyword.trim().toLowerCase();
|
||||
if (query && !`${item.modelKey} ${item.displayName}`.toLowerCase().includes(query)) return false;
|
||||
if (query && !`${item.modelKey} ${item.providerModelKey} ${item.displayName}`.toLowerCase().includes(query)) return false;
|
||||
if (capability !== "all" && item.capability !== capability) return false;
|
||||
if (status === "enabled" && !item.enabled) return false;
|
||||
if (status === "disabled" && item.enabled) return false;
|
||||
@@ -361,17 +399,20 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-semibold">模型身份</h2>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Form.Item name="modelKey" label="模型标识" rules={[{ required: true, message: "请输入模型标识" }]}>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Form.Item name="modelKey" label="产品模型标识" rules={[{ required: true, message: "请输入产品模型标识" }]}>
|
||||
<Input
|
||||
prefix={
|
||||
<span className="grid size-6 place-items-center">
|
||||
<ModelIcon model={modelKey} />
|
||||
</span>
|
||||
}
|
||||
placeholder="例如:deepseek-chat、gpt-5、glm-4.5"
|
||||
placeholder="例如:seedance-2-5"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="providerModelKey" label="上游模型 ID">
|
||||
<Input placeholder="留空则使用产品模型标识" />
|
||||
</Form.Item>
|
||||
<Form.Item name="displayName" label="后台显示名称">
|
||||
<Input placeholder="不填则使用模型标识" />
|
||||
</Form.Item>
|
||||
@@ -392,48 +433,35 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
</div>
|
||||
{modelCapability === "text" || modelCapability === "image" || modelCapability === "video" ? (
|
||||
<Form.Item name="capabilityConfig" rules={[{ required: true, message: `请配置${capabilityLabel(modelCapability)}能力参数` }]}>
|
||||
<ModelCapabilityEditor capability={modelCapability} model={modelKey} protocol={form.getFieldValue("protocol")} />
|
||||
<ModelCapabilityEditor capability={modelCapability} model={providerModelKey || modelKey} protocol={form.getFieldValue("protocol")} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="admin-form-section">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-semibold">计费</h2>
|
||||
<h2 className="text-sm font-semibold">规格价格档</h2>
|
||||
</div>
|
||||
<Form.Item name="billingMode" label="计费方式" rules={[{ required: true }]}>
|
||||
<Segmented
|
||||
block
|
||||
options={[
|
||||
{ label: "按次计费", value: "fixed_request" },
|
||||
{ label: "按秒计费", value: "per_second", disabled: modelCapability !== "video" },
|
||||
{ label: "Token 计费", value: "token", disabled: !modelProtocolSupportsTokenBilling(modelCapability, modelProtocol) },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{billingMode === "token" ? (
|
||||
modelCapability === "video" ? (
|
||||
<Form.Item name="outputTokenPrice" label="视频 / 百万 Token" rules={[{ required: true, message: "请输入视频 Token 价格" }]}>
|
||||
<InputNumber style={{ width: "100%" }} min={0.000001} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<Form.Item name="inputTokenPrice" label="输入 / 百万 Token" rules={[{ required: true, message: "请输入输入价格" }]}>
|
||||
<InputNumber style={{ width: "100%" }} min={0} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
<Form.Item name="outputTokenPrice" label="输出 / 百万 Token" rules={[{ required: true, message: "请输入输出价格" }]}>
|
||||
<InputNumber style={{ width: "100%" }} min={0} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
<Form.Item name="cachedTokenPrice" label="缓存 / 百万 Token" rules={[{ required: true, message: "请输入缓存价格" }]}>
|
||||
<InputNumber style={{ width: "100%" }} min={0} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<Form.Item name="unitPrice" label={billingMode === "per_second" ? "每秒消耗积分" : "每次消耗积分"} rules={[{ required: true, message: "请输入积分价格" }]}>
|
||||
<InputNumber style={{ width: "100%" }} min={0} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.List name="priceTiers" rules={[{ validator: async (_, value) => { if (!value?.length) throw new Error("请至少配置一个价格档"); } }]}>
|
||||
{(fields, { add, remove }, { errors }) => (
|
||||
<div className="space-y-2">
|
||||
{fields.map((field, index) => (
|
||||
<PriceTierFields
|
||||
key={field.key}
|
||||
index={field.name}
|
||||
ordinal={index + 1}
|
||||
form={form}
|
||||
capability={modelCapability}
|
||||
protocol={modelProtocol}
|
||||
capabilityConfig={capabilityConfig}
|
||||
onRemove={() => remove(field.name)}
|
||||
/>
|
||||
))}
|
||||
<Button icon={<Plus className="size-4" />} onClick={() => add(defaultPriceTier())}>新增价格档</Button>
|
||||
<Form.ErrorList errors={errors} />
|
||||
</div>
|
||||
)}
|
||||
</Form.List>
|
||||
</section>
|
||||
|
||||
<section className="admin-form-section">
|
||||
@@ -454,25 +482,172 @@ function capabilityLabel(value: ChannelModel["capability"]) {
|
||||
return { text: "文本", image: "图片", video: "视频", audio: "音频", "": "待配置" }[value];
|
||||
}
|
||||
|
||||
function billingSummary(item: ChannelModel) {
|
||||
if (item.billingMode !== "token") {
|
||||
return `${formatCredits(item.unitPriceMicrocredits)} 积分 / ${item.billingMode === "per_second" ? "秒" : "次"}`;
|
||||
}
|
||||
function PriceTierFields({
|
||||
index,
|
||||
ordinal,
|
||||
form,
|
||||
capability,
|
||||
protocol,
|
||||
capabilityConfig,
|
||||
onRemove,
|
||||
}: {
|
||||
index: number;
|
||||
ordinal: number;
|
||||
form: FormInstance<FormValues>;
|
||||
capability: EditableCapability | undefined;
|
||||
protocol: ModelProtocol | undefined;
|
||||
capabilityConfig?: ModelCapabilityConfig;
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const billingMode = Form.useWatch(["priceTiers", index, "billingMode"], form) || "fixed_request";
|
||||
const video = capabilityConfig?.video;
|
||||
const resolutionOptions = video?.resolutions || [];
|
||||
const durationOptions = video?.duration.selection === "enum" ? video.duration.values || [] : [];
|
||||
const tokenEnabled = Boolean(capability && protocol && modelProtocolSupportsTokenBilling(capability, protocol));
|
||||
const isVideo = capability === "video";
|
||||
const isImage = capability === "image";
|
||||
const selectorColumnClass = isVideo || isImage ? "lg:col-span-3" : "lg:col-span-6";
|
||||
const controlsColumnClass = billingMode === "token" && !isVideo ? "lg:col-span-3" : "lg:col-span-5";
|
||||
return (
|
||||
<div className="text-xs leading-5">
|
||||
{item.capability === "video" ? (
|
||||
<div>视频 {formatCredits(item.outputTokenPriceMicrocredits)} / 百万</div>
|
||||
) : (
|
||||
<>
|
||||
<div>输入 {formatCredits(item.inputTokenPriceMicrocredits)} / 百万</div>
|
||||
<div>输出 {formatCredits(item.outputTokenPriceMicrocredits)} / 百万</div>
|
||||
<div>缓存 {formatCredits(item.cachedTokenPriceMicrocredits)} / 百万</div>
|
||||
</>
|
||||
)}
|
||||
<div className="rounded-md border border-border bg-muted/10 p-3">
|
||||
<div className="mb-2 flex items-center justify-between gap-3">
|
||||
<div className="text-sm font-medium">价格档 {ordinal}</div>
|
||||
<Button type="text" danger aria-label={`删除价格档 ${ordinal}`} title="删除价格档" icon={<X className="size-4" />} onClick={onRemove} />
|
||||
</div>
|
||||
<div className="grid gap-3 lg:grid-cols-12">
|
||||
<Form.Item className={`mb-0 ${selectorColumnClass}`} name={[index, "operation"]} label="生成方式" rules={[{ required: true, message: "请选择生成方式" }]}>
|
||||
<Select options={operationOptions(capability)} />
|
||||
</Form.Item>
|
||||
{isVideo ? (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "resolution"]} label="分辨率" rules={[{ required: true, message: "请选择分辨率" }]}>
|
||||
<Select options={[{ label: "任意分辨率", value: "*" }, ...resolutionOptions.map((value) => ({ label: value.toUpperCase(), value }))]} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
{isVideo ? (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "videoSeconds"]} label="时长" rules={[{ required: true, message: "请输入时长" }]}>
|
||||
{durationOptions.length ? <Select options={[{ label: "任意时长", value: 0 }, ...durationOptions.map((value) => ({ label: `${value} 秒`, value }))]} /> : <InputNumber className="w-full" min={0} precision={0} />}
|
||||
</Form.Item>
|
||||
) : null}
|
||||
{isImage ? (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "quality"]} label="质量/分辨率" rules={[{ required: true, message: "请选择质量或分辨率" }]}>
|
||||
<Select options={[{ label: "任意质量", value: "*" }, { label: "1K", value: "1k" }, { label: "2K", value: "2k" }, { label: "4K", value: "4k" }]} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
{isImage ? (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "size"]} label="画幅/尺寸">
|
||||
<Input placeholder="任意,或 1:1、16:9、1024x1024" />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item className={`mb-0 ${selectorColumnClass}`} name={[index, "providerModelKey"]} label="上游模型 ID">
|
||||
<Input placeholder="留空则使用模型默认上游 ID" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
<div className="grid items-end gap-3 lg:grid-cols-12">
|
||||
<Form.Item className="mb-0 lg:col-span-4" name={[index, "billingMode"]} label="计费方式" rules={[{ required: true }]}>
|
||||
<Segmented
|
||||
className="w-full"
|
||||
options={[
|
||||
{ label: "按次", value: "fixed_request" },
|
||||
{ label: "按秒", value: "per_second", disabled: !isVideo },
|
||||
{ label: "Token", value: "token", disabled: !tokenEnabled },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{billingMode === "token" ? (
|
||||
isVideo ? (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "outputTokenPrice"]} label="视频 / 百万 Token" rules={[{ required: true, message: "请输入视频 Token 价格" }]}>
|
||||
<InputNumber className="w-full" min={0.000001} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-3 lg:col-span-5">
|
||||
<Form.Item className="mb-0" name={[index, "inputTokenPrice"]} label="输入 / 百万 Token" rules={[{ required: true, message: "请输入输入价格" }]}><InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} /></Form.Item>
|
||||
<Form.Item className="mb-0" name={[index, "outputTokenPrice"]} label="输出 / 百万 Token" rules={[{ required: true, message: "请输入输出价格" }]}><InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} /></Form.Item>
|
||||
<Form.Item className="mb-0" name={[index, "cachedTokenPrice"]} label="缓存 / 百万 Token" rules={[{ required: true, message: "请输入缓存价格" }]}><InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} /></Form.Item>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<Form.Item className="mb-0 lg:col-span-3" name={[index, "unitPrice"]} label={billingMode === "per_second" ? "每秒消耗积分" : "每次消耗积分"} rules={[{ required: true, message: "请输入积分价格" }]}>
|
||||
<InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} />
|
||||
</Form.Item>
|
||||
)}
|
||||
<div className={`flex items-center gap-6 ${controlsColumnClass}`}>
|
||||
<Form.Item name={[index, "priceConfigured"]} label="价格已配置" valuePropName="checked" className="mb-0"><Switch /></Form.Item>
|
||||
<Form.Item name={[index, "enabled"]} label="启用此价格档" valuePropName="checked" className="mb-0"><Switch /></Form.Item>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function defaultPriceTier(): PriceTierFormValues {
|
||||
return { operation: "*", quality: "*", size: "*", resolution: "*", videoSeconds: 0, providerModelKey: "", billingMode: "fixed_request", unitPrice: 0, inputTokenPrice: 0, outputTokenPrice: 0, cachedTokenPrice: 0, priceConfigured: true, enabled: true };
|
||||
}
|
||||
|
||||
function priceTierToForm(tier: ChannelModelPriceTier): PriceTierFormValues {
|
||||
return {
|
||||
operation: tier.selector?.operation || "*", quality: tier.selector?.quality || "*", size: tier.selector?.size || "*",
|
||||
resolution: tier.resolution || "*", videoSeconds: tier.videoSeconds || 0, providerModelKey: tier.providerModelKey || "", billingMode: tier.billingMode,
|
||||
unitPrice: tier.unitPriceMicrocredits / 1_000_000, inputTokenPrice: tier.inputTokenPriceMicrocredits / 1_000_000,
|
||||
outputTokenPrice: tier.outputTokenPriceMicrocredits / 1_000_000, cachedTokenPrice: tier.cachedTokenPriceMicrocredits / 1_000_000,
|
||||
priceConfigured: tier.priceConfigured, enabled: tier.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function legacyPriceTierToForm(item: ChannelModel): PriceTierFormValues {
|
||||
return {
|
||||
operation: "*", quality: "*", size: "*", resolution: "*", videoSeconds: 0, providerModelKey: item.providerModelKey || "", billingMode: item.billingMode,
|
||||
unitPrice: item.unitPriceMicrocredits / 1_000_000, inputTokenPrice: item.inputTokenPriceMicrocredits / 1_000_000,
|
||||
outputTokenPrice: item.outputTokenPriceMicrocredits / 1_000_000, cachedTokenPrice: item.cachedTokenPriceMicrocredits / 1_000_000,
|
||||
priceConfigured: item.priceConfigured, enabled: item.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function billingSummary(item: ChannelModel) {
|
||||
const tiers = item.priceTiers?.filter((tier) => tier.enabled && tier.priceConfigured) || [];
|
||||
if (!tiers.length) return <AdminStatusBadge label="未配置价格" tone="warning" />;
|
||||
return <div className="space-y-1 text-xs leading-5">{tiers.slice(0, 3).map((tier) => <div key={tier.id}>{priceTierLabel(tier)}</div>)}{tiers.length > 3 ? <div className="text-foreground/45">另有 {tiers.length - 3} 个规格价格档</div> : null}</div>;
|
||||
}
|
||||
|
||||
function priceTierLabel(tier: ChannelModelPriceTier) {
|
||||
const selector = tier.selector || {};
|
||||
const specParts = [
|
||||
selector.operation && selector.operation !== "*" ? operationLabel(selector.operation) : "任意生成方式",
|
||||
selector.quality && selector.quality !== "*" ? selector.quality.toUpperCase() : "",
|
||||
selector.size && selector.size !== "*" ? selector.size : "",
|
||||
tier.resolution === "*" ? "" : tier.resolution.toUpperCase(),
|
||||
tier.videoSeconds ? `${tier.videoSeconds} 秒` : "",
|
||||
].filter(Boolean);
|
||||
const spec = specParts.length ? specParts.join(" / ") : "默认规格";
|
||||
if (tier.billingMode === "token") return `${spec} · ${formatCredits(tier.outputTokenPriceMicrocredits)} / 百万 Token`;
|
||||
return `${spec} · ${formatCredits(tier.unitPriceMicrocredits)} 积分 / ${tier.billingMode === "per_second" ? "秒" : "次"}`;
|
||||
}
|
||||
|
||||
function operationOptions(capability: EditableCapability | undefined) {
|
||||
const options = [{ label: "任意生成方式", value: "*" }];
|
||||
if (capability === "image") return [...options, { label: "文生图", value: "text_to_image" }, { label: "图生图", value: "image_to_image" }];
|
||||
if (capability === "video") return [...options, { label: "文生视频", value: "text_to_video" }, { label: "图生视频", value: "image_to_video" }, { label: "视频生视频", value: "video_to_video" }];
|
||||
if (capability === "text") return [...options, { label: "文本生成", value: "text_generation" }];
|
||||
return options;
|
||||
}
|
||||
|
||||
function operationLabel(operation: string) {
|
||||
return ({ text_to_image: "文生图", image_to_image: "图生图", text_to_video: "文生视频", image_to_video: "图生视频", video_to_video: "视频生视频", text_generation: "文本生成" } as Record<string, string>)[operation] || operation;
|
||||
}
|
||||
|
||||
function skuSelectorFromForm(capability: EditableCapability, tier: PriceTierFormValues) {
|
||||
const selector: Record<string, string> = {};
|
||||
if (tier.operation && tier.operation !== "*") selector.operation = tier.operation;
|
||||
if (capability === "video") {
|
||||
if (tier.resolution && tier.resolution !== "*") selector.vquality = tier.resolution;
|
||||
if (Number(tier.videoSeconds) > 0) selector.videoSeconds = String(Number(tier.videoSeconds));
|
||||
}
|
||||
if (capability === "image") {
|
||||
if (tier.quality && tier.quality !== "*") selector.quality = tier.quality;
|
||||
if (tier.size && tier.size !== "*") selector.size = tier.size;
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
function formatCredits(value: number) {
|
||||
return (value / 1_000_000).toLocaleString("zh-CN", { maximumFractionDigits: 6 });
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Alert, App, Button, Drawer, Form, Input, InputNumber, Modal, Segmented, Select, Switch, Table, Tag } from "antd";
|
||||
import { Alert, App, Button, Drawer, Form, Input, InputNumber, Modal, Select, Switch, Table, Tag } from "antd";
|
||||
import type { FormInstance } from "antd";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import { Archive, FlaskConical, GitBranch, Layers3, Pencil, Plus, Search } from "lucide-react";
|
||||
@@ -7,8 +7,6 @@ import { useDeferredValue, useEffect, useMemo, useState, type ReactNode } from "
|
||||
import { PaginationBar } from "@/components/layout/workspace-page";
|
||||
import { ModelIconPicker, ModelLogo } from "@/components/model-logo";
|
||||
import { CapabilityCardPicker } from "@/components/model-protocol-picker";
|
||||
import { formatCredits } from "@/constant/credits";
|
||||
import { modelProtocolSupportsTokenBilling } from "@/lib/model-protocols";
|
||||
import { AdminPageFrame } from "@/pages/admin/components/admin-shell";
|
||||
import { AdminDataTable, AdminFilterChip, AdminRowActions, AdminStatusBadge, AdminTableEmpty } from "@/pages/admin/components/admin-ui";
|
||||
import { listAdminChannels } from "@/services/api/auth";
|
||||
@@ -132,7 +130,7 @@ export default function LogicalModelsPage() {
|
||||
capability,
|
||||
enabled: true,
|
||||
sortOrder: models.length,
|
||||
pricePolicy: "unified",
|
||||
pricePolicy: "channel",
|
||||
billingMode: "fixed_request",
|
||||
unitPriceMicrocredits: 0,
|
||||
inputPriceMicrocredits: 0,
|
||||
@@ -279,12 +277,7 @@ export default function LogicalModelsPage() {
|
||||
|
||||
return (
|
||||
<AdminPageFrame
|
||||
title="模型目录"
|
||||
actions={
|
||||
<Button type="primary" icon={<Plus className="size-4" />} onClick={() => openModel()}>
|
||||
新增模型
|
||||
</Button>
|
||||
}
|
||||
title="前台模型目录"
|
||||
>
|
||||
<AdminDataTable
|
||||
toolbar={
|
||||
@@ -363,7 +356,8 @@ export default function LogicalModelsPage() {
|
||||
routes: [],
|
||||
capabilitySpec: emptyCapabilitySpec(capability),
|
||||
defaultOptions: {},
|
||||
billingMode: capability === "text" ? "token" : capability === "video" ? "per_second" : "fixed_request",
|
||||
pricePolicy: "channel",
|
||||
billingMode: "fixed_request",
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -416,8 +410,8 @@ export default function LogicalModelsPage() {
|
||||
<DefaultOptionsEditor spec={modelCapabilitySpec} />
|
||||
</Form.Item>
|
||||
</DrawerSection>
|
||||
<DrawerSection title="用户价格">
|
||||
<PricingFields channelModels={channelModels} />
|
||||
<DrawerSection title="系统规格价格">
|
||||
<PricingFields />
|
||||
</DrawerSection>
|
||||
</Form>
|
||||
</Drawer>
|
||||
@@ -600,114 +594,24 @@ function logicalModelStatusTag(item: AdminLogicalModel) {
|
||||
return <AdminStatusBadge label="可用" tone="success" />;
|
||||
}
|
||||
|
||||
function PricingFields({ channelModels }: { channelModels: ChannelModel[] }) {
|
||||
function PricingFields() {
|
||||
const form = Form.useFormInstance<LogicalModelFormValues>();
|
||||
const pricePolicy = Form.useWatch("pricePolicy") as LogicalModelMutation["pricePolicy"] | undefined;
|
||||
const billingMode = Form.useWatch("billingMode") as LogicalModelMutation["billingMode"] | undefined;
|
||||
const capability = Form.useWatch("capability") as CapabilityKind | undefined;
|
||||
const routes = (Form.useWatch("routes") || []) as RouteRuleRow[];
|
||||
const enabledRoutes = routes.filter((route) => route.enabled);
|
||||
const tokenBillingSupported =
|
||||
capability === "text" ||
|
||||
(capability === "video" &&
|
||||
enabledRoutes.length > 0 &&
|
||||
enabledRoutes.every((route) => {
|
||||
const channelModel = channelModels.find((item) => item.id === route.channelModelId);
|
||||
return modelProtocolSupportsTokenBilling(channelModel?.capability, channelModel?.protocol);
|
||||
}));
|
||||
const modes: Array<{ label: string; value: LogicalModelMutation["billingMode"]; disabled?: boolean }> = [{ label: "按次", value: "fixed_request" }];
|
||||
if (capability === "video") {
|
||||
modes.push({ label: "按秒", value: "per_second" });
|
||||
modes.push({ label: "Token", value: "token", disabled: !tokenBillingSupported });
|
||||
}
|
||||
if (capability === "text") modes.push({ label: "Token", value: "token" });
|
||||
|
||||
useEffect(() => {
|
||||
if (pricePolicy === "unified" && billingMode === "token" && !tokenBillingSupported) {
|
||||
form.setFieldValue("billingMode", capability === "video" ? "per_second" : "fixed_request");
|
||||
}
|
||||
}, [billingMode, capability, form, pricePolicy, tokenBillingSupported]);
|
||||
|
||||
const changePolicy = (value: string | number) => {
|
||||
const nextPolicy = value as LogicalModelMutation["pricePolicy"];
|
||||
if (nextPolicy !== "unified") return;
|
||||
const supportedModes = modes.filter((item) => !item.disabled).map((item) => item.value);
|
||||
if (!billingMode || !supportedModes.includes(billingMode)) {
|
||||
form.setFieldValue("billingMode", capability === "text" ? "token" : capability === "video" ? "per_second" : "fixed_request");
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Form.Item name="pricePolicy" label="定价策略">
|
||||
<Segmented
|
||||
block
|
||||
options={[
|
||||
{ label: "跟随供应价格", value: "channel" },
|
||||
{ label: "统一定价", value: "unified" },
|
||||
]}
|
||||
onChange={changePolicy}
|
||||
/>
|
||||
</Form.Item>
|
||||
{pricePolicy === "unified" ? (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Form.Item name="billingMode" label="计费方式">
|
||||
<Segmented block options={modes} />
|
||||
</Form.Item>
|
||||
{billingMode !== "token" ? (
|
||||
<Form.Item name="unitPriceMicrocredits" label={billingMode === "per_second" ? "每秒消耗积分" : "每次消耗积分"}>
|
||||
<CreditsInput />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
</div>
|
||||
{capability === "video" && !tokenBillingSupported ? <div className="mb-3 text-xs leading-5 text-foreground/50">Token 计费仅在所有启用供应线路都使用火山方舟视频协议时可用。</div> : null}
|
||||
{billingMode === "token" ? (
|
||||
capability === "video" ? (
|
||||
<Form.Item name="outputPriceMicrocredits" label="视频 / 百万 Token" rules={[{ type: "number", min: 1, message: "请输入视频 Token 价格" }]}>
|
||||
<CreditsInput />
|
||||
</Form.Item>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<Form.Item name="inputPriceMicrocredits" label="输入 / 百万 Token">
|
||||
<CreditsInput />
|
||||
</Form.Item>
|
||||
<Form.Item name="outputPriceMicrocredits" label="输出 / 百万 Token">
|
||||
<CreditsInput />
|
||||
</Form.Item>
|
||||
<Form.Item name="cachedPriceMicrocredits" label="缓存 / 百万 Token">
|
||||
<CreditsInput />
|
||||
</Form.Item>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-md bg-muted/20 px-3 py-3 text-xs leading-5 text-foreground/55">用户费用按实际命中的供应线路价格计算。故障切换到更高价格线路时会重新校验余额。</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CreditsInput({ value = 0, onChange }: { value?: number; onChange?: (value: number) => void }) {
|
||||
return <InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} value={value / 1_000_000} onChange={(next) => onChange?.(Math.round((next || 0) * 1_000_000))} />;
|
||||
form.setFieldsValue({
|
||||
pricePolicy: "channel",
|
||||
billingMode: "fixed_request",
|
||||
unitPriceMicrocredits: 0,
|
||||
inputPriceMicrocredits: 0,
|
||||
outputPriceMicrocredits: 0,
|
||||
cachedPriceMicrocredits: 0,
|
||||
});
|
||||
}, [form]);
|
||||
return <div className="rounded-md bg-muted/20 px-3 py-3 text-xs leading-5 text-foreground/55">价格、上游 SKU 和可用规格只在“系统渠道 / 模型管理”配置。前台模型只负责展示、能力范围和故障切换,不再保存第二份价格。</div>;
|
||||
}
|
||||
|
||||
function logicalPriceLabel(item: AdminLogicalModel) {
|
||||
if (item.pricePolicy === "channel") return <span className="text-xs">跟随供应价格</span>;
|
||||
if (item.billingMode === "token" && item.capability === "video") return <span className="text-xs">视频 {formatCredits(item.outputPriceMicrocredits)} / 百万 Token</span>;
|
||||
if (item.billingMode === "token")
|
||||
return (
|
||||
<div className="text-xs">
|
||||
<div>输入 {formatCredits(item.inputPriceMicrocredits)} / 百万</div>
|
||||
<div>输出 {formatCredits(item.outputPriceMicrocredits)} / 百万</div>
|
||||
<div className="text-foreground/45">缓存 {formatCredits(item.cachedPriceMicrocredits)} / 百万</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<span className="text-xs">
|
||||
{formatCredits(item.unitPriceMicrocredits)} / {item.billingMode === "per_second" ? "秒" : "次"}
|
||||
</span>
|
||||
);
|
||||
if (!item.priceTiers.length) return <span className="text-xs text-foreground/45">待配置系统规格价格</span>;
|
||||
return <span className="text-xs">{item.priceTiers.length} 个系统规格档</span>;
|
||||
}
|
||||
|
||||
function logicalModelToForm(item: AdminLogicalModel): LogicalModelFormValues {
|
||||
@@ -719,12 +623,12 @@ function logicalModelToForm(item: AdminLogicalModel): LogicalModelFormValues {
|
||||
capability: item.capability,
|
||||
enabled: item.enabled,
|
||||
sortOrder: item.sortOrder,
|
||||
pricePolicy: item.pricePolicy,
|
||||
billingMode: item.billingMode,
|
||||
unitPriceMicrocredits: item.unitPriceMicrocredits,
|
||||
inputPriceMicrocredits: item.inputPriceMicrocredits,
|
||||
outputPriceMicrocredits: item.outputPriceMicrocredits,
|
||||
cachedPriceMicrocredits: item.cachedPriceMicrocredits,
|
||||
pricePolicy: "channel",
|
||||
billingMode: "fixed_request",
|
||||
unitPriceMicrocredits: 0,
|
||||
inputPriceMicrocredits: 0,
|
||||
outputPriceMicrocredits: 0,
|
||||
cachedPriceMicrocredits: 0,
|
||||
capabilitySpec: item.capabilitySpec,
|
||||
defaultOptions: item.defaultOptions,
|
||||
routes: item.routes.map((route) => ({ channelModelId: route.channelModelId, enabled: route.enabled, priority: route.priority, weight: route.weight })),
|
||||
@@ -741,12 +645,12 @@ function logicalModelPayload(values: LogicalModelFormValues, sourceSpecs: Capabi
|
||||
capability: values.capability,
|
||||
enabled: values.enabled,
|
||||
sortOrder: values.sortOrder || 0,
|
||||
pricePolicy: values.pricePolicy,
|
||||
billingMode: values.billingMode,
|
||||
unitPriceMicrocredits: values.unitPriceMicrocredits || 0,
|
||||
inputPriceMicrocredits: values.inputPriceMicrocredits || 0,
|
||||
outputPriceMicrocredits: values.outputPriceMicrocredits || 0,
|
||||
cachedPriceMicrocredits: values.cachedPriceMicrocredits || 0,
|
||||
pricePolicy: "channel",
|
||||
billingMode: "fixed_request",
|
||||
unitPriceMicrocredits: 0,
|
||||
inputPriceMicrocredits: 0,
|
||||
outputPriceMicrocredits: 0,
|
||||
cachedPriceMicrocredits: 0,
|
||||
capabilitySpec,
|
||||
defaultOptions: sanitizeDefaults(capabilitySpec, values.defaultOptions),
|
||||
routes: values.routes.map((route) => ({ ...route, priority: route.priority || 0, weight: route.weight || 0 })),
|
||||
|
||||
@@ -1152,7 +1152,7 @@ function CreationComposer(props: ComposerProps) {
|
||||
<ModePicker mode={props.mode} onModeChange={props.onModeChange} />
|
||||
<Tooltip title="从本机上传附件"><button type="button" className="creation-chat-control" onClick={() => props.fileInputRef.current?.click()} disabled={props.busy || !referencesSupported} aria-label="从本机上传附件"><Paperclip /><span>附件</span></button></Tooltip>
|
||||
<Tooltip title={!referencesSupported ? "当前模型不支持参考媒体" : "从素材库选择参考内容"}><button type="button" className="creation-chat-control" onClick={props.onOpenLibrary} disabled={props.busy || !referencesSupported} aria-label="打开素材库选择参考内容"><FolderOpen /><span>素材库</span></button></Tooltip>
|
||||
<ModelPicker config={props.config} value={props.model} onChange={props.onModelChange} capability={props.mode} requirements={props.modelRequirements} className="creation-model-picker" placeholder={`选择${modeLabels[props.mode]}模型`} showSelectedPrice={false} variant="creation" />
|
||||
<ModelPicker config={props.config} value={props.model} onChange={props.onModelChange} capability={props.mode} requirements={props.modelRequirements} className="creation-model-picker" placeholder={`选择${modeLabels[props.mode]}模型`} showSelectedPrice variant="creation" />
|
||||
{props.mode === "video" || (props.mode === "image" && imageSettingsSupported) ? <GenerationSettingsMenu {...props} /> : null}
|
||||
{props.mode === "video" ? <DurationMenu profile={props.videoProfile} seconds={props.seconds} onChange={props.setSeconds} /> : null}
|
||||
</div>
|
||||
|
||||
@@ -31,12 +31,25 @@ export type PublicLogicalModel = {
|
||||
inputPriceMicrocredits: number;
|
||||
outputPriceMicrocredits: number;
|
||||
cachedPriceMicrocredits: number;
|
||||
priceTiers: PublicLogicalModelPriceTier[];
|
||||
legacyModelIds: string[];
|
||||
capabilitySpec: CapabilitySpec;
|
||||
capabilityProfiles: CapabilitySpec[];
|
||||
defaultOptions: Record<string, unknown>;
|
||||
available: boolean;
|
||||
};
|
||||
|
||||
export type PublicLogicalModelPriceTier = {
|
||||
selector: Record<string, string>;
|
||||
resolution: string;
|
||||
videoSeconds: number;
|
||||
billingMode: "fixed_request" | "per_second" | "token";
|
||||
unitPriceMicrocredits: number;
|
||||
inputTokenPriceMicrocredits: number;
|
||||
outputTokenPriceMicrocredits: number;
|
||||
cachedTokenPriceMicrocredits: number;
|
||||
};
|
||||
|
||||
export type AdminLogicalRoute = {
|
||||
id: string;
|
||||
channelModelId: string;
|
||||
@@ -73,6 +86,7 @@ export type LogicalModelMutation = {
|
||||
inputPriceMicrocredits: number;
|
||||
outputPriceMicrocredits: number;
|
||||
cachedPriceMicrocredits: number;
|
||||
legacyModelIds?: string[];
|
||||
capabilitySpec: CapabilitySpec;
|
||||
defaultOptions: Record<string, unknown>;
|
||||
routes: Array<{ channelModelId: string; enabled: boolean; priority: number; weight: number }>;
|
||||
@@ -83,6 +97,14 @@ export type RouteSimulationResult = {
|
||||
candidates: Array<{ routeId: string; channelModelId: string; channelModelKey: string; channelModelName: string; priority: number; weight: number; enabled: boolean; matched: boolean; blocked: boolean; inPool: boolean; reasons?: string[] }>;
|
||||
};
|
||||
|
||||
export type LogicalModelQuote = {
|
||||
logicalModelId: string;
|
||||
billingMode: PublicLogicalModel["billingMode"];
|
||||
quantity: number;
|
||||
amountMicrocredits: number;
|
||||
estimated: boolean;
|
||||
};
|
||||
|
||||
export function listLogicalModels() {
|
||||
return request<{ models: PublicLogicalModel[] }>(apiClient.get("/models"));
|
||||
}
|
||||
@@ -91,6 +113,10 @@ export function listAvailableLogicalModels(intent: ModelRequestIntent) {
|
||||
return request<{ models: PublicLogicalModel[] }>(apiClient.post("/models/available", intent));
|
||||
}
|
||||
|
||||
export function quoteLogicalModel(id: string, intent: ModelRequestIntent, signal?: AbortSignal) {
|
||||
return request<{ quote: LogicalModelQuote }>(apiClient.post(`/models/${encodeURIComponent(id)}/quote`, intent, { signal }));
|
||||
}
|
||||
|
||||
export function listAdminLogicalModels() {
|
||||
return request<{ models: AdminLogicalModel[] }>(apiClient.get("/admin/logical-models"));
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ export type ChannelModel = {
|
||||
id: string;
|
||||
channelId: string;
|
||||
modelKey: string;
|
||||
providerModelKey: string;
|
||||
displayName: string;
|
||||
capability: "text" | "image" | "video" | "audio" | "";
|
||||
protocol?: import("@/lib/model-protocols").ModelProtocol;
|
||||
@@ -63,10 +64,49 @@ export type ChannelModel = {
|
||||
priceVersion: number;
|
||||
capabilityVersion?: number;
|
||||
capabilityConfig?: import("@/lib/model-capabilities").ModelCapabilityConfig;
|
||||
priceTiers: ChannelModelPriceTier[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type ChannelModelPriceTier = {
|
||||
id: string;
|
||||
channelModelId: string;
|
||||
selector: Record<string, string>;
|
||||
selectorKey: string;
|
||||
resolution: string;
|
||||
videoSeconds: number;
|
||||
providerModelKey: string;
|
||||
billingMode: "fixed_request" | "per_second" | "token";
|
||||
unitPriceMicrocredits: number;
|
||||
inputTokenPriceMicrocredits: number;
|
||||
outputTokenPriceMicrocredits: number;
|
||||
cachedTokenPriceMicrocredits: number;
|
||||
priceConfigured: boolean;
|
||||
enabled: boolean;
|
||||
priceVersion: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
// 系统渠道模型的写入合同。标量价格只用于兼容旧管理请求;新的后台界面只提交 priceTiers。
|
||||
export type ChannelModelMutation = {
|
||||
modelKey: string;
|
||||
providerModelKey?: string;
|
||||
displayName?: string;
|
||||
capability: ChannelModel["capability"];
|
||||
protocol?: ChannelModel["protocol"];
|
||||
enabled?: boolean;
|
||||
capabilityConfig?: ChannelModel["capabilityConfig"];
|
||||
priceTiers?: Array<Omit<ChannelModelPriceTier, "id" | "channelModelId" | "selectorKey" | "priceVersion" | "createdAt" | "updatedAt">>;
|
||||
billingMode?: ChannelModel["billingMode"];
|
||||
unitPriceMicrocredits?: number;
|
||||
inputTokenPriceMicrocredits?: number;
|
||||
outputTokenPriceMicrocredits?: number;
|
||||
cachedTokenPriceMicrocredits?: number;
|
||||
priceConfigured?: boolean;
|
||||
};
|
||||
|
||||
export type LinuxDOSetting = {
|
||||
enabled: boolean;
|
||||
clientId: string;
|
||||
@@ -230,15 +270,15 @@ export function fetchAdminChannelModels(channelId: string) {
|
||||
return request<{ models: string[]; added: number }>(api.post(`/admin/channels/${encodeURIComponent(channelId)}/models/fetch`));
|
||||
}
|
||||
|
||||
export function testAdminChannelModel(channelId: string, input: Pick<ChannelModel, "modelKey" | "capability" | "protocol"> & { capabilityConfig?: ChannelModel["capabilityConfig"] }) {
|
||||
export function testAdminChannelModel(channelId: string, input: Pick<ChannelModel, "modelKey" | "providerModelKey" | "capability" | "protocol"> & { capabilityConfig?: ChannelModel["capabilityConfig"] }) {
|
||||
return request<{ durationMs: number }>(api.post(`/admin/channels/${encodeURIComponent(channelId)}/models/test`, input, { timeout: 10 * 60 * 1000 }));
|
||||
}
|
||||
|
||||
export function createAdminChannelModel(channelId: string, input: Omit<ChannelModel, "id" | "channelId" | "priceVersion" | "createdAt" | "updatedAt">) {
|
||||
export function createAdminChannelModel(channelId: string, input: ChannelModelMutation) {
|
||||
return request<{ model: ChannelModel }>(api.post(`/admin/channels/${encodeURIComponent(channelId)}/models`, input));
|
||||
}
|
||||
|
||||
export function updateAdminChannelModel(channelId: string, id: string, input: Omit<ChannelModel, "id" | "channelId" | "priceVersion" | "createdAt" | "updatedAt">) {
|
||||
export function updateAdminChannelModel(channelId: string, id: string, input: ChannelModelMutation) {
|
||||
return request<{ model: ChannelModel }>(api.patch(`/admin/channels/${encodeURIComponent(channelId)}/models/${encodeURIComponent(id)}`, input));
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { ModelCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { useLocalDreaminaModelStore } from "@/stores/use-local-dreamina-model-store";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
import type { DreaminaLocalModel } from "@/services/local-dreamina-model-catalog";
|
||||
import type { CapabilitySpec } from "@/services/api/logical-models";
|
||||
import type { CapabilitySpec, PublicLogicalModelPriceTier } from "@/services/api/logical-models";
|
||||
|
||||
export type ApiCallFormat = "openai" | "gemini";
|
||||
export type ChannelInterfaceType = ModelProtocol;
|
||||
@@ -31,6 +31,8 @@ export type ModelChannel = {
|
||||
apiFormat: ApiCallFormat;
|
||||
interfaceType?: ChannelInterfaceType;
|
||||
models: string[];
|
||||
// 仅平台目录使用:将已保存的旧 SKU 选择重定向到当前模型家族。
|
||||
modelAliases?: Record<string, string>;
|
||||
scope?: "system" | "user";
|
||||
enabled?: boolean;
|
||||
hasApiKey?: boolean;
|
||||
@@ -53,6 +55,7 @@ export type ModelChannel = {
|
||||
logicalModelId?: string;
|
||||
logicalCapabilitySpec?: CapabilitySpec;
|
||||
logicalCapabilityProfiles?: CapabilitySpec[];
|
||||
logicalPriceTiers?: PublicLogicalModelPriceTier[];
|
||||
defaultOptions?: Record<string, unknown>;
|
||||
}>;
|
||||
transport?: "backend-channel" | "local-runtime";
|
||||
@@ -481,10 +484,12 @@ export function normalizeModelOptionValue(value: unknown, channels: ModelChannel
|
||||
const decoded = decodeChannelModel(model);
|
||||
if (decoded) {
|
||||
const channel = channels.find((item) => item.id === decoded.channelId);
|
||||
return channel && channel.models.includes(decoded.model) ? model : "";
|
||||
const resolved = channel?.modelAliases?.[decoded.model] || decoded.model;
|
||||
return channel && channel.models.includes(resolved) ? encodeChannelModel(channel.id, resolved) : "";
|
||||
}
|
||||
const channel = channels.find((item) => item.models.includes(model)) || channels[0];
|
||||
return channel && channel.models.includes(model) ? encodeChannelModel(channel.id, model) : "";
|
||||
const channel = channels.find((item) => item.models.includes(model) || Boolean(item.modelAliases?.[model])) || channels[0];
|
||||
const resolved = channel?.modelAliases?.[model] || model;
|
||||
return channel && channel.models.includes(resolved) ? encodeChannelModel(channel.id, resolved) : "";
|
||||
}
|
||||
|
||||
export function resolveModelChannel(config: AiConfig, value: string) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { canvasConnectionError } from "../src/lib/canvas/canvas-connection-polic
|
||||
import { assertCanvasImageReferenceLimit, buildGenerationConfig, canvasImageReferenceLimitError, resolveCanvasGenerationModel } from "../src/lib/canvas/canvas-project-generation";
|
||||
import { defaultModelCapabilityConfig } from "../src/lib/model-capabilities";
|
||||
import { groupModelsByDisplayName, modelCompatibilityError, modelGroupReferenceLimits, resolveCompatibleModel, resolveModelGenerationDefaults } from "../src/lib/model-selection";
|
||||
import { defaultConfig, type AiConfig, type ModelChannel } from "../src/stores/use-config-store";
|
||||
import { defaultConfig, normalizeModelOptionValue, type AiConfig, type ModelChannel } from "../src/stores/use-config-store";
|
||||
import { CanvasNodeType, type CanvasConnection, type CanvasNodeData } from "../src/types/canvas";
|
||||
|
||||
function policyConfig(): AiConfig {
|
||||
@@ -167,6 +167,61 @@ describe("逻辑模型选择", () => {
|
||||
expect(modelCompatibilityError(config, "relay::cinema-image", requirements)).toContain("参考音频");
|
||||
});
|
||||
|
||||
test("逻辑视频模型将 720 与 720p 视为同一分辨率", () => {
|
||||
const model = "cinema-720p";
|
||||
const channel: ModelChannel = {
|
||||
id: "logical-video",
|
||||
name: "平台视频模型",
|
||||
baseUrl: "/api",
|
||||
apiKey: "system",
|
||||
apiFormat: "openai",
|
||||
scope: "system",
|
||||
models: [model],
|
||||
modelCosts: [{
|
||||
model,
|
||||
capability: "video",
|
||||
billingMode: "per_second",
|
||||
unitPriceMicrocredits: 1,
|
||||
logicalCapabilitySpec: {
|
||||
version: 1,
|
||||
capability: "video",
|
||||
operations: ["text_to_video"],
|
||||
inputs: {},
|
||||
options: {
|
||||
videoSeconds: { min: 1, max: 15, step: 1 },
|
||||
size: { values: ["16:9"] },
|
||||
vquality: { values: ["720p"] },
|
||||
videoGenerateAudio: { values: [false] },
|
||||
videoWatermark: { values: [false] },
|
||||
},
|
||||
},
|
||||
}],
|
||||
};
|
||||
const value = `logical-video::${model}`;
|
||||
const config = { ...defaultConfig, channels: [channel], models: [value], videoModels: [value], videoModel: value };
|
||||
|
||||
expect(modelCompatibilityError(config, value, {
|
||||
capability: "video",
|
||||
input: { textCount: 1, imageCount: 0, videoCount: 0, audioCount: 0, characterCount: 0 },
|
||||
options: { size: "16:9", videoSeconds: 6, vquality: "720", videoGenerateAudio: false, videoWatermark: false },
|
||||
})).toBe("");
|
||||
});
|
||||
|
||||
test("已保存的旧 SKU 选择会解析到新的模型家族", () => {
|
||||
const channel: ModelChannel = {
|
||||
id: "managed",
|
||||
name: "平台模型",
|
||||
baseUrl: "/api",
|
||||
apiKey: "system",
|
||||
apiFormat: "openai",
|
||||
scope: "system",
|
||||
models: ["family-seedance-2-5"],
|
||||
modelAliases: { "legacy-seedance-720": "family-seedance-2-5" },
|
||||
};
|
||||
|
||||
expect(normalizeModelOptionValue("managed::legacy-seedance-720", [channel])).toBe("managed::family-seedance-2-5");
|
||||
});
|
||||
|
||||
test("逻辑模型容量使用同名细分模型的最大值", () => {
|
||||
const config = policyConfig();
|
||||
expect(modelGroupReferenceLimits(config, "relay::cinema-text", "video")).toEqual({ maxImages: 1, maxVideos: 0, maxAudios: 1 });
|
||||
|
||||
Reference in new issue
Block a user