Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
phsl
/
api
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
2cb2a43f
authored
Nov 13, 2026
by
renyizhao
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
对接api_hub
parent
fba7e550
Hide whitespace changes
Inline
Side-by-side
Showing
36 changed files
with
3305 additions
and
2113 deletions
+3305
-2113
computility-module-apihub/computility-module-apihub-api/src/main/java/com/luhu/computility/module/apihub/api/apihub/ApiHubUserApi.java
+28
-0
computility-module-apihub/computility-module-apihub-api/src/main/java/com/luhu/computility/module/apihub/api/newapi/NewApiUserApi.java
+0
-25
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/api/NewApiUserApiServiceImpl.java
+0
-58
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/api/apihub/ApiHubUserApiServiceImpl.java
+68
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/config/ApiHubProperties.java
+50
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubModelPriceVO.java
+131
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubResponse.java
+49
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubTokenVO.java
+60
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubUserVO.java
+65
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/AppAiTokenController.java
+38
-48
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/AppAiModelController.java
+29
-952
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelPricingVO.java
+102
-151
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelSampleVO.java
+34
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelUsageVO.java
+60
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelVO.java
+0
-41
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppParamVO.java
+53
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppPricingVO.java
+0
-36
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/framework/security/config/SecurityConfiguration.java
+0
-2
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubClient.java
+790
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpoint.java
+96
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpointParamProvider.java
+26
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpointRegistry.java
+156
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubModelPriceService.java
+491
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubSampleBuilder.java
+246
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubUsageService.java
+88
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/YamlApiHubEndpointParamProvider.java
+104
-0
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/newapi/AiTokenService.java
+250
-181
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/newapi/NewApiClient.java
+1
-603
computility-module-apihub/computility-module-apihub-biz/src/main/resources/apihub/endpoint-params.yaml
+176
-0
computility-module-member/src/main/java/com/luhu/computility/module/member/dal/dataobject/user/MemberUserDO.java
+28
-0
computility-module-member/src/main/java/com/luhu/computility/module/member/service/recharge/RechargeAgreementPdfService.java
+14
-16
computility-module-member/src/main/java/com/luhu/computility/module/member/service/user/MemberUserService.java
+13
-0
computility-module-member/src/main/java/com/luhu/computility/module/member/service/user/MemberUserServiceImpl.java
+13
-0
computility-server/src/main/resources/application-local.yaml
+9
-0
sql/migration/2026_11_11_add_member_user_api_hub_fields.sql
+20
-0
sql/migration/2026_11_11_add_member_user_api_hub_password.sql
+17
-0
No files found.
computility-module-apihub/computility-module-apihub-api/src/main/java/com/luhu/computility/module/apihub/api/apihub/ApiHubUserApi.java
0 → 100644
View file @
2cb2a43f
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
);
}
computility-module-apihub/computility-module-apihub-api/src/main/java/com/luhu/computility/module/apihub/api/newapi/NewApiUserApi.java
deleted
100644 → 0
View file @
fba7e550
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
);
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/api/NewApiUserApiServiceImpl.java
deleted
100644 → 0
View file @
fba7e550
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
;
}
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/api/apihub/ApiHubUserApiServiceImpl.java
0 → 100644
View file @
2cb2a43f
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
;
}
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/config/ApiHubProperties.java
0 → 100644
View file @
2cb2a43f
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"
);
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubModelPriceVO.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubResponse.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubTokenVO.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/admin/apihub/ApiHubUserVO.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/AppAiTokenController.java
View file @
2cb2a43f
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
newApi
Properties
;
private
ApiHubProperties
apiHub
Properties
;
@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
.
get
NewapiUsername
(),
user
.
get
NewapiPassword
(),
user
.
get
NewapiUserI
d
(),
user
.
get
NewapiAccessToken
(),
user
.
get
Newapi
Key
()
user
.
get
ApiHubUserId
(),
user
.
get
ApiHubUsername
(),
user
.
get
ApiHubPasswor
d
(),
user
.
get
ApiHubTokenId
(),
user
.
get
ApiHub
Key
()
);
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
.
get
NewApiUserId
()
!=
null
?
result
.
getNewApiUserId
()
:
user
.
getNewapi
UserId
(),
result
.
get
NewApiAccessToken
()
!=
null
?
result
.
getNewApiAccessToken
()
:
user
.
getNewapiAccessToken
(),
result
.
getApi
Key
()
!=
null
?
result
.
getApiKey
()
:
user
.
getNewapiKey
(),
result
.
get
NewApiUsername
()
!=
null
?
result
.
getNewApiUsername
()
:
user
.
getNewapiUsername
(),
result
.
get
NewApiPassword
()
!=
null
?
result
.
getNewApiPassword
()
:
user
.
getNewapiPassword
()
result
.
get
ApiHub
UserId
(),
result
.
get
ApiHubUsername
(),
result
.
getApi
HubPassword
(),
result
.
get
ApiHubTokenId
(),
result
.
get
ApiHubKey
()
);
}
...
...
@@ -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
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/AppAiModelController.java
View file @
2cb2a43f
...
...
@@ -3,1002 +3,79 @@ package com.luhu.computility.module.apihub.controller.app.aimodel;
import
cn.hutool.core.util.StrUtil
;
import
com.luhu.computility.framework.common.pojo.CommonResult
;
import
com.luhu.computility.framework.security.core.util.SecurityFrameworkUtils
;
import
com.luhu.computility.module.apihub.controller.admin.newapi.NewApiResponse
;
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.controller.app.aimodel.vo.AppModelPricingVO
;
import
com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppModelVO
;
import
com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppPricingVO
;
import
com.luhu.computility.module.apihub.service.newapi.NewApiClient
;
import
com.luhu.computility.module.apihub.service.apihub.ApiHubClient
;
import
com.luhu.computility.module.apihub.service.apihub.ApiHubModelPriceService
;
import
com.luhu.computility.module.member.dal.dataobject.user.MemberUserDO
;
import
com.luhu.computility.module.member.service.user.MemberUserService
;
import
io.swagger.v3.oas.annotations.Operation
;
import
io.swagger.v3.oas.annotations.tags.Tag
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.validation.annotation.Validated
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
javax.annotation.Resource
;
import
javax.validation.constraints.Max
;
import
javax.validation.constraints.Min
;
import
java.math.BigDecimal
;
import
java.math.RoundingMode
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.List
;
import
java.util.Map
;
/**
* APP端 - AI 模型与定价接口
*
* <p>数据源已从 new-api 切换为 api_hub(管理端 {@code GET /api/model-prices}),
* 价格口径与 api_hub 一致:在售模型清单、标价×售卖倍率×折扣×用户倍率 = 用户实付价。
*
* @author puhui
*/
@Slf4j
@RestController
@RequestMapping
(
"/app/ai"
)
@Tag
(
name
=
"APP端 - AI模型与定价"
)
@Validated
public
class
AppAiModelController
{
/**
* 业务倍率系数:puhui 在 New API 价格基础上额外乘的固定系数
*/
private
static
final
BigDecimal
BUSINESS_RATIO
=
new
BigDecimal
(
"2"
);
@Resource
private
ApiHubModelPriceService
apiHubModelPriceService
;
@Resource
private
NewApiClient
newApi
Client
;
private
ApiHubClient
apiHub
Client
;
@Resource
private
MemberUserService
memberUserService
;
/**
* 获取定价信息(原始)
*/
@GetMapping
(
"/pricing"
)
@Operation
(
summary
=
"获取 New API 定价信息(含模型定价和分组倍率,按当前登录用户权限)"
)
public
CommonResult
<
AppPricingVO
>
getPricing
()
{
String
accessToken
=
getCurrentUserAccessToken
();
String
userId
=
getCurrentUserNewApiId
();
NewApiResponse
<
Map
<
String
,
Object
>>
resp
=
newApiClient
.
getPricing
(
accessToken
,
userId
);
if
(
resp
.
getSuccess
()
==
null
||
!
resp
.
getSuccess
()
||
resp
.
getData
()
==
null
)
{
log
.
error
(
"[getPricing] 调用 New API 失败:{}"
,
resp
.
getMessage
());
return
CommonResult
.
error
(
1
,
"获取定价失败: "
+
resp
.
getMessage
());
}
return
CommonResult
.
success
(
buildPricingVO
(
resp
.
getData
()));
}
/**
* 获取模型列表(带元数据)
*/
@GetMapping
(
"/models"
)
@Operation
(
summary
=
"获取 New API 模型列表(带元数据和图标)"
)
public
CommonResult
<
List
<
AppModelVO
>>
getModels
(
@RequestParam
(
defaultValue
=
"1"
)
@Min
(
value
=
1
,
message
=
"页码 page 最小值为 1"
)
Integer
page
,
@RequestParam
(
defaultValue
=
"100"
)
@Min
(
value
=
1
,
message
=
"每页条数 pageSize 最小值为 1"
)
@Max
(
value
=
100
,
message
=
"每页条数 pageSize 最大值为 100"
)
Integer
pageSize
)
{
NewApiResponse
<
Map
<
String
,
Object
>>
resp
=
newApiClient
.
getModels
(
page
,
pageSize
);
if
(
resp
.
getSuccess
()
==
null
||
!
resp
.
getSuccess
()
||
resp
.
getData
()
==
null
)
{
log
.
error
(
"[getModels] 调用 New API 失败:{}"
,
resp
.
getMessage
());
return
CommonResult
.
error
(
1
,
"获取模型列表失败: "
+
resp
.
getMessage
());
}
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
items
=
(
List
<
Map
<
String
,
Object
>>)
resp
.
getData
().
get
(
"items"
);
if
(
items
==
null
)
{
return
CommonResult
.
success
(
Collections
.
emptyList
());
}
// 顺便获取 vendor 用于图标 fallback
List
<
Map
<
String
,
Object
>>
vendors
=
null
;
NewApiResponse
<
Map
<
String
,
Object
>>
pricingResp
=
newApiClient
.
getPricing
(
null
,
null
);
if
(
pricingResp
.
getSuccess
()
!=
null
&&
pricingResp
.
getSuccess
()
&&
pricingResp
.
getData
()
!=
null
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
v
=
(
List
<
Map
<
String
,
Object
>>)
pricingResp
.
getData
().
get
(
"vendors"
);
vendors
=
v
;
}
List
<
AppModelVO
>
result
=
new
ArrayList
<>();
for
(
Map
<
String
,
Object
>
item
:
items
)
{
AppModelVO
vo
=
new
AppModelVO
();
vo
.
setId
(
toLong
(
item
.
get
(
"id"
)));
vo
.
setModelName
((
String
)
item
.
get
(
"model_name"
));
vo
.
setIcon
((
String
)
item
.
get
(
"icon"
));
vo
.
setStatus
(
toInteger
(
item
.
get
(
"status"
)));
vo
.
setDescription
((
String
)
item
.
get
(
"description"
));
// 解析 enable_groups
Object
eg
=
item
.
get
(
"enable_groups"
);
if
(
eg
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
enableGroups
=
(
List
<
String
>)
eg
;
vo
.
setEnableGroups
(
enableGroups
);
}
// 解析 endpoints(JSON 字符串)
Object
ep
=
item
.
get
(
"endpoints"
);
if
(
ep
instanceof
String
)
{
try
{
vo
.
setEndpoints
(
com
.
luhu
.
computility
.
framework
.
common
.
util
.
json
.
JsonUtils
.
parseArray
((
String
)
ep
,
String
.
class
));
}
catch
(
Exception
e
)
{
log
.
warn
(
"[getModels] 解析 endpoints 失败:{}"
,
ep
);
}
}
else
if
(
ep
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
endpoints
=
(
List
<
String
>)
ep
;
vo
.
setEndpoints
(
endpoints
);
}
// vendor 名称匹配(不主动推断 icon,New API 没配就保持 null)
if
(
StrUtil
.
isBlank
(
vo
.
getVendorName
()))
{
vo
.
setVendorName
(
resolveVendorName
(
vo
.
getModelName
(),
vendors
));
}
result
.
add
(
vo
);
}
return
CommonResult
.
success
(
result
);
}
/**
* 聚合接口:模型列表 + 定价
* 获取模型列表 + 价格(api_hub 在售模型)
*/
@GetMapping
(
"/models-with-pricing"
)
@Operation
(
summary
=
"获取模型列表
及定价(已按当前用户分组倍率计算好价格
)"
)
@Operation
(
summary
=
"获取模型列表
与价格(数据源 api_hub
)"
)
public
CommonResult
<
List
<
AppModelPricingVO
>>
getModelsWithPricing
()
{
// 1. 用当前用户 token 调 /api/pricing,拿到该用户实际生效的 group_ratio
String
accessToken
=
getCurrentUserAccessToken
();
String
userId
=
getCurrentUserNewApiId
();
NewApiResponse
<
Map
<
String
,
Object
>>
pricingResp
=
newApiClient
.
getPricing
(
accessToken
,
userId
);
if
(
pricingResp
.
getSuccess
()
==
null
||
!
pricingResp
.
getSuccess
()
||
pricingResp
.
getData
()
==
null
)
{
log
.
error
(
"[getModelsWithPricing] 获取定价失败:{}"
,
pricingResp
.
getMessage
());
return
CommonResult
.
error
(
1
,
"获取定价失败"
);
}
Map
<
String
,
Object
>
pricingData
=
pricingResp
.
getData
();
// 业务最终倍率 = group_ratio.default × 业务系数(仅按量计费使用)
BigDecimal
groupRatio
=
resolveGroupRatio
(
pricingData
);
// 原始倍率 = group_ratio.default(按次计费使用,不叠加 puhui 业务系数)
BigDecimal
plainGroupRatio
=
resolvePlainGroupRatio
(
pricingData
);
// 2. 构造 model_name -> pricing 索引
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
modelPricingList
=
(
List
<
Map
<
String
,
Object
>>)
pricingData
.
get
(
"data"
);
log
.
info
(
"[诊断] /api/pricing 返回的 model 数量 = {}"
,
modelPricingList
==
null
?
0
:
modelPricingList
.
size
());
Map
<
String
,
Map
<
String
,
Object
>>
pricingIndex
=
new
java
.
util
.
HashMap
<>();
if
(
modelPricingList
!=
null
)
{
for
(
Map
<
String
,
Object
>
p
:
modelPricingList
)
{
Object
name
=
p
.
get
(
"model_name"
);
if
(
name
!=
null
)
{
pricingIndex
.
put
(
name
.
toString
(),
p
);
}
}
}
// 3. 获取供应商
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
vendors
=
(
List
<
Map
<
String
,
Object
>>)
pricingData
.
get
(
"vendors"
);
// 3.5 提取顶级 supported_endpoint(端点 → URL 路径映射)
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Map
<
String
,
Object
>>
topEndpoints
=
(
Map
<
String
,
Map
<
String
,
Object
>>)
pricingData
.
get
(
"supported_endpoint"
);
// 4. 拉取所有模型元数据(分页循环,因 New API page_size 上限为 100)
NewApiResponse
<
List
<
Map
<
String
,
Object
>>>
modelsResp
=
newApiClient
.
getAllModels
();
if
(
modelsResp
.
getSuccess
()
==
null
||
!
modelsResp
.
getSuccess
()
||
modelsResp
.
getData
()
==
null
)
{
log
.
error
(
"[getModelsWithPricing] 获取模型列表失败:{}"
,
modelsResp
.
getMessage
());
return
CommonResult
.
error
(
1
,
"获取模型列表失败"
);
}
List
<
Map
<
String
,
Object
>>
items
=
modelsResp
.
getData
();
log
.
info
(
"[诊断] /api/models/ 返回的 items 数量 = {}"
,
items
==
null
?
0
:
items
.
size
());
if
(
items
==
null
||
items
.
isEmpty
())
{
return
CommonResult
.
success
(
Collections
.
emptyList
());
}
List
<
AppModelPricingVO
>
result
=
new
ArrayList
<>();
for
(
Map
<
String
,
Object
>
item
:
items
)
{
String
modelName
=
(
String
)
item
.
get
(
"model_name"
);
if
(
modelName
==
null
)
continue
;
AppModelPricingVO
vo
=
new
AppModelPricingVO
();
vo
.
setModelName
(
modelName
);
vo
.
setIcon
((
String
)
item
.
get
(
"icon"
));
vo
.
setStatus
(
toInteger
(
item
.
get
(
"status"
)));
vo
.
setDescription
((
String
)
item
.
get
(
"description"
));
vo
.
setTags
((
String
)
item
.
get
(
"tags"
));
// enable_groups
Object
eg
=
item
.
get
(
"enable_groups"
);
if
(
eg
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
egs
=
(
List
<
String
>)
eg
;
vo
.
setEnableGroups
(
egs
);
}
// 合并 pricing
Map
<
String
,
Object
>
pricing
=
pricingIndex
.
get
(
modelName
);
if
(
pricing
!=
null
)
{
// supportedEndpoints:从 pricing 数据的 supported_endpoint_types 读取
// (projects memory 硬约束:不可为 null,来源于 NewAPI 的 supported_endpoint_types)
Object
pricingEps
=
pricing
.
get
(
"supported_endpoint_types"
);
if
(
pricingEps
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
pEps
=
(
List
<
String
>)
pricingEps
;
vo
.
setSupportedEndpoints
(
pEps
);
}
vo
.
setQuotaType
(
toInteger
(
pricing
.
get
(
"quota_type"
)));
vo
.
setModelRatio
(
toBigDecimal
(
pricing
.
get
(
"model_ratio"
)));
vo
.
setModelPrice
(
toBigDecimal
(
pricing
.
get
(
"model_price"
)));
vo
.
setCompletionRatio
(
toBigDecimal
(
pricing
.
get
(
"completion_ratio"
)));
vo
.
setCacheRatio
(
toBigDecimal
(
pricing
.
get
(
"cache_ratio"
)));
vo
.
setCreateCacheRatio
(
toBigDecimal
(
pricing
.
get
(
"create_cache_ratio"
)));
BigDecimal
imageRatio
=
toBigDecimal
(
pricing
.
get
(
"image_ratio"
));
BigDecimal
audioRatio
=
toBigDecimal
(
pricing
.
get
(
"audio_ratio"
));
BigDecimal
audioCompletionRatio
=
toBigDecimal
(
pricing
.
get
(
"audio_completion_ratio"
));
// 分档计费信息
String
billingMode
=
(
String
)
pricing
.
get
(
"billing_mode"
);
String
billingExpr
=
(
String
)
pricing
.
get
(
"billing_expr"
);
vo
.
setBillingMode
(
billingMode
);
vo
.
setBillingExpr
(
billingExpr
);
// 提前提取 billing_usage_schema,用于 tier 计费字段单位推断(happyhorse 等按秒/次计费模型)
Map
<
String
,
Object
>
billingUsageSchemaForTiers
=
null
;
Object
schemaObjForTiers
=
pricing
.
get
(
"billing_usage_schema"
);
if
(
schemaObjForTiers
instanceof
Map
)
{
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
schemaMap
=
(
Map
<
String
,
Object
>)
schemaObjForTiers
;
billingUsageSchemaForTiers
=
schemaMap
;
}
// 解析分档表达式
if
(
"tiered_expr"
.
equals
(
billingMode
)
&&
billingExpr
!=
null
)
{
List
<
AppModelPricingVO
.
TierVO
>
tiers
=
parseTieredExpr
(
billingExpr
,
groupRatio
,
billingUsageSchemaForTiers
);
vo
.
setTiers
(
tiers
);
// 解析条件乘数
List
<
AppModelPricingVO
.
ConditionMultiplierVO
>
conditionMultipliers
=
parseConditionMultipliers
(
billingExpr
);
vo
.
setConditionMultipliers
(
conditionMultipliers
);
}
// 计算价格
BigDecimal
modelPrice
=
vo
.
getModelPrice
()
!=
null
?
vo
.
getModelPrice
()
:
BigDecimal
.
ZERO
;
BigDecimal
modelRatio
=
vo
.
getModelRatio
()
!=
null
?
vo
.
getModelRatio
()
:
BigDecimal
.
ZERO
;
BigDecimal
completionRatio
=
vo
.
getCompletionRatio
()
!=
null
?
vo
.
getCompletionRatio
()
:
BigDecimal
.
ONE
;
BigDecimal
cacheRatio
=
vo
.
getCacheRatio
()
!=
null
?
vo
.
getCacheRatio
()
:
BigDecimal
.
ZERO
;
BigDecimal
createCacheRatio
=
vo
.
getCreateCacheRatio
()
!=
null
?
vo
.
getCreateCacheRatio
()
:
BigDecimal
.
ZERO
;
if
(
vo
.
getQuotaType
()
!=
null
&&
vo
.
getQuotaType
()
==
1
)
{
// 按次计费(quota_type=1):使用原始 group_ratio.default,不叠加 puhui 业务系数
BigDecimal
perCallPrice
=
modelPrice
.
multiply
(
plainGroupRatio
)
.
setScale
(
4
,
RoundingMode
.
HALF_UP
);
vo
.
setInputPrice
(
perCallPrice
);
vo
.
setOutputPrice
(
perCallPrice
);
}
else
{
// 按量计费(quota_type=0):应用 groupRatio(含 BUSINESS_RATIO)。
// 精度保留 4 位小数,避免 modelRatio × groupRatio(如 0.1435 × 2 = 0.287)
// 被四舍五入到 2 位后丢失精度;前端 formatPrice 用 toFixed(4) 去末尾 0 显示。
BigDecimal
inputPrice
=
modelPrice
.
add
(
modelRatio
).
multiply
(
groupRatio
).
setScale
(
4
,
RoundingMode
.
HALF_UP
);
vo
.
setInputPrice
(
inputPrice
);
vo
.
setOutputPrice
(
modelPrice
.
add
(
modelRatio
.
multiply
(
completionRatio
)).
multiply
(
groupRatio
).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
// 缓存价格 = cache_ratio × 输入价格(输入价格已包含 groupRatio)
vo
.
setCacheReadPrice
(
cacheRatio
.
multiply
(
inputPrice
).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
vo
.
setCacheCreatePrice
(
createCacheRatio
.
multiply
(
inputPrice
).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
// 图片输入价格 = image_ratio × 输入价格
if
(
imageRatio
!=
null
&&
imageRatio
.
compareTo
(
BigDecimal
.
ZERO
)
>
0
)
{
vo
.
setImageInputPrice
(
imageRatio
.
multiply
(
inputPrice
).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 音频输入价格 = audio_ratio × 输入价格
if
(
audioRatio
!=
null
&&
audioRatio
.
compareTo
(
BigDecimal
.
ZERO
)
>
0
)
{
vo
.
setAudioInputPrice
(
audioRatio
.
multiply
(
inputPrice
).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 音频补全价格 = audio_completion_ratio × 音频输入价格
if
(
audioCompletionRatio
!=
null
&&
audioCompletionRatio
.
compareTo
(
BigDecimal
.
ZERO
)
>
0
&&
vo
.
getAudioInputPrice
()
!=
null
)
{
vo
.
setAudioCompletionPrice
(
audioCompletionRatio
.
multiply
(
vo
.
getAudioInputPrice
()).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
}
}
vo
.
setGroupRatio
(
groupRatio
);
// vendor 名称匹配(不主动推断 icon,New API 没配就保持 null)
vo
.
setVendorName
(
resolveVendorName
(
modelName
,
vendors
));
// endpoints:每个模型都带上顶级 supported_endpoint,前端按需取
if
(
topEndpoints
!=
null
)
{
vo
.
setEndpoints
(
topEndpoints
);
}
// 解析使用方式相关字段(来自 pricing.txt)
if
(
pricing
!=
null
)
{
// api_examples:使用示例数组(每个含 endpoint/profile/providers/groups)
Object
apiExamplesObj
=
pricing
.
get
(
"api_examples"
);
if
(
apiExamplesObj
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
apiExamplesRaw
=
(
List
<
Map
<
String
,
Object
>>)
apiExamplesObj
;
List
<
AppModelPricingVO
.
ApiExampleVO
>
apiExamples
=
new
ArrayList
<>();
for
(
Map
<
String
,
Object
>
ae
:
apiExamplesRaw
)
{
AppModelPricingVO
.
ApiExampleVO
aeVo
=
new
AppModelPricingVO
.
ApiExampleVO
();
aeVo
.
setEndpoint
((
String
)
ae
.
get
(
"endpoint"
));
aeVo
.
setProfile
((
String
)
ae
.
get
(
"profile"
));
Object
providers
=
ae
.
get
(
"providers"
);
if
(
providers
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
ps
=
(
List
<
String
>)
providers
;
aeVo
.
setProviders
(
ps
);
}
Object
groups
=
ae
.
get
(
"groups"
);
if
(
groups
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
String
>
gs
=
(
List
<
String
>)
groups
;
aeVo
.
setGroups
(
gs
);
}
apiExamples
.
add
(
aeVo
);
}
vo
.
setApiExamples
(
apiExamples
);
}
// billing_usage_schema:参数定义
Object
schemaObj
=
pricing
.
get
(
"billing_usage_schema"
);
if
(
schemaObj
instanceof
Map
)
{
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
schemaMap
=
(
Map
<
String
,
Object
>)
schemaObj
;
vo
.
setBillingUsageSchema
(
schemaMap
);
}
// billing_usage_examples:示例数据
Object
examplesObj
=
pricing
.
get
(
"billing_usage_examples"
);
if
(
examplesObj
instanceof
List
)
{
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
examples
=
(
List
<
Map
<
String
,
Object
>>)
examplesObj
;
vo
.
setBillingUsageExamples
(
examples
);
}
}
result
.
add
(
vo
);
}
log
.
info
(
"[诊断] 最终返回的模型数量 = {}, 唯一 modelName 数量 = {}"
,
result
.
size
(),
result
.
stream
().
map
(
AppModelPricingVO:
:
getModelName
).
distinct
().
count
());
return
CommonResult
.
success
(
result
);
Double
userPriceMultiplier
=
resolveCurrentUserPriceMultiplier
();
List
<
AppModelPricingVO
>
models
=
apiHubModelPriceService
.
listModelPricing
(
userPriceMultiplier
);
log
.
info
(
"[查询模型列表与价格] 用户价格倍率={}, 模型数={}"
,
userPriceMultiplier
,
models
.
size
());
return
CommonResult
.
success
(
models
);
}
/**
* 从 pricing 原始数据中解析业务最终倍率 = group_ratio.default × 业务系数
*/
private
BigDecimal
resolveGroupRatio
(
Map
<
String
,
Object
>
pricingData
)
{
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
groupRatioMap
=
(
Map
<
String
,
Object
>)
pricingData
.
get
(
"group_ratio"
);
if
(
groupRatioMap
==
null
)
{
return
BUSINESS_RATIO
;
}
Object
defaultRatio
=
groupRatioMap
.
get
(
"default"
);
log
.
info
(
"[resolveGroupRatio] pricing.group_ratio.default={}"
,
defaultRatio
);
if
(
defaultRatio
==
null
)
{
return
BUSINESS_RATIO
;
}
try
{
BigDecimal
base
=
new
BigDecimal
(
String
.
valueOf
(
defaultRatio
));
return
base
.
multiply
(
BUSINESS_RATIO
);
}
catch
(
Exception
e
)
{
log
.
warn
(
"[resolveGroupRatio] 解析 group_ratio.default 失败:{}"
,
defaultRatio
);
return
BUSINESS_RATIO
;
}
}
/**
* 从 pricing 原始数据中解析原始 group_ratio.default(不叠加 puhui 业务系数,按次计费使用)
*/
private
BigDecimal
resolvePlainGroupRatio
(
Map
<
String
,
Object
>
pricingData
)
{
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
groupRatioMap
=
(
Map
<
String
,
Object
>)
pricingData
.
get
(
"group_ratio"
);
if
(
groupRatioMap
==
null
)
{
return
BigDecimal
.
ONE
;
}
Object
defaultRatio
=
groupRatioMap
.
get
(
"default"
);
if
(
defaultRatio
==
null
)
{
return
BigDecimal
.
ONE
;
}
try
{
return
new
BigDecimal
(
String
.
valueOf
(
defaultRatio
));
}
catch
(
Exception
e
)
{
log
.
warn
(
"[resolvePlainGroupRatio] 解析 group_ratio.default 失败:{}"
,
defaultRatio
);
return
BigDecimal
.
ONE
;
}
}
/**
* 获取当前登录用户的 New API accessToken(无则返回 null)
*/
private
String
getCurrentUserAccessToken
()
{
MemberUserDO
user
=
getCurrentMemberUser
();
return
user
==
null
?
null
:
user
.
getNewapiAccessToken
();
}
/**
* 获取当前登录用户在 New API 的 userId(无则返回 null)
*/
private
String
getCurrentUserNewApiId
()
{
MemberUserDO
user
=
getCurrentMemberUser
();
return
user
==
null
||
user
.
getNewapiUserId
()
==
null
?
null
:
user
.
getNewapiUserId
().
toString
();
}
/**
* 获取当前登录用户的 MemberUserDO
* 取当前登录用户在 api_hub 的价格倍率({@code users.price_multiplier})。
*
* <p>取不到时按 1 处理,保证价格展示不因查询失败而整体不可用。
*/
private
MemberUserDO
getCurrentMemberUs
er
()
{
private
Double
resolveCurrentUserPriceMultipli
er
()
{
try
{
Long
userId
=
SecurityFrameworkUtils
.
getLoginUserId
(
);
if
(
user
Id
==
null
)
{
MemberUserDO
user
=
memberUserService
.
getUser
(
SecurityFrameworkUtils
.
getLoginUserId
()
);
if
(
user
==
null
||
StrUtil
.
isBlank
(
user
.
getApiHubUsername
())
)
{
return
null
;
}
return
memberUserService
.
getUser
(
userId
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[getCurrentMemberUser] 异常"
,
e
);
return
null
;
}
}
/**
* 构造定价 VO
*/
private
AppPricingVO
buildPricingVO
(
Map
<
String
,
Object
>
data
)
{
AppPricingVO
vo
=
new
AppPricingVO
();
// 分组倍率
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
groupRatioMap
=
(
Map
<
String
,
Object
>)
data
.
get
(
"group_ratio"
);
if
(
groupRatioMap
!=
null
)
{
Map
<
String
,
BigDecimal
>
ratios
=
new
java
.
util
.
HashMap
<>();
groupRatioMap
.
forEach
((
k
,
v
)
->
{
try
{
ratios
.
put
(
k
,
new
BigDecimal
(
String
.
valueOf
(
v
)));
}
catch
(
Exception
ignored
)
{
}
});
vo
.
setGroupRatios
(
ratios
);
}
// 当前用户实际生效倍率(已含业务系数)
vo
.
setGroupRatio
(
resolveGroupRatio
(
data
));
// 支持的端点
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
supportedEndpoint
=
(
Map
<
String
,
Object
>)
data
.
get
(
"supported_endpoint"
);
vo
.
setSupportedEndpoint
(
supportedEndpoint
);
// 供应商列表
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
vendors
=
(
List
<
Map
<
String
,
Object
>>)
data
.
get
(
"vendors"
);
vo
.
setVendors
(
vendors
);
// 模型定价(原始)
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
modelPricing
=
(
List
<
Map
<
String
,
Object
>>)
data
.
get
(
"data"
);
vo
.
setModelPricing
(
modelPricing
);
return
vo
;
}
/**
* 根据 model_name 推断 icon 名
*/
private
String
resolveIconByName
(
String
modelName
,
List
<
Map
<
String
,
Object
>>
vendors
)
{
if
(
modelName
==
null
)
return
"AI"
;
String
lower
=
modelName
.
toLowerCase
();
if
(
lower
.
contains
(
"qwen"
))
return
"Qwen.Color"
;
if
(
lower
.
contains
(
"deepseek"
))
return
"DeepSeek.Color"
;
if
(
lower
.
contains
(
"doubao"
))
return
"Doubao.Color"
;
if
(
lower
.
contains
(
"gpt"
)
||
lower
.
contains
(
"openai"
)
||
lower
.
contains
(
"o1"
)
||
lower
.
contains
(
"o3"
)
||
lower
.
contains
(
"o4"
))
return
"OpenAI"
;
if
(
lower
.
contains
(
"claude"
))
return
"Claude.Color"
;
if
(
lower
.
contains
(
"gemini"
))
return
"Gemini.Color"
;
if
(
lower
.
contains
(
"llama"
)
||
lower
.
contains
(
"meta"
))
return
"Meta"
;
if
(
lower
.
contains
(
"moonshot"
)
||
lower
.
contains
(
"kimi"
))
return
"Moonshot"
;
if
(
lower
.
contains
(
"glm"
)
||
lower
.
contains
(
"zhipu"
)
||
lower
.
contains
(
"chatglm"
))
return
"Zhipu.Color"
;
if
(
lower
.
contains
(
"embedding"
)
||
lower
.
contains
(
"bge"
)
||
lower
.
contains
(
"m3e"
)
||
lower
.
contains
(
"bge-m3"
))
return
"Embedding"
;
if
(
lower
.
contains
(
"rerank"
))
return
"Rerank"
;
if
(
lower
.
contains
(
"stable"
)
||
lower
.
contains
(
"sdxl"
))
return
"StableDiffusion"
;
if
(
lower
.
contains
(
"wav2lip"
)
||
lower
.
contains
(
"tts"
)
||
lower
.
contains
(
"asr"
)
||
lower
.
contains
(
"audio"
))
return
"Audio"
;
if
(
lower
.
contains
(
"mistral"
)
||
lower
.
contains
(
"mixtral"
))
return
"Mistral"
;
if
(
lower
.
contains
(
"yi"
))
return
"Yi"
;
if
(
lower
.
contains
(
"baichuan"
))
return
"Baichuan"
;
if
(
lower
.
contains
(
"minimax"
))
return
"MiniMax.Color"
;
if
(
lower
.
contains
(
"hunyuan"
)
||
lower
.
contains
(
"tencent"
))
return
"Hunyuan"
;
if
(
lower
.
contains
(
"spark"
)
||
lower
.
contains
(
"xunfei"
)
||
lower
.
contains
(
"iflytek"
))
return
"Spark"
;
if
(
lower
.
contains
(
"sensenova"
)
||
lower
.
contains
(
"sense"
))
return
"SenseNova"
;
return
"AI"
;
}
/**
* 根据 model_name 推断 vendor 名
*/
private
String
resolveVendorName
(
String
modelName
,
List
<
Map
<
String
,
Object
>>
vendors
)
{
if
(
modelName
==
null
)
return
null
;
if
(
vendors
!=
null
)
{
for
(
Map
<
String
,
Object
>
v
:
vendors
)
{
Object
name
=
v
.
get
(
"name"
);
if
(
name
==
null
)
continue
;
String
n
=
name
.
toString
().
toLowerCase
();
if
(
modelName
.
toLowerCase
().
contains
(
n
))
{
return
name
.
toString
();
}
}
}
return
null
;
}
private
Long
toLong
(
Object
o
)
{
if
(
o
==
null
)
return
null
;
if
(
o
instanceof
Number
)
return
((
Number
)
o
).
longValue
();
try
{
return
Long
.
parseLong
(
o
.
toString
());
}
catch
(
Exception
ignored
)
{
return
null
;
}
}
private
Integer
toInteger
(
Object
o
)
{
if
(
o
==
null
)
return
null
;
if
(
o
instanceof
Number
)
return
((
Number
)
o
).
intValue
();
try
{
return
Integer
.
parseInt
(
o
.
toString
());
}
catch
(
Exception
ignored
)
{
return
null
;
}
}
private
BigDecimal
toBigDecimal
(
Object
o
)
{
if
(
o
==
null
)
return
null
;
if
(
o
instanceof
Number
)
return
new
BigDecimal
(
o
.
toString
());
if
(
o
instanceof
String
)
{
try
{
return
new
BigDecimal
((
String
)
o
);
}
catch
(
Exception
ignored
)
{
ApiHubResponse
<
ApiHubUserVO
>
resp
=
apiHubClient
.
getUserByUsername
(
user
.
getApiHubUsername
());
if
(!
Boolean
.
TRUE
.
equals
(
resp
.
getSuccess
())
||
resp
.
getData
()
==
null
)
{
log
.
warn
(
"[查询模型列表与价格] 查询 api_hub 用户价格倍率失败: {}"
,
resp
.
getMessage
());
return
null
;
}
}
return
null
;
}
/**
* 解析分档计费表达式
* 格式: (条件1 ? tier("档位1", p*x + c*y + cr*a + cc*b + ...) : 条件2 ? tier("档位2", ...) : tier("档位3", ...)) * (条件 ? 倍率 : 1) * ...
*
* 使用括号深度匹配(而非简单正则)来正确支持参数内嵌的 u("field") 嵌套调用,
* 否则旧实现会把 u("tokens") 的内层 ) 误识别为外层 tier(...) 的闭合,导致:
* 1. params 截断为 u("tokens"
* 2. 后续档位 conditionDesc 包含前一档 params 的残骸
* 3. 最后一档(无 ? 的兜底档)被错误地给 null
*/
private
List
<
AppModelPricingVO
.
TierVO
>
parseTieredExpr
(
String
billingExpr
,
BigDecimal
groupRatio
,
Map
<
String
,
Object
>
billingUsageSchema
)
{
List
<
AppModelPricingVO
.
TierVO
>
tiers
=
new
java
.
util
.
ArrayList
<>();
if
(
billingExpr
==
null
||
billingExpr
.
isEmpty
())
{
return
tiers
;
}
try
{
// 1. 用括号深度匹配找出所有 tier(...) 的精确 [start, end] 范围
List
<
int
[]>
tierRanges
=
findAllTierRanges
(
billingExpr
);
if
(
tierRanges
.
isEmpty
())
{
return
tiers
;
}
// 截取到最后一个 tier(...) 结束,去掉尾部的条件乘数
int
lastTierEnd
=
tierRanges
.
get
(
tierRanges
.
size
()
-
1
)[
1
];
String
tierExpr
=
billingExpr
.
substring
(
0
,
lastTierEnd
);
// 2. 解析每个 tier 的标签和参数
List
<
TierInfo
>
tierInfos
=
new
java
.
util
.
ArrayList
<>();
for
(
int
[]
range
:
tierRanges
)
{
int
start
=
range
[
0
];
int
end
=
range
[
1
];
// tier(...) 内部的全部内容(去掉首尾括号)
String
inner
=
billingExpr
.
substring
(
start
+
"tier("
.
length
(),
end
).
trim
();
// 找顶层逗号(depth=0,不在字符串里)来切分 label 和 params
int
commaIdx
=
findTopLevelComma
(
inner
);
if
(
commaIdx
<
0
)
continue
;
String
label
=
inner
.
substring
(
0
,
commaIdx
).
trim
();
if
(
label
.
startsWith
(
"\""
)
&&
label
.
endsWith
(
"\""
))
{
label
=
label
.
substring
(
1
,
label
.
length
()
-
1
);
}
String
params
=
inner
.
substring
(
commaIdx
+
1
).
trim
();
tierInfos
.
add
(
new
TierInfo
(
start
,
end
,
label
,
params
));
}
if
(
tierInfos
.
isEmpty
())
{
return
tiers
;
}
// 3. 遍历每个 tier,提取其条件描述
for
(
int
i
=
0
;
i
<
tierInfos
.
size
();
i
++)
{
TierInfo
info
=
tierInfos
.
get
(
i
);
AppModelPricingVO
.
TierVO
tier
=
new
AppModelPricingVO
.
TierVO
();
tier
.
setName
(
info
.
label
);
// 解析参数部分,提取各倍率
parseTierParams
(
tier
,
info
.
params
,
billingUsageSchema
);
// 提取条件:在 (上一个 tier 结束 + 1) 到当前 tier 开始的段落里找顶层 ?
int
segStart
=
(
i
==
0
)
?
0
:
tierInfos
.
get
(
i
-
1
).
end
+
1
;
int
segEnd
=
info
.
start
;
String
segment
=
tierExpr
.
substring
(
segStart
,
segEnd
);
int
qIdx
=
findTopLevelQuestionMark
(
segment
);
if
(
qIdx
>=
0
)
{
String
condition
=
segment
.
substring
(
0
,
qIdx
).
trim
();
// 清理前导 ( : 和空白
condition
=
condition
.
replaceAll
(
"^[\\s(:]+"
,
""
);
// 去掉首尾成对的括号
while
(
condition
.
startsWith
(
"("
)
&&
condition
.
endsWith
(
")"
))
{
condition
=
condition
.
substring
(
1
,
condition
.
length
()
-
1
).
trim
();
}
tier
.
setConditionDesc
(
simplifyCondition
(
condition
));
}
else
if
(
i
==
tierInfos
.
size
()
-
1
)
{
// 最后一个 tier 没有 ?: 出现,是默认兜底档位
tier
.
setConditionDesc
(
"默认"
);
}
tiers
.
add
(
tier
);
}
return
resp
.
getData
().
getPriceMultiplier
();
}
catch
(
Exception
e
)
{
log
.
warn
(
"[parseTieredExpr] 解析分档表达式失败:{}"
,
billingExpr
,
e
);
}
return
tiers
;
}
/**
* tier 解析过程的中间结果
*/
private
static
class
TierInfo
{
final
int
start
;
final
int
end
;
final
String
label
;
final
String
params
;
TierInfo
(
int
start
,
int
end
,
String
label
,
String
params
)
{
this
.
start
=
start
;
this
.
end
=
end
;
this
.
label
=
label
;
this
.
params
=
params
;
}
}
/**
* 用括号深度匹配找出表达式中所有 tier(...) 的精确起止位置。
* 兼容参数里嵌套的 u("field") 调用,避免被内层 ) 误截断。
*/
private
List
<
int
[]>
findAllTierRanges
(
String
expr
)
{
List
<
int
[]>
ranges
=
new
java
.
util
.
ArrayList
<>();
int
searchFrom
=
0
;
while
(
true
)
{
int
idx
=
expr
.
indexOf
(
"tier("
,
searchFrom
);
if
(
idx
<
0
)
break
;
// depth 初始为 1(外层 tier( 的左括号)
int
depth
=
1
;
int
end
=
-
1
;
for
(
int
i
=
idx
+
"tier("
.
length
();
i
<
expr
.
length
();
i
++)
{
char
ch
=
expr
.
charAt
(
i
);
if
(
ch
==
'('
)
depth
++;
else
if
(
ch
==
')'
)
{
depth
--;
if
(
depth
==
0
)
{
end
=
i
;
break
;
}
}
}
if
(
end
<
0
)
break
;
ranges
.
add
(
new
int
[]{
idx
,
end
});
searchFrom
=
end
+
1
;
}
return
ranges
;
}
/**
* 在字符串中找到深度=0 且不在引号内的第一个逗号位置(用于切分 tier(label, params))
*/
private
int
findTopLevelComma
(
String
inner
)
{
int
depth
=
0
;
boolean
inQuote
=
false
;
for
(
int
i
=
0
;
i
<
inner
.
length
();
i
++)
{
char
ch
=
inner
.
charAt
(
i
);
if
(
ch
==
'"'
)
{
inQuote
=
!
inQuote
;
}
else
if
(!
inQuote
)
{
if
(
ch
==
'('
)
depth
++;
else
if
(
ch
==
')'
)
depth
--;
else
if
(
ch
==
','
&&
depth
==
0
)
return
i
;
}
}
return
-
1
;
}
/**
* 在段落里找顶层 ? 的位置(深度=0、未在引号内)。
* 返回最右侧的顶层 ?,因为三元表达式段落里通常只有一个 ? 在末尾。
*/
private
int
findTopLevelQuestionMark
(
String
segment
)
{
int
depth
=
0
;
int
lastQ
=
-
1
;
boolean
inQuote
=
false
;
for
(
int
i
=
0
;
i
<
segment
.
length
();
i
++)
{
char
ch
=
segment
.
charAt
(
i
);
if
(
ch
==
'"'
)
{
inQuote
=
!
inQuote
;
}
else
if
(!
inQuote
)
{
if
(
ch
==
'('
)
depth
++;
else
if
(
ch
==
')'
)
depth
--;
else
if
(
ch
==
'?'
&&
depth
==
0
)
{
lastQ
=
i
;
}
}
}
return
lastQ
;
}
/**
* 解析 tier 参数部分,提取各扩展价格倍率
* 格式: p * x + c * y + cr * a + cc * b + cc1h * c1 + img * d + img_o * e + ai * f + ao * g
* 或 u("field") * X [/ 1000000] (动态计费:tokens 为每百万 token,其余字段按 schema.unit)
*
* @param billingUsageSchema 计费用法 schema(用于推断 u("field") 的字段单位)
*/
private
void
parseTierParams
(
AppModelPricingVO
.
TierVO
tier
,
String
params
,
Map
<
String
,
Object
>
billingUsageSchema
)
{
if
(
params
==
null
||
params
.
isEmpty
())
{
return
;
}
// 提取 u("field") * X [/ 1000000](动态计费)
// 例如 u("tokens") * 29.14 / 1000000 => tokensMultiplier = 29.14(每百万 token)
// u("seconds") * 0.4104 => tokensMultiplier = 0.4104(每 1 秒)
java
.
util
.
regex
.
Pattern
tokensPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"u\\s*\\(\\s*\"(\\w+)\"\\s*\\)\\s*\\*\\s*([\\d.]+)\\s*(?:/\\s*1000000)?"
);
java
.
util
.
regex
.
Matcher
tokensMatcher
=
tokensPattern
.
matcher
(
params
);
if
(
tokensMatcher
.
find
())
{
String
field
=
tokensMatcher
.
group
(
1
);
BigDecimal
multiplier
=
new
BigDecimal
(
tokensMatcher
.
group
(
2
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
);
tier
.
setTokensMultiplier
(
multiplier
);
tier
.
setUsageField
(
field
);
tier
.
setUsageUnit
(
resolveUsageUnit
(
billingUsageSchema
,
field
));
}
// 提取 p * x
java
.
util
.
regex
.
Pattern
pPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"p\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
pMatcher
=
pPattern
.
matcher
(
params
);
if
(
pMatcher
.
find
())
{
tier
.
setInputRatio
(
new
BigDecimal
(
pMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 c * x
java
.
util
.
regex
.
Pattern
cPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"c\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
cMatcher
=
cPattern
.
matcher
(
params
);
if
(
cMatcher
.
find
())
{
tier
.
setOutputRatio
(
new
BigDecimal
(
cMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 cr * x (缓存读取)
java
.
util
.
regex
.
Pattern
crPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"cr\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
crMatcher
=
crPattern
.
matcher
(
params
);
if
(
crMatcher
.
find
())
{
tier
.
setCacheReadRatio
(
new
BigDecimal
(
crMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 cc * x (缓存创建 5分钟)
java
.
util
.
regex
.
Pattern
ccPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"cc\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
ccMatcher
=
ccPattern
.
matcher
(
params
);
if
(
ccMatcher
.
find
())
{
tier
.
setCacheCreateRatio
(
new
BigDecimal
(
ccMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 cc1h * x (缓存创建 1小时)
java
.
util
.
regex
.
Pattern
cc1hPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"cc1h\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
cc1hMatcher
=
cc1hPattern
.
matcher
(
params
);
if
(
cc1hMatcher
.
find
())
{
tier
.
setCacheCreate1hRatio
(
new
BigDecimal
(
cc1hMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 img * x (图片输入)
java
.
util
.
regex
.
Pattern
imgPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"img\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
imgMatcher
=
imgPattern
.
matcher
(
params
);
if
(
imgMatcher
.
find
())
{
tier
.
setImageInputRatio
(
new
BigDecimal
(
imgMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 img_o * x (图片输出)
java
.
util
.
regex
.
Pattern
img_oPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"img_o\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
img_oMatcher
=
img_oPattern
.
matcher
(
params
);
if
(
img_oMatcher
.
find
())
{
tier
.
setImageOutputRatio
(
new
BigDecimal
(
img_oMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 ai * x (音频输入)
java
.
util
.
regex
.
Pattern
aiPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"ai\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
aiMatcher
=
aiPattern
.
matcher
(
params
);
if
(
aiMatcher
.
find
())
{
tier
.
setAudioInputRatio
(
new
BigDecimal
(
aiMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
// 提取 ao * x (音频输出)
java
.
util
.
regex
.
Pattern
aoPattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"ao\\s*\\*\\s*([\\d.]+)"
);
java
.
util
.
regex
.
Matcher
aoMatcher
=
aoPattern
.
matcher
(
params
);
if
(
aoMatcher
.
find
())
{
tier
.
setAudioOutputRatio
(
new
BigDecimal
(
aoMatcher
.
group
(
1
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
));
}
}
/**
* 通过 billing_usage_schema 推断 u("field") 引用字段的单位。
* 例如 field=seconds → unit=second,field=tokens → unit=token,field=input_images → unit=count。
* 推断失败时返回 null,由前端兜底为 "token"。
*/
private
String
resolveUsageUnit
(
Map
<
String
,
Object
>
billingUsageSchema
,
String
field
)
{
if
(
billingUsageSchema
==
null
||
field
==
null
||
field
.
isEmpty
())
{
return
null
;
}
Object
fieldDef
=
billingUsageSchema
.
get
(
field
);
if
(!(
fieldDef
instanceof
Map
))
{
log
.
warn
(
"[查询模型列表与价格] 查询 api_hub 用户价格倍率异常: {}"
,
e
.
getMessage
());
return
null
;
}
@SuppressWarnings
(
"unchecked"
)
Map
<
String
,
Object
>
fieldMap
=
(
Map
<
String
,
Object
>)
fieldDef
;
Object
unit
=
fieldMap
.
get
(
"unit"
);
return
unit
==
null
?
null
:
unit
.
toString
();
}
/**
* 简化条件描述
*/
private
String
simplifyCondition
(
String
condition
)
{
if
(
condition
==
null
||
condition
.
isEmpty
())
{
return
""
;
}
return
condition
.
replaceAll
(
"\\s+&&\\s+"
,
" 且 "
)
.
replaceAll
(
"\\s+\\|\\|\\s+"
,
" 或 "
)
.
replace
(
"len"
,
"长度"
)
.
replace
(
" p "
,
" 输入 "
)
.
replace
(
" c "
,
" 输出 "
)
.
replace
(
"p >"
,
"输入 >"
)
.
replace
(
"p <"
,
"输入 <"
)
.
replace
(
"p >="
,
"输入 >="
)
.
replace
(
"p <="
,
"输入 <="
)
.
replace
(
"p=="
,
"输入 =="
)
.
replace
(
"c >"
,
"输出 >"
)
.
replace
(
"c <"
,
"输出 <"
)
.
replace
(
"c >="
,
"输出 >="
)
.
replace
(
"c <="
,
"输出 <="
)
.
replace
(
"c=="
,
"输出 =="
)
.
trim
();
}
/**
* 解析条件乘数表达式
* 格式: ((条件) ? 倍率 : 1) * ((条件) ? 倍率 : 1) * ...
*/
private
List
<
AppModelPricingVO
.
ConditionMultiplierVO
>
parseConditionMultipliers
(
String
billingExpr
)
{
List
<
AppModelPricingVO
.
ConditionMultiplierVO
>
multipliers
=
new
java
.
util
.
ArrayList
<>();
if
(
billingExpr
==
null
||
billingExpr
.
isEmpty
())
{
return
multipliers
;
}
try
{
// 找到最后一个 tier(...) 结束的位置
int
lastTierEnd
=
-
1
;
int
searchStart
=
0
;
while
(
true
)
{
int
tierStart
=
billingExpr
.
indexOf
(
"tier("
,
searchStart
);
if
(
tierStart
==
-
1
)
break
;
int
depth
=
0
;
int
i
=
tierStart
;
for
(;
i
<
billingExpr
.
length
();
i
++)
{
char
ch
=
billingExpr
.
charAt
(
i
);
if
(
ch
==
'('
)
depth
++;
else
if
(
ch
==
')'
)
{
depth
--;
if
(
depth
==
0
)
{
lastTierEnd
=
i
+
1
;
break
;
}
}
}
searchStart
=
i
+
1
;
}
if
(
lastTierEnd
==
-
1
||
lastTierEnd
>=
billingExpr
.
length
())
{
return
multipliers
;
}
// 提取条件乘数部分(最后一个 tier(...) 之后的内容)
String
multiplierExpr
=
billingExpr
.
substring
(
lastTierEnd
).
replaceAll
(
"^\\s*\\)\\s*\\*\\s*"
,
""
);
// 用栈匹配方式解析每个条件组: ((... ) ? 倍率 : 1)
int
pos
=
0
;
while
(
pos
<
multiplierExpr
.
length
())
{
// 找到下一个 ( 的位置
int
startParen
=
multiplierExpr
.
indexOf
(
'('
,
pos
);
if
(
startParen
==
-
1
)
break
;
// 从这个 ( 开始,找到对应的 )
int
depth
=
0
;
int
i
=
startParen
;
for
(;
i
<
multiplierExpr
.
length
();
i
++)
{
char
ch
=
multiplierExpr
.
charAt
(
i
);
if
(
ch
==
'('
)
depth
++;
else
if
(
ch
==
')'
)
{
depth
--;
if
(
depth
==
0
)
{
// 找到了对应的 )
// 提取从 startParen 到 i+1 的内容(完整条件组)
String
group
=
multiplierExpr
.
substring
(
startParen
,
i
+
1
);
// 检查是否是条件组格式: (... ) ? 倍率 : 1
int
questionMark
=
group
.
lastIndexOf
(
'?'
);
int
colonIndex
=
group
.
lastIndexOf
(
':'
);
if
(
questionMark
>
0
&&
colonIndex
>
questionMark
)
{
String
condition
=
group
.
substring
(
1
,
questionMark
).
trim
();
// 去掉首尾括号
String
afterQuestion
=
group
.
substring
(
questionMark
+
1
,
colonIndex
).
trim
();
try
{
BigDecimal
multiplier
=
new
BigDecimal
(
afterQuestion
).
setScale
(
1
,
RoundingMode
.
HALF_UP
);
AppModelPricingVO
.
ConditionMultiplierVO
cm
=
new
AppModelPricingVO
.
ConditionMultiplierVO
();
cm
.
setMultiplier
(
multiplier
);
cm
.
setDescription
(
parseConditionDesc
(
condition
));
multipliers
.
add
(
cm
);
}
catch
(
NumberFormatException
ignored
)
{}
}
pos
=
i
+
1
;
break
;
}
}
}
if
(
i
>=
multiplierExpr
.
length
())
break
;
}
}
catch
(
Exception
e
)
{
log
.
warn
(
"[parseConditionMultipliers] 解析条件乘数失败:{}"
,
billingExpr
,
e
);
}
return
multipliers
;
}
/**
* 解析条件描述为用户可读文字
*/
private
String
parseConditionDesc
(
String
condition
)
{
if
(
condition
==
null
||
condition
.
isEmpty
())
{
return
""
;
}
String
result
=
condition
;
// 先处理 has(header(...), "xxx") 这种模式
result
=
result
.
replaceAll
(
"has\\s*\\(\\s*header\\s*\\(\\s*\"([^\"]+)\"\\s*\\)\\s*,\\s*\"([^\"]+)\"\\s*\\)"
,
"请求头 $1 包含 \"$2\""
);
// 替换逻辑运算符
result
=
result
.
replaceAll
(
"\\s+&&\\s+"
,
" 且 "
);
result
=
result
.
replaceAll
(
"\\s+\\|\\|\\s+"
,
" 或 "
);
// 时间条件 - 完整函数调用替换
result
=
result
.
replaceAll
(
"hour\\s*\\(\\s*\"([^\"]+)\"\\s*\\)"
,
"小时"
);
result
=
result
.
replaceAll
(
"minute\\s*\\(\\s*\"([^\"]+)\"\\s*\\)"
,
"分钟"
);
result
=
result
.
replaceAll
(
"weekday\\s*\\(\\s*\"([^\"]+)\"\\s*\\)"
,
"星期"
);
result
=
result
.
replaceAll
(
"month\\s*\\(\\s*\"([^\"]+)\"\\s*\\)"
,
"月份"
);
result
=
result
.
replaceAll
(
"day\\s*\\(\\s*\"([^\"]+)\"\\s*\\)"
,
"日期"
);
// 请求参数条件
result
=
result
.
replaceAll
(
"param\\s*\\(\\s*\"([^\"]+)\"\\s*\\)\\s*"
,
"请求参数 $1 "
);
result
=
result
.
replaceAll
(
"param\\s*\\(\\s*\"([^\"]+)\"\\s*\\)\\s*!=\\s*nil"
,
"请求参数 $1 存在"
);
// 请求头条件 - 处理剩余的 header()
result
=
result
.
replaceAll
(
"header\\s*\\(\\s*\"([^\"]+)\"\\s*\\)\\s*!=\\s*\"\""
,
"请求头 $1 存在"
);
result
=
result
.
replaceAll
(
"header\\s*\\(\\s*\"([^\"]+)\"\\s*\\)\\s*"
,
"请求头 $1 "
);
// 比较运算符
result
=
result
.
replace
(
">="
,
" ≥ "
);
result
=
result
.
replace
(
"<="
,
" ≤ "
);
result
=
result
.
replace
(
"=="
,
" = "
);
result
=
result
.
replace
(
"!="
,
" ≠ "
);
result
=
result
.
replace
(
">"
,
" > "
);
result
=
result
.
replace
(
"<"
,
" < "
);
// 清理多余空格
result
=
result
.
replaceAll
(
"\\s+"
,
" "
);
result
=
result
.
trim
();
return
result
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelPricingVO.java
View file @
2cb2a43f
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
;
/**
* 视频价格 480p(元 / 秒)
*/
private
BigDecimal
videoPrice480p
;
@Schema
(
description
=
"音频输入价格(元/1k tokens),已乘 groupRatio"
)
private
BigDecimal
audioInputPrice
;
/**
* 视频价格 720p(元 / 秒)
*/
private
BigDecimal
videoPrice720p
;
@Schema
(
description
=
"音频补全价格(元/1k tokens),已乘 groupRatio"
)
private
BigDecimal
audioCompletionPrice
;
/**
* 视频价格 1080p(元 / 秒)
*/
private
BigDecimal
videoPrice1080p
;
@Schema
(
description
=
"状态:1-启用,0-禁用"
)
private
Integer
status
;
/**
* 状态:1=启用、0=禁用
*/
private
Integer
status
=
1
;
@Schema
(
description
=
"模型描述(未设置则为空)"
)
/**
* 模型描述
*/
private
String
description
;
@Schema
(
description
=
"模型标签,多个用逗号分隔"
)
/**
* 标签(逗号分隔)
*/
private
String
tags
;
@Schema
(
description
=
"计费模式:tiered_expr-分档计费"
)
/**
* 计费模式:视频分档模型为 {@code video_tiered},其余为空
*/
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 数组)
*/
@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
;
}
/**
* 分档信息 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
;
/**
* 按 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
;
/**
* tokensMultiplier 对应的计费字段名(如 tokens/seconds)。
* 仅当 tokensMultiplier 非空时有意义,用于前端明确当前档位在计什么。
*/
@Schema
(
description
=
"tokensMultiplier 对应的计费字段名(如 tokens/seconds/input_images)"
)
private
String
usageField
;
/**
* usageField 在 billing_usage_schema 中的 unit(如 token/second/count)。
* 仅当 tokensMultiplier 非空时有意义,用于前端选择展示单位文案(token/秒/次)。
*/
@Schema
(
description
=
"usageField 在 schema 中的 unit(token/second/count),用于前端选择展示单位文案"
)
private
String
usageUnit
;
}
/**
* 条件乘数 VO
*/
@Data
@Schema
(
description
=
"条件乘数"
)
public
static
class
ConditionMultiplierVO
{
@Schema
(
description
=
"条件描述(用户可读的文字)"
)
private
String
description
;
@Schema
(
description
=
"倍率"
)
private
BigDecimal
multiplier
;
}
}
/**
* 上下文长度
*/
private
String
contextLength
;
/**
* 最大输出长度
*/
private
String
maxOutputLength
;
/**
* 所属渠道名
*/
private
String
channelName
;
/**
* 模型类型标签(text / multimodal / image_gen / video_gen / embedding / rerank / speech)
*/
private
List
<
String
>
modalities
=
new
ArrayList
<>();
/**
* 使用方法:一个端点一条(含调用示例与参数说明)
*
* <p>一个模型带多个模型类型时会有多条
*/
private
List
<
AppModelUsageVO
>
usageMethods
=
new
ArrayList
<>();
}
\ No newline at end of file
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelSampleVO.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelUsageVO.java
0 → 100644
View file @
2cb2a43f
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
<>();
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppModelVO.java
deleted
100644 → 0
View file @
fba7e550
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppParamVO.java
0 → 100644
View file @
2cb2a43f
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/controller/app/aimodel/vo/AppPricingVO.java
deleted
100644 → 0
View file @
fba7e550
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
;
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/framework/security/config/SecurityConfiguration.java
View file @
2cb2a43f
...
...
@@ -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
();
}
...
...
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubClient.java
0 → 100644
View file @
2cb2a43f
package
com
.
luhu
.
computility
.
module
.
apihub
.
service
.
apihub
;
import
cn.hutool.core.util.StrUtil
;
import
cn.hutool.http.HttpRequest
;
import
cn.hutool.http.HttpResponse
;
import
cn.hutool.json.JSONObject
;
import
cn.hutool.json.JSONUtil
;
import
com.fasterxml.jackson.core.type.TypeReference
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.luhu.computility.module.apihub.config.ApiHubProperties
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubModelPriceVO
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubResponse
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubTokenVO
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubUserVO
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.stereotype.Service
;
import
javax.annotation.Resource
;
import
java.net.URI
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.time.Duration
;
import
java.util.ArrayList
;
import
java.util.Base64
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
/**
* api_hub 管理端客户端
*
* <p>api_hub 管理端接口统一在 /api 前缀下,对外接口在 /v1/open 与 /v1/data,本类只用管理端路径。
*
* <p>三个硬约束(见迁移计划阶段 1):
* <ol>
* <li>登录在 api_hub 配了 database_url 时强制校验图形验证码,验证码明文在 captcha_id 的 base64 段里</li>
* <li>创建用户时 group_name 必填且必须是已存在分组,username 全局唯一,mobile 非空时须为 11 位手机号</li>
* <li>创建密钥时同一用户下 name + kind 只允许一个启用中的密钥(kind 为空则不限制),重复创建报 409</li>
* </ol>
*
* @author puhui
*/
@Slf4j
@Service
public
class
ApiHubClient
{
@Resource
private
ApiHubProperties
apiHubProperties
;
@Resource
private
ObjectMapper
objectMapper
;
private
static
final
String
HEADER_AUTH
=
"Authorization"
;
/**
* PATCH 请求专用客户端
*
* <p>Hutool 底层是 HttpURLConnection,JDK 17 下发 PATCH 会因模块系统限制抛
* InaccessibleObjectException,故 PATCH 走 JDK 11+ 内置 HttpClient。
*/
private
static
final
java
.
net
.
http
.
HttpClient
PATCH_HTTP_CLIENT
=
java
.
net
.
http
.
HttpClient
.
newBuilder
().
connectTimeout
(
Duration
.
ofSeconds
(
30
)).
build
();
/**
* api_hub 初始化只 seed 了 default 分组
*/
private
static
final
String
DEFAULT_GROUP_NAME
=
"default"
;
/**
* 管理端令牌内存缓存,失效后自动重新登录
*/
private
volatile
String
cachedToken
;
/**
* 管理端令牌过期时间戳(毫秒),留出缓冲提前重登,避免边界失效
*/
private
volatile
long
cachedTokenExpireAt
;
/**
* 令牌过期前的刷新缓冲(毫秒):api_hub 默认令牌 TTL 72 小时,这里提前 5 分钟重登,
* 避免请求正好打在过期边界上
*/
private
static
final
long
TOKEN_REFRESH_BUFFER_MS
=
5
*
60
*
1000L
;
/**
* 令牌有效期读不出来时的兜底值(毫秒),与 api_hub 默认 TOKEN_TTL_HOURS=72 对齐
*/
private
static
final
long
TOKEN_TTL_FALLBACK_MS
=
72
*
3600
*
1000L
;
/**
* 登录失败后的冷却时间(毫秒)
*
* <p>api_hub 的登录失败计数是「按用户名」和「按 IP」双维度取大的,
* 15 分钟内 5 次失败就锁 15 分钟(锁的是整个出口 IP 的登录)。
* puhui 每次令牌失效都会重新登录,若密码配错会被反复触发把 api_hub 管理端锁死,
* 故登录失败后进入冷却期,期间直接失败不再重试。
*/
private
static
final
long
LOGIN_FAIL_COOLDOWN_MS
=
5
*
60
*
1000L
;
/**
* 登录失败冷却截止时间戳(毫秒),0 表示不处于冷却期
*/
private
volatile
long
loginFailCooldownUntil
;
/**
* 管理端登录,返回令牌
*
* <p>api_hub 配了 database_url 时强制校验图形验证码,且无开关可关,
* 故登录前先取一次验证码,从 captcha_id 的 base64 段直接解出明文 code 提交。
*
* @return 登录失败时 message 为错误描述
*/
public
ApiHubResponse
<
String
>
login
()
{
String
username
=
apiHubProperties
.
getAdminUsername
();
String
password
=
apiHubProperties
.
getAdminPassword
();
if
(
StrUtil
.
isBlank
(
username
)
||
StrUtil
.
isBlank
(
password
))
{
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"api_hub 管理端账号或密码未配置"
)
.
build
();
}
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/auth/login"
;
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"username"
,
username
);
body
.
put
(
"password"
,
password
);
body
.
put
(
"otp_code"
,
""
);
// 验证码:获取失败不阻断(api_hub 未配 database_url 时不校验验证码),
// 但 api_hub 配了 database_url 时必须带上,否则登录报「图形验证码错误」
String
captchaId
=
null
;
String
captchaCode
=
null
;
try
{
ApiHubResponse
<
String
>
captcha
=
fetchCaptcha
();
if
(
Boolean
.
TRUE
.
equals
(
captcha
.
getSuccess
())
&&
StrUtil
.
isNotBlank
(
captcha
.
getData
()))
{
String
rawCaptchaId
=
captcha
.
getData
();
captchaId
=
rawCaptchaId
;
captchaCode
=
decodeCaptchaCode
(
rawCaptchaId
);
}
}
catch
(
Exception
e
)
{
log
.
warn
(
"[ApiHubClient.login] 获取图形验证码失败,将不带验证码尝试登录: {}"
,
e
.
getMessage
());
}
if
(
StrUtil
.
isNotBlank
(
captchaId
)
&&
StrUtil
.
isNotBlank
(
captchaCode
))
{
body
.
put
(
"captcha_id"
,
captchaId
);
body
.
put
(
"captcha_code"
,
captchaCode
);
}
log
.
info
(
"[ApiHubClient.login] 请求URL: {}, username={}"
,
url
,
username
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
String
message
=
extractDetail
(
response
.
body
(),
"登录失败"
);
log
.
warn
(
"[ApiHubClient.login] 登录失败, status={}, message={}"
,
status
,
message
);
// 密码错误会触发 api_hub 的登录失败锁定(按 IP 计,5 次锁 15 分钟),
// 故进入冷却期,避免反复重试把管理端锁死;验证码错误等其它原因不冷却
if
(
isCredentialError
(
status
,
message
))
{
this
.
loginFailCooldownUntil
=
System
.
currentTimeMillis
()
+
LOGIN_FAIL_COOLDOWN_MS
;
log
.
warn
(
"[ApiHubClient.login] 账号密码错误,进入 {} 秒冷却期"
,
LOGIN_FAIL_COOLDOWN_MS
/
1000
);
}
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
message
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
response
.
body
());
String
token
=
json
.
getStr
(
"token"
);
if
(
StrUtil
.
isBlank
(
token
))
{
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"登录响应缺少 token 字段"
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
// 令牌有效期从 payload 的 exp 解析,读不到则按 api_hub 默认 72 小时兜底
long
expireAt
=
parseTokenExpireAt
(
token
);
this
.
cachedToken
=
token
;
this
.
cachedTokenExpireAt
=
expireAt
;
this
.
loginFailCooldownUntil
=
0L
;
log
.
info
(
"[ApiHubClient.login] 登录成功, token 过期时间={}"
,
expireAt
);
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
true
)
.
data
(
token
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.login] 请求异常"
,
e
);
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 获取图形验证码,返回 captcha_id
*
* <p>响应结构:{@code {"captcha_id": "...", "svg": "..."}}
*/
public
ApiHubResponse
<
String
>
fetchCaptcha
()
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/auth/captcha"
;
try
{
HttpResponse
response
=
HttpRequest
.
get
(
url
)
.
timeout
(
30000
)
.
execute
();
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"获取图形验证码失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
response
.
body
());
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
true
)
.
data
(
json
.
getStr
(
"captcha_id"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.fetchCaptcha] 请求异常"
,
e
);
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 从 captcha_id 中解出验证码明文
*
* <p>captcha_id 结构为 {@code base64url(JSON{code,exp,nonce}).HMAC签名},
* 第一段是 base64url 编码的 JSON,明文 code 就在其中,无需解析 SVG 图形。
*
* @return 验证码明文,解码失败返回 null
*/
public
String
decodeCaptchaCode
(
String
captchaId
)
{
if
(
StrUtil
.
isBlank
(
captchaId
))
{
return
null
;
}
try
{
String
[]
parts
=
captchaId
.
split
(
"\\."
);
if
(
parts
.
length
<
1
||
StrUtil
.
isBlank
(
parts
[
0
]))
{
return
null
;
}
// api_hub 用 urlsafe base64 且去掉了尾部 padding,解码前需补回
String
raw
=
parts
[
0
];
int
padding
=
raw
.
length
()
%
4
;
if
(
padding
>
0
)
{
raw
=
raw
+
"="
.
repeat
(
4
-
padding
);
}
byte
[]
decoded
=
Base64
.
getUrlDecoder
().
decode
(
raw
);
JSONObject
json
=
JSONUtil
.
parseObj
(
new
String
(
decoded
,
StandardCharsets
.
UTF_8
));
return
json
.
getStr
(
"code"
);
}
catch
(
Exception
e
)
{
log
.
warn
(
"[ApiHubClient.decodeCaptchaCode] 解码验证码失败: {}"
,
e
.
getMessage
());
return
null
;
}
}
/**
* 创建 api_hub 用户
*
* <p>username 需全局唯一,重复创建 api_hub 返回 409「用户名已存在」,
* 调用方应按「用户已存在」处理而非失败。
*
* @param mobile puhui 用户手机号,为空或非 11 位大陆手机号时传空串(api_hub 会拒绝非法手机号)
*/
public
ApiHubResponse
<
ApiHubUserVO
>
createUser
(
String
username
,
String
password
,
String
mobile
)
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/users"
;
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"username"
,
username
);
body
.
put
(
"password"
,
password
);
body
.
put
(
"role"
,
"user"
);
body
.
put
(
"group_name"
,
DEFAULT_GROUP_NAME
);
body
.
put
(
"enabled"
,
true
);
String
normalizedMobile
=
normalizeMobile
(
mobile
);
body
.
put
(
"mobile"
,
normalizedMobile
!=
null
?
normalizedMobile
:
""
);
log
.
info
(
"[ApiHubClient.createUser] 请求URL: {}, username={}, mobile={}"
,
url
,
username
,
normalizedMobile
);
return
executeJson
(
url
,
body
,
ApiHubUserVO
.
class
);
}
/**
* 修改 api_hub 用户
*
* <p>用于给已存在的用户补写手机号或重置密码:
* <ul>
* <li>api_hub 侧只存密码哈希,没有「查询明文密码」接口,puhui 忘记密码时只能重置</li>
* <li>改密码会让该用户的登录令牌立即失效(api_hub 会 bump token_version)</li>
* </ul>
*
* <p>这里用 JDK 11+ 内置的 {@code java.net.http.HttpClient} 而非 Hutool:
* Hutool 底层是 HttpURLConnection,JDK 17 下发 PATCH 需要反射改写
* {@code HttpURLConnection.methods} 静态字段,模块系统会抛 InaccessibleObjectException。
*
* @param userId api_hub 用户 ID
* @param body 待更新字段,可传 password / mobile 等
*/
public
ApiHubResponse
<
ApiHubUserVO
>
patchUser
(
Long
userId
,
Map
<
String
,
Object
>
body
)
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/users/"
+
userId
;
Map
<
String
,
Object
>
payload
=
new
HashMap
<>(
body
);
if
(
payload
.
containsKey
(
"mobile"
))
{
String
normalizedMobile
=
normalizeMobile
((
String
)
payload
.
get
(
"mobile"
));
payload
.
put
(
"mobile"
,
normalizedMobile
!=
null
?
normalizedMobile
:
""
);
}
log
.
info
(
"[ApiHubClient.patchUser] 请求URL: {}, userId={}, fields={}"
,
url
,
userId
,
payload
.
keySet
());
try
{
java
.
net
.
http
.
HttpResponse
<
String
>
response
=
sendPatchWithAuth
(
url
,
JSONUtil
.
toJsonStr
(
payload
));
int
status
=
response
.
statusCode
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"修改 api_hub 用户失败"
))
.
status
(
status
)
.
build
();
}
ApiHubUserVO
user
=
objectMapper
.
readValue
(
response
.
body
(),
ApiHubUserVO
.
class
);
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
true
)
.
data
(
user
)
.
status
(
status
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.patchUser] 请求异常, userId={}"
,
userId
,
e
);
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 发送 PATCH 请求;令牌失效时清缓存重登后重试一次
*/
private
java
.
net
.
http
.
HttpResponse
<
String
>
sendPatchWithAuth
(
String
url
,
String
json
)
throws
Exception
{
java
.
net
.
http
.
HttpResponse
<
String
>
response
=
PATCH_HTTP_CLIENT
.
send
(
buildPatchRequest
(
url
,
json
,
getAdminToken
()),
java
.
net
.
http
.
HttpResponse
.
BodyHandlers
.
ofString
());
if
(
response
.
statusCode
()
==
401
)
{
log
.
info
(
"[ApiHubClient.sendPatchWithAuth] 令牌失效,重新登录后重试"
);
clearToken
();
response
=
PATCH_HTTP_CLIENT
.
send
(
buildPatchRequest
(
url
,
json
,
getAdminToken
()),
java
.
net
.
http
.
HttpResponse
.
BodyHandlers
.
ofString
());
}
return
response
;
}
private
java
.
net
.
http
.
HttpRequest
buildPatchRequest
(
String
url
,
String
json
,
String
token
)
{
return
java
.
net
.
http
.
HttpRequest
.
newBuilder
()
.
uri
(
URI
.
create
(
url
))
.
timeout
(
Duration
.
ofSeconds
(
30
))
.
header
(
"Content-Type"
,
"application/json"
)
.
header
(
HEADER_AUTH
,
"Bearer "
+
token
)
.
method
(
"PATCH"
,
java
.
net
.
http
.
HttpRequest
.
BodyPublishers
.
ofString
(
json
,
StandardCharsets
.
UTF_8
))
.
build
();
}
/**
* 按用户名查询 api_hub 用户
*
* <p>用于创建用户返回 409「用户名已存在」后续建:先查已有用户拿到 user_id 再继续签发密钥。
*
* @return 用户列表(接口按 username 模糊匹配,返回结果里需再按 username 精确过滤)
*/
public
ApiHubResponse
<
List
<
ApiHubUserVO
>>
listUsersByUsername
(
String
username
)
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/users?q="
+
URLEncoder
.
encode
(
username
,
StandardCharsets
.
UTF_8
);
log
.
info
(
"[ApiHubClient.listUsersByUsername] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
executeWithAuth
(
HttpRequest
.
get
(
url
));
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
List
<
ApiHubUserVO
>>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"查询用户失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
List
<
ApiHubUserVO
>
users
=
objectMapper
.
readValue
(
response
.
body
(),
new
TypeReference
<
List
<
ApiHubUserVO
>>()
{
});
return
ApiHubResponse
.<
List
<
ApiHubUserVO
>>
builder
()
.
success
(
true
)
.
data
(
users
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.listUsersByUsername] 请求异常"
,
e
);
return
ApiHubResponse
.<
List
<
ApiHubUserVO
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 按用户名精确查询单个 api_hub 用户
*
* <p>api_hub 没有「按用户 ID 查单个用户」的接口,{@code GET /api/users?q=} 是对
* username / mobile 的模糊匹配,故这里取回候选列表后在本地按 username 精确过滤。
*
* @param username api_hub 用户名(即登录账号)
* @return 匹配到的用户;未匹配到时 success=false、data 为 null
*/
public
ApiHubResponse
<
ApiHubUserVO
>
getUserByUsername
(
String
username
)
{
if
(
StrUtil
.
isBlank
(
username
))
{
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
false
)
.
message
(
"用户名不能为空"
)
.
build
();
}
ApiHubResponse
<
List
<
ApiHubUserVO
>>
resp
=
listUsersByUsername
(
username
);
if
(!
Boolean
.
TRUE
.
equals
(
resp
.
getSuccess
()))
{
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
false
)
.
message
(
resp
.
getMessage
())
.
status
(
resp
.
getStatus
())
.
build
();
}
List
<
ApiHubUserVO
>
users
=
resp
.
getData
();
if
(
users
!=
null
)
{
for
(
ApiHubUserVO
user
:
users
)
{
if
(
username
.
equals
(
user
.
getUsername
()))
{
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
true
)
.
data
(
user
)
.
status
(
resp
.
getStatus
())
.
build
();
}
}
}
log
.
warn
(
"[ApiHubClient.getUserByUsername] 未找到精确匹配的用户: username={}"
,
username
);
return
ApiHubResponse
.<
ApiHubUserVO
>
builder
()
.
success
(
false
)
.
message
(
"api_hub 用户不存在: "
+
username
)
.
status
(
resp
.
getStatus
())
.
build
();
}
/**
* 查询 api_hub 模型售价明细
*
* <p>管理端接口 {@code GET /api/model-prices},返回所有「渠道 × 模型」的售价行,
* 含标价、售卖倍率、折扣、视频分档价、模态、在售状态等。
*
* @return 售价明细列表(失败时 success=false、data 为 null)
*/
public
ApiHubResponse
<
List
<
ApiHubModelPriceVO
>>
listModelPrices
()
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/model-prices"
;
log
.
info
(
"[ApiHubClient.listModelPrices] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
executeWithAuth
(
HttpRequest
.
get
(
url
));
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
List
<
ApiHubModelPriceVO
>>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"查询模型售价失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
List
<
ApiHubModelPriceVO
>
prices
=
objectMapper
.
readValue
(
response
.
body
(),
new
TypeReference
<
List
<
ApiHubModelPriceVO
>>()
{
});
return
ApiHubResponse
.<
List
<
ApiHubModelPriceVO
>>
builder
()
.
success
(
true
)
.
data
(
prices
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.listModelPrices] 请求异常"
,
e
);
return
ApiHubResponse
.<
List
<
ApiHubModelPriceVO
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 查询 api_hub 全部密钥
*
* <p>管理端接口只提供全量查询,调用方需按 user_id + name 自行过滤。
*/
public
ApiHubResponse
<
List
<
ApiHubTokenVO
>>
listTokens
()
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/tokens"
;
log
.
info
(
"[ApiHubClient.listTokens] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
executeWithAuth
(
HttpRequest
.
get
(
url
));
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
List
<
ApiHubTokenVO
>>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"查询密钥失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
List
<
ApiHubTokenVO
>
tokens
=
objectMapper
.
readValue
(
response
.
body
(),
new
TypeReference
<
List
<
ApiHubTokenVO
>>()
{
});
return
ApiHubResponse
.<
List
<
ApiHubTokenVO
>>
builder
()
.
success
(
true
)
.
data
(
tokens
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.listTokens] 请求异常"
,
e
);
return
ApiHubResponse
.<
List
<
ApiHubTokenVO
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 创建 api_hub 密钥
*
* <p>必须传 {@code unlimited=true}:扣费落在用户行而非 tokens.quota,
* unlimited=0 时新用户余额为 0,网关余额门禁会直接返回 402「余额不足」。
*
* <p>返回的 data.key 即为明文密钥。
*/
public
ApiHubResponse
<
ApiHubTokenVO
>
createToken
(
Long
userId
,
String
name
,
String
kind
)
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/tokens"
;
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"user_id"
,
userId
);
body
.
put
(
"name"
,
name
);
body
.
put
(
"kind"
,
StrUtil
.
blankToDefault
(
kind
,
""
));
body
.
put
(
"unlimited"
,
true
);
body
.
put
(
"group_name"
,
DEFAULT_GROUP_NAME
);
log
.
info
(
"[ApiHubClient.createToken] 请求URL: {}, userId={}, name={}"
,
url
,
userId
,
name
);
return
executeJson
(
url
,
body
,
ApiHubTokenVO
.
class
);
}
/**
* 取密钥明文
*
* <p>密钥列表接口不返回明文,需走此接口解密(历史密钥无法解密,api_hub 返回 409)。
*/
public
ApiHubResponse
<
String
>
revealToken
(
Long
tokenId
)
{
String
url
=
apiHubProperties
.
getBaseUrl
()
+
"/api/tokens/"
+
tokenId
+
"/reveal"
;
log
.
info
(
"[ApiHubClient.revealToken] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
executeWithAuth
(
HttpRequest
.
post
(
url
)
.
body
(
"{}"
)
.
contentType
(
"application/json"
));
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"取密钥明文失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
response
.
body
());
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
true
)
.
data
(
json
.
getStr
(
"key"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.revealToken] 请求异常"
,
e
);
return
ApiHubResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 执行带管理端鉴权的 JSON 请求,401 时自动重登并重试一次
*/
private
<
T
>
ApiHubResponse
<
T
>
executeJson
(
String
url
,
Map
<
String
,
Object
>
body
,
Class
<
T
>
dataClass
)
{
try
{
HttpRequest
request
=
HttpRequest
.
post
(
url
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
);
HttpResponse
response
=
executeWithAuth
(
request
);
int
status
=
response
.
getStatus
();
if
(
status
<
200
||
status
>=
300
)
{
return
ApiHubResponse
.<
T
>
builder
()
.
success
(
false
)
.
message
(
extractDetail
(
response
.
body
(),
"请求失败"
))
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
T
data
=
objectMapper
.
readValue
(
response
.
body
(),
dataClass
);
return
ApiHubResponse
.<
T
>
builder
()
.
success
(
true
)
.
data
(
data
)
.
status
(
status
)
.
httpResponse
(
response
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[ApiHubClient.executeJson] 请求异常, url={}"
,
url
,
e
);
return
ApiHubResponse
.<
T
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 附加管理端令牌执行请求;令牌失效(401)时重新登录并重试一次
*
* <p>令牌会因三种原因失效:TTL 到期、api_hub 改密码导致代次校验失败、账号被禁用。
* 前两种重登即可恢复;第三种重登也无解,重试一次后仍返回 401,由调用方按失败处理。
*/
private
HttpResponse
executeWithAuth
(
HttpRequest
request
)
{
request
.
header
(
HEADER_AUTH
,
"Bearer "
+
getAdminToken
());
request
.
timeout
(
30000
);
HttpResponse
response
=
request
.
execute
();
if
(
response
.
getStatus
()
==
401
)
{
// 令牌过期或 api_hub 改了密码导致代次校验失败,清缓存后重登再试一次
log
.
info
(
"[ApiHubClient.executeWithAuth] 令牌失效,重新登录后重试"
);
clearToken
();
request
.
header
(
HEADER_AUTH
,
"Bearer "
+
getAdminToken
());
response
=
request
.
execute
();
}
return
response
;
}
/**
* 获取管理端令牌:内存缓存 + TTL 过期重登
*
* <p>api_hub 的登录令牌有效期有限(默认 72 小时),且改密码后旧令牌立即失效,
* 故不提供手动配置令牌的方式,统一走「登录 → 缓存 → 过期或 401 后重登」。
*/
private
String
getAdminToken
()
{
String
cached
=
this
.
cachedToken
;
if
(
StrUtil
.
isNotBlank
(
cached
)
&&
System
.
currentTimeMillis
()
<
this
.
cachedTokenExpireAt
)
{
return
cached
;
}
synchronized
(
this
)
{
cached
=
this
.
cachedToken
;
if
(
StrUtil
.
isNotBlank
(
cached
)
&&
System
.
currentTimeMillis
()
<
this
.
cachedTokenExpireAt
)
{
return
cached
;
}
// 上次登录因账号密码错误失败,处于冷却期,直接失败不再重试,避免把 api_hub 管理端锁死
if
(
System
.
currentTimeMillis
()
<
this
.
loginFailCooldownUntil
)
{
throw
new
IllegalStateException
(
"api_hub 管理端登录失败处于冷却期,请检查配置的账号密码"
);
}
ApiHubResponse
<
String
>
resp
=
login
();
if
(!
Boolean
.
TRUE
.
equals
(
resp
.
getSuccess
())
||
StrUtil
.
isBlank
(
resp
.
getData
()))
{
throw
new
IllegalStateException
(
"api_hub 管理端登录失败: "
+
resp
.
getMessage
());
}
return
resp
.
getData
();
}
}
/**
* 判断登录失败是否为账号密码错误(这类失败会触发 api_hub 的登录锁定,需冷却)
*/
private
boolean
isCredentialError
(
int
status
,
String
message
)
{
if
(
status
==
429
)
{
// 已被 api_hub 锁定,等价于账号密码错误
return
true
;
}
return
status
==
401
&&
message
!=
null
&&
message
.
contains
(
"用户名或密码错误"
);
}
/**
* 清空令牌缓存
*/
public
void
clearToken
()
{
this
.
cachedToken
=
null
;
this
.
cachedTokenExpireAt
=
0L
;
}
/**
* 从令牌 payload 解析过期时间戳(毫秒)
*
* <p>令牌结构为 {@code base64url(JSON{uid,exp,nonce,tv}).HMAC签名},
* 解析失败时按 api_hub 默认 72 小时兜底。
*/
private
long
parseTokenExpireAt
(
String
token
)
{
long
fallback
=
System
.
currentTimeMillis
()
+
TOKEN_TTL_FALLBACK_MS
;
try
{
String
[]
parts
=
token
.
split
(
"\\."
);
if
(
parts
.
length
<
1
||
StrUtil
.
isBlank
(
parts
[
0
]))
{
return
fallback
;
}
String
raw
=
parts
[
0
];
int
padding
=
raw
.
length
()
%
4
;
if
(
padding
>
0
)
{
raw
=
raw
+
"="
.
repeat
(
4
-
padding
);
}
byte
[]
decoded
=
Base64
.
getUrlDecoder
().
decode
(
raw
);
JSONObject
json
=
JSONUtil
.
parseObj
(
new
String
(
decoded
,
StandardCharsets
.
UTF_8
));
Long
exp
=
json
.
getLong
(
"exp"
);
if
(
exp
==
null
||
exp
<=
0
)
{
return
fallback
;
}
// 提前 5 分钟失效,避免边界时刻请求打到过期令牌
return
exp
*
1000L
-
TOKEN_REFRESH_BUFFER_MS
;
}
catch
(
Exception
e
)
{
log
.
warn
(
"[ApiHubClient.parseTokenExpireAt] 解析令牌过期时间失败,使用兜底值: {}"
,
e
.
getMessage
());
return
fallback
;
}
}
/**
* 从错误响应体中提取 detail 作为错误信息
*/
private
String
extractDetail
(
String
body
,
String
defaultMessage
)
{
if
(
StrUtil
.
isBlank
(
body
))
{
return
defaultMessage
;
}
try
{
JSONObject
json
=
JSONUtil
.
parseObj
(
body
);
String
detail
=
json
.
getStr
(
"detail"
);
if
(
StrUtil
.
isNotBlank
(
detail
))
{
return
detail
;
}
String
message
=
json
.
getStr
(
"message"
);
if
(
StrUtil
.
isNotBlank
(
message
))
{
return
message
;
}
}
catch
(
Exception
ignored
)
{
}
return
defaultMessage
;
}
/**
* 规范化手机号为 api_hub 可接受的 11 位号码
*
* <p>api_hub 的 mobile 校验规则是 {@code 1\d{10}}(必须 11 位、以 1 开头),
* 而 puhui 侧允许带国际区号({@code +86} / {@code 0086}),这里统一剥离前缀。
*
* @return 规范化后的 11 位手机号,非法时返回 null
*/
public
String
normalizeMobile
(
String
mobile
)
{
if
(
StrUtil
.
isBlank
(
mobile
))
{
return
null
;
}
String
text
=
mobile
.
trim
();
if
(
text
.
startsWith
(
"+86"
))
{
text
=
text
.
substring
(
3
);
}
else
if
(
text
.
startsWith
(
"0086"
))
{
text
=
text
.
substring
(
4
);
}
return
text
.
matches
(
"^1\\d{10}$"
)
?
text
:
null
;
}
/**
* 过滤出指定用户下、指定名称且启用中的密钥
*
* @param userId api_hub 用户 ID
* @param name 密钥名称
*/
public
List
<
ApiHubTokenVO
>
filterEnabledTokens
(
List
<
ApiHubTokenVO
>
tokens
,
Long
userId
,
String
name
)
{
List
<
ApiHubTokenVO
>
result
=
new
ArrayList
<>();
if
(
tokens
==
null
)
{
return
result
;
}
for
(
ApiHubTokenVO
token
:
tokens
)
{
if
(!
userId
.
equals
(
token
.
getUserId
()))
{
continue
;
}
if
(!
name
.
equals
(
token
.
getName
()))
{
continue
;
}
if
(!
Integer
.
valueOf
(
1
).
equals
(
token
.
getEnabled
()))
{
continue
;
}
result
.
add
(
token
);
}
return
result
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpoint.java
0 → 100644
View file @
2cb2a43f
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
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpointParamProvider.java
0 → 100644
View file @
2cb2a43f
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
);
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubEndpointRegistry.java
0 → 100644
View file @
2cb2a43f
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
()));
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubModelPriceService.java
0 → 100644
View file @
2cb2a43f
package
com
.
luhu
.
computility
.
module
.
apihub
.
service
.
apihub
;
import
cn.hutool.core.util.StrUtil
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubModelPriceVO
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubResponse
;
import
com.luhu.computility.module.apihub.controller.app.aimodel.vo.AppModelPricingVO
;
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.math.BigDecimal
;
import
java.math.RoundingMode
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.Comparator
;
import
java.util.LinkedHashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.stream.Collectors
;
/**
* 模型市场「模型 + 价格」服务,数据源为 api_hub 管理端 {@code GET /api/model-prices}。
*
* <p>口径对齐 api_hub 自身的用户侧计价逻辑({@code relay.calculate_cost}):
* <pre>
* 用户实付价 = 标价 × 售卖倍率(sell_multiplier) × 折扣系数(discount / 10)
* </pre>
* 其中折扣为 0 表示无折扣(系数取 1)。puhui 开通的 api_hub 用户自身
* {@code price_multiplier} 恒为 1,故不再乘用户倍率。
*
* <p>在售口径对齐 api_hub 的 {@code available_model_ids}:
* 仅 {@code enabled = 1} 且未被自动隔离的模型才展示;对外模型 id 取别名,别名为空时用真实模型名。
* 同一模型多渠道时取「输入实付价最低」的那条渠道(与 api_hub {@code _model_catalog} 一致)。
*
* @author puhui
*/
@Slf4j
@Service
public
class
ApiHubModelPriceService
{
/**
* 价格类型:按量(token 计费)
*/
public
static
final
String
PRICE_TYPE_METERED
=
"metered"
;
/**
* 价格类型:按张(图片计费)
*/
public
static
final
String
PRICE_TYPE_PER_IMAGE
=
"per_image"
;
/**
* 价格类型:视频分档(按秒计费)
*/
public
static
final
String
PRICE_TYPE_PER_VIDEO
=
"per_video"
;
/**
* 计费模式标记:视频分档
*/
public
static
final
String
BILLING_MODE_VIDEO_TIERED
=
"video_tiered"
;
@Resource
private
ApiHubClient
apiHubClient
;
@Resource
private
ApiHubUsageService
apiHubUsageService
;
/**
* 查询 api_hub 在售模型列表与价格
*
* @param userPriceMultiplier 当前用户在 api_hub 的价格倍率({@code users.price_multiplier}),
* 为空时按 1 处理
* @return 模型 + 价格列表;api_hub 不可达时返回空列表
*/
public
List
<
AppModelPricingVO
>
listModelPricing
(
Double
userPriceMultiplier
)
{
double
userMultiplier
=
userPriceMultiplier
!=
null
&&
userPriceMultiplier
>
0
?
userPriceMultiplier
:
1
D
;
ApiHubResponse
<
List
<
ApiHubModelPriceVO
>>
resp
=
apiHubClient
.
listModelPrices
();
if
(!
Boolean
.
TRUE
.
equals
(
resp
.
getSuccess
())
||
resp
.
getData
()
==
null
)
{
log
.
error
(
"[ApiHubModelPriceService.listModelPricing] 查询 api_hub 模型售价失败: {}"
,
resp
.
getMessage
());
return
Collections
.
emptyList
();
}
// ① 只保留在售(enabled=1 且未被自动隔离)的行
List
<
ApiHubModelPriceVO
>
sellable
=
new
ArrayList
<>();
for
(
ApiHubModelPriceVO
row
:
resp
.
getData
())
{
if
(
isSellable
(
row
))
{
sellable
.
add
(
row
);
}
}
// ② 同一对外模型 id 多渠道时,取输入实付价最低的那条
Map
<
String
,
ApiHubModelPriceVO
>
best
=
new
LinkedHashMap
<>();
for
(
ApiHubModelPriceVO
row
:
sellable
)
{
String
key
=
displayModelId
(
row
);
if
(
StrUtil
.
isBlank
(
key
))
{
continue
;
}
ApiHubModelPriceVO
exists
=
best
.
get
(
key
);
if
(
exists
==
null
||
netPrice
(
row
.
getInputPrice
(),
row
,
userMultiplier
)
<
netPrice
(
exists
.
getInputPrice
(),
exists
,
userMultiplier
))
{
best
.
put
(
key
,
row
);
}
}
// ③ 组装返回
List
<
AppModelPricingVO
>
result
=
new
ArrayList
<>(
best
.
size
());
for
(
ApiHubModelPriceVO
row
:
best
.
values
())
{
result
.
add
(
toModelPricing
(
row
,
userMultiplier
));
}
result
.
sort
(
Comparator
.
comparing
(
AppModelPricingVO:
:
getModelName
,
String
.
CASE_INSENSITIVE_ORDER
));
return
result
;
}
/**
* 是否在售:api_hub 用 enabled=1 表示在售,被系统自动隔离的模型不展示
*/
private
boolean
isSellable
(
ApiHubModelPriceVO
row
)
{
if
(
row
==
null
)
{
return
false
;
}
if
(
normalizeEnabled
(
row
.
getEnabled
())
!=
1
)
{
return
false
;
}
return
!
Boolean
.
TRUE
.
equals
(
row
.
getAutoQuarantined
());
}
/**
* 归一化 api_hub 的 enabled 字段
*
* <p>api_hub 返回的类型不统一:已配置售价的行是数字 1/0,仅渠道存在但未配置售价的行是布尔值。
*/
private
int
normalizeEnabled
(
Object
enabled
)
{
if
(
enabled
instanceof
Boolean
)
{
return
((
Boolean
)
enabled
)
?
1
:
0
;
}
if
(
enabled
instanceof
Number
)
{
return
((
Number
)
enabled
).
intValue
();
}
if
(
enabled
instanceof
String
)
{
String
text
=
((
String
)
enabled
).
trim
();
if
(
"1"
.
equals
(
text
)
||
"true"
.
equalsIgnoreCase
(
text
))
{
return
1
;
}
}
return
0
;
}
/**
* 对外模型 id:有别名用别名,否则用真实模型名
*/
private
String
displayModelId
(
ApiHubModelPriceVO
row
)
{
return
StrUtil
.
isNotBlank
(
row
.
getAlias
())
?
row
.
getAlias
()
:
row
.
getModel
();
}
/**
* 输入实付价(元 / 百万 token),用于多渠道比价
*/
private
double
netPrice
(
Double
configured
,
ApiHubModelPriceVO
row
,
double
userPriceMultiplier
)
{
if
(
configured
==
null
)
{
return
0
D
;
}
return
configured
*
sellMultiplier
(
row
)
*
discountFactor
(
row
)
*
userPriceMultiplier
;
}
private
double
sellMultiplier
(
ApiHubModelPriceVO
row
)
{
return
row
.
getSellMultiplier
()
!=
null
?
row
.
getSellMultiplier
()
:
1
D
;
}
/**
* 折扣系数:api_hub 的 discount 是折数(8.5 表示 8.5 折),0 表示无折扣
*/
private
double
discountFactor
(
ApiHubModelPriceVO
row
)
{
Double
discount
=
row
.
getDiscount
();
return
discount
!=
null
&&
discount
>
0
?
discount
/
10
D
:
1
D
;
}
private
BigDecimal
toPrice
(
Double
configured
,
ApiHubModelPriceVO
row
,
double
userPriceMultiplier
)
{
if
(
configured
==
null
||
configured
<=
0
)
{
return
null
;
}
return
BigDecimal
.
valueOf
(
netPrice
(
configured
,
row
,
userPriceMultiplier
)).
setScale
(
4
,
RoundingMode
.
HALF_UP
);
}
private
AppModelPricingVO
toModelPricing
(
ApiHubModelPriceVO
row
,
double
userPriceMultiplier
)
{
AppModelPricingVO
vo
=
new
AppModelPricingVO
();
String
modelId
=
displayModelId
(
row
);
vo
.
setModelName
(
modelId
);
vo
.
setIcon
(
resolveIconByName
(
modelId
));
vo
.
setVendorName
(
resolveVendorName
(
modelId
));
vo
.
setDescription
(
resolveDescription
(
row
));
vo
.
setTags
(
resolveTags
(
row
));
vo
.
setModalities
(
row
.
getModalities
()
==
null
?
new
ArrayList
<>()
:
row
.
getModalities
());
// 使用方法:端点由模型类型映射,一个模型可能带多个类型 → 多条使用说明
List
<
AppModelUsageVO
>
usageMethods
=
apiHubUsageService
.
buildUsageMethods
(
modelId
,
vo
.
getModalities
());
vo
.
setUsageMethods
(
usageMethods
);
vo
.
setSupportedEndpoints
(
usageMethods
.
stream
()
.
map
(
AppModelUsageVO:
:
getEndpoint
)
.
collect
(
Collectors
.
toList
()));
vo
.
setContextLength
(
row
.
getContextLength
());
vo
.
setMaxOutputLength
(
row
.
getMaxOutputLength
());
vo
.
setChannelName
(
row
.
getChannelName
());
vo
.
setStatus
(
normalizeEnabled
(
row
.
getEnabled
()));
BigDecimal
inputPrice
=
toPrice
(
row
.
getInputPrice
(),
row
,
userPriceMultiplier
);
BigDecimal
outputPrice
=
toPrice
(
row
.
getOutputPrice
(),
row
,
userPriceMultiplier
);
BigDecimal
cacheReadPrice
=
toPrice
(
row
.
getCacheInputPrice
(),
row
,
userPriceMultiplier
);
BigDecimal
cacheCreatePrice
=
toPrice
(
row
.
getCacheOutputPrice
(),
row
,
userPriceMultiplier
);
BigDecimal
imagePrice
=
toPrice
(
row
.
getImagePrice
(),
row
,
userPriceMultiplier
);
BigDecimal
video480p
=
toPrice
(
row
.
getVideoPrice480p
(),
row
,
userPriceMultiplier
);
BigDecimal
video720p
=
toPrice
(
row
.
getVideoPrice720p
(),
row
,
userPriceMultiplier
);
BigDecimal
video1080p
=
toPrice
(
row
.
getVideoPrice1080p
(),
row
,
userPriceMultiplier
);
vo
.
setInputPrice
(
inputPrice
);
vo
.
setOutputPrice
(
outputPrice
);
vo
.
setCacheReadPrice
(
cacheReadPrice
);
vo
.
setCacheCreatePrice
(
cacheCreatePrice
);
vo
.
setImagePrice
(
imagePrice
);
vo
.
setVideoPrice480p
(
video480p
);
vo
.
setVideoPrice720p
(
video720p
);
vo
.
setVideoPrice1080p
(
video1080p
);
String
priceType
=
resolvePriceType
(
row
,
inputPrice
,
outputPrice
,
imagePrice
,
video480p
,
video720p
,
video1080p
);
vo
.
setPriceType
(
priceType
);
switch
(
priceType
)
{
case
PRICE_TYPE_PER_VIDEO:
vo
.
setQuotaType
(
2
);
vo
.
setBillingMode
(
BILLING_MODE_VIDEO_TIERED
);
break
;
case
PRICE_TYPE_PER_IMAGE:
vo
.
setQuotaType
(
1
);
break
;
default
:
vo
.
setQuotaType
(
0
);
break
;
}
return
vo
;
}
/**
* 判定价格类型
*
* <p>优先看是否配了视频分档价;没有 token 价时才按图片/视频模型类型归类;
* 其余按 token 计费。
*/
private
String
resolvePriceType
(
ApiHubModelPriceVO
row
,
BigDecimal
inputPrice
,
BigDecimal
outputPrice
,
BigDecimal
imagePrice
,
BigDecimal
video480p
,
BigDecimal
video720p
,
BigDecimal
video1080p
)
{
if
(
video480p
!=
null
||
video720p
!=
null
||
video1080p
!=
null
)
{
return
PRICE_TYPE_PER_VIDEO
;
}
boolean
noTokenPrice
=
(
inputPrice
==
null
&&
outputPrice
==
null
);
if
(
noTokenPrice
)
{
if
(
imagePrice
!=
null
||
hasType
(
row
,
"image_gen"
))
{
return
PRICE_TYPE_PER_IMAGE
;
}
if
(
hasType
(
row
,
"video_gen"
))
{
return
PRICE_TYPE_PER_VIDEO
;
}
}
return
PRICE_TYPE_METERED
;
}
private
boolean
hasType
(
ApiHubModelPriceVO
row
,
String
type
)
{
List
<
String
>
modalities
=
row
.
getModalities
();
return
modalities
!=
null
&&
modalities
.
contains
(
type
);
}
/**
* api_hub 没有模型描述字段,这里按模型类型生成一句简短说明
*/
private
String
resolveDescription
(
ApiHubModelPriceVO
row
)
{
List
<
String
>
modalities
=
row
.
getModalities
();
if
(
modalities
==
null
||
modalities
.
isEmpty
())
{
return
"文本对话模型"
;
}
StringBuilder
sb
=
new
StringBuilder
();
for
(
String
type
:
modalities
)
{
String
label
=
typeDescLabel
(
type
);
if
(
label
==
null
)
{
continue
;
}
if
(
sb
.
length
()
>
0
)
{
sb
.
append
(
"、"
);
}
sb
.
append
(
label
);
}
return
sb
.
length
()
>
0
?
sb
.
toString
()
:
"文本对话模型"
;
}
/**
* 标签取模型类型,便于前端筛选
*/
private
String
resolveTags
(
ApiHubModelPriceVO
row
)
{
List
<
String
>
modalities
=
row
.
getModalities
();
if
(
modalities
==
null
||
modalities
.
isEmpty
())
{
return
null
;
}
StringBuilder
sb
=
new
StringBuilder
();
for
(
String
type
:
modalities
)
{
String
label
=
typeLabel
(
type
);
if
(
label
==
null
)
{
continue
;
}
if
(
sb
.
length
()
>
0
)
{
sb
.
append
(
","
);
}
sb
.
append
(
label
);
}
return
sb
.
length
()
>
0
?
sb
.
toString
()
:
null
;
}
/**
* 模型类型 → 描述文案
*/
private
String
typeDescLabel
(
String
type
)
{
if
(
type
==
null
)
{
return
null
;
}
switch
(
type
)
{
case
"text"
:
return
"文本对话模型"
;
case
"multimodal"
:
return
"多模态对话模型"
;
case
"image_gen"
:
return
"图像生成模型"
;
case
"video_gen"
:
return
"视频生成模型"
;
case
"embedding"
:
return
"向量嵌入模型"
;
case
"rerank"
:
return
"文本重排模型"
;
case
"speech"
:
return
"语音模型"
;
default
:
return
null
;
}
}
/**
* 模型类型 → 标签文案
*/
private
String
typeLabel
(
String
type
)
{
if
(
type
==
null
)
{
return
null
;
}
switch
(
type
)
{
case
"text"
:
return
"文本"
;
case
"multimodal"
:
return
"多模态"
;
case
"image_gen"
:
return
"图像生成"
;
case
"video_gen"
:
return
"视频生成"
;
case
"embedding"
:
return
"向量嵌入"
;
case
"rerank"
:
return
"文本重排"
;
case
"speech"
:
return
"语音"
;
default
:
return
null
;
}
}
/**
* 根据模型名推断图标
*/
private
String
resolveIconByName
(
String
modelName
)
{
if
(
modelName
==
null
)
{
return
"AI"
;
}
String
lower
=
modelName
.
toLowerCase
();
if
(
lower
.
contains
(
"qwen"
))
{
return
"Qwen.Color"
;
}
if
(
lower
.
contains
(
"deepseek"
))
{
return
"DeepSeek.Color"
;
}
if
(
lower
.
contains
(
"doubao"
))
{
return
"Doubao.Color"
;
}
if
(
lower
.
contains
(
"gpt"
)
||
lower
.
contains
(
"openai"
)
||
lower
.
contains
(
"o1"
)
||
lower
.
contains
(
"o3"
)
||
lower
.
contains
(
"o4"
))
{
return
"OpenAI"
;
}
if
(
lower
.
contains
(
"claude"
))
{
return
"Claude.Color"
;
}
if
(
lower
.
contains
(
"gemini"
))
{
return
"Gemini.Color"
;
}
if
(
lower
.
contains
(
"llama"
)
||
lower
.
contains
(
"meta"
))
{
return
"Meta"
;
}
if
(
lower
.
contains
(
"moonshot"
)
||
lower
.
contains
(
"kimi"
))
{
return
"Moonshot"
;
}
if
(
lower
.
contains
(
"glm"
)
||
lower
.
contains
(
"zhipu"
)
||
lower
.
contains
(
"chatglm"
))
{
return
"Zhipu.Color"
;
}
if
(
lower
.
contains
(
"embedding"
)
||
lower
.
contains
(
"bge"
)
||
lower
.
contains
(
"m3e"
))
{
return
"Embedding"
;
}
if
(
lower
.
contains
(
"rerank"
))
{
return
"Rerank"
;
}
if
(
lower
.
contains
(
"stable"
)
||
lower
.
contains
(
"sdxl"
))
{
return
"StableDiffusion"
;
}
if
(
lower
.
contains
(
"wav2lip"
)
||
lower
.
contains
(
"tts"
)
||
lower
.
contains
(
"asr"
)
||
lower
.
contains
(
"audio"
))
{
return
"Audio"
;
}
if
(
lower
.
contains
(
"mistral"
)
||
lower
.
contains
(
"mixtral"
))
{
return
"Mistral"
;
}
if
(
lower
.
contains
(
"yi"
))
{
return
"Yi"
;
}
if
(
lower
.
contains
(
"baichuan"
))
{
return
"Baichuan"
;
}
if
(
lower
.
contains
(
"minimax"
))
{
return
"MiniMax.Color"
;
}
if
(
lower
.
contains
(
"hunyuan"
)
||
lower
.
contains
(
"tencent"
))
{
return
"Hunyuan"
;
}
if
(
lower
.
contains
(
"spark"
)
||
lower
.
contains
(
"xunfei"
)
||
lower
.
contains
(
"iflytek"
))
{
return
"Spark"
;
}
if
(
lower
.
contains
(
"sensenova"
)
||
lower
.
contains
(
"sense"
))
{
return
"SenseNova"
;
}
return
"AI"
;
}
/**
* 根据模型名推断厂商
*/
private
String
resolveVendorName
(
String
modelName
)
{
if
(
modelName
==
null
)
{
return
null
;
}
String
lower
=
modelName
.
toLowerCase
();
if
(
lower
.
contains
(
"qwen"
))
{
return
"阿里云"
;
}
if
(
lower
.
contains
(
"deepseek"
))
{
return
"DeepSeek"
;
}
if
(
lower
.
contains
(
"doubao"
))
{
return
"字节跳动"
;
}
if
(
lower
.
contains
(
"gpt"
)
||
lower
.
contains
(
"openai"
)
||
lower
.
contains
(
"o1"
)
||
lower
.
contains
(
"o3"
)
||
lower
.
contains
(
"o4"
))
{
return
"OpenAI"
;
}
if
(
lower
.
contains
(
"claude"
))
{
return
"Anthropic"
;
}
if
(
lower
.
contains
(
"gemini"
))
{
return
"Google"
;
}
if
(
lower
.
contains
(
"llama"
)
||
lower
.
contains
(
"meta"
))
{
return
"Meta"
;
}
if
(
lower
.
contains
(
"moonshot"
)
||
lower
.
contains
(
"kimi"
))
{
return
"月之暗面"
;
}
if
(
lower
.
contains
(
"glm"
)
||
lower
.
contains
(
"zhipu"
)
||
lower
.
contains
(
"chatglm"
))
{
return
"智谱 AI"
;
}
if
(
lower
.
contains
(
"mistral"
)
||
lower
.
contains
(
"mixtral"
))
{
return
"Mistral"
;
}
if
(
lower
.
contains
(
"minimax"
))
{
return
"MiniMax"
;
}
if
(
lower
.
contains
(
"hunyuan"
)
||
lower
.
contains
(
"tencent"
))
{
return
"腾讯"
;
}
if
(
lower
.
contains
(
"spark"
)
||
lower
.
contains
(
"xunfei"
)
||
lower
.
contains
(
"iflytek"
))
{
return
"讯飞"
;
}
if
(
lower
.
contains
(
"sensenova"
)
||
lower
.
contains
(
"sense"
))
{
return
"商汤"
;
}
return
null
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubSampleBuilder.java
0 → 100644
View file @
2cb2a43f
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
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/ApiHubUsageService.java
0 → 100644
View file @
2cb2a43f
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
;
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/apihub/YamlApiHubEndpointParamProvider.java
0 → 100644
View file @
2cb2a43f
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
);
}
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/newapi/AiTokenService.java
View file @
2cb2a43f
package
com
.
luhu
.
computility
.
module
.
apihub
.
service
.
newapi
;
import
cn.hutool.core.util.RandomUtil
;
import
cn.hutool.core.util.StrUtil
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubResponse
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubTokenVO
;
import
com.luhu.computility.module.apihub.controller.admin.apihub.ApiHubUserVO
;
import
com.luhu.computility.module.apihub.controller.admin.newapi.*
;
import
com.luhu.computility.module.apihub.service.apihub.ApiHubClient
;
import
lombok.AllArgsConstructor
;
import
lombok.experimental.Accessors
;
import
lombok.Builder
;
...
...
@@ -13,6 +18,7 @@ import org.springframework.stereotype.Service;
import
javax.annotation.Resource
;
import
java.math.BigDecimal
;
import
java.math.RoundingMode
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.regex.Matcher
;
...
...
@@ -25,6 +31,9 @@ public class AiTokenService {
@Resource
private
NewApiClient
newApiClient
;
@Resource
private
ApiHubClient
apiHubClient
;
/**
* 额度换算比例:1 元 = 500000 quota(与 NewAPI QuotaPerUnit 一致)
*/
...
...
@@ -46,222 +55,267 @@ public class AiTokenService {
*/
private
static
final
Pattern
GIFT_PATTERN
=
Pattern
.
compile
(
"^Increased user quota by (\\d+)$"
);
public
AiTokenResult
getOrCreateToken
(
Long
userId
,
String
displayName
,
String
newApiUsername
,
String
newApiPassword
,
Long
newApiUserId
,
String
newApiAccessToken
,
String
newApiKey
)
{
log
.
info
(
"[AiTokenService] userId={}, hasApiKey={}"
,
userId
,
newApiKey
!=
null
&&
!
newApiKey
.
isEmpty
());
if
(
newApiKey
!=
null
&&
!
newApiKey
.
isEmpty
())
{
log
.
info
(
"[AiTokenService] 用户已有apiKey,直接返回"
);
return
AiTokenResult
.
builder
()
.
success
(
true
)
.
hasToken
(
true
)
.
apiKey
(
newApiKey
)
.
build
();
}
if
(
newApiUsername
!=
null
&&
!
newApiUsername
.
isEmpty
()
&&
newApiAccessToken
!=
null
&&
!
newApiAccessToken
.
isEmpty
())
{
log
.
info
(
"[AiTokenService] 有账号密码和AccessToken,从第4步开始"
);
return
createTokenStep4
(
newApiUserId
.
intValue
(),
newApiAccessToken
,
userId
,
newApiUsername
,
newApiPassword
);
}
if
(
newApiUsername
!=
null
&&
!
newApiUsername
.
isEmpty
())
{
log
.
info
(
"[AiTokenService] 有账号密码,从第2步开始"
);
return
createTokenStep2
(
newApiUsername
,
newApiPassword
,
userId
);
}
log
.
info
(
"[AiTokenService] 无账号密码,从第1步开始"
);
return
createTokenFull
(
userId
,
displayName
);
}
/**
* 开通 api_hub 账号并签发 API Key
*
* <p>api_hub 侧用户名固定为 {@code puhui_{userId}},密钥名固定为 {@code puhui_{userId}_token}。
* 用户已存在时按「已存在」处理(查回 user_id 后继续签发密钥),保证重复触发开通幂等。
*
* @param userId puhui 用户 ID
* @param mobile puhui 用户手机号,格式非法时不传给 api_hub
* @param apiHubUserId 已记录的 api_hub 用户 ID
* @param apiHubUsername 已记录的 api_hub 用户名
* @param apiHubPassword 已记录的 api_hub 明文登录密码
* @param apiHubTokenId 已记录的 api_hub 密钥 ID
* @param apiHubKey 已有的 api_hub 明文密钥,非空则直接返回
*/
public
AiTokenResult
getOrCreateToken
(
Long
userId
,
String
mobile
,
Long
apiHubUserId
,
String
apiHubUsername
,
String
apiHubPassword
,
Long
apiHubTokenId
,
String
apiHubKey
)
{
log
.
info
(
"[AiTokenService] userId={}, hasApiHubKey={}"
,
userId
,
StrUtil
.
isNotBlank
(
apiHubKey
));
private
AiTokenResult
createTokenFull
(
Long
userId
,
String
displayName
)
{
String
username
=
"puhui_"
+
userId
;
String
password
=
RandomUtil
.
randomString
(
12
);
log
.
info
(
"[AiTokenService.createTokenFull] 准备注册: username={}, displayName={}"
,
username
,
displayName
);
try
{
// 使用管理员接口注册(关闭游客注册后使用)
NewApiResponse
<
Void
>
registerResp
=
newApiClient
.
adminRegister
(
username
,
password
,
displayName
);
log
.
info
(
"[AiTokenService.createTokenFull] 注册结果: success={}, message={}"
,
registerResp
.
getSuccess
(),
registerResp
.
getMessage
());
String
tokenName
=
"puhui_"
+
userId
+
"_token"
;
if
(!
Boolean
.
TRUE
.
equals
(
registerResp
.
getSuccess
()))
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"注册NewAPI账号失败: "
+
registerResp
.
getMessage
())
.
build
();
// 已有明文密钥,直接返回
if
(
StrUtil
.
isNotBlank
(
apiHubKey
))
{
String
password
=
apiHubPassword
;
Long
effectiveUserId
=
apiHubUserId
;
String
effectiveUsername
=
apiHubUsername
;
// 老数据没有明文密码时,这里补一次重置,保证 puhui 侧始终掌握可用凭据
if
(
StrUtil
.
isBlank
(
password
))
{
ApiHubUserVO
exist
=
findApiHubUser
(
username
);
if
(
exist
!=
null
)
{
password
=
syncApiHubCredentials
(
exist
,
mobile
,
null
);
effectiveUserId
=
exist
.
getId
();
effectiveUsername
=
exist
.
getUsername
();
}
}
return
createTokenStep2
(
username
,
password
,
userId
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[AiTokenService.createTokenFull] 注册异常"
,
e
);
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"注册NewAPI账号异常: "
+
e
.
getMessage
())
.
success
(
true
)
.
hasToken
(
true
)
.
apiKey
(
apiHubKey
)
.
apiHubUserId
(
effectiveUserId
)
.
apiHubUsername
(
effectiveUsername
)
.
apiHubPassword
(
password
)
.
apiHubTokenId
(
apiHubTokenId
)
.
apiHubKey
(
apiHubKey
)
.
build
();
}
}
private
AiTokenResult
createTokenStep2
(
String
username
,
String
password
,
Long
userId
)
{
log
.
info
(
"[AiTokenService.createTokenStep2] 准备登录: username={}"
,
username
);
try
{
// ① 登录拿短期 JWT
NewApiResponse
<
NewApiLoginRespVO
>
loginResp
=
newApiClient
.
login
(
username
,
password
);
log
.
info
(
"[AiTokenService.createTokenStep2] 登录结果: success={}, message={}"
,
loginResp
.
getSuccess
(),
loginResp
.
getMessage
());
if
(!
Boolean
.
TRUE
.
equals
(
loginResp
.
getSuccess
())
||
loginResp
.
getData
()
==
null
)
{
// ① 准备 api_hub 用户(已存在则查回 user_id,保证可重复触发开通)
ApiHubAccount
account
=
createOrGetApiHubUser
(
username
,
mobile
,
apiHubPassword
);
if
(
account
==
null
||
account
.
getUser
()
==
null
||
account
.
getUser
().
getId
()
==
null
)
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"登录NewAPI失败: "
+
loginResp
.
getMessage
())
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
hasToken
(
false
)
.
message
(
"创建 api_hub 用户失败"
)
.
build
();
}
ApiHubUserVO
user
=
account
.
getUser
();
String
shortJwt
=
loginResp
.
getData
().
getAccessToken
();
Long
newApiUserId
=
loginResp
.
getData
().
getUserId
();
log
.
info
(
"[AiTokenService.createTokenStep2] 登录成功, newApiUserId={}, shortJwt={}***"
,
newApiUserId
,
safePrefix
(
shortJwt
));
// ② 密码方式安全验证,拿一次性 proof_token
NewApiResponse
<
String
>
verifyResp
=
newApiClient
.
verifyPassword
(
shortJwt
,
newApiUserId
.
intValue
(),
password
,
"access_token.generate"
);
log
.
info
(
"[AiTokenService.createTokenStep2] 安全验证结果: success={}, message={}"
,
verifyResp
.
getSuccess
(),
verifyResp
.
getMessage
());
if
(!
Boolean
.
TRUE
.
equals
(
verifyResp
.
getSuccess
())
||
verifyResp
.
getData
()
==
null
||
verifyResp
.
getData
().
isEmpty
())
{
// ② 准备 api_hub 密钥(先查同名启用中的密钥,有则复用)
ApiHubTokenVO
token
=
getOrCreateApiHubToken
(
user
.
getId
(),
tokenName
);
if
(
token
==
null
||
token
.
getId
()
==
null
||
StrUtil
.
isBlank
(
token
.
getKey
()))
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"NewAPI安全验证失败: "
+
verifyResp
.
getMessage
())
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
newApiUserId
(
newApiUserId
)
.
hasToken
(
false
)
.
message
(
"签发 api_hub 密钥失败"
)
.
build
();
}
String
proof
=
verifyResp
.
getData
();
// ③ 拿长期 AccessToken(29~33 位)
NewApiResponse
<
String
>
tokenResp
=
newApiClient
.
generateAccessToken
(
shortJwt
,
newApiUserId
.
intValue
(),
proof
);
log
.
info
(
"[AiTokenService.createTokenStep2] 长期AccessToken结果: success={}, message={}"
,
tokenResp
.
getSuccess
(),
tokenResp
.
getMessage
());
if
(!
Boolean
.
TRUE
.
equals
(
tokenResp
.
getSuccess
())
||
tokenResp
.
getData
()
==
null
||
tokenResp
.
getData
().
isEmpty
())
{
// 降级:用短期 JWT 直接走 step4,newapi_access_token 此时会写入短期 JWT
// (依赖日志告警 + 下次成功 login 自然刷新)
log
.
warn
(
"[AiTokenService.createTokenStep2] 获取长期AccessToken失败,降级用短期JWT: message={}"
,
tokenResp
.
getMessage
());
return
createTokenStep4
(
newApiUserId
.
intValue
(),
shortJwt
,
userId
,
username
,
password
);
}
String
longTermToken
=
tokenResp
.
getData
();
log
.
info
(
"[AiTokenService.createTokenStep2] 长期AccessToken获取成功: {}***"
,
safePrefix
(
longTermToken
));
// ④ 用长期 token 走 step4(accessToken 形参 = 长期 token,最终自然写入 result.newApiAccessToken)
return
createTokenStep4
(
newApiUserId
.
intValue
(),
longTermToken
,
userId
,
username
,
password
);
return
AiTokenResult
.
builder
()
.
success
(
true
)
.
hasToken
(
true
)
.
apiKey
(
token
.
getKey
())
.
apiHubUserId
(
user
.
getId
())
.
apiHubUsername
(
user
.
getUsername
())
.
apiHubPassword
(
account
.
getPassword
())
.
apiHubTokenId
(
token
.
getId
())
.
apiHubKey
(
token
.
getKey
())
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[AiTokenService
.createTokenStep2] 登录异常"
,
e
);
log
.
error
(
"[AiTokenService
] 开通 api_hub 密钥异常, userId={}"
,
userId
,
e
);
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"登录NewAPI异常: "
+
(
e
.
getMessage
()
==
null
?
e
.
getClass
().
getSimpleName
()
:
e
.
getMessage
()))
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
hasToken
(
false
)
.
message
(
"开通 api_hub 密钥异常: "
+
e
.
getMessage
())
.
build
();
}
}
private
static
String
safePrefix
(
String
s
)
{
if
(
s
==
null
||
s
.
isEmpty
())
{
return
"null"
;
/**
* 创建 api_hub 用户;用户名已存在(409)时查回已有用户,保证开通流程可重复触发
*
* <p>密码策略:api_hub 只存密码哈希,没有查询明文密码的接口,
* 所以 puhui 侧必须自己留一份明文密码,用户才能登录 api_hub 控制台。
*
* @param savedPassword puhui 已保存的明文密码,非空则直接复用(不再重置,避免踢掉用户登录态)
*/
private
ApiHubAccount
createOrGetApiHubUser
(
String
username
,
String
mobile
,
String
savedPassword
)
{
String
password
=
StrUtil
.
isNotBlank
(
savedPassword
)
?
savedPassword
:
RandomUtil
.
randomString
(
12
);
ApiHubResponse
<
ApiHubUserVO
>
createResp
=
apiHubClient
.
createUser
(
username
,
password
,
mobile
);
if
(
Boolean
.
TRUE
.
equals
(
createResp
.
getSuccess
())
&&
createResp
.
getData
()
!=
null
)
{
log
.
info
(
"[AiTokenService] 创建 api_hub 用户成功: username={}, userId={}"
,
username
,
createResp
.
getData
().
getId
());
return
new
ApiHubAccount
(
createResp
.
getData
(),
password
);
}
return
s
.
substring
(
0
,
Math
.
min
(
5
,
s
.
length
()));
}
private
AiTokenResult
createTokenStep4
(
Integer
newApiUserId
,
String
accessToken
,
Long
userId
,
String
username
,
String
password
)
{
String
tokenName
=
"puhui_"
+
userId
+
"_token"
;
log
.
info
(
"[AiTokenService.createTokenStep4] 准备创建令牌: newApiUserId={}, tokenName={}"
,
newApiUserId
,
tokenName
);
try
{
NewApiResponse
<
Void
>
createResp
=
newApiClient
.
createToken
(
accessToken
,
newApiUserId
,
tokenName
);
log
.
info
(
"[AiTokenService.createTokenStep4] 创建令牌结果: success={}, message={}"
,
createResp
.
getSuccess
(),
createResp
.
getMessage
());
if
(
isUsernameConflict
(
createResp
))
{
// 用户名已存在不是失败:查回已有用户拿 user_id,继续走签发密钥流程
ApiHubUserVO
exist
=
findApiHubUser
(
username
);
if
(
exist
!=
null
)
{
log
.
info
(
"[AiTokenService] api_hub 用户已存在,复用: username={}, userId={}"
,
username
,
exist
.
getId
());
String
effectivePassword
=
syncApiHubCredentials
(
exist
,
mobile
,
savedPassword
);
return
new
ApiHubAccount
(
exist
,
effectivePassword
);
}
log
.
warn
(
"[AiTokenService] api_hub 用户已存在但查询不到: username={}"
,
username
);
}
else
{
log
.
warn
(
"[AiTokenService] 创建 api_hub 用户失败: username={}, message={}"
,
username
,
createResp
.
getMessage
());
}
return
null
;
}
if
(!
Boolean
.
TRUE
.
equals
(
createResp
.
getSuccess
()))
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"创建令牌失败: "
+
createResp
.
getMessage
())
.
newApiUserId
(
newApiUserId
.
longValue
())
.
newApiAccessToken
(
accessToken
)
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
build
();
/**
* 按用户名查询 api_hub 用户
*/
private
ApiHubUserVO
findApiHubUser
(
String
username
)
{
ApiHubResponse
<
List
<
ApiHubUserVO
>>
listResp
=
apiHubClient
.
listUsersByUsername
(
username
);
if
(
Boolean
.
TRUE
.
equals
(
listResp
.
getSuccess
())
&&
listResp
.
getData
()
!=
null
)
{
for
(
ApiHubUserVO
exist
:
listResp
.
getData
())
{
if
(
username
.
equals
(
exist
.
getUsername
()))
{
return
exist
;
}
}
}
return
null
;
}
NewApiResponse
<
NewApiTokenPageVO
>
listResp
=
newApiClient
.
getTokenList
(
accessToken
,
newApiUserId
);
log
.
info
(
"[AiTokenService.createTokenStep4] 获取令牌列表结果: success={}, message={}"
,
listResp
.
getSuccess
(),
listResp
.
getMessage
());
/**
* 同步 api_hub 账号的登录密码与手机号
*
* <p>密码:api_hub 侧只存哈希,查不到明文。puhui 已保存明文则直接复用;
* 没有则重新生成并通过 PATCH 重置(重置会让该用户已有的登录令牌失效)。
*
* <p>手机号:api_hub 的 mobile 字段即登录账号的手机号,为空或与 puhui 不一致时补写。
*
* @return puhui 侧应保存的明文密码,重置失败时返回 null
*/
private
String
syncApiHubCredentials
(
ApiHubUserVO
exist
,
String
mobile
,
String
savedPassword
)
{
String
effectivePassword
=
savedPassword
;
boolean
resetPassword
=
StrUtil
.
isBlank
(
effectivePassword
);
if
(
resetPassword
)
{
effectivePassword
=
RandomUtil
.
randomString
(
12
);
}
if
(!
Boolean
.
TRUE
.
equals
(
listResp
.
getSuccess
())
||
listResp
.
getData
()
==
null
||
listResp
.
getData
().
getItems
()
==
null
||
listResp
.
getData
().
getItems
().
isEmpty
()
)
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"获取令牌列表失败: "
+
listResp
.
getMessage
())
.
newApiUserId
(
newApiUserId
.
longValue
())
.
newApiAccessToken
(
accessToken
)
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
build
()
;
}
Map
<
String
,
Object
>
patch
=
new
HashMap
<>();
if
(
resetPassword
)
{
patch
.
put
(
"password"
,
effectivePassword
);
}
String
normalizedMobile
=
apiHubClient
.
normalizeMobile
(
mobile
);
if
(
StrUtil
.
isNotBlank
(
normalizedMobile
)
&&
!
normalizedMobile
.
equals
(
exist
.
getMobile
()))
{
patch
.
put
(
"mobile"
,
normalizedMobile
);
}
if
(
patch
.
isEmpty
())
{
return
effectivePassword
;
}
Long
tokenId
=
listResp
.
getData
().
getItems
().
get
(
0
).
getId
();
log
.
info
(
"[AiTokenService.createTokenStep4] 获取到tokenId={}"
,
tokenId
);
ApiHubResponse
<
ApiHubUserVO
>
patchResp
=
apiHubClient
.
patchUser
(
exist
.
getId
(),
patch
);
if
(!
Boolean
.
TRUE
.
equals
(
patchResp
.
getSuccess
()))
{
log
.
warn
(
"[AiTokenService] 同步 api_hub 用户信息失败: username={}, message={}"
,
exist
.
getUsername
(),
patchResp
.
getMessage
());
// 密码重置失败意味着 puhui 拿不到可用凭据,返回 null 不落库
return
resetPassword
?
null
:
effectivePassword
;
}
log
.
info
(
"[AiTokenService] 同步 api_hub 用户信息成功: username={}, fields={}"
,
exist
.
getUsername
(),
patch
.
keySet
());
return
effectivePassword
;
}
NewApiResponse
<
Map
<
String
,
Object
>>
keyResp
=
newApiClient
.
getTokenKey
(
accessToken
,
newApiUserId
,
tokenId
);
log
.
info
(
"[AiTokenService.createTokenStep4] 获取apiKey结果: success={}, message={}"
,
keyResp
.
getSuccess
(),
keyResp
.
getMessage
());
/**
* 判断是否为 api_hub 的「用户名已存在」(HTTP 409)
*/
private
boolean
isUsernameConflict
(
ApiHubResponse
<
ApiHubUserVO
>
resp
)
{
if
(
resp
==
null
)
{
return
false
;
}
if
(
Integer
.
valueOf
(
409
).
equals
(
resp
.
getStatus
()))
{
return
true
;
}
return
resp
.
getMessage
()
!=
null
&&
resp
.
getMessage
().
contains
(
"用户名已存在"
);
}
if
(!
Boolean
.
TRUE
.
equals
(
keyResp
.
getSuccess
())
||
keyResp
.
getData
()
==
null
)
{
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"获取apiKey失败: "
+
keyResp
.
getMessage
())
.
newApiUserId
(
newApiUserId
.
longValue
())
.
newApiAccessToken
(
accessToken
)
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
build
();
/**
* 签发 api_hub 密钥
*
* <p>先查该 user_id 下是否已有启用中的同名密钥,有则复用(走 reveal 取明文),没有才创建。
* 创建时必须带 unlimited=true:新用户余额为 0,不带不限额网关会直接返回 402「余额不足」。
*/
private
ApiHubTokenVO
getOrCreateApiHubToken
(
Long
apiHubUserId
,
String
tokenName
)
{
ApiHubResponse
<
List
<
ApiHubTokenVO
>>
listResp
=
apiHubClient
.
listTokens
();
if
(!
Boolean
.
TRUE
.
equals
(
listResp
.
getSuccess
())
||
listResp
.
getData
()
==
null
)
{
log
.
warn
(
"[ApiTokenService] 查询 api_hub 密钥列表失败: {}"
,
listResp
.
getMessage
());
}
else
{
List
<
ApiHubTokenVO
>
exists
=
apiHubClient
.
filterEnabledTokens
(
listResp
.
getData
(),
apiHubUserId
,
tokenName
);
if
(!
exists
.
isEmpty
())
{
ApiHubTokenVO
token
=
exists
.
get
(
0
);
ApiHubResponse
<
String
>
revealResp
=
apiHubClient
.
revealToken
(
token
.
getId
());
if
(
Boolean
.
TRUE
.
equals
(
revealResp
.
getSuccess
())
&&
StrUtil
.
isNotBlank
(
revealResp
.
getData
()))
{
token
.
setKey
(
revealResp
.
getData
());
log
.
info
(
"[ApiTokenService] 复用已有 api_hub 密钥: tokenId={}, name={}"
,
token
.
getId
(),
token
.
getName
());
return
token
;
}
log
.
warn
(
"[ApiTokenService] 取已有 api_hub 密钥明文失败: tokenId={}, message={}"
,
token
.
getId
(),
revealResp
.
getMessage
());
}
}
Map
<
String
,
Object
>
keyData
=
keyResp
.
getData
();
String
apiKey
=
(
String
)
keyData
.
get
(
"key"
);
log
.
info
(
"[AiTokenService.createTokenStep4] apiKey获取成功: {}***"
,
apiKey
.
substring
(
0
,
Math
.
min
(
5
,
apiKey
.
length
())));
// 创建(unlimited=true:新用户余额为 0,不设不限额网关会返回 402 余额不足)
ApiHubResponse
<
ApiHubTokenVO
>
createResp
=
apiHubClient
.
createToken
(
apiHubUserId
,
tokenName
,
null
);
if
(!
Boolean
.
TRUE
.
equals
(
createResp
.
getSuccess
())
||
createResp
.
getData
()
==
null
)
{
log
.
warn
(
"[ApiTokenService] 创建 api_hub 密钥失败: userId={}, name={}, message={}"
,
apiHubUserId
,
tokenName
,
createResp
.
getMessage
());
return
null
;
}
return
AiTokenResult
.
builder
()
.
success
(
true
)
.
hasToken
(
true
)
.
apiKey
(
apiKey
)
.
newApiUserId
(
newApiUserId
.
longValue
())
.
newApiAccessToken
(
accessToken
)
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
build
();
}
catch
(
Exception
e
)
{
log
.
error
(
"[AiTokenService.createTokenStep4] 创建令牌异常"
,
e
);
return
AiTokenResult
.
builder
()
.
success
(
false
)
.
message
(
"创建令牌异常: "
+
e
.
getMessage
())
.
newApiUserId
(
newApiUserId
.
longValue
())
.
newApiAccessToken
(
accessToken
)
.
newApiUsername
(
username
)
.
newApiPassword
(
password
)
.
build
();
ApiHubTokenVO
token
=
createResp
.
getData
();
if
(
StrUtil
.
isNotBlank
(
token
.
getKey
()))
{
return
token
;
}
// 创建响应未带明文时走 reveal 取明文
ApiHubResponse
<
String
>
revealResp
=
apiHubClient
.
revealToken
(
token
.
getId
());
if
(!
Boolean
.
TRUE
.
equals
(
revealResp
.
getSuccess
())
||
StrUtil
.
isBlank
(
revealResp
.
getData
()))
{
log
.
warn
(
"[AiTokenService] 取 api_hub 密钥明文失败: tokenId={}, message={}"
,
token
.
getId
(),
revealResp
.
getMessage
());
return
null
;
}
token
.
setKey
(
revealResp
.
getData
());
return
token
;
}
/**
* api_hub 账号信息:用户对象 + puhui 侧掌握的明文密码
*/
@Data
@Accessors
(
chain
=
true
)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public
static
class
ApiHubAccount
{
/**
* api_hub 用户对象
*/
private
ApiHubUserVO
user
;
/**
* api_hub 登录密码(明文),重置失败时为 null
*/
private
String
password
;
}
@Data
@Accessors
(
chain
=
true
)
@Builder
...
...
@@ -272,10 +326,26 @@ public class AiTokenService {
private
Boolean
hasToken
;
private
String
apiKey
;
private
String
message
;
private
Long
newApiUserId
;
private
String
newApiAccessToken
;
private
String
newApiUsername
;
private
String
newApiPassword
;
/**
* api_hub 用户 ID
*/
private
Long
apiHubUserId
;
/**
* api_hub 用户名
*/
private
String
apiHubUsername
;
/**
* api_hub 登录密码(明文)
*/
private
String
apiHubPassword
;
/**
* api_hub 密钥 ID
*/
private
Long
apiHubTokenId
;
/**
* api_hub 密钥明文
*/
private
String
apiHubKey
;
}
/**
...
...
@@ -500,4 +570,4 @@ public class AiTokenService {
.
giftAmount
(
giftYuan
.
setScale
(
2
,
RoundingMode
.
HALF_UP
))
.
build
();
}
}
\ No newline at end of file
}
computility-module-apihub/computility-module-apihub-biz/src/main/java/com/luhu/computility/module/apihub/service/newapi/NewApiClient.java
View file @
2cb2a43f
...
...
@@ -29,607 +29,6 @@ public class NewApiClient {
private
static
final
String
HEADER_USER
=
"New-Api-User"
;
private
static
final
String
HEADER_AUTH
=
"Authorization"
;
private
static
final
String
USER_ANONYMOUS
=
"-1"
;
public
NewApiResponse
<
NewApiUserVO
>
register
(
String
username
,
String
password
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/user/register"
;
log
.
info
(
"[NewApiClient.register] 请求URL: {}"
,
url
);
log
.
info
(
"[NewApiClient.register] 请求参数: username={}, password={}"
,
username
,
"***"
);
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"username"
,
username
);
body
.
put
(
"password"
,
password
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
USER_ANONYMOUS
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.register] 响应状态: {}"
,
response
.
getStatus
());
log
.
info
(
"[NewApiClient.register] 响应内容: {}"
,
response
.
body
());
return
parseResponse
(
response
,
NewApiUserVO
.
class
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.register] 请求异常"
,
e
);
return
NewApiResponse
.<
NewApiUserVO
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 管理员注册用户(关闭游客注册后使用此接口)
* POST /api/user/
*
* @param displayName 显示名称(对应 NewAPI 的 display_name 字段),为空时 NewAPI 会默认取 username
*/
public
NewApiResponse
<
Void
>
adminRegister
(
String
username
,
String
password
,
String
displayName
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/user/"
;
log
.
info
(
"[NewApiClient.adminRegister] 请求URL: {}"
,
url
);
log
.
info
(
"[NewApiClient.adminRegister] 请求参数: username={}, password={}, displayName={}"
,
username
,
"***"
,
displayName
);
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"username"
,
username
);
body
.
put
(
"password"
,
password
);
if
(
StrUtil
.
isNotBlank
(
displayName
))
{
body
.
put
(
"display_name"
,
displayName
);
}
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
newApiProperties
.
getAdminUserId
()))
.
header
(
HEADER_AUTH
,
"Bearer "
+
newApiProperties
.
getAdminToken
())
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.adminRegister] 响应状态: {}"
,
response
.
getStatus
());
log
.
info
(
"[NewApiClient.adminRegister] 响应内容: {}"
,
response
.
body
());
return
parseResponse
(
response
,
Void
.
class
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.adminRegister] 请求异常"
,
e
);
return
NewApiResponse
.<
Void
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 用户登录(NewAPI v3 /api/user/login)
*
* <p>NewAPI v3 登录响应 data 字段结构:
* <pre>
* {
* "access_token": "...", // 直接可用作 Bearer 凭据
* "token_type": "Bearer",
* "user": { "id": 123, "username": "...", ... }
* }
* </pre>
* 旧实现错误地把整个 data 映射到 NewApiUserVO,导致 userId 拿不到;
* 本方法改为显式从 data.access_token 和 data.user.id 取值,避免依赖
* session cookie 和后续 /api/user/token 步骤。
*/
public
NewApiResponse
<
NewApiLoginRespVO
>
login
(
String
username
,
String
password
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/user/login"
;
log
.
info
(
"[NewApiClient.login] 请求URL: {}"
,
url
);
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"username"
,
username
);
body
.
put
(
"password"
,
password
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
USER_ANONYMOUS
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.login] 响应状态: {}"
,
response
.
getStatus
());
NewApiResponse
<
NewApiLoginRespVO
>
resp
=
parseLoginResponse
(
response
);
resp
.
setHttpResponse
(
response
);
return
resp
;
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.login] 请求异常"
,
e
);
return
NewApiResponse
.<
NewApiLoginRespVO
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 解析 NewAPI /api/user/login 响应
*
* <p>只关心 data.access_token、data.token_type、data.user.id、data.user.username;
* 不抛异常,统一返回 NewApiResponse 调用方判断。
*/
private
NewApiResponse
<
NewApiLoginRespVO
>
parseLoginResponse
(
HttpResponse
response
)
{
try
{
String
body
=
response
.
body
();
if
(
StrUtil
.
isBlank
(
body
))
{
return
NewApiResponse
.<
NewApiLoginRespVO
>
builder
()
.
success
(
false
)
.
message
(
"Empty response"
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
body
);
NewApiResponse
<
NewApiLoginRespVO
>
result
=
new
NewApiResponse
<>();
result
.
setSuccess
(
json
.
getBool
(
"success"
));
result
.
setMessage
(
json
.
getStr
(
"message"
));
if
(!
Boolean
.
TRUE
.
equals
(
json
.
getBool
(
"success"
)))
{
return
result
;
}
JSONObject
data
=
json
.
getJSONObject
(
"data"
);
if
(
data
==
null
)
{
return
NewApiResponse
.<
NewApiLoginRespVO
>
builder
()
.
success
(
false
)
.
message
(
"登录响应缺少 data 字段"
)
.
build
();
}
NewApiLoginRespVO
vo
=
new
NewApiLoginRespVO
();
vo
.
setAccessToken
(
data
.
getStr
(
"access_token"
));
vo
.
setTokenType
(
data
.
getStr
(
"token_type"
));
JSONObject
user
=
data
.
getJSONObject
(
"user"
);
if
(
user
!=
null
)
{
Object
idObj
=
user
.
get
(
"id"
);
if
(
idObj
instanceof
Number
)
{
vo
.
setUserId
(((
Number
)
idObj
).
longValue
());
}
else
if
(
idObj
!=
null
)
{
try
{
vo
.
setUserId
(
Long
.
parseLong
(
idObj
.
toString
()));
}
catch
(
NumberFormatException
ignored
)
{
}
}
vo
.
setUsername
(
user
.
getStr
(
"username"
));
}
if
(
vo
.
getAccessToken
()
==
null
||
vo
.
getAccessToken
().
isEmpty
()
||
vo
.
getUserId
()
==
null
)
{
return
NewApiResponse
.<
NewApiLoginRespVO
>
builder
()
.
success
(
false
)
.
message
(
"登录响应缺少 access_token 或 user.id"
)
.
build
();
}
result
.
setData
(
vo
);
return
result
;
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.parseLoginResponse] 解析响应异常"
,
e
);
return
NewApiResponse
.<
NewApiLoginRespVO
>
builder
()
.
success
(
false
)
.
message
(
"解析响应失败: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 密码方式安全验证:POST /api/verify
*
* <p>用于 NewAPI v3 的敏感操作(如 access_token.generate)需要先验证当前密码,
* 拿到一次性 proof_token 后再调后续接口。
* <p>接口:{@code POST /api/verify}
* <p>Header:{@code New-Api-User=<id>}, {@code Authorization: Bearer <accessToken>}
* <p>Body:{@code {"method":"password","scope":"<scope>","password":"<pwd>"}}
* <p>响应 data 字段包含 {@code proof_token},需透传给后续接口的 {@code X-Security-Proof} Header。
*
* @param accessToken 短期 JWT(来自 /api/user/login 响应)
* @param userId NewAPI 用户 ID
* @param password 用户明文密码(puhui 这边自动注册的 12 位随机密码)
* @param scope 验证范围,如 {@code "access_token.generate"}
*/
public
NewApiResponse
<
String
>
verifyPassword
(
String
accessToken
,
Integer
userId
,
String
password
,
String
scope
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/verify"
;
log
.
info
(
"[NewApiClient.verifyPassword] 请求URL: {}, scope={}"
,
url
,
scope
);
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"method"
,
"password"
);
body
.
put
(
"scope"
,
scope
);
body
.
put
(
"password"
,
password
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.verifyPassword] 响应状态: {}"
,
response
.
getStatus
());
return
parseVerifyResponse
(
response
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.verifyPassword] 请求异常"
,
e
);
return
NewApiResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
(
e
.
getMessage
()
==
null
?
e
.
getClass
().
getSimpleName
()
:
e
.
getMessage
()))
.
build
();
}
}
/**
* 解析 /api/verify 响应,仅提取 data.proof_token。
* 不抛异常,统一封装 NewApiResponse。
*/
private
NewApiResponse
<
String
>
parseVerifyResponse
(
HttpResponse
response
)
{
try
{
String
body
=
response
.
body
();
if
(
StrUtil
.
isBlank
(
body
))
{
return
NewApiResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"Empty response"
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
body
);
NewApiResponse
<
String
>
result
=
new
NewApiResponse
<>();
result
.
setSuccess
(
json
.
getBool
(
"success"
));
result
.
setMessage
(
json
.
getStr
(
"message"
));
if
(
Boolean
.
TRUE
.
equals
(
json
.
getBool
(
"success"
)))
{
JSONObject
data
=
json
.
getJSONObject
(
"data"
);
if
(
data
!=
null
)
{
String
proof
=
data
.
getStr
(
"proof_token"
);
if
(
proof
!=
null
&&
!
proof
.
isEmpty
())
{
result
.
setData
(
proof
);
}
}
}
return
result
;
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.parseVerifyResponse] 解析响应异常"
,
e
);
return
NewApiResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"解析响应失败: "
+
(
e
.
getMessage
()
==
null
?
e
.
getClass
().
getSimpleName
()
:
e
.
getMessage
()))
.
build
();
}
}
/**
* 生成长期 AccessToken:GET /api/user/token
*
* <p>NewAPI v3 中此接口需要先完成安全验证({@link #verifyPassword}),
* 通过 {@code X-Security-Proof} Header 提交 proof_token。
* <p>接口:{@code GET /api/user/token}
* <p>Header:{@code New-Api-User=<id>}, {@code Authorization: Bearer <accessToken>}, {@code X-Security-Proof=<proof>}
* <p>响应 data 字段是 29~33 位的随机字符串,会被 NewAPI 写入 {@code users.access_token} 列。
* <p>该 token 是长期有效的,可替代短期 JWT 作为后续管理类接口的 Bearer 凭据。
*/
public
NewApiResponse
<
String
>
generateAccessToken
(
String
accessToken
,
Integer
userId
,
String
proofToken
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/user/token"
;
log
.
info
(
"[NewApiClient.generateAccessToken] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
HttpRequest
.
get
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
header
(
"X-Security-Proof"
,
proofToken
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.generateAccessToken] 响应状态: {}"
,
response
.
getStatus
());
return
parseResponse
(
response
,
String
.
class
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.generateAccessToken] 请求异常"
,
e
);
return
NewApiResponse
.<
String
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
(
e
.
getMessage
()
==
null
?
e
.
getClass
().
getSimpleName
()
:
e
.
getMessage
()))
.
build
();
}
}
public
NewApiResponse
<
Void
>
createToken
(
String
accessToken
,
Integer
userId
,
String
name
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/token/"
;
log
.
info
(
"[NewApiClient.createToken] 请求URL: {}"
,
url
);
Map
<
String
,
Object
>
body
=
new
HashMap
<>();
body
.
put
(
"name"
,
name
);
body
.
put
(
"remain_quota"
,
0
);
body
.
put
(
"expired_time"
,
-
1
);
body
.
put
(
"unlimited_quota"
,
true
);
body
.
put
(
"model_limits_enabled"
,
false
);
body
.
put
(
"model_limits"
,
""
);
body
.
put
(
"cross_group_retry"
,
false
);
body
.
put
(
"group"
,
""
);
body
.
put
(
"allow_ips"
,
""
);
body
.
put
(
"remain_amount"
,
0
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
body
(
JSONUtil
.
toJsonStr
(
body
))
.
contentType
(
"application/json"
)
.
timeout
(
30000
)
.
execute
();
return
parseResponse
(
response
,
Void
.
class
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.createToken] 请求异常"
,
e
);
return
NewApiResponse
.<
Void
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
public
NewApiResponse
<
NewApiTokenPageVO
>
getTokenList
(
String
accessToken
,
Integer
userId
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/token/?p=1&size=10"
;
log
.
info
(
"[NewApiClient.getTokenList] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
HttpRequest
.
get
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
timeout
(
30000
)
.
execute
();
return
parseResponse
(
response
,
NewApiTokenPageVO
.
class
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.getTokenList] 请求异常"
,
e
);
return
NewApiResponse
.<
NewApiTokenPageVO
>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
@SuppressWarnings
(
"unchecked"
)
public
NewApiResponse
<
Map
<
String
,
Object
>>
getTokenKey
(
String
accessToken
,
Integer
userId
,
Long
tokenId
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/token/"
+
tokenId
+
"/key"
;
log
.
info
(
"[NewApiClient.getTokenKey] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
HttpRequest
.
post
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.getTokenKey] 响应状态: {}"
,
response
.
getStatus
());
log
.
info
(
"[NewApiClient.getTokenKey] 响应内容: {}"
,
response
.
body
());
String
body
=
response
.
body
();
JSONObject
json
=
JSONUtil
.
parseObj
(
body
);
NewApiResponse
<
Map
<
String
,
Object
>>
result
=
new
NewApiResponse
<>();
result
.
setSuccess
(
json
.
getBool
(
"success"
));
result
.
setMessage
(
json
.
getStr
(
"message"
));
result
.
setHttpResponse
(
response
);
if
(
json
.
containsKey
(
"data"
)
&&
!
json
.
isNull
(
"data"
))
{
Object
data
=
json
.
get
(
"data"
);
if
(
data
instanceof
Map
)
{
result
.
setData
((
Map
<
String
,
Object
>)
data
);
}
else
{
result
.
setData
((
Map
<
String
,
Object
>)
JSONUtil
.
parseObj
(
data
.
toString
()));
}
}
return
result
;
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.getTokenKey] 请求异常"
,
e
);
return
NewApiResponse
.<
Map
<
String
,
Object
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 获取用户信息(包含 quota 余额)
*/
public
NewApiResponse
<
Map
<
String
,
Object
>>
getUserInfo
(
String
accessToken
,
Integer
userId
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/user/self"
;
log
.
info
(
"[NewApiClient.getUserInfo] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
HttpRequest
.
get
(
url
)
.
header
(
HEADER_USER
,
String
.
valueOf
(
userId
))
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
)
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.getUserInfo] 响应状态: {}"
,
response
.
getStatus
());
log
.
info
(
"[NewApiClient.getUserInfo] 响应内容: {}"
,
response
.
body
());
String
body
=
response
.
body
();
if
(
StrUtil
.
isBlank
(
body
))
{
return
NewApiResponse
.<
Map
<
String
,
Object
>>
builder
()
.
success
(
false
)
.
message
(
"Empty response"
)
.
httpResponse
(
response
)
.
build
();
}
JSONObject
json
=
JSONUtil
.
parseObj
(
body
);
NewApiResponse
<
Map
<
String
,
Object
>>
result
=
new
NewApiResponse
<>();
result
.
setSuccess
(
json
.
getBool
(
"success"
));
result
.
setMessage
(
json
.
getStr
(
"message"
));
result
.
setHttpResponse
(
response
);
if
(
json
.
containsKey
(
"data"
)
&&
!
json
.
isNull
(
"data"
))
{
Object
data
=
json
.
get
(
"data"
);
if
(
data
instanceof
Map
)
{
result
.
setData
((
Map
<
String
,
Object
>)
data
);
}
else
{
result
.
setData
((
Map
<
String
,
Object
>)
JSONUtil
.
parseObj
(
data
.
toString
()));
}
}
return
result
;
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.getUserInfo] 请求异常"
,
e
);
return
NewApiResponse
.<
Map
<
String
,
Object
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
build
();
}
}
/**
* 获取定价信息(含模型定价、分组倍率、支持端点)
* GET /api/pricing
*
* @param accessToken 用户访问令牌(可空)。传入后使用对应账号权限请求,group_ratio.default 即为该用户实际倍率;不传则匿名请求。
* @param userId 用户在 New API 的 userId(与 accessToken 配套传入,用于 New-Api-User 头)。可空。
*/
public
NewApiResponse
<
Map
<
String
,
Object
>>
getPricing
(
String
accessToken
,
String
userId
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/pricing"
;
log
.
info
(
"[NewApiClient.getPricing] 请求URL: {}, 带token={}, 带userId={}"
,
url
,
StrUtil
.
isNotBlank
(
accessToken
),
StrUtil
.
isNotBlank
(
userId
));
try
{
HttpRequest
request
=
HttpRequest
.
get
(
url
).
timeout
(
30000
);
if
(
StrUtil
.
isBlank
(
accessToken
))
{
// 匿名请求
request
.
header
(
HEADER_USER
,
USER_ANONYMOUS
);
}
else
{
// 带 token 时同时传 New-Api-User 头
if
(
StrUtil
.
isNotBlank
(
userId
))
{
request
.
header
(
HEADER_USER
,
userId
);
}
request
.
header
(
HEADER_AUTH
,
"Bearer "
+
accessToken
);
}
HttpResponse
response
=
request
.
execute
();
log
.
info
(
"[NewApiClient.getPricing] 响应状态: {}"
,
response
.
getStatus
());
return
parseMapResponse
(
response
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.getPricing] 请求异常"
,
e
);
return
NewApiResponse
.<
Map
<
String
,
Object
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
httpResponse
(
null
)
.
build
();
}
}
/**
* 获取模型列表(管理员权限)
* GET /api/models/?p=0&page_size=100
*
* 注意:New API 服务端对 page_size 存在上限(最大 100),
* 超过 100 仍按 100 返回,因此需要分页循环拉取全部模型。
*/
public
NewApiResponse
<
Map
<
String
,
Object
>>
getModels
(
Integer
page
,
Integer
pageSize
)
{
String
url
=
newApiProperties
.
getBaseUrl
()
+
"/api/models/"
;
if
(
page
!=
null
||
pageSize
!=
null
)
{
StringBuilder
sb
=
new
StringBuilder
(
url
).
append
(
"?"
);
if
(
page
!=
null
)
sb
.
append
(
"p="
).
append
(
page
);
if
(
page
!=
null
&&
pageSize
!=
null
)
sb
.
append
(
"&"
);
if
(
pageSize
!=
null
)
sb
.
append
(
"page_size="
).
append
(
pageSize
);
url
=
sb
.
toString
();
}
log
.
info
(
"[NewApiClient.getModels] 请求URL: {}"
,
url
);
try
{
HttpResponse
response
=
HttpRequest
.
get
(
url
)
.
header
(
HEADER_USER
,
newApiProperties
.
getAdminUserId
())
.
header
(
HEADER_AUTH
,
"Bearer "
+
newApiProperties
.
getAdminToken
())
.
timeout
(
30000
)
.
execute
();
log
.
info
(
"[NewApiClient.getModels] 响应状态: {}"
,
response
.
getStatus
());
return
parseMapResponse
(
response
);
}
catch
(
Exception
e
)
{
log
.
error
(
"[NewApiClient.getModels] 请求异常"
,
e
);
return
NewApiResponse
.<
Map
<
String
,
Object
>>
builder
()
.
success
(
false
)
.
message
(
"请求异常: "
+
e
.
getMessage
())
.
httpResponse
(
null
)
.
build
();
}
}
/**
* 循环分页拉取全部模型(解决 New API page_size 上限 100 的限制)
*
* <p>注意:New API 的 {@code p} 参数是 <b>1-based</b>(不是 0-based),
* 从 1 开始计数。p=0 会被服务端当作 p=1 处理,导致拉两遍首页。
*
* @return 包含全部模型 items 列表的响应
*/
public
NewApiResponse
<
List
<
Map
<
String
,
Object
>>>
getAllModels
()
{
// New API 服务端 page_size 上限为 100,按 100 循环
final
int
pageSize
=
100
;
// 安全上限:防止 total 字段异常时死循环
final
int
maxPages
=
200
;
List
<
Map
<
String
,
Object
>>
allItems
=
new
java
.
util
.
ArrayList
<>();
// 记录已见过的 model_name,作为分页重叠的安全网
java
.
util
.
Set
<
String
>
seenModelNames
=
new
java
.
util
.
HashSet
<>();
int
total
=
-
1
;
// New API 分页从 1 开始(p=0 会被当作 p=1)
for
(
int
page
=
1
;
page
<=
maxPages
;
page
++)
{
NewApiResponse
<
Map
<
String
,
Object
>>
resp
=
getModels
(
page
,
pageSize
);
if
(
resp
.
getSuccess
()
==
null
||
!
resp
.
getSuccess
()
||
resp
.
getData
()
==
null
)
{
log
.
error
(
"[NewApiClient.getAllModels] 第 {} 页拉取失败:{}"
,
page
,
resp
.
getMessage
());
return
NewApiResponse
.<
List
<
Map
<
String
,
Object
>>>
builder
()
.
success
(
false
)
.
message
(
"拉取第 "
+
page
+
" 页失败: "
+
resp
.
getMessage
())
.
httpResponse
(
resp
.
getHttpResponse
())
.
build
();
}
Map
<
String
,
Object
>
data
=
resp
.
getData
();
// 首次请求解析 total
if
(
page
==
1
)
{
Object
totalObj
=
data
.
get
(
"total"
);
if
(
totalObj
instanceof
Number
)
{
total
=
((
Number
)
totalObj
).
intValue
();
}
else
if
(
totalObj
!=
null
)
{
try
{
total
=
Integer
.
parseInt
(
totalObj
.
toString
());
}
catch
(
Exception
ignored
)
{
}
}
log
.
info
(
"[NewApiClient.getAllModels] 模型总数 total={}"
,
total
);
}
@SuppressWarnings
(
"unchecked"
)
List
<
Map
<
String
,
Object
>>
items
=
(
List
<
Map
<
String
,
Object
>>)
data
.
get
(
"items"
);
if
(
items
==
null
||
items
.
isEmpty
())
{
break
;
}
// 按 model_name 去重加入(防御 New API 分页重叠的潜在 bug)
for
(
Map
<
String
,
Object
>
item
:
items
)
{
Object
nameObj
=
item
.
get
(
"model_name"
);
if
(
nameObj
==
null
)
continue
;
if
(
seenModelNames
.
add
(
nameObj
.
toString
()))
{
allItems
.
add
(
item
);
}
}
// 终止条件 1:已拉满 total
if
(
total
>
0
&&
allItems
.
size
()
>=
total
)
{
break
;
}
// 终止条件 2:本次返回不足一页(最后一页)
if
(
items
.
size
()
<
pageSize
)
{
break
;
}
}
log
.
info
(
"[NewApiClient.getAllModels] 去重后模型数={}, 期望 total={}"
,
allItems
.
size
(),
total
);
NewApiResponse
<
List
<
Map
<
String
,
Object
>>>
result
=
new
NewApiResponse
<>();
result
.
setSuccess
(
true
);
result
.
setData
(
allItems
);
return
result
;
}
/**
* 获取个人日志统计
...
...
@@ -897,4 +296,4 @@ public class NewApiClient {
}
}
}
\ No newline at end of file
}
computility-module-apihub/computility-module-apihub-biz/src/main/resources/apihub/endpoint-params.yaml
0 → 100644
View file @
2cb2a43f
# 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
computility-module-member/src/main/java/com/luhu/computility/module/member/dal/dataobject/user/MemberUserDO.java
View file @
2cb2a43f
...
...
@@ -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
;
}
computility-module-member/src/main/java/com/luhu/computility/module/member/service/recharge/RechargeAgreementPdfService.java
View file @
2cb2a43f
package
com
.
luhu
.
computility
.
module
.
member
.
service
.
recharge
;
import
com.luhu.computility.module.apihub.api.
newapi.NewApi
UserApi
;
import
com.luhu.computility.module.apihub.api.
apihub.ApiHub
UserApi
;
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
newApi
UserApi
;
private
final
ApiHubUserApi
apiHub
UserApi
;
/**
* 生成并保存协议 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
=
query
NewApi
BalanceYuan
(
user
);
//
api_hub
余额查询失败时降级为只显示本次充值金额。
BigDecimal
currentBalance
=
query
ApiHub
BalanceYuan
(
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
;
}
}
...
...
computility-module-member/src/main/java/com/luhu/computility/module/member/service/user/MemberUserService.java
View file @
2cb2a43f
...
...
@@ -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
);
}
computility-module-member/src/main/java/com/luhu/computility/module/member/service/user/MemberUserServiceImpl.java
View file @
2cb2a43f
...
...
@@ -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
());
}
}
computility-server/src/main/resources/application-local.yaml
View file @
2cb2a43f
...
...
@@ -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
:
...
...
sql/migration/2026_11_11_add_member_user_api_hub_fields.sql
0 → 100644
View file @
2cb2a43f
-- ============================================================
-- 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%';
sql/migration/2026_11_11_add_member_user_api_hub_password.sql
0 → 100644
View file @
2cb2a43f
-- ============================================================
-- 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%';
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment