feat(ai): 实现AI模型调用的积分计费功能
- 后端根据请求体中的n参数计算AI调用次数并扣减用户积分 - 添加readAIRequestCount函数解析multipart/form-data和JSON格式的请求体获取调用次数 - 前端Canvas组件中显示预计消耗的积分数量 - 在助手面板、配置节点面板和提示面板中集成积分成本计算和展示 - 优化模型选择器在云端模式下的模型列表显示逻辑 - 添加CreditSymbol组件用于统一积分图标显示 - 实现requestCreditCost函数计算远程调用的积分消耗 - 更新文档中关于积分扣费和模型配置的相关说明
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
# 待测试
|
||||
|
||||
- 用户模块新增 `users` 完整字段和 `credit_logs` 表;账号密码注册/登录已开放,后端 `/api/v1` 模型渠道接口需要登录后调用;Linux.do OAuth 登录参数移到后台系统设置,登录页按开关展示 Linux.do 按钮并使用 `public/icons/linuxdo.svg` 图标,Linux.do 原始资料写入 `users.extra.linuxDo`;后台 `/admin/users` 可新增、编辑、删除用户并在编辑弹窗内调整算力点,编辑用户不修改头像和算力点,算力点变化会写入 `credit_logs`;后台新增 `/admin/credit-logs` 算力点日志表格和增删改接口,需要确认注册、登录、Linux.do 配置保存和回调、后台筛选分页、用户保存删除、算力点调整、日志增删改查、登录态下生图/对话/视频和算力点流水都正常。
|
||||
- 管理后台 `/admin/settings` 公开配置新增模型算力点配置;后端 `/api/v1` 生图、图生图、对话和视频创建接口会在上游调用成功后按模型扣除用户算力点并写入 `credit_logs` 的 `ai_consume` 记录,余额不足会拒绝调用,前端远程调用成功后会刷新当前用户信息;系统可用模型临时删除时会保留 JSON 里的历史模型算力点配置,渠道里临时移除模型时公开配置下拉仍保留已见过的模型候选,需要确认不同模型扣费、余额不足拦截、流水记录、顶部余额更新、算力点输入不回跳、临时删除模型后配置保留和可重新添加正常。
|
||||
- 管理后台 `/admin/settings` 公开配置新增模型算力点配置;后端 `/api/v1` 生图、图生图、对话和视频创建接口会在上游调用成功后按模型扣除用户算力点并写入 `credit_logs` 的 `ai_consume` 记录,余额不足会拒绝调用,前端远程调用成功后会刷新当前用户信息;系统可用模型临时删除时会保留 JSON 里的历史模型算力点配置,渠道里临时移除模型时公开配置下拉仍保留已见过的模型候选,云端默认模型为空时前端会回落到第一个系统可用模型,云端模型下拉为空时不会弹出配置弹窗,需要确认不同模型扣费、余额不足拦截、流水记录、顶部余额更新、算力点输入不回跳、临时删除模型后配置保留和可重新添加正常。
|
||||
- 画布详情页右上角用户头像左侧新增当前算力点余额展示,未登录或无用户信息时显示 0,需要确认登录、未登录和调用后刷新余额显示正常。
|
||||
- 画布节点下方对话框、右侧助手发送按钮和生成配置节点开始生成按钮新增本次预计消耗算力点展示,费用来自公开配置的模型算力点,未配置显示 0,生图按生成张数倍乘;画布里的模型下拉在云端模式下会使用后台公开配置返回的系统可用模型,需要确认文本、生图、图生图、生成配置节点和本地直连模式显示正常。
|
||||
- 配置弹窗和后台公开配置新增默认视频模型;视频节点通过设置弹层单独配置视频质量、尺寸和秒数,连接图片节点时会作为 `input_reference` 参考图生成视频,并按 OpenAI 视频接口格式提交 `multipart/form-data`、`size`、`seconds`、`vquality` 和参考图参数,需要确认本地直连和云端渠道下默认视频模型选择、节点视频参数配置、参考图生成、保存和重试都正常。
|
||||
- 画布新增视频节点:工具栏可新建视频节点,上传/拖拽本地视频后可在节点内播放、下载、保存到我的素材;节点下方对话框和生成配置节点支持视频生成,前端会调用 OpenAI 兼容 `videos` 接口并把生成结果保存为本地视频 Blob;后端远程渠道新增 `/api/v1/videos`、`/api/v1/videos/:id`、`/api/v1/videos/:id/content` 代理,需要确认本地渠道和远程渠道都能生成、轮询和下载视频。
|
||||
- 图片和视频节点会按素材或生成结果的真实宽高比调整节点尺寸;空图片/视频节点在尺寸设置切换到 16:9、9:16 等比例时也会同步调整节点外框,需要确认上传、生成、重试、素材插入和空节点尺寸切换后的黑边情况。
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
@@ -75,6 +76,7 @@ func proxyAIRequest(w http.ResponseWriter, r *http.Request, path string) {
|
||||
Fail(w, "AI 接口请求失败")
|
||||
return
|
||||
}
|
||||
credits *= readAIRequestCount(body, contentType)
|
||||
if err := service.EnsureUserCredits(user.ID, credits); err != nil {
|
||||
FailError(w, err)
|
||||
return
|
||||
@@ -174,6 +176,34 @@ func readMultipartModel(body []byte, contentType string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func readAIRequestCount(body []byte, contentType string) int {
|
||||
count := 1
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
_, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return count
|
||||
}
|
||||
form, err := multipart.NewReader(bytes.NewReader(body), params["boundary"]).ReadForm(32 << 20)
|
||||
if err != nil {
|
||||
return count
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
if values := form.Value["n"]; len(values) > 0 {
|
||||
_, _ = fmt.Sscan(values[0], &count)
|
||||
}
|
||||
} else {
|
||||
var payload struct {
|
||||
N int `json:"n"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &payload)
|
||||
count = payload.N
|
||||
}
|
||||
if count < 1 {
|
||||
return 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
var errMissingModel = &aiError{"缺少模型名称"}
|
||||
|
||||
type aiError struct {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { motion } from "motion/react";
|
||||
import { ImageGenerationPending } from "@/components/image-generation-pending";
|
||||
import { ModelPicker } from "@/components/model-picker";
|
||||
import { useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { CreditSymbol, requestCreditCost } from "@/constant/credits";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { nanoid } from "nanoid";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -41,8 +42,8 @@ type CanvasAssistantPanelProps = {
|
||||
|
||||
export function CanvasAssistantPanel({ nodes, selectedNodeIds, sessions, activeSessionId, onSelectNodeIds, onSessionsChange, onInsertImage, onInsertText, onPasteImage, onCollapseStart, onCollapse }: CanvasAssistantPanelProps) {
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const config = useConfigStore((state) => state.config);
|
||||
const effectiveConfig = useEffectiveConfig();
|
||||
const modelCosts = useConfigStore((state) => state.publicSettings?.modelChannel.modelCosts);
|
||||
const cleanupImages = useAssetStore((state) => state.cleanupImages);
|
||||
const updateConfig = useConfigStore((state) => state.updateConfig);
|
||||
const isAiConfigReady = useConfigStore((state) => state.isAiConfigReady);
|
||||
@@ -328,6 +329,7 @@ export function CanvasAssistantPanel({ nodes, selectedNodeIds, sessions, activeS
|
||||
if (selectedNodeIds.has(id)) onSelectNodeIds(new Set(Array.from(selectedNodeIds).filter((nodeId) => nodeId !== id)));
|
||||
}}
|
||||
onPasteImage={onPasteImage}
|
||||
modelCosts={modelCosts}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -372,6 +374,7 @@ function AssistantComposer({
|
||||
onMissingConfig,
|
||||
onRemoveReference,
|
||||
onPasteImage,
|
||||
modelCosts,
|
||||
}: {
|
||||
mode: AssistantMode;
|
||||
prompt: string;
|
||||
@@ -385,8 +388,11 @@ function AssistantComposer({
|
||||
onMissingConfig: () => void;
|
||||
onRemoveReference: (id: string) => void;
|
||||
onPasteImage: (file: File) => void;
|
||||
modelCosts?: { model: string; credits: number }[];
|
||||
}) {
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const activeModel = mode === "image" ? config.imageModel || config.model : config.textModel || config.model;
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, modelCosts, model: activeModel, count: mode === "image" ? config.count : 1 });
|
||||
|
||||
return (
|
||||
<div className="px-2 pb-2" onWheelCapture={(event) => event.stopPropagation()}>
|
||||
@@ -431,13 +437,19 @@ function AssistantComposer({
|
||||
</div>
|
||||
<Button
|
||||
type="primary"
|
||||
shape="circle"
|
||||
className="!h-10 !w-10 !min-w-10 shrink-0"
|
||||
icon={isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
|
||||
className="!h-10 !min-w-16 shrink-0 !rounded-full !px-3"
|
||||
disabled={isRunning || !prompt.trim()}
|
||||
onClick={() => void onSubmit()}
|
||||
aria-label="发送"
|
||||
/>
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="inline-flex items-center gap-1 text-xs font-medium tabular-nums">
|
||||
<CreditSymbol />
|
||||
{credits.toLocaleString()}
|
||||
</span>
|
||||
{isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,8 @@ import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Edit3, Eye, Image as ImageIc
|
||||
import { App, Button, Empty, Input, InputNumber, Modal, Segmented } from "antd";
|
||||
|
||||
import { ModelPicker } from "@/components/model-picker";
|
||||
import { defaultConfig, useConfigStore, type AiConfig } from "@/stores/use-config-store";
|
||||
import { defaultConfig, useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { CreditSymbol, requestCreditCost } from "@/constant/credits";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import { CanvasSizePicker } from "./canvas-size-picker";
|
||||
@@ -29,12 +30,14 @@ export function CanvasConfigNodePanel({ node, isRunning, inputSummary, inputs, o
|
||||
const [previewOpen, setPreviewOpen] = useState(false);
|
||||
const [editingTextId, setEditingTextId] = useState<string | null>(null);
|
||||
const [editingText, setEditingText] = useState("");
|
||||
const globalConfig = useConfigStore((state) => state.config);
|
||||
const globalConfig = useEffectiveConfig();
|
||||
const modelCosts = useConfigStore((state) => state.publicSettings?.modelChannel.modelCosts);
|
||||
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const mode = node.metadata?.generationMode || "image";
|
||||
const config = buildNodeConfig(globalConfig, node, mode);
|
||||
const count = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(node.metadata?.count || 3)) || 1)));
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, modelCosts, model: config.model, count: mode === "image" ? count : 1 });
|
||||
const chipStyle = { background: theme.node.fill, borderColor: theme.node.stroke, color: theme.node.text };
|
||||
const textInputs = inputs.filter((input) => input.type === "text");
|
||||
const imageInputs = inputs.filter((input) => input.type === "image");
|
||||
@@ -127,9 +130,15 @@ export function CanvasConfigNodePanel({ node, isRunning, inputSummary, inputs, o
|
||||
disabled={isRunning || (!inputSummary.textCount && !inputSummary.imageCount)}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onClick={() => onGenerate(node.id)}
|
||||
icon={isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <Play className="size-4" />}
|
||||
>
|
||||
开始生成
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<CreditSymbol />
|
||||
{credits.toLocaleString()}
|
||||
</span>
|
||||
{isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <Play className="size-4" />}
|
||||
<span>开始生成</span>
|
||||
</span>
|
||||
</Button>
|
||||
<Modal
|
||||
title="输入预览"
|
||||
|
||||
@@ -5,7 +5,8 @@ import { ArrowUp, LoaderCircle } from "lucide-react";
|
||||
import { Button } from "antd";
|
||||
|
||||
import { ModelPicker } from "@/components/model-picker";
|
||||
import { defaultConfig, useConfigStore, type AiConfig } from "@/stores/use-config-store";
|
||||
import { defaultConfig, useConfigStore, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
|
||||
import { CreditSymbol, requestCreditCost } from "@/constant/credits";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { useThemeStore } from "@/stores/use-theme-store";
|
||||
import { CanvasImageSettingsPopover } from "./canvas-image-settings-popover";
|
||||
@@ -25,7 +26,8 @@ type CanvasNodePromptPanelProps = {
|
||||
};
|
||||
|
||||
export function CanvasNodePromptPanel({ node, isRunning, onPromptChange, onConfigChange, onGenerate, onImageSettingsOpenChange }: CanvasNodePromptPanelProps) {
|
||||
const globalConfig = useConfigStore((state) => state.config);
|
||||
const globalConfig = useEffectiveConfig();
|
||||
const modelCosts = useConfigStore((state) => state.publicSettings?.modelChannel.modelCosts);
|
||||
const openConfigDialog = useConfigStore((state) => state.openConfigDialog);
|
||||
const theme = canvasThemes[useThemeStore((state) => state.theme)];
|
||||
const mode = defaultMode(node.type);
|
||||
@@ -34,6 +36,7 @@ export function CanvasNodePromptPanel({ node, isRunning, onPromptChange, onConfi
|
||||
const hasImageContent = node.type === CanvasNodeType.Image && Boolean(node.metadata?.content);
|
||||
const isEditingExistingContent = hasTextContent || hasImageContent;
|
||||
const [prompt, setPrompt] = useState(isEditingExistingContent ? "" : node.metadata?.prompt || "");
|
||||
const credits = requestCreditCost({ channelMode: config.channelMode, modelCosts, model: config.model, count: mode === "image" ? config.count : 1 });
|
||||
|
||||
useEffect(() => {
|
||||
setPrompt(isEditingExistingContent ? "" : node.metadata?.prompt || "");
|
||||
@@ -98,13 +101,19 @@ export function CanvasNodePromptPanel({ node, isRunning, onPromptChange, onConfi
|
||||
</div>
|
||||
<Button
|
||||
type="primary"
|
||||
shape="circle"
|
||||
className="!h-10 !w-10 !min-w-10 shrink-0"
|
||||
className="!h-10 !min-w-16 shrink-0 !rounded-full !px-3"
|
||||
disabled={isRunning || !prompt.trim()}
|
||||
onClick={submit}
|
||||
icon={isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
|
||||
aria-label="生成"
|
||||
/>
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="inline-flex items-center gap-1 text-xs font-medium tabular-nums">
|
||||
<CreditSymbol />
|
||||
{credits.toLocaleString()}
|
||||
</span>
|
||||
{isRunning ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@ import Link from "next/link";
|
||||
import { AnimatedThemeToggler } from "@/components/ui/animated-theme-toggler";
|
||||
import { GitHubLink } from "@/components/layout/github-link";
|
||||
import { VersionReleaseModal } from "@/components/layout/version-release-modal";
|
||||
import { CreditSymbol } from "@/constant/credits";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { useConfigStore } from "@/stores/use-config-store";
|
||||
@@ -63,7 +64,7 @@ export function UserStatusActions({ showConfig = true, variant = "default", onOp
|
||||
{variant === "canvas" ? (
|
||||
<Tooltip title="当前算力点余额" placement="bottom">
|
||||
<div className="flex h-8 shrink-0 items-center gap-1.5 px-1.5 text-xs font-medium tabular-nums opacity-75 transition hover:opacity-100" style={{ color: canvasTheme.node.text }}>
|
||||
<span className="text-sm leading-none">⚡️</span>
|
||||
<CreditSymbol className="text-sm leading-none" />
|
||||
<span>{credits.toLocaleString()}</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
|
||||
@@ -20,7 +20,7 @@ type ModelPickerProps = {
|
||||
export function ModelPicker({ config, value, onChange, className, fullWidth = false, placeholder = "选择模型", onMissingConfig }: ModelPickerProps) {
|
||||
const pickerId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const options = useMemo(() => Array.from(new Set([value, ...config.models].filter(Boolean))), [config.models, value]);
|
||||
const options = useMemo(() => Array.from(new Set([...(config.channelMode === "local" ? [value] : []), ...config.models].filter(Boolean))), [config.channelMode, config.models, value]);
|
||||
const current = value || "";
|
||||
|
||||
useEffect(() => {
|
||||
@@ -36,7 +36,7 @@ export function ModelPicker({ config, value, onChange, className, fullWidth = fa
|
||||
open={open}
|
||||
value={current}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen && !options.length) {
|
||||
if (nextOpen && !options.length && config.channelMode === "local") {
|
||||
onMissingConfig?.();
|
||||
return;
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export function ModelPicker({ config, value, onChange, className, fullWidth = fa
|
||||
))
|
||||
) : (
|
||||
<SelectItem value="__empty__" disabled>
|
||||
请先到配置里拉取模型列表
|
||||
{config.channelMode === "remote" ? "暂无可用模型" : "请先到配置里拉取模型列表"}
|
||||
</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ComponentProps } from "react";
|
||||
import { Zap } from "lucide-react";
|
||||
|
||||
export function CreditSymbol({ className, ...props }: ComponentProps<"span">) {
|
||||
return (
|
||||
<span {...props} className={`inline-flex items-center justify-center ${className || ""}`}>
|
||||
<Zap className="size-[1em] fill-current" strokeWidth={2.4} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export type ModelCreditCost = {
|
||||
model: string;
|
||||
credits: number;
|
||||
};
|
||||
|
||||
export function modelCreditCost(modelCosts: ModelCreditCost[] | undefined, model: string) {
|
||||
return modelCosts?.find((item) => item.model === model)?.credits || 0;
|
||||
}
|
||||
|
||||
export function requestCreditCost(options: { channelMode: string; modelCosts?: ModelCreditCost[]; model: string; count?: string | number }) {
|
||||
if (options.channelMode !== "remote") return 0;
|
||||
const count = Math.max(1, Math.floor(Math.abs(Number(options.count)) || 1));
|
||||
return modelCreditCost(options.modelCosts, options.model) * count;
|
||||
}
|
||||
@@ -61,14 +61,15 @@ function resolveEffectiveConfig(config: AiConfig, modelChannel: AdminPublicSetti
|
||||
const channelMode = modelChannel?.allowCustomChannel ? config.channelMode : "remote";
|
||||
if (channelMode === "local" || !modelChannel) return { ...config, channelMode };
|
||||
const models = modelChannel.availableModels;
|
||||
const fallbackModel = modelChannel.defaultModel || models[0] || "";
|
||||
return {
|
||||
...config,
|
||||
channelMode,
|
||||
models,
|
||||
model: models.includes(config.model) ? config.model : modelChannel.defaultModel,
|
||||
imageModel: models.includes(config.imageModel) ? config.imageModel : modelChannel.defaultImageModel || modelChannel.defaultModel,
|
||||
videoModel: models.includes(config.videoModel) ? config.videoModel : modelChannel.defaultVideoModel || modelChannel.defaultModel || "sora-2",
|
||||
textModel: models.includes(config.textModel) ? config.textModel : modelChannel.defaultTextModel || modelChannel.defaultModel,
|
||||
model: models.includes(config.model) ? config.model : fallbackModel,
|
||||
imageModel: models.includes(config.imageModel) ? config.imageModel : modelChannel.defaultImageModel || fallbackModel,
|
||||
videoModel: models.includes(config.videoModel) ? config.videoModel : modelChannel.defaultVideoModel || fallbackModel,
|
||||
textModel: models.includes(config.textModel) ? config.textModel : modelChannel.defaultTextModel || fallbackModel,
|
||||
systemPrompt: modelChannel.systemPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user