Files
monkey-ai-web/src/hooks/models/useModelSelector.js
T
qiubaishen 6160a23117 sync: 同步总仓库 luoguang/monkey-ai weiyuan@bfdfb339 的 web/ 改动
同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2)
范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json)

- 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models
- 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s
- dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台)
- b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join
- 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文
- e4c301d5 fix: merge enterprise task record date filters
- c9369b95 feat: expose enterprise image and video task records
- a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2)
- 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写
- 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费
- f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口
- 8cdf1994 fix(topup): reset amount when switching from PayPal
- 93a4ac34 feat(baidu): configure Seedance liveness header by channel
- cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21)
- 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分)
- e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分)
- b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足
- e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销
- 584aad52 style(web): 个人中心侧边栏按 prettier 换行
- b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView
- eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤
- 8b254d49 fix: 小程序里隐藏企业充值入口与页面
- a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转
- cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票
- c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费
- 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式
- 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
2026-11-10 11:05:34 +08:00

266 lines
8.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback } from 'react';
import { API, showError } from '../../helpers';
import i18next from 'i18next';
import {
MODEL_CATEGORY,
inferModelCategory,
getModelsByCategory,
} from '../../constants/model-category.constant';
/**
* 模型选择Hook
* @param {string} category - 模型分类(可选,如果指定则只获取该分类的模型)
*/
export const useModelSelector = (category = null) => {
const [models, setModels] = useState([]);
const [filteredModels, setFilteredModels] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedModel, setSelectedModel] = useState(null);
// 根据前端分类映射到后端 category 参数
const getCategoryParam = useCallback((frontendCategory) => {
if (!frontendCategory) return '';
// 图片相关分类
if (
[
MODEL_CATEGORY.IMAGE_GENERATION,
MODEL_CATEGORY.TEXT_TO_IMAGE,
MODEL_CATEGORY.IMAGE_TO_IMAGE,
].includes(frontendCategory)
) {
return 'image';
}
// 视频相关分类
if (
[
MODEL_CATEGORY.VIDEO_GENERATION,
MODEL_CATEGORY.TEXT_TO_VIDEO,
MODEL_CATEGORY.IMAGE_TO_VIDEO,
].includes(frontendCategory)
) {
return 'video';
}
// 默认返回空(使用文本模型配置)
return '';
}, []);
// 加载模型列表
const loadModels = useCallback(async () => {
setLoading(true);
try {
// 根据分类确定 category 参数
const categoryParam = getCategoryParam(category);
const categoryQuery = categoryParam ? `&category=${categoryParam}` : '';
// 并行获取模型列表和价格信息
// 使用 /api/user/models 接口,普通用户可访问
const [modelsRes, pricingRes] = await Promise.all([
API.get(`/api/user/models/?page_size=1000${categoryQuery}`),
// discount_scope=personal:体验中心/模型选择器的调用恒走个人计费(属于企业的用户按所属企业等级),
// 企业 web 会话下若跟随会话作用域会标成当前所选企业的价格
API.get('/api/pricing?discount_scope=personal').catch(() => ({
data: { success: true, data: [] },
})), // 如果pricing接口失败,使用空数组
]);
const { success, message, data } = modelsRes.data;
if (success) {
const allModels = data?.items || data || [];
// 等级锁态元数据(§6.2):后端已剔除 hidden,剩余仅 callable/visible;
// visible 表示「仅可见、不可调用」,前端展示锁态并禁止选中提交(最终仍以调用闸门为准)。
const levelStates = data?.level_states || {};
const pricingData = pricingRes.data?.data || [];
const groupRatioMap = pricingRes.data?.group_ratio || {};
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},乘在分组倍率之上
const groupModelDiscountMap =
pricingRes.data?.group_model_discount || {};
// 当前登录用户分组(用于计算实际价格 = model_price * 分组倍率)
let userGroup = '';
try {
userGroup =
JSON.parse(localStorage.getItem('user') || '{}')?.group || '';
} catch {
userGroup = '';
}
const userGroupRatio =
typeof groupRatioMap[userGroup] === 'number'
? groupRatioMap[userGroup]
: 1;
// 创建pricing映射表,以模型名称为key
const pricingMap = {};
pricingData.forEach((pricing) => {
pricingMap[pricing.model_name] = pricing;
});
// 为每个模型推断分类(如果没有 categories 字段)并添加价格信息
const modelsWithCategory = allModels.map((model) => {
// 添加价格信息
const pricing = pricingMap[model.model_name] || {};
let modelWithCategory = { ...model };
// 如果后端返回了 categories 数组,直接使用
if (Array.isArray(model.categories) && model.categories.length > 0) {
modelWithCategory = model;
}
// 如果有 category 单个字段,转换为 categories 数组
else if (model.category) {
modelWithCategory = {
...model,
categories: [model.category],
};
}
// 否则通过模型名称推断分类
else {
const inferredCategory = inferModelCategory(
model.model_name,
model.endpoint_type,
);
modelWithCategory = {
...model,
categories: [inferredCategory],
};
}
// 合并价格信息(group_ratio 为当前用户所在分组的有效倍率,已含该模型的等级折扣修正)
return {
...modelWithCategory,
model_ratio: pricing.model_ratio,
model_price: pricing.model_price,
quota_type: pricing.quota_type,
completion_ratio: pricing.completion_ratio,
// 浮点乘积收敛 4 位小数,避免展示 0.7200000000000001 类脏数字
group_ratio: parseFloat(
(
userGroupRatio *
(groupModelDiscountMap?.[userGroup]?.[model.model_name] ?? 1)
).toFixed(4),
),
// callable(默认)/ visible(锁定,不可调用)
level_state: levelStates[model.model_name] || 'callable',
level_locked: levelStates[model.model_name] === 'visible',
};
});
setModels(modelsWithCategory);
// 如果指定了分类,进行筛选
if (category) {
const filtered = getModelsByCategory(modelsWithCategory, category);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型(避免默认选中锁定模型导致提交即 403)
if (filtered.length > 0) {
const firstCallable = filtered.find((m) => !m.level_locked);
setSelectedModel((prev) =>
prev && filtered.some((m) => m.id === prev.id && !m.level_locked)
? prev
: firstCallable || null,
);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(modelsWithCategory);
}
} else {
showError(message || i18next.t('获取模型列表失败'));
}
} catch (error) {
console.error('加载模型失败:', error);
showError(
i18next.t('加载模型失败: {{message}}', { message: error.message }),
);
} finally {
setLoading(false);
}
}, [category, getCategoryParam]);
// 切换模型分类
const filterByCategory = useCallback(
(newCategory) => {
if (newCategory) {
const filtered = getModelsByCategory(models, newCategory);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型
if (filtered.length > 0) {
setSelectedModel(filtered.find((m) => !m.level_locked) || null);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(models);
}
},
[models],
);
// 根据ID选择模型
const selectModelById = useCallback(
(modelId) => {
const model = filteredModels.find((m) => m.id === modelId);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 根据模型名称选择模型
const selectModelByName = useCallback(
(modelName) => {
const model = filteredModels.find((m) => m.model_name === modelName);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 初始加载和category变化时重新加载
useEffect(() => {
loadModels();
}, [loadModels]);
return {
// 数据
allModels: models,
models: filteredModels,
selectedModel,
loading,
// 操作方法
loadModels,
filterByCategory,
selectModelById,
selectModelByName,
setSelectedModel,
};
};