pricing.go 11 KB

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