Commit 2cb2a43f by renyizhao

对接api_hub

parent fba7e550
package com.luhu.computility.module.apihub.api.apihub;
import java.math.BigDecimal;
/**
* api_hub 用户相关 API 接口
*
* <p>供其他模块(member 等)通过 RPC 调用 apihub 模块查询 api_hub 网关用户信息。
*
* @author luhu
*/
public interface ApiHubUserApi {
/**
* 获取 api_hub 网关上指定用户的当前余额(单位:元,保留 2 位小数)。
*
* <p>api_hub 的额度单位本身就是「元」,此处按配置项
* {@code computility.api-hub.quota-per-yuan}(默认 1)换算成「元」。
*
* <p>失败时(如 api_hub 不可达、用户不存在)返回 {@code null},由调用方自行决定 fallback。
*
* @param apiHubUserId api_hub 用户 ID(对应 member_user.api_hub_user_id),用于校验匹配到的用户
* @param apiHubUsername api_hub 用户名(登录账号,对应 member_user.api_hub_username)
* @return 余额(元),失败返回 {@code null}
*/
BigDecimal getQuotaYuan(Long apiHubUserId, String apiHubUsername);
}
package com.luhu.computility.module.apihub.api.newapi;
import java.math.BigDecimal;
/**
* New API 用户相关 API 接口
*
* <p>供其他模块(member 等)通过 RPC 调用 apihub 模块查询 New API 网关用户信息。
*
* @author luhu
*/
public interface NewApiUserApi {
/**
* 获取 New API 网关上指定用户的当前余额(单位:元,保留 2 位小数)。
*
* <p>失败时(如 token 失效、网络异常)返回 {@code null},由调用方自行决定 fallback。
*
* @param accessToken New API 网关用户 access_token
* @param newApiUserId New API 网关用户 ID
* @return 余额(元),失败返回 {@code null}
*/
BigDecimal getQuotaYuan(String accessToken, Integer newApiUserId);
}
package com.luhu.computility.module.apihub.api;
import com.luhu.computility.module.apihub.api.newapi.NewApiUserApi;
import com.luhu.computility.module.apihub.controller.admin.newapi.NewApiResponse;
import com.luhu.computility.module.apihub.service.newapi.NewApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
/**
* {@link NewApiUserApi} 实现,封装 New API 网关用户余额查询。
*
* <p>复用现有 {@link NewApiClient#getUserInfo}(quota 单位 1元 = 500000),
* 在此层把 quota 转换成元(保留 2 位小数)。
*
* @author luhu
*/
@Slf4j
@Service
public class NewApiUserApiServiceImpl implements NewApiUserApi {
/** New API 配额单位:1 元 = 500000 quota */
private static final BigDecimal QUOTA_PER_YUAN = new BigDecimal("500000");
@Resource
private NewApiClient newApiClient;
@Override
public BigDecimal getQuotaYuan(String accessToken, Integer newApiUserId) {
if (accessToken == null || accessToken.isEmpty() || newApiUserId == null) {
return null;
}
try {
NewApiResponse<Map<String, Object>> resp = newApiClient.getUserInfo(accessToken, newApiUserId);
if (resp == null || !Boolean.TRUE.equals(resp.getSuccess()) || resp.getData() == null) {
log.warn("[NewApiUserApi.getQuotaYuan] New API 返回失败 newApiUserId={} message={}",
newApiUserId, resp == null ? "null" : resp.getMessage());
return null;
}
Object quotaObj = resp.getData().get("quota");
if (!(quotaObj instanceof Number)) {
log.warn("[NewApiUserApi.getQuotaYuan] quota 字段缺失或非数值 newApiUserId={} quota={}",
newApiUserId, quotaObj);
return null;
}
long quota = ((Number) quotaObj).longValue();
return BigDecimal.valueOf(quota)
.divide(QUOTA_PER_YUAN, 2, RoundingMode.HALF_UP);
} catch (Exception e) {
log.error("[NewApiUserApi.getQuotaYuan] 查询 New API 余额异常 newApiUserId={}", newApiUserId, e);
return null;
}
}
}
package com.luhu.computility.module.apihub.api.apihub;
import cn.hutool.core.util.StrUtil;
import com.luhu.computility.module.apihub.config.ApiHubProperties;
import com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubResponse;
import com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubUserVO;
import com.luhu.computility.module.apihub.service.apihub.ApiHubClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* {@link ApiHubUserApi} 实现,封装 api_hub 网关用户余额查询。
*
* <p>取数走管理端接口 {@code GET /api/users}(api_hub 没有按用户 ID 查单个用户的接口,
* {@code q=} 是 username / mobile 的模糊匹配,故取回后在本地按 username 精确过滤)。
* 接口返回的 {@code quota} 是「可用余额」= {@code max(0, quota - used_quota)},单位是元。
*
* @author luhu
*/
@Slf4j
@Service
public class ApiHubUserApiServiceImpl implements ApiHubUserApi {
@Resource
private ApiHubClient apiHubClient;
@Resource
private ApiHubProperties apiHubProperties;
@Override
public BigDecimal getQuotaYuan(Long apiHubUserId, String apiHubUsername) {
if (StrUtil.isBlank(apiHubUsername)) {
return null;
}
try {
ApiHubResponse<ApiHubUserVO> resp = apiHubClient.getUserByUsername(apiHubUsername);
if (!Boolean.TRUE.equals(resp.getSuccess()) || resp.getData() == null) {
log.warn("[ApiHubUserApi.getQuotaYuan] 查询 api_hub 用户失败, username={}, message={}",
apiHubUsername, resp.getMessage());
return null;
}
ApiHubUserVO user = resp.getData();
// api_hub_user_id 与查回的用户不一致说明本地记录与 api_hub 已经脱节,余额不可信
if (apiHubUserId != null && !apiHubUserId.equals(user.getId())) {
log.warn("[ApiHubUserApi.getQuotaYuan] api_hub 用户 ID 不匹配, 本地={}, api_hub={}, username={}",
apiHubUserId, user.getId(), apiHubUsername);
return null;
}
BigDecimal quota = user.getQuota() != null
? BigDecimal.valueOf(user.getQuota())
: BigDecimal.ZERO;
// api_hub 额度单位就是元,quotaPerYuan 默认 1;保留配置项是为了将来可调
BigDecimal quotaPerYuan = apiHubProperties.getQuotaPerYuan();
if (quotaPerYuan == null || quotaPerYuan.compareTo(BigDecimal.ZERO) <= 0) {
log.error("[ApiHubUserApi.getQuotaYuan] 额度换算比例配置非法: {}", quotaPerYuan);
return null;
}
return quota.divide(quotaPerYuan, 2, RoundingMode.HALF_UP);
} catch (Exception e) {
log.error("[ApiHubUserApi.getQuotaYuan] 查询 api_hub 余额异常, username={}", apiHubUsername, e);
return null;
}
}
}
package com.luhu.computility.module.apihub.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
/**
* api_hub 管理端配置项
*
* <p>api_hub 管理端接口统一在 /api 前缀下,对外接口在 /v1/open 与 /v1/data。
*
* @author puhui
*/
@Component
@ConfigurationProperties(prefix = "computility.api-hub")
@Data
public class ApiHubProperties {
/**
* api_hub 服务根地址,例如 http://127.0.0.1:8000
*/
private String baseUrl;
/**
* 管理端账号(需具备 users:write / tokens:write 权限,即 admin 或 operator 角色)
*/
private String adminUsername;
/**
* 管理端账号密码,需能取明文:阶段 5 的充值接口要求请求体带 password 做二次确认
*/
private String adminPassword;
/**
* 对外 Data API Key,本期预留不使用(管理端路径不需要,对外接口才需要)
*/
private String dataApiKey;
/**
* api_hub 额度单位与「元」的换算比例:1 元 = 多少个 api_hub 额度单位
*
* <p>api_hub 的额度单位本身<strong>就是「元」</strong>:{@code users.quota} 是浮点元,
* 入账逻辑 {@code _credit_quota} 累加的 amount 也是元,与 new-api 的 500000 quota/元
* 完全不同,故默认值是 1。保留配置项是为了将来额度单位变化时可调,不在代码里硬编码。
*/
private BigDecimal quotaPerYuan = new BigDecimal("1");
}
package com.luhu.computility.module.apihub.controller.admin.apihub;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import java.util.List;
/**
* api_hub 管理端模型售价对象(对应 {@code GET /api/model-prices} 的单行)
*
* <p>api_hub 返回字段为下划线风格(sell_multiplier / video_price_480p),此处按蛇形映射;
* 视频分档价字段名里的数字紧跟下划线(如 {@code video_price_480p}),
* 蛇形策略无法自动还原,故单独用 {@link JsonProperty} 指定。
*
* @author puhui
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class ApiHubModelPriceVO {
/**
* model_prices 表主键;为 null 表示该模型未在「模型售价」里配置(仅渠道里有)
*/
private Long id;
/**
* 渠道 ID
*/
private Integer channelId;
/**
* 渠道名
*/
private String channelName;
/**
* 模型名(真实名)
*/
private String model;
/**
* 模型别名(对外暴露的模型 id;为空时对外就是 model 本身)
*/
private String alias;
/**
* 输入价格(标价,元 / 百万 token)
*/
private Double inputPrice;
/**
* 输出价格(标价,元 / 百万 token)
*/
private Double outputPrice;
/**
* 缓存读取价格(标价,元 / 百万 token)
*/
private Double cacheInputPrice;
/**
* 缓存写入价格(标价,元 / 百万 token)
*/
private Double cacheOutputPrice;
/**
* 图片价格(标价,元 / 张)
*/
private Double imagePrice;
/**
* 视频价格 480p(标价,元 / 次)
*/
@JsonProperty("video_price_480p")
private Double videoPrice480p;
/**
* 视频价格 720p(标价,元 / 次)
*/
@JsonProperty("video_price_720p")
private Double videoPrice720p;
/**
* 视频价格 1080p(标价,元 / 次)
*/
@JsonProperty("video_price_1080p")
private Double videoPrice1080p;
/**
* 售卖倍率(标价 → 售价,计价时乘在标价上)
*/
private Double sellMultiplier;
/**
* 模型折扣(折数,0 表示无折扣;8.5 表示 8.5 折)
*/
private Double discount;
/**
* 上下文长度
*/
private String contextLength;
/**
* 最大输出长度
*/
private String maxOutputLength;
/**
* 模型类型标签(text / multimodal / image_gen / video_gen / embedding / rerank / speech)
*/
private List<String> modalities;
/**
* 是否在售
*
* <p>api_hub 这个字段类型不统一:已在「模型售价」里配置的行是数字 {@code 1},
* 仅渠道存在但未配置售价的行是布尔 {@code false},故这里用 Object 接收再归一化。
*/
private Object enabled;
/**
* 是否被系统自动隔离停售
*/
private Boolean autoQuarantined;
}
package com.luhu.computility.module.apihub.controller.admin.apihub;
import cn.hutool.http.HttpResponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* api_hub 管理端接口响应包装
*
* <p>api_hub 管理端接口直接返回业务对象(如创建用户返回用户行、创建密钥返回密钥行),
* 出错时返回 HTTP 4xx/5xx 与 {@code {"ok": false, "detail": "..."}},
* 与 new-api 的 {@code {success, message, data}} 结构不同,故单独建模。
*
* @author puhui
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApiHubResponse<T> {
/**
* 是否成功(HTTP 状态码为 2xx)
*/
private Boolean success;
/**
* 错误信息,来自响应体的 detail 字段
*/
private String message;
/**
* 业务数据
*/
private T data;
/**
* HTTP 状态码
*/
private Integer status;
/**
* 原始响应,用于需要读取响应头的场景
*/
private HttpResponse httpResponse;
}
package com.luhu.computility.module.apihub.controller.admin.apihub;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
/**
* api_hub 管理端密钥对象(对应 tokens 表行)
*
* <p>api_hub 返回字段为下划线风格(user_id / key_prefix),此处按蛇形映射。
*
* @author puhui
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class ApiHubTokenVO {
/**
* 密钥 ID
*/
private Long id;
/**
* 所属 api_hub 用户 ID
*/
private Long userId;
/**
* 密钥名称
*/
private String name;
/**
* 密钥种类
*/
private String kind;
/**
* 密钥前缀(明文不会在列表接口返回)
*/
private String keyPrefix;
/**
* 是否不限额(api_hub 用 0/1 表示)
*/
private Integer unlimited;
/**
* 是否启用(api_hub 用 0/1 表示)
*/
private Integer enabled;
/**
* 创建密钥时接口会额外返回明文 key,复用已有密钥时需再调 reveal 接口获取
*/
private String key;
}
package com.luhu.computility.module.apihub.controller.admin.apihub;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
/**
* api_hub 管理端用户对象(对应 users 表行)
*
* <p>api_hub 返回字段为下划线风格(group_name / used_quota),此处按蛇形映射。
*
* @author puhui
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class ApiHubUserVO {
/**
* api_hub 用户 ID
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 手机号
*/
private String mobile;
/**
* 角色
*/
private String role;
/**
* 分组名称
*/
private String groupName;
/**
* 剩余额度
*/
private Double quota;
/**
* 已用额度
*/
private Double usedQuota;
/**
* 用户价格倍率(api_hub 计费时乘在标价上,默认 1)
*/
private Double priceMultiplier;
/**
* 是否启用(api_hub 用 0/1 表示)
*/
private Integer enabled;
}
package com.luhu.computility.module.apihub.controller.app;
import cn.hutool.core.util.StrUtil;
import com.luhu.computility.framework.security.core.util.SecurityFrameworkUtils;
import com.luhu.computility.module.apihub.config.NewApiProperties;
import com.luhu.computility.module.apihub.api.apihub.ApiHubUserApi;
import com.luhu.computility.module.apihub.config.ApiHubProperties;
import com.luhu.computility.module.apihub.controller.admin.newapi.AiTokenRespVO;
import com.luhu.computility.module.apihub.controller.admin.newapi.NewApiResponse;
import com.luhu.computility.module.apihub.service.newapi.AiTokenService;
import com.luhu.computility.module.apihub.service.newapi.NewApiClient;
import com.luhu.computility.module.member.dal.dataobject.user.MemberUserDO;
import com.luhu.computility.module.member.service.user.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import java.math.BigDecimal;
@Slf4j
@RestController
......@@ -26,10 +26,10 @@ public class AppAiTokenController {
private MemberUserService memberUserService;
@Resource
private NewApiClient newApiClient;
private ApiHubUserApi apiHubUserApi;
@Resource
private NewApiProperties newApiProperties;
private ApiHubProperties apiHubProperties;
@PostMapping("/get")
public AiTokenRespVO getToken() {
......@@ -45,34 +45,37 @@ public class AppAiTokenController {
.build();
}
log.info("[获取令牌] 用户信息: newapiUsername={}, newapiPassword={}, newapiUserId={}, newapiAccessToken={}, newapiKey={}",
user.getNewapiUsername(), user.getNewapiPassword() != null ? "***" : null,
user.getNewapiUserId(), user.getNewapiAccessToken() != null ? "***" : null,
user.getNewapiKey() != null ? "***" : null);
log.info("[获取令牌] 用户信息: apiHubUsername={}, apiHubUserId={}, apiHubTokenId={}, apiHubKey={}",
user.getApiHubUsername(), user.getApiHubUserId(), user.getApiHubTokenId(),
user.getApiHubKey() != null ? "***" : null);
AiTokenService.AiTokenResult result = aiTokenService.getOrCreateToken(
user.getId(),
user.getMobile(),
user.getNewapiUsername(),
user.getNewapiPassword(),
user.getNewapiUserId(),
user.getNewapiAccessToken(),
user.getNewapiKey()
user.getApiHubUserId(),
user.getApiHubUsername(),
user.getApiHubPassword(),
user.getApiHubTokenId(),
user.getApiHubKey()
);
log.info("[获取令牌] 结果: success={}, hasToken={}, apiKey={}, message={}",
result.getSuccess(), result.getHasToken(),
result.getApiKey() != null ? "***" : null, result.getMessage());
if (Boolean.TRUE.equals(result.getSuccess()) || result.getNewApiUserId() != null || result.getNewApiUsername() != null) {
log.info("[获取令牌] 更新用户NewAPI信息");
memberUserService.updateNewApiInfo(
// 只有完整拿到 api_hub 用户ID + 密钥ID + 明文密钥才落库,失败时不写入半截数据
if (Boolean.TRUE.equals(result.getSuccess())
&& result.getApiHubUserId() != null
&& result.getApiHubTokenId() != null
&& result.getApiHubKey() != null && !result.getApiHubKey().isEmpty()) {
log.info("[获取令牌] 更新用户 api_hub 信息");
memberUserService.updateApiHubInfo(
userId,
result.getNewApiUserId() != null ? result.getNewApiUserId() : user.getNewapiUserId(),
result.getNewApiAccessToken() != null ? result.getNewApiAccessToken() : user.getNewapiAccessToken(),
result.getApiKey() != null ? result.getApiKey() : user.getNewapiKey(),
result.getNewApiUsername() != null ? result.getNewApiUsername() : user.getNewapiUsername(),
result.getNewApiPassword() != null ? result.getNewApiPassword() : user.getNewapiPassword()
result.getApiHubUserId(),
result.getApiHubUsername(),
result.getApiHubPassword(),
result.getApiHubTokenId(),
result.getApiHubKey()
);
}
......@@ -98,37 +101,23 @@ public class AppAiTokenController {
.build();
}
boolean hasToken = user.getNewapiKey() != null && !user.getNewapiKey().isEmpty();
boolean hasToken = StrUtil.isNotBlank(user.getApiHubKey());
log.info("[查询令牌] hasToken={}, apiKey={}", hasToken, hasToken ? "***" : null);
// 获取 New API 真实余额
String balance = "0.00";
if (hasToken && user.getNewapiUserId() != null && user.getNewapiAccessToken() != null) {
try {
Integer newapiUserId = Integer.parseInt(user.getNewapiUserId().toString());
NewApiResponse<Map<String, Object>> infoResp = newApiClient.getUserInfo(
user.getNewapiAccessToken(), newapiUserId);
if (infoResp.getSuccess() && infoResp.getData() != null) {
Map<String, Object> data = infoResp.getData();
Long quota = data.get("quota") != null ? ((Number) data.get("quota")).longValue() : 0L;
// 1元 = 500000 quota
double yuan = quota / 500000.0;
balance = String.format("%.2f", yuan);
log.info("[查询令牌] New API 余额: quota={}, yuan={}", quota, balance);
}
} catch (Exception e) {
log.error("[查询令牌] 获取 New API 余额失败", e);
}
// api_hub 余额:查询失败(api_hub 不可达 / 用户不存在)时返回 null,前端展示 "--"
BigDecimal balance = null;
if (hasToken) {
balance = apiHubUserApi.getQuotaYuan(user.getApiHubUserId(), user.getApiHubUsername());
log.info("[查询令牌] api_hub 余额: {}", balance);
}
AiTokenRespVO.AiTokenRespVOBuilder builder = AiTokenRespVO.builder()
return AiTokenRespVO.builder()
.success(true)
.hasToken(hasToken)
.apiKey(user.getNewapiKey())
.balance(balance)
.baseUrl(newApiProperties.getBaseUrl());
return builder.build();
.apiKey(user.getApiHubKey())
.balance(balance != null ? balance.toPlainString() : null)
.baseUrl(apiHubProperties.getBaseUrl())
.build();
}
}
\ No newline at end of file
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* APP端 - 模型定价信息 VO(聚合后)
* 模型市场「模型 + 价格」返回对象
*
* <p>数据来源已切换为 api_hub({@code GET /api/model-prices}),价格口径与 api_hub 一致:
* <ul>
* <li>输入/输出/缓存价格单位是「元 / 百万 token」,已是用户实际扣费价(含售卖倍率与折扣)</li>
* <li>图片价格单位是「元 / 张」,视频分档价格单位是「元 / 秒」(api_hub 按生成秒数 × 档位价计费)</li>
* </ul>
*
* @author puhui
*/
@Data
@Accessors(chain = true)
@Schema(description = "APP端 - 模型定价信息")
public class AppModelPricingVO {
@Schema(description = "模型名")
/**
* 模型名(对外 id:api_hub 有别名时是别名,否则是真实模型名)
*/
private String modelName;
@Schema(description = "图标名(lobehub 风格,如 Qwen.Color)")
/**
* 模型图标
*/
private String icon;
@Schema(description = "供应商名")
/**
* 模型厂商
*/
private String vendorName;
@Schema(description = "支持的端点列表")
private List<String> supportedEndpoints;
@Schema(description = "支持的分组列表")
private List<String> enableGroups;
@Schema(description = "计价方式:0-按倍率,1-按固定价")
private Integer quotaType;
@Schema(description = "模型倍率")
private BigDecimal modelRatio;
@Schema(description = "固定价(元/1k tokens)")
private BigDecimal modelPrice;
@Schema(description = "补全价格倍率")
private BigDecimal completionRatio;
@Schema(description = "缓存读取价格倍率")
private BigDecimal cacheRatio;
/**
* 支持的端点
*/
private List<String> supportedEndpoints = new ArrayList<>();
@Schema(description = "缓存创建价格倍率")
private BigDecimal createCacheRatio;
/**
* 计量方式:0=按量(token 计费)、1=按次(图片按张等)、2=按分辨率分档(视频)
*/
private Integer quotaType = 0;
@Schema(description = "当前用户分组倍率")
private BigDecimal groupRatio;
/**
* 价格类型:metered=按量、per_image=按张、per_video=视频分档
*/
private String priceType;
@Schema(description = "输入价格(元/1k tokens),已乘 groupRatio")
/**
* 输入价格(元 / 百万 token)
*/
private BigDecimal inputPrice;
@Schema(description = "输出价格(元/1k tokens),已乘 groupRatio")
/**
* 输出价格(元 / 百万 token)
*/
private BigDecimal outputPrice;
@Schema(description = "缓存读取价格(元/1k tokens),已乘 groupRatio")
/**
* 缓存读取价格(元 / 百万 token)
*/
private BigDecimal cacheReadPrice;
@Schema(description = "缓存创建价格(元/1k tokens),已乘 groupRatio")
/**
* 缓存写入价格(元 / 百万 token)
*/
private BigDecimal cacheCreatePrice;
@Schema(description = "图片输入价格(元/1k tokens),已乘 groupRatio")
private BigDecimal imageInputPrice;
/**
* 图片价格(元 / 张)
*/
private BigDecimal imagePrice;
@Schema(description = "音频输入价格(元/1k tokens),已乘 groupRatio")
private BigDecimal audioInputPrice;
/**
* 视频价格 480p(元 / 秒)
*/
private BigDecimal videoPrice480p;
@Schema(description = "音频补全价格(元/1k tokens),已乘 groupRatio")
private BigDecimal audioCompletionPrice;
/**
* 视频价格 720p(元 / 秒)
*/
private BigDecimal videoPrice720p;
@Schema(description = "状态:1-启用,0-禁用")
private Integer status;
/**
* 视频价格 1080p(元 / 秒)
*/
private BigDecimal videoPrice1080p;
@Schema(description = "模型描述(未设置则为空)")
/**
* 状态:1=启用、0=禁用
*/
private Integer status = 1;
/**
* 模型描述
*/
private String description;
@Schema(description = "模型标签,多个用逗号分隔")
/**
* 标签(逗号分隔)
*/
private String tags;
@Schema(description = "计费模式:tiered_expr-分档计费")
private String billingMode;
@Schema(description = "分档计费表达式")
private String billingExpr;
@Schema(description = "分档列表")
private List<TierVO> tiers;
@Schema(description = "条件乘数列表")
private List<ConditionMultiplierVO> conditionMultipliers;
@Schema(description = "API 使用示例(含 endpoint、profile、providers、groups)")
private List<ApiExampleVO> apiExamples;
@Schema(description = "端点 → URL 路径映射(来自 pricing.supported_endpoint,每个模型都带,便于前端按需取)")
private Map<String, Map<String, Object>> endpoints;
@Schema(description = "计费用法 schema(仅 openai-video 等模型有)")
private Map<String, Object> billingUsageSchema;
@Schema(description = "计费用法示例")
private List<Map<String, Object>> billingUsageExamples;
/**
* API 使用示例(来自 pricing.txt 的 api_examples 数组)
* 计费模式:视频分档模型为 {@code video_tiered},其余为空
*/
@Data
@Schema(description = "API 使用示例")
public static class ApiExampleVO {
@Schema(description = "端点类型,如 openai、openai-video、embeddings")
private String endpoint;
@Schema(description = "调用配置,如 standard、seedance2、ctyun-seedream")
private String profile;
@Schema(description = "服务商列表")
private List<String> providers;
@Schema(description = "适用分组列表")
private List<String> groups;
}
private String billingMode;
/**
* 分档信息 VO
* 上下文长度
*/
@Data
@Schema(description = "分档信息")
public static class TierVO {
@Schema(description = "档位名称")
private String name;
@Schema(description = "输入倍率")
private BigDecimal inputRatio;
@Schema(description = "输出倍率")
private BigDecimal outputRatio;
@Schema(description = "档位条件描述")
private String conditionDesc;
// 扩展价格倍率
@Schema(description = "缓存读取倍率")
private BigDecimal cacheReadRatio;
@Schema(description = "缓存创建倍率(5分钟)")
private BigDecimal cacheCreateRatio;
@Schema(description = "缓存创建倍率(1小时)")
private BigDecimal cacheCreate1hRatio;
@Schema(description = "图片输入倍率")
private BigDecimal imageInputRatio;
@Schema(description = "图片输出倍率")
private BigDecimal imageOutputRatio;
@Schema(description = "音频输入倍率")
private BigDecimal audioInputRatio;
@Schema(description = "音频输出倍率")
private BigDecimal audioOutputRatio;
private String contextLength;
/**
* 按 usage 计费的倍率(seedance / happyhorse 风格 u("field") * X 中的 X)。
* 适用于 openai-video 等按动态字段(token/second/count)计费的档位。
* 单位 = 元 / 每 usageUnit 单位(tokens 时为每百万 token,需配合 schema 推断)。
* 前端展示时优先于 inputRatio/outputRatio。
* 最大输出长度
*/
@Schema(description = "按 usage 计费的倍率(u(\"field\") * X 中的 X)")
private BigDecimal tokensMultiplier;
private String maxOutputLength;
/**
* tokensMultiplier 对应的计费字段名(如 tokens/seconds)。
* 仅当 tokensMultiplier 非空时有意义,用于前端明确当前档位在计什么。
* 所属渠道名
*/
@Schema(description = "tokensMultiplier 对应的计费字段名(如 tokens/seconds/input_images)")
private String usageField;
private String channelName;
/**
* usageField 在 billing_usage_schema 中的 unit(如 token/second/count)。
* 仅当 tokensMultiplier 非空时有意义,用于前端选择展示单位文案(token/秒/次)。
* 模型类型标签(text / multimodal / image_gen / video_gen / embedding / rerank / speech)
*/
@Schema(description = "usageField 在 schema 中的 unit(token/second/count),用于前端选择展示单位文案")
private String usageUnit;
}
private List<String> modalities = new ArrayList<>();
/**
* 条件乘数 VO
* 使用方法:一个端点一条(含调用示例与参数说明)
*
* <p>一个模型带多个模型类型时会有多条
*/
@Data
@Schema(description = "条件乘数")
public static class ConditionMultiplierVO {
@Schema(description = "条件描述(用户可读的文字)")
private String description;
@Schema(description = "倍率")
private BigDecimal multiplier;
}
private List<AppModelUsageVO> usageMethods = new ArrayList<>();
}
\ No newline at end of file
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 模型调用示例(某种编程语言的代码片段)
*
* @author puhui
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppModelSampleVO {
/**
* 编程语言标识:curl / python / typescript / javascript
*/
private String language;
/**
* 语言名称,如 cURL / Python / TypeScript / JavaScript
*/
private String title;
/**
* 示例代码
*/
private String code;
}
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
/**
* 模型「使用方法」返回对象:一个端点 = 一段调用示例 + 一张参数说明表
*
* <p>一个模型可能带多个模型类型(如同时是 text 与 embedding),此时会有多条使用方式说明,
* 每条对应 api_hub 的一个真实端点。
*
* @author puhui
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppModelUsageVO {
/**
* 端点标识:chat / embeddings / rerank / images / videos / audio
*/
private String endpoint;
/**
* 端点中文名,如 对话补全
*/
private String endpointName;
/**
* 请求方法,api_hub 的这几个端点都是 POST
*/
private String method;
/**
* 请求路径,如 /v1/chat/completions
*/
private String path;
/**
* 对外 base_url(含 /v1),用户拼完整地址用
*/
private String baseUrl;
/**
* 各语言调用示例
*/
private List<AppModelSampleVO> samples = new ArrayList<>();
/**
* 参数说明
*/
private List<AppParamVO> params = new ArrayList<>();
}
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.List;
/**
* APP端 - 模型信息 VO
*/
@Data
@Accessors(chain = true)
@Schema(description = "APP端 - 模型信息")
public class AppModelVO {
@Schema(description = "模型ID")
private Long id;
@Schema(description = "模型名")
private String modelName;
@Schema(description = "图标名")
private String icon;
@Schema(description = "供应商名(自动匹配)")
private String vendorName;
@Schema(description = "支持的端点")
private List<String> endpoints;
@Schema(description = "支持的分组")
private List<String> enableGroups;
@Schema(description = "状态:1-启用,0-禁用")
private Integer status;
@Schema(description = "模型描述(未设置则为空)")
private String description;
}
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 模型调用参数说明
*
* <p>参数说明由 puhui 侧静态配置维护({@code resources/apihub/endpoint-params.yaml}),
* 只列 api_hub 自身会读取、校验或有确定语义的参数;api_hub 原样透传给上游、
* 自己不解释的参数不列,避免误导用户。
*
* @author puhui
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppParamVO {
/**
* 参数名
*/
private String name;
/**
* 参数类型,如 string / number / boolean / array / object
*/
private String type;
/**
* 是否必填
*/
private Boolean required;
/**
* 默认值,无默认值时为空
*/
private String defaultValue;
/**
* 取值范围,无范围限制时为空
*/
private String range;
/**
* 用户可读说明
*/
private String description;
}
package com.luhu.computility.module.apihub.controller.app.aimodel.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.List;
import java.util.Map;
/**
* APP端 - 定价信息 VO
*/
@Data
@Accessors(chain = true)
@Schema(description = "APP端 - 定价信息")
public class AppPricingVO {
@Schema(description = "当前用户所属分组名")
private String group;
@Schema(description = "当前分组倍率")
private java.math.BigDecimal groupRatio;
@Schema(description = "所有可用分组及倍率")
private Map<String, java.math.BigDecimal> groupRatios;
@Schema(description = "支持的端点")
private Map<String, Object> supportedEndpoint;
@Schema(description = "供应商列表(用于图标 fallback)")
private List<Map<String, Object>> vendors;
@Schema(description = "模型定价列表(原始数据)")
private List<Map<String, Object>> modelPricing;
}
......@@ -20,8 +20,6 @@ public class SecurityConfiguration {
public void customize(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry registry) {
// APP 端 AI 模型与定价接口:未登录也可访问(按游客价格展示)
// 注:URL 实际为 /app-api/app/ai/xxx(prefix=/app-api,controller RequestMapping=/app/ai)
registry.requestMatchers(buildAppApi("/app/ai/pricing")).permitAll();
registry.requestMatchers(buildAppApi("/app/ai/models")).permitAll();
registry.requestMatchers(buildAppApi("/app/ai/models-with-pricing")).permitAll();
}
......
package com.luhu.computility.module.apihub.service.apihub;
/**
* api_hub 对外网关(/v1)支持的端点
*
* <p>路径与 api_hub 的 {@code app/api/gateway.py} 路由一一对应,示例代码里的路径必须
* 与此处完全一致,否则用户复制出去会 404。
*
* <p>api_hub 只提供 OpenAI 兼容风格,没有 Anthropic Messages、Gemini generateContent
* 这类专有路径。
*
* @author puhui
*/
public enum ApiHubEndpoint {
/**
* 对话补全(OpenAI 兼容)
*/
CHAT("chat", "对话补全", "/v1/chat/completions", "chat.completions.create"),
/**
* 向量嵌入
*/
EMBEDDINGS("embeddings", "向量嵌入", "/v1/embeddings", "embeddings.create"),
/**
* 文本重排
*/
RERANK("rerank", "文本重排", "/v1/rerank", null),
/**
* 图像生成
*/
IMAGES("images", "图像生成", "/v1/images/generations", "images.generate"),
/**
* 视频生成
*/
VIDEOS("videos", "视频生成", "/v1/videos/generations", null),
/**
* 语音合成
*/
AUDIO("audio", "语音合成", "/v1/audio/speech", null);
/**
* 端点标识
*/
private final String id;
/**
* 端点中文名
*/
private final String name;
/**
* 相对 base_url 的请求路径
*/
private final String path;
/**
* OpenAI 官方 SDK 里的调用方法路径,如 chat.completions.create;为 null 表示
* 没有官方 SDK 方法,示例里用裸 HTTP 请求
*/
private final String sdkMethod;
ApiHubEndpoint(String id, String name, String path, String sdkMethod) {
this.id = id;
this.name = name;
this.path = path;
this.sdkMethod = sdkMethod;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public String getSdkMethod() {
return sdkMethod;
}
/**
* 是否能用 OpenAI 官方 SDK 调用
*/
public boolean isSdkSupported() {
return sdkMethod != null;
}
}
package com.luhu.computility.module.apihub.service.apihub;
import com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppParamVO;
import java.util.List;
/**
* 端点参数说明提供者
*
* <p>api_hub 没有任何参数元数据,参数说明只能由 puhui 侧维护。抽成接口是为了留一个
* 替换点:若后续 api_hub 提供了模型元数据接口(计划里的 R1),换成从那里取即可,
* 上层的组装逻辑不用动。
*
* @author puhui
*/
public interface ApiHubEndpointParamProvider {
/**
* 取某个端点的参数说明
*
* @param endpointId 端点标识,如 chat
* @return 参数说明列表,端点不存在时返回空列表
*/
List<AppParamVO> getParams(String endpointId);
}
package com.luhu.computility.module.apihub.service.apihub;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 端点注册表:模型类型 → 端点,以及各端点的请求体模板
*
* <p>模型类型取自 api_hub 的 {@code model_prices.modalities}(api_hub 内部叫「模型类型」,
* 取值与 {@code db.MODEL_TYPE_LABELS} 一致)。一个对外模型 id 可能同时带多个类型
* (同一行配多个类型,或跨渠道合并),因此这里返回的是端点列表而不是单个端点。
*
* @author puhui
*/
@Component
public class ApiHubEndpointRegistry {
/**
* 模型类型 → 端点。api_hub 的七类模型类型里,multimodal 与 text 走同一个对话端点。
*/
private static final Map<String, ApiHubEndpoint> TYPE_ENDPOINT_MAP = new LinkedHashMap<>();
/**
* 各端点的请求体模板(JSON 缩进格式,{@code {{model}}} 会被替换成对外模型 id)
*
* <p>模板里的字段只取 api_hub 自身会读取或校验的参数,不铺开 OpenAI 的全量参数:
* 那些参数 api_hub 原样透传给上游,能否生效完全取决于渠道上游,写进文档会误导用户。
*
* <p>这是请求体的唯一事实来源,curl / 裸 HTTP / OpenAI SDK 三种示例都从它渲染,
* 避免多处模板各写一份、改一处漏一处。
*/
private static final Map<ApiHubEndpoint, String> BODY_TEMPLATES = new LinkedHashMap<>();
/**
* 各端点响应里值得打印的字段路径
*/
private static final Map<ApiHubEndpoint, String[]> RESPONSE_HINTS = new LinkedHashMap<>();
static {
TYPE_ENDPOINT_MAP.put("text", ApiHubEndpoint.CHAT);
TYPE_ENDPOINT_MAP.put("multimodal", ApiHubEndpoint.CHAT);
TYPE_ENDPOINT_MAP.put("embedding", ApiHubEndpoint.EMBEDDINGS);
TYPE_ENDPOINT_MAP.put("rerank", ApiHubEndpoint.RERANK);
TYPE_ENDPOINT_MAP.put("image_gen", ApiHubEndpoint.IMAGES);
TYPE_ENDPOINT_MAP.put("video_gen", ApiHubEndpoint.VIDEOS);
TYPE_ENDPOINT_MAP.put("speech", ApiHubEndpoint.AUDIO);
BODY_TEMPLATES.put(ApiHubEndpoint.CHAT, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"messages\": [\n"
+ " {\n"
+ " \"role\": \"user\",\n"
+ " \"content\": \"你好,请介绍一下你自己。\"\n"
+ " }\n"
+ " ]\n"
+ "}");
RESPONSE_HINTS.put(ApiHubEndpoint.CHAT, new String[]{"response.choices[0].message.content"});
BODY_TEMPLATES.put(ApiHubEndpoint.EMBEDDINGS, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"input\": \"需要向量化的文本\"\n"
+ "}");
RESPONSE_HINTS.put(ApiHubEndpoint.EMBEDDINGS, new String[]{"response.data[0].embedding"});
BODY_TEMPLATES.put(ApiHubEndpoint.RERANK, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"query\": \"什么是向量检索?\",\n"
+ " \"documents\": [\n"
+ " \"向量检索是在语义空间做近似匹配的技术\",\n"
+ " \"本平台通过 api_hub 对外提供模型能力\"\n"
+ " ],\n"
+ " \"top_n\": 2\n"
+ "}");
BODY_TEMPLATES.put(ApiHubEndpoint.IMAGES, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"prompt\": \"一只戴着围巾的橘猫,坐在窗边\"\n"
+ "}");
RESPONSE_HINTS.put(ApiHubEndpoint.IMAGES, new String[]{"response.data[0].url"});
BODY_TEMPLATES.put(ApiHubEndpoint.VIDEOS, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"prompt\": \"镜头缓慢推近,落日下的海边\",\n"
+ " \"resolution\": \"720p\",\n"
+ " \"duration\": 5,\n"
+ " \"ratio\": \"16:9\"\n"
+ "}");
BODY_TEMPLATES.put(ApiHubEndpoint.AUDIO, "{\n"
+ " \"model\": \"{{model}}\",\n"
+ " \"input\": \"你好,这是一段语音合成示例。\",\n"
+ " \"voice\": \"Cherry\"\n"
+ "}");
}
/**
* 按模型类型解析端点列表
*
* @param modelTypes 模型类型集合(api_hub 的 modalities),可为空
* @return 端点列表,按注册表固定顺序去重
*/
public List<ApiHubEndpoint> resolveEndpoints(Collection<String> modelTypes) {
if (modelTypes == null || modelTypes.isEmpty()) {
// 模型类型缺失时按最常见的对话模型处理
return Collections.singletonList(ApiHubEndpoint.CHAT);
}
List<ApiHubEndpoint> endpoints = new ArrayList<>();
for (Map.Entry<String, ApiHubEndpoint> entry : TYPE_ENDPOINT_MAP.entrySet()) {
if (!endpoints.contains(entry.getValue()) && containsIgnoreCase(modelTypes, entry.getKey())) {
endpoints.add(entry.getValue());
}
}
if (endpoints.isEmpty()) {
endpoints.add(ApiHubEndpoint.CHAT);
}
return endpoints;
}
/**
* 取端点的请求体模板
*/
public String bodyTemplate(ApiHubEndpoint endpoint) {
return BODY_TEMPLATES.get(endpoint);
}
/**
* 取端点响应里值得打印的字段路径
*/
public String[] responseHints(ApiHubEndpoint endpoint) {
String[] hints = RESPONSE_HINTS.get(endpoint);
return hints == null ? new String[0] : hints;
}
private boolean containsIgnoreCase(Collection<String> values, String target) {
for (String value : values) {
if (value != null && value.trim().equalsIgnoreCase(target)) {
return true;
}
}
return false;
}
/**
* 供测试与文档使用:全部模型类型
*/
public List<String> allModelTypes() {
return Collections.unmodifiableList(new ArrayList<>(TYPE_ENDPOINT_MAP.keySet()));
}
}
package com.luhu.computility.module.apihub.service.apihub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppModelSampleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 调用示例生成器
*
* <p>示例代码里的路径、模型名、请求体都取自 api_hub 的真实形态:
* 路径来自 {@link ApiHubEndpoint},模型名是用户实际能调用的对外 id,
* 请求体骨架来自 {@link ApiHubEndpointRegistry} 里唯一的 JSON 模板。
*
* @author puhui
*/
@Slf4j
@Component
public class ApiHubSampleBuilder {
private static final String API_KEY_PLACEHOLDER = "YOUR_API_KEY";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final ApiHubEndpointRegistry endpointRegistry;
public ApiHubSampleBuilder(ApiHubEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
}
/**
* 生成一个端点的全部语言示例
*
* @param endpoint 端点
* @param modelName 对外模型 id
* @param apiBase api_hub 对外地址(不带 /v1)
* @return 示例列表
*/
public List<AppModelSampleVO> build(ApiHubEndpoint endpoint, String modelName, String apiBase) {
String base = normalizeBase(apiBase);
String openAiBaseUrl = base + "/v1";
String url = base + endpoint.getPath();
String body = endpointRegistry.bodyTemplate(endpoint).replace("{{model}}", modelName);
List<AppModelSampleVO> samples = new ArrayList<>();
samples.add(AppModelSampleVO.builder()
.language("curl").title("cURL").code(buildCurl(url, body)).build());
samples.add(AppModelSampleVO.builder()
.language("python").title("Python").code(buildPython(endpoint, modelName, openAiBaseUrl, url, body)).build());
samples.add(AppModelSampleVO.builder()
.language("typescript").title("TypeScript").code(buildTypeScript(endpoint, modelName, openAiBaseUrl, url, body)).build());
samples.add(AppModelSampleVO.builder()
.language("javascript").title("JavaScript").code(buildJavaScript(endpoint, modelName, openAiBaseUrl, url, body)).build());
return samples;
}
/**
* 拼 cURL 示例
*/
private String buildCurl(String url, String body) {
return "curl -X POST \"" + url + "\" \\\n"
+ " -H \"Authorization: Bearer " + API_KEY_PLACEHOLDER + "\" \\\n"
+ " -H \"Content-Type: application/json\" \\\n"
+ " -d '" + body + "'";
}
/**
* 拼 Python 示例:能用 OpenAI SDK 的走 SDK,其余走 requests
*/
private String buildPython(ApiHubEndpoint endpoint, String modelName, String openAiBaseUrl, String url, String body) {
if (endpoint.isSdkSupported()) {
StringBuilder sb = new StringBuilder();
sb.append("from openai import OpenAI\n\n");
sb.append("client = OpenAI(api_key=\"").append(API_KEY_PLACEHOLDER)
.append("\", base_url=\"").append(openAiBaseUrl).append("\")\n\n");
sb.append("response = client.").append(endpoint.getSdkMethod()).append("(\n");
sb.append(renderSdkArgs(endpoint, modelName, " ", true));
sb.append(")\n");
sb.append("print(").append(pythonPrintExpression(endpoint)).append(")");
return sb.toString();
}
StringBuilder sb = new StringBuilder();
sb.append("import requests\n\n");
sb.append("response = requests.post(\n");
sb.append(" \"").append(url).append("\",\n");
sb.append(" headers={\n");
sb.append(" \"Authorization\": \"Bearer ").append(API_KEY_PLACEHOLDER).append("\",\n");
sb.append(" \"Content-Type\": \"application/json\",\n");
sb.append(" },\n");
sb.append(" json=").append(indentBlock(body, 4)).append(",\n");
sb.append(")\n");
sb.append("print(response.json())");
return sb.toString();
}
/**
* 拼 TypeScript 示例
*/
private String buildTypeScript(ApiHubEndpoint endpoint, String modelName, String openAiBaseUrl, String url, String body) {
return buildEsm(endpoint, modelName, openAiBaseUrl, url, body, true);
}
/**
* 拼 JavaScript 示例
*/
private String buildJavaScript(ApiHubEndpoint endpoint, String modelName, String openAiBaseUrl, String url, String body) {
return buildEsm(endpoint, modelName, openAiBaseUrl, url, body, false);
}
private String buildEsm(ApiHubEndpoint endpoint, String modelName, String openAiBaseUrl, String url, String body, boolean typed) {
StringBuilder sb = new StringBuilder();
if (endpoint.isSdkSupported()) {
sb.append("import OpenAI from \"openai\";\n\n");
sb.append("const client = new OpenAI({\n");
sb.append(" apiKey: \"").append(API_KEY_PLACEHOLDER).append("\",\n");
sb.append(" baseURL: \"").append(openAiBaseUrl).append("\",\n");
sb.append("});\n\n");
sb.append("const response = await client.").append(endpoint.getSdkMethod()).append("({\n");
sb.append(renderSdkArgs(endpoint, modelName, " ", false));
sb.append("});\n");
sb.append("console.log(").append(jsPrintExpression(endpoint)).append(");");
return sb.toString();
}
sb.append("const response = await fetch(\"").append(url).append("\", {\n");
sb.append(" method: \"POST\",\n");
sb.append(" headers: {\n");
sb.append(" Authorization: `Bearer ${process.env.API_KEY}`,\n");
sb.append(" \"Content-Type\": \"application/json\",\n");
sb.append(" },\n");
sb.append(" body: JSON.stringify(").append(indentBlock(body, 2)).append("),\n");
sb.append("});\n");
sb.append("console.log(await response.json());");
return sb.toString();
}
/**
* 从请求体模板渲染 OpenAI SDK 的关键字参数
*
* @param indent 每个参数行的缩进
* @param pythonStyle true=Python 的 {@code name=value} 写法;false=JS/TS 的 {@code name: value} 写法
*/
private String renderSdkArgs(ApiHubEndpoint endpoint, String modelName, String indent, boolean pythonStyle) {
StringBuilder sb = new StringBuilder();
JsonNode node = parseBody(endpoint, modelName);
if (node == null) {
return sb.toString();
}
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
sb.append(indent).append(field.getKey())
.append(pythonStyle ? "=" : ": ")
.append(toLiteral(field.getValue()))
.append(",\n");
}
return sb.toString();
}
/**
* 请求体模板转 JSON
*/
private JsonNode parseBody(ApiHubEndpoint endpoint, String modelName) {
try {
String body = endpointRegistry.bodyTemplate(endpoint).replace("{{model}}", modelName);
return OBJECT_MAPPER.readTree(body);
} catch (Exception e) {
log.error("[ApiHubSampleBuilder] 解析请求体模板失败, endpoint={}", endpoint.getId(), e);
return null;
}
}
/**
* JSON 值转 Python / JS 字面量
*/
private String toLiteral(JsonNode node) {
if (node.isNull()) {
return "None";
}
if (node.isBoolean()) {
return node.booleanValue() ? "True" : "False";
}
if (node.isTextual()) {
return "\"" + node.textValue().replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
return node.toString();
}
/**
* Python 里打印响应的表达式
*/
private String pythonPrintExpression(ApiHubEndpoint endpoint) {
String[] hints = endpointRegistry.responseHints(endpoint);
return hints.length > 0 ? hints[0] : "response";
}
/**
* JS 里打印响应的表达式
*/
private String jsPrintExpression(ApiHubEndpoint endpoint) {
String[] hints = endpointRegistry.responseHints(endpoint);
return hints.length > 0 ? hints[0] : "response";
}
/**
* 给多行文本加缩进(首行不加)
*/
private String indentBlock(String text, int spaces) {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < spaces; i++) {
pad.append(' ');
}
String[] lines = text.split("\n");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
if (i > 0) {
sb.append("\n").append(pad);
}
sb.append(lines[i]);
}
return sb.toString();
}
/**
* 规整 api_hub 对外地址:去掉尾部斜杠,避免出现 //v1
*/
private String normalizeBase(String apiBase) {
if (apiBase == null || apiBase.trim().isEmpty()) {
return "";
}
String base = apiBase.trim();
while (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
if (base.endsWith("/v1")) {
base = base.substring(0, base.length() - 3);
}
return base;
}
}
package com.luhu.computility.module.apihub.service.apihub;
import com.luhu.computility.module.apihub.config.ApiHubProperties;
import com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppModelUsageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 组装模型的「使用方法」
*
* <p>规则:
* <ol>
* <li>端点由 api_hub 的模型类型({@code model_prices.modalities})映射而来,
* 一个模型带多个类型时会有多条使用说明</li>
* <li>base_url 取 puhui 自己配置的 api_hub 对外地址,不额外调 api_hub 的对外接口</li>
* <li>示例代码里的模型名用对外 id(api_hub 配了别名时是别名)</li>
* <li>参数说明由 puhui 侧静态配置维护,只列 api_hub 自身有语义的参数</li>
* </ol>
*
* @author puhui
*/
@Slf4j
@Service
public class ApiHubUsageService {
@Resource
private ApiHubEndpointRegistry endpointRegistry;
@Resource
private ApiHubSampleBuilder sampleBuilder;
@Resource
private ApiHubEndpointParamProvider paramProvider;
@Resource
private ApiHubProperties apiHubProperties;
/**
* 组装一个模型的使用方法
*
* @param modelName 对外模型 id
* @param modelTypes 模型类型(api_hub 的 modalities)
* @return 使用方法列表,一个端点一条
*/
public List<AppModelUsageVO> buildUsageMethods(String modelName, Collection<String> modelTypes) {
List<AppModelUsageVO> usageMethods = new ArrayList<>();
if (modelName == null || modelName.trim().isEmpty()) {
return usageMethods;
}
String baseUrl = normalizeBase(apiHubProperties.getBaseUrl());
List<ApiHubEndpoint> endpoints = endpointRegistry.resolveEndpoints(modelTypes);
for (ApiHubEndpoint endpoint : endpoints) {
usageMethods.add(AppModelUsageVO.builder()
.endpoint(endpoint.getId())
.endpointName(endpoint.getName())
.method("POST")
.path(endpoint.getPath())
.baseUrl(baseUrl)
.samples(sampleBuilder.build(endpoint, modelName, baseUrl))
.params(paramProvider.getParams(endpoint.getId()))
.build());
}
return usageMethods;
}
/**
* 规整 api_hub 对外地址:去掉尾部斜杠与结尾的 /v1,避免拼出 //v1
*/
private String normalizeBase(String apiBase) {
if (apiBase == null || apiBase.trim().isEmpty()) {
return "";
}
String base = apiBase.trim();
while (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
if (base.endsWith("/v1")) {
base = base.substring(0, base.length() - 3);
}
return base;
}
}
package com.luhu.computility.module.apihub.service.apihub;
import com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppParamVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 从 yaml 读取端点参数说明
*
* <p>配置文件:{@code resources/apihub/endpoint-params.yaml}
*
* @author puhui
*/
@Slf4j
@Component
public class YamlApiHubEndpointParamProvider implements ApiHubEndpointParamProvider {
private static final String RESOURCE_PATH = "apihub/endpoint-params.yaml";
/**
* 解析结果缓存:yaml 是静态内容,解析一次就够
*/
private volatile Map<String, List<AppParamVO>> cache;
@Override
public List<AppParamVO> getParams(String endpointId) {
if (endpointId == null || endpointId.isEmpty()) {
return Collections.emptyList();
}
Map<String, List<AppParamVO>> all = load();
List<AppParamVO> params = all.get(endpointId);
return params == null ? Collections.emptyList() : params;
}
@SuppressWarnings("unchecked")
private Map<String, List<AppParamVO>> load() {
Map<String, List<AppParamVO>> cached = this.cache;
if (cached != null) {
return cached;
}
synchronized (this) {
if (this.cache != null) {
return this.cache;
}
Map<String, List<AppParamVO>> loaded = Collections.emptyMap();
try {
YamlMapFactoryBean factory = new YamlMapFactoryBean();
factory.setResources(new ClassPathResource(RESOURCE_PATH));
Map<String, Object> root = factory.getObject();
Object endpointsObj = root == null ? null : root.get("endpoints");
if (endpointsObj instanceof Map) {
Map<String, Object> endpoints = (Map<String, Object>) endpointsObj;
Map<String, List<AppParamVO>> result = new java.util.LinkedHashMap<>();
for (Map.Entry<String, Object> entry : endpoints.entrySet()) {
Object endpointObj = entry.getValue();
if (!(endpointObj instanceof Map)) {
continue;
}
Object paramsObj = ((Map<String, Object>) endpointObj).get("params");
if (!(paramsObj instanceof List)) {
result.put(entry.getKey(), new ArrayList<>());
continue;
}
List<AppParamVO> params = new ArrayList<>();
for (Object paramObj : (List<Object>) paramsObj) {
if (paramObj instanceof Map) {
params.add(toParam((Map<String, Object>) paramObj));
}
}
result.put(entry.getKey(), params);
}
loaded = result;
}
} catch (Exception e) {
log.error("[ApiHubEndpointParamProvider] 解析参数说明 yaml 失败, path={}", RESOURCE_PATH, e);
}
this.cache = loaded;
return loaded;
}
}
private AppParamVO toParam(Map<String, Object> raw) {
return AppParamVO.builder()
.name(string(raw.get("name")))
.type(string(raw.get("type")))
.required(Boolean.TRUE.equals(raw.get("required")))
.defaultValue(string(raw.get("defaultValue")))
.range(string(raw.get("range")))
.description(string(raw.get("description")))
.build();
}
private String string(Object value) {
return value == null ? null : String.valueOf(value);
}
}
# api_hub 调用参数说明(puhui 侧静态维护)
#
# 只列 api_hub 自身会读取、校验或有确定语义的参数。
# api_hub 对 OpenAI 兼容协议是整包透传(payload = dict(body)),像 frequency_penalty、
# seed、response_format、logprobs 这类参数它自己不解释也不校验,能不能生效完全取决于
# 背后的渠道上游,因此不写进这里,避免给用户错误预期。
#
# 路径与参数口径均对齐 api_hub 的 backend/app/relay.py,改动前请核对上游实现。
endpoints:
chat:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致(api_hub 配了别名时用别名)
- name: messages
type: array
required: true
description: 对话消息数组,按顺序传入历史消息与本轮提问;user 消息的 content 不能为空
- name: messages[].role
type: string
required: true
range: system / user / assistant / tool
description: 消息角色
- name: messages[].content
type: string | array
required: true
description: "文本内容;多模态模型可传数组,形如 [{\"type\":\"text\",\"text\":\"描述\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"https://...\"}}],图片必须是公网可访问的直链或 data URI,不能用本地路径"
- name: stream
type: boolean
required: false
defaultValue: "false"
description: 是否流式返回;为 true 时按 SSE 逐段返回
- name: max_tokens
type: number
required: false
description: 本次生成的最大 token 数
- name: temperature
type: number
required: false
defaultValue: "1"
range: "0 ~ 2"
description: 采样温度,值越高结果越发散
- name: top_p
type: number
required: false
defaultValue: "1"
range: "0 ~ 1"
description: 核采样阈值,与 temperature 二选一调整效果
- name: tools
type: array
required: false
description: 工具(函数)定义列表,OpenAI 兼容格式
- name: tool_choice
type: string | object
required: false
range: auto / none / required 或指定某个函数对象
description: 工具调用策略
embeddings:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致
- name: input
type: string | array
required: true
description: 待向量化的文本;传数组表示批量编码
rerank:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致
- name: query
type: string
required: true
description: 查询串,与 documents 做相关性打分
- name: documents
type: array
required: true
description: 待重排的文档数组
- name: top_n
type: number
required: false
description: 返回重排后相关性最高的前 N 条,不传则返回全部
images:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致
- name: prompt
type: string
required: true
description: 图片描述(提示词)
- name: n
type: number
required: false
defaultValue: "1"
description: 生成图片数量
- name: size
type: string
required: false
description: 输出尺寸,形如 1024x1024;可选值取决于模型
videos:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致
- name: prompt
type: string
required: true
description: 视频内容描述(提示词)
- name: resolution
type: string
required: true
range: 480p / 720p / 1080p
description: 输出分辨率档位,决定按哪档价格计费(默认按 720p)
- name: size
type: string
required: false
description: 输出尺寸,形如 1920x1080;api_hub 会按短边推算分辨率档位
- name: duration
type: number
required: false
range: "1 ~ 60"
description: 视频时长(秒),整数;按「时长秒数 × 档位价」计费
- name: ratio
type: string
required: false
range: 16:9 / 9:16 / 1:1 / 4:3 / 3:4 / 21:9 / adaptive
description: 画面宽高比;不同渠道协议支持的取值不同,超出会被拒绝
- name: image_url
type: string
required: false
description: 参考图片地址,支持公网直链、data URI
- name: video_url
type: string
required: false
description: 参考视频地址,支持公网直链、data URI
- name: audio_url
type: string
required: false
description: 参考音频地址,支持公网直链、data URI
- name: omni_reference_task_type
type: string
required: false
range: auto / reference / edit / extend
description: 参考素材的任务类型,仅部分模型支持
audio:
params:
- name: model
type: string
required: true
description: 模型名称,需与模型市场展示的模型 ID 一致
- name: input
type: string
required: true
description: 需要合成的文本
- name: voice
type: string
required: false
description: 音色名,可选值取决于模型
- name: response_format
type: string
required: false
description: 音频格式,如 mp3 / opus / aac / flac / wav / pcm
......@@ -152,6 +152,8 @@ public class MemberUserDO extends TenantBaseDO {
private Long newapiUserId;
/**
* NewAPI 访问令牌
*
* @deprecated 已废弃:api_hub 迁移后不再写入,改用 {@link #apiHubKey}
*/
private String newapiAccessToken;
/**
......@@ -167,4 +169,30 @@ public class MemberUserDO extends TenantBaseDO {
*/
private String newapiPassword;
// ========== api_hub 相关信息 ==========
/**
* api_hub 用户ID
*/
private Long apiHubUserId;
/**
* api_hub 用户名
*/
private String apiHubUsername;
/**
* api_hub 登录密码
*
* <p>api_hub 侧只存密码哈希,puhui 需要保留明文才能让用户登录 api_hub 控制台,
* 并在需要时重置密码(api_hub 无「查询明文密码」接口)。
*/
private String apiHubPassword;
/**
* api_hub 密钥ID
*/
private Long apiHubTokenId;
/**
* api_hub API Key(明文)
*/
private String apiHubKey;
}
package com.luhu.computility.module.member.service.recharge;
import com.luhu.computility.module.apihub.api.newapi.NewApiUserApi;
import com.luhu.computility.module.apihub.api.apihub.ApiHubUserApi;
import com.luhu.computility.module.infra.api.file.FileApi;
import com.luhu.computility.module.member.dal.dataobject.recharge.MemberRechargeDO;
import com.luhu.computility.module.member.dal.dataobject.user.MemberUserDO;
......@@ -60,7 +60,7 @@ public class RechargeAgreementPdfService {
private final MemberRechargeMapper rechargeMapper;
private final MemberUserService memberUserService;
private final FileApi fileApi;
private final NewApiUserApi newApiUserApi;
private final ApiHubUserApi apiHubUserApi;
/**
* 生成并保存协议 PDF。
......@@ -101,11 +101,11 @@ public class RechargeAgreementPdfService {
? recharge.getAmount().setScale(2, RoundingMode.HALF_UP)
: BigDecimal.ZERO.setScale(2);
// 余额合计 = 充值前 New API 余额 + 本次充值金额
// 协议是在点击"确认充值"那一刻签署的(此时支付未完成、New API 余额也未到账),
// 余额合计 = 充值前 api_hub 余额 + 本次充值金额
// 协议是在点击"确认充值"那一刻签署的(此时支付未完成、api_hub 余额也未到账),
// 这里的"余额合计"按用户口径取预期到账后总额。
// New API 余额查询失败时降级为只显示本次充值金额。
BigDecimal currentBalance = queryNewApiBalanceYuan(user);
// api_hub 余额查询失败时降级为只显示本次充值金额。
BigDecimal currentBalance = queryApiHubBalanceYuan(user);
BigDecimal totalBalance = (currentBalance != null ? currentBalance : BigDecimal.ZERO)
.add(rechargeAmount)
.setScale(2, RoundingMode.HALF_UP);
......@@ -151,22 +151,20 @@ public class RechargeAgreementPdfService {
// ============ 私有工具方法 ============
/**
* 查询用户在 New API 网关上的当前余额(元)。
* 查询用户在 api_hub 网关上的当前余额(元)。
*
* <p>用户未拿到 New API access_token(如 newapi_user_id / newapi_access_token 为空)
* <p>用户尚未在 api_hub 开通(api_hub_user_id / api_hub_username 为空)
* 或查询失败时返回 {@code null},由调用方降级处理。
*/
private BigDecimal queryNewApiBalanceYuan(MemberUserDO user) {
if (user == null
|| user.getNewapiAccessToken() == null || user.getNewapiAccessToken().isEmpty()
|| user.getNewapiUserId() == null) {
private BigDecimal queryApiHubBalanceYuan(MemberUserDO user) {
if (user == null || user.getApiHubUserId() == null
|| user.getApiHubUsername() == null || user.getApiHubUsername().isEmpty()) {
return null;
}
try {
Integer newApiUserId = Integer.parseInt(user.getNewapiUserId().toString());
return newApiUserApi.getQuotaYuan(user.getNewapiAccessToken(), newApiUserId);
} catch (NumberFormatException e) {
log.warn("[充值协议PDF] newapiUserId 不是合法数字: {}", user.getNewapiUserId());
return apiHubUserApi.getQuotaYuan(user.getApiHubUserId(), user.getApiHubUsername());
} catch (Exception e) {
log.warn("[充值协议PDF] 查询 api_hub 余额失败: {}", e.getMessage());
return null;
}
}
......
......@@ -226,4 +226,17 @@ public interface MemberUserService {
void updateNewApiInfo(Long userId, Long newapiUserId, String newapiAccessToken, String newapiKey,
String newapiUsername, String newapiPassword);
/**
* 更新用户的 api_hub 相关信息
*
* @param userId 用户编号
* @param apiHubUserId api_hub 用户ID
* @param apiHubUsername api_hub 用户名
* @param apiHubPassword api_hub 登录密码(明文)
* @param apiHubTokenId api_hub 密钥ID
* @param apiHubKey api_hub 密钥明文
*/
void updateApiHubInfo(Long userId, Long apiHubUserId, String apiHubUsername, String apiHubPassword,
Long apiHubTokenId, String apiHubKey);
}
......@@ -354,4 +354,17 @@ public class MemberUserServiceImpl implements MemberUserService {
.build());
}
@Override
public void updateApiHubInfo(Long userId, Long apiHubUserId, String apiHubUsername, String apiHubPassword,
Long apiHubTokenId, String apiHubKey) {
memberUserMapper.updateById(MemberUserDO.builder()
.id(userId)
.apiHubUserId(apiHubUserId)
.apiHubUsername(apiHubUsername)
.apiHubPassword(apiHubPassword)
.apiHubTokenId(apiHubTokenId)
.apiHubKey(apiHubKey)
.build());
}
}
......@@ -215,6 +215,15 @@ computility:
base-url: http://localhost:3000
admin-token: f454ND2IhDKJqSxST4XBCLyR+wDOVEo=
admin-user-id: 1
api-hub:
base-url: http://localhost:8000
admin-username: admin
admin-password: nexgate-admin
# 预留:调用 api_hub 对外接口用的 Key,本阶段未使用
data-api-key: ''
# api_hub 额度单位 → 元的换算比例(1 元 = 多少额度单位)
# api_hub 的额度单位本身就是「元」,故为 1;保留配置项是为了将来额度单位变化时可调
quota-per-yuan: 1
captcha:
enable: false # 本地环境,暂时关闭图片验证码,方便登录等接口的测试;
security:
......
-- ============================================================
-- api_hub 迁移 · 阶段 1
-- 目标:member_user 增加 api_hub 用户与密钥字段,承载 puhui 用户在 api_hub 的开通结果
-- 适用库:new_computility
-- 前置:ApiHubProperties / ApiHubClient 已就位,AiTokenService 已切换为 api_hub 开通流程
-- 说明:
-- - newapi_* 字段暂不删除,阶段 1 仅新增 api_hub_* 字段
-- - api_hub_key 存明文密钥,对应 api_hub 的 tokens 表 key_cipher 解密结果
-- ============================================================
USE `new_computility`;
ALTER TABLE `member_user`
ADD COLUMN `api_hub_user_id` BIGINT DEFAULT NULL COMMENT 'api_hub 用户ID' AFTER `newapi_password`,
ADD COLUMN `api_hub_username` VARCHAR(64) DEFAULT NULL COMMENT 'api_hub 用户名' AFTER `api_hub_user_id`,
ADD COLUMN `api_hub_token_id` BIGINT DEFAULT NULL COMMENT 'api_hub 密钥ID' AFTER `api_hub_username`,
ADD COLUMN `api_hub_key` VARCHAR(255) DEFAULT NULL COMMENT 'api_hub API Key(明文)' AFTER `api_hub_token_id`;
-- 验证:
-- SHOW COLUMNS FROM `member_user` LIKE 'api_hub%';
-- ============================================================
-- api_hub 迁移 · 阶段 1(补充)
-- 目标:member_user 增加 api_hub 登录密码字段
-- 适用库:new_computility
-- 前置:已执行 2026_11_11_add_member_user_api_hub_fields.sql
-- 说明:
-- - api_hub 侧只保存 password_hash,没有查询明文密码的接口
-- - puhui 侧保留明文,便于用户登录 api_hub 控制台、以及需要时重置密码
-- ============================================================
USE `new_computility`;
ALTER TABLE `member_user`
ADD COLUMN `api_hub_password` VARCHAR(128) DEFAULT NULL COMMENT 'api_hub 登录密码(明文)' AFTER `api_hub_username`;
-- 验证:
-- SHOW COLUMNS FROM `member_user` LIKE 'api_hub%';
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment