pricing.go 9.2 KB

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