pricing.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 := make([]string, 0, len(raw))
  186. for k, v := range raw {
  187. switch v.(type) {
  188. case string, map[string]interface{}:
  189. if !common.StringsContains(endpoints, k) {
  190. endpoints = append(endpoints, k)
  191. }
  192. }
  193. }
  194. if len(endpoints) > 0 {
  195. modelSupportEndpointsStr[modelName] = endpoints
  196. }
  197. }
  198. }
  199. modelSupportEndpointTypes = make(map[string][]constant.EndpointType)
  200. for model, endpoints := range modelSupportEndpointsStr {
  201. supportedEndpoints := make([]constant.EndpointType, 0)
  202. for _, endpointStr := range endpoints {
  203. endpointType := constant.EndpointType(endpointStr)
  204. supportedEndpoints = append(supportedEndpoints, endpointType)
  205. }
  206. modelSupportEndpointTypes[model] = supportedEndpoints
  207. }
  208. // 构建全局 supportedEndpointMap(默认 + 自定义覆盖)
  209. supportedEndpointMap = make(map[string]common.EndpointInfo)
  210. // 1. 默认端点
  211. for _, endpoints := range modelSupportEndpointTypes {
  212. for _, et := range endpoints {
  213. if info, ok := common.GetDefaultEndpointInfo(et); ok {
  214. if _, exists := supportedEndpointMap[string(et)]; !exists {
  215. supportedEndpointMap[string(et)] = info
  216. }
  217. }
  218. }
  219. }
  220. // 2. 自定义端点(models 表)覆盖默认
  221. for _, meta := range metaMap {
  222. if strings.TrimSpace(meta.Endpoints) == "" {
  223. continue
  224. }
  225. var raw map[string]interface{}
  226. if err := json.Unmarshal([]byte(meta.Endpoints), &raw); err == nil {
  227. for k, v := range raw {
  228. switch val := v.(type) {
  229. case string:
  230. supportedEndpointMap[k] = common.EndpointInfo{Path: val, Method: "POST"}
  231. case map[string]interface{}:
  232. ep := common.EndpointInfo{Method: "POST"}
  233. if p, ok := val["path"].(string); ok {
  234. ep.Path = p
  235. }
  236. if m, ok := val["method"].(string); ok {
  237. ep.Method = strings.ToUpper(m)
  238. }
  239. supportedEndpointMap[k] = ep
  240. default:
  241. // ignore unsupported types
  242. }
  243. }
  244. }
  245. }
  246. pricingMap = make([]Pricing, 0)
  247. for model, groups := range modelGroupsMap {
  248. pricing := Pricing{
  249. ModelName: model,
  250. EnableGroup: groups.Items(),
  251. SupportedEndpointTypes: modelSupportEndpointTypes[model],
  252. }
  253. // 补充模型元数据(描述、标签、供应商、状态)
  254. if meta, ok := metaMap[model]; ok {
  255. // 若模型被禁用(status!=1),则直接跳过,不返回给前端
  256. if meta.Status != 1 {
  257. continue
  258. }
  259. pricing.Description = meta.Description
  260. pricing.Icon = meta.Icon
  261. pricing.Tags = meta.Tags
  262. pricing.VendorID = meta.VendorID
  263. }
  264. modelPrice, findPrice := ratio_setting.GetModelPrice(model, false)
  265. if findPrice {
  266. pricing.ModelPrice = modelPrice
  267. pricing.QuotaType = 1
  268. } else {
  269. modelRatio, _, _ := ratio_setting.GetModelRatio(model)
  270. pricing.ModelRatio = modelRatio
  271. pricing.CompletionRatio = ratio_setting.GetCompletionRatio(model)
  272. pricing.QuotaType = 0
  273. }
  274. pricingMap = append(pricingMap, pricing)
  275. }
  276. // 刷新缓存映射,供高并发快速查询
  277. modelEnableGroupsLock.Lock()
  278. modelEnableGroups = make(map[string][]string)
  279. modelQuotaTypeMap = make(map[string]int)
  280. for _, p := range pricingMap {
  281. modelEnableGroups[p.ModelName] = p.EnableGroup
  282. modelQuotaTypeMap[p.ModelName] = p.QuotaType
  283. }
  284. modelEnableGroupsLock.Unlock()
  285. lastGetPricingTime = time.Now()
  286. }
  287. // GetSupportedEndpointMap 返回全局端点到路径的映射
  288. func GetSupportedEndpointMap() map[string]common.EndpointInfo {
  289. return supportedEndpointMap
  290. }