pricing.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. package model
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/setting/billing_setting"
  11. "github.com/QuantumNous/new-api/setting/ratio_setting"
  12. "github.com/QuantumNous/new-api/types"
  13. )
  14. type Pricing struct {
  15. ModelName string `json:"model_name"`
  16. Description string `json:"description,omitempty"`
  17. Icon string `json:"icon,omitempty"`
  18. Tags string `json:"tags,omitempty"`
  19. VendorID int `json:"vendor_id,omitempty"`
  20. QuotaType int `json:"quota_type"`
  21. ModelRatio float64 `json:"model_ratio"`
  22. ModelPrice float64 `json:"model_price"`
  23. OwnerBy string `json:"owner_by"`
  24. CompletionRatio float64 `json:"completion_ratio"`
  25. CacheRatio *float64 `json:"cache_ratio,omitempty"`
  26. CreateCacheRatio *float64 `json:"create_cache_ratio,omitempty"`
  27. ImageRatio *float64 `json:"image_ratio,omitempty"`
  28. AudioRatio *float64 `json:"audio_ratio,omitempty"`
  29. AudioCompletionRatio *float64 `json:"audio_completion_ratio,omitempty"`
  30. EnableGroup []string `json:"enable_groups"`
  31. SupportedEndpointTypes []constant.EndpointType `json:"supported_endpoint_types"`
  32. BillingMode string `json:"billing_mode,omitempty"`
  33. BillingExpr string `json:"billing_expr,omitempty"`
  34. PricingVersion string `json:"pricing_version,omitempty"`
  35. }
  36. type PricingVendor struct {
  37. ID int `json:"id"`
  38. Name string `json:"name"`
  39. Description string `json:"description,omitempty"`
  40. Icon string `json:"icon,omitempty"`
  41. }
  42. var (
  43. pricingMap []Pricing
  44. vendorsList []PricingVendor
  45. supportedEndpointMap map[string]common.EndpointInfo
  46. lastGetPricingTime time.Time
  47. updatePricingLock sync.Mutex
  48. // 缓存映射:模型名 -> 启用分组 / 计费类型
  49. modelEnableGroups = make(map[string][]string)
  50. modelQuotaTypeMap = make(map[string]int)
  51. modelEnableGroupsLock = sync.RWMutex{}
  52. )
  53. var (
  54. modelSupportEndpointTypes = make(map[string][]constant.EndpointType)
  55. modelSupportEndpointsLock = sync.RWMutex{}
  56. )
  57. func GetPricing() []Pricing {
  58. if time.Since(lastGetPricingTime) > time.Minute*1 || len(pricingMap) == 0 {
  59. updatePricingLock.Lock()
  60. defer updatePricingLock.Unlock()
  61. // Double check after acquiring the lock
  62. if time.Since(lastGetPricingTime) > time.Minute*1 || len(pricingMap) == 0 {
  63. modelSupportEndpointsLock.Lock()
  64. defer modelSupportEndpointsLock.Unlock()
  65. updatePricing()
  66. }
  67. }
  68. return pricingMap
  69. }
  70. func InvalidatePricingCache() {
  71. updatePricingLock.Lock()
  72. defer updatePricingLock.Unlock()
  73. pricingMap = nil
  74. vendorsList = nil
  75. lastGetPricingTime = time.Time{}
  76. }
  77. // GetVendors 返回当前定价接口使用到的供应商信息
  78. func GetVendors() []PricingVendor {
  79. if time.Since(lastGetPricingTime) > time.Minute*1 || len(pricingMap) == 0 {
  80. // 保证先刷新一次
  81. GetPricing()
  82. }
  83. return vendorsList
  84. }
  85. func GetModelSupportEndpointTypes(model string) []constant.EndpointType {
  86. if model == "" {
  87. return make([]constant.EndpointType, 0)
  88. }
  89. modelSupportEndpointsLock.RLock()
  90. defer modelSupportEndpointsLock.RUnlock()
  91. if endpoints, ok := modelSupportEndpointTypes[model]; ok {
  92. return endpoints
  93. }
  94. return make([]constant.EndpointType, 0)
  95. }
  96. func updatePricing() {
  97. //modelRatios := common.GetModelRatios()
  98. enableAbilities, err := GetAllEnableAbilityWithChannels()
  99. if err != nil {
  100. common.SysLog(fmt.Sprintf("GetAllEnableAbilityWithChannels error: %v", err))
  101. return
  102. }
  103. // 预加载模型元数据与供应商一次,避免循环查询
  104. var allMeta []Model
  105. _ = DB.Find(&allMeta).Error
  106. metaMap := make(map[string]*Model)
  107. prefixList := make([]*Model, 0)
  108. suffixList := make([]*Model, 0)
  109. containsList := make([]*Model, 0)
  110. for i := range allMeta {
  111. m := &allMeta[i]
  112. if m.NameRule == NameRuleExact {
  113. metaMap[m.ModelName] = m
  114. } else {
  115. switch m.NameRule {
  116. case NameRulePrefix:
  117. prefixList = append(prefixList, m)
  118. case NameRuleSuffix:
  119. suffixList = append(suffixList, m)
  120. case NameRuleContains:
  121. containsList = append(containsList, m)
  122. }
  123. }
  124. }
  125. // 将非精确规则模型匹配到 metaMap
  126. for _, m := range prefixList {
  127. for _, pricingModel := range enableAbilities {
  128. if strings.HasPrefix(pricingModel.Model, m.ModelName) {
  129. if _, exists := metaMap[pricingModel.Model]; !exists {
  130. metaMap[pricingModel.Model] = m
  131. }
  132. }
  133. }
  134. }
  135. for _, m := range suffixList {
  136. for _, pricingModel := range enableAbilities {
  137. if strings.HasSuffix(pricingModel.Model, m.ModelName) {
  138. if _, exists := metaMap[pricingModel.Model]; !exists {
  139. metaMap[pricingModel.Model] = m
  140. }
  141. }
  142. }
  143. }
  144. for _, m := range containsList {
  145. for _, pricingModel := range enableAbilities {
  146. if strings.Contains(pricingModel.Model, m.ModelName) {
  147. if _, exists := metaMap[pricingModel.Model]; !exists {
  148. metaMap[pricingModel.Model] = m
  149. }
  150. }
  151. }
  152. }
  153. // 预加载供应商
  154. var vendors []Vendor
  155. _ = DB.Find(&vendors).Error
  156. vendorMap := make(map[int]*Vendor)
  157. for i := range vendors {
  158. vendorMap[vendors[i].Id] = &vendors[i]
  159. }
  160. // 初始化默认供应商映射
  161. initDefaultVendorMapping(metaMap, vendorMap, enableAbilities)
  162. // 构建对前端友好的供应商列表
  163. vendorsList = make([]PricingVendor, 0, len(vendorMap))
  164. for _, v := range vendorMap {
  165. vendorsList = append(vendorsList, PricingVendor{
  166. ID: v.Id,
  167. Name: v.Name,
  168. Description: v.Description,
  169. Icon: v.Icon,
  170. })
  171. }
  172. modelGroupsMap := make(map[string]*types.Set[string])
  173. for _, ability := range enableAbilities {
  174. groups, ok := modelGroupsMap[ability.Model]
  175. if !ok {
  176. groups = types.NewSet[string]()
  177. modelGroupsMap[ability.Model] = groups
  178. }
  179. groups.Add(ability.Group)
  180. }
  181. //这里使用切片而不是Set,因为一个模型可能支持多个端点类型,并且第一个端点是优先使用端点
  182. modelSupportEndpointsStr := make(map[string][]string)
  183. // 先根据已有能力填充原生端点
  184. for _, ability := range enableAbilities {
  185. endpoints := modelSupportEndpointsStr[ability.Model]
  186. channelTypes := common.GetEndpointTypesByChannelType(ability.ChannelType, ability.Model)
  187. for _, channelType := range channelTypes {
  188. if !common.StringsContains(endpoints, string(channelType)) {
  189. endpoints = append(endpoints, string(channelType))
  190. }
  191. }
  192. modelSupportEndpointsStr[ability.Model] = endpoints
  193. }
  194. // 再补充模型自定义端点:若配置有效则替换默认端点,不做合并
  195. for modelName, meta := range metaMap {
  196. if strings.TrimSpace(meta.Endpoints) == "" {
  197. continue
  198. }
  199. var raw map[string]interface{}
  200. if err := json.Unmarshal([]byte(meta.Endpoints), &raw); err == nil {
  201. endpoints := make([]string, 0, len(raw))
  202. for k, v := range raw {
  203. switch v.(type) {
  204. case string, map[string]interface{}:
  205. if !common.StringsContains(endpoints, k) {
  206. endpoints = append(endpoints, k)
  207. }
  208. }
  209. }
  210. if len(endpoints) > 0 {
  211. modelSupportEndpointsStr[modelName] = endpoints
  212. }
  213. }
  214. }
  215. modelSupportEndpointTypes = make(map[string][]constant.EndpointType)
  216. for model, endpoints := range modelSupportEndpointsStr {
  217. supportedEndpoints := make([]constant.EndpointType, 0)
  218. for _, endpointStr := range endpoints {
  219. endpointType := constant.EndpointType(endpointStr)
  220. supportedEndpoints = append(supportedEndpoints, endpointType)
  221. }
  222. modelSupportEndpointTypes[model] = supportedEndpoints
  223. }
  224. // 构建全局 supportedEndpointMap(默认 + 自定义覆盖)
  225. supportedEndpointMap = make(map[string]common.EndpointInfo)
  226. // 1. 默认端点
  227. for _, endpoints := range modelSupportEndpointTypes {
  228. for _, et := range endpoints {
  229. if info, ok := common.GetDefaultEndpointInfo(et); ok {
  230. if _, exists := supportedEndpointMap[string(et)]; !exists {
  231. supportedEndpointMap[string(et)] = info
  232. }
  233. }
  234. }
  235. }
  236. // 2. 自定义端点(models 表)覆盖默认
  237. for _, meta := range metaMap {
  238. if strings.TrimSpace(meta.Endpoints) == "" {
  239. continue
  240. }
  241. var raw map[string]interface{}
  242. if err := json.Unmarshal([]byte(meta.Endpoints), &raw); err == nil {
  243. for k, v := range raw {
  244. switch val := v.(type) {
  245. case string:
  246. supportedEndpointMap[k] = common.EndpointInfo{Path: val, Method: "POST"}
  247. case map[string]interface{}:
  248. ep := common.EndpointInfo{Method: "POST"}
  249. if p, ok := val["path"].(string); ok {
  250. ep.Path = p
  251. }
  252. if m, ok := val["method"].(string); ok {
  253. ep.Method = strings.ToUpper(m)
  254. }
  255. supportedEndpointMap[k] = ep
  256. default:
  257. // ignore unsupported types
  258. }
  259. }
  260. }
  261. }
  262. pricingMap = make([]Pricing, 0)
  263. for model, groups := range modelGroupsMap {
  264. pricing := Pricing{
  265. ModelName: model,
  266. EnableGroup: groups.Items(),
  267. SupportedEndpointTypes: modelSupportEndpointTypes[model],
  268. }
  269. // 补充模型元数据(描述、标签、供应商、状态)
  270. if meta, ok := metaMap[model]; ok {
  271. // 若模型被禁用(status!=1),则直接跳过,不返回给前端
  272. if meta.Status != 1 {
  273. continue
  274. }
  275. pricing.Description = meta.Description
  276. pricing.Icon = meta.Icon
  277. pricing.Tags = meta.Tags
  278. pricing.VendorID = meta.VendorID
  279. }
  280. modelPrice, findPrice := ratio_setting.GetModelPrice(model, false)
  281. if findPrice {
  282. pricing.ModelPrice = modelPrice
  283. pricing.QuotaType = 1
  284. } else {
  285. modelRatio, _, _ := ratio_setting.GetModelRatio(model)
  286. pricing.ModelRatio = modelRatio
  287. pricing.CompletionRatio = ratio_setting.GetCompletionRatio(model)
  288. pricing.QuotaType = 0
  289. }
  290. if cacheRatio, ok := ratio_setting.GetCacheRatio(model); ok {
  291. pricing.CacheRatio = &cacheRatio
  292. }
  293. if createCacheRatio, ok := ratio_setting.GetCreateCacheRatio(model); ok {
  294. pricing.CreateCacheRatio = &createCacheRatio
  295. }
  296. if imageRatio, ok := ratio_setting.GetImageRatio(model); ok {
  297. pricing.ImageRatio = &imageRatio
  298. }
  299. if ratio_setting.ContainsAudioRatio(model) {
  300. audioRatio := ratio_setting.GetAudioRatio(model)
  301. pricing.AudioRatio = &audioRatio
  302. }
  303. if ratio_setting.ContainsAudioCompletionRatio(model) {
  304. audioCompletionRatio := ratio_setting.GetAudioCompletionRatio(model)
  305. pricing.AudioCompletionRatio = &audioCompletionRatio
  306. }
  307. if billingMode := billing_setting.GetBillingMode(model); billingMode == "tiered_expr" {
  308. if expr, ok := billing_setting.GetBillingExpr(model); ok && strings.TrimSpace(expr) != "" {
  309. pricing.BillingMode = billingMode
  310. pricing.BillingExpr = expr
  311. }
  312. }
  313. pricingMap = append(pricingMap, pricing)
  314. }
  315. // 防止大更新后数据不通用
  316. if len(pricingMap) > 0 {
  317. pricingMap[0].PricingVersion = "5a90f2b86c08bd983a9a2e6d66c255f4eaef9c4bc934386d2b6ae84ef0ff1f1f"
  318. }
  319. // 刷新缓存映射,供高并发快速查询
  320. modelEnableGroupsLock.Lock()
  321. modelEnableGroups = make(map[string][]string)
  322. modelQuotaTypeMap = make(map[string]int)
  323. for _, p := range pricingMap {
  324. modelEnableGroups[p.ModelName] = p.EnableGroup
  325. modelQuotaTypeMap[p.ModelName] = p.QuotaType
  326. }
  327. modelEnableGroupsLock.Unlock()
  328. lastGetPricingTime = time.Now()
  329. }
  330. // GetSupportedEndpointMap 返回全局端点到路径的映射
  331. func GetSupportedEndpointMap() map[string]common.EndpointInfo {
  332. return supportedEndpointMap
  333. }