pricing.go 9.4 KB

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