25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

288 lines
10 KiB

  1. package model
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "sync"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/QuantumNous/new-api/setting/ratio_setting"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/clause"
  11. )
  12. // 渠道定价缓存
  13. var (
  14. channelPricingCache = make(map[string]*ChannelPricing) // key: "modelName:channelId"
  15. channelPricingCacheLock sync.RWMutex
  16. )
  17. // QuotaType 计费类型
  18. const (
  19. QuotaTypeByTokens = 0 // 按量计费
  20. QuotaTypeByCall = 1 // 按次计费
  21. )
  22. // ChannelPricing 渠道定价表
  23. // 支持同一模型在不同渠道设置不同价格
  24. type ChannelPricing struct {
  25. Id int `json:"id" gorm:"primaryKey"`
  26. ModelName string `json:"model_name" gorm:"size:128;not null;uniqueIndex:idx_model_channel,priority:1"`
  27. ChannelId int `json:"channel_id" gorm:"not null;uniqueIndex:idx_model_channel,priority:2;index"`
  28. QuotaType int `json:"quota_type" gorm:"default:0"` // 0=按量, 1=按次
  29. ModelRatio float64 `json:"model_ratio" gorm:"default:0"`
  30. CompletionRatio float64 `json:"completion_ratio" gorm:"default:0"`
  31. ModelPrice float64 `json:"model_price" gorm:"default:0"`
  32. TagIds string `json:"tag_ids" gorm:"type:varchar(255)"` // 逗号分隔的标签ID
  33. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  34. UpdatedTime int64 `json:"updated_time" gorm:"bigint"`
  35. DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
  36. // === 新增字段(0 = 未设置,回退全局值) ===
  37. CacheRatio float64 `json:"cache_ratio" gorm:"default:0"`
  38. CacheCreationRatio float64 `json:"cache_creation_ratio" gorm:"default:0"`
  39. ImageRatio float64 `json:"image_ratio" gorm:"default:0"`
  40. AudioRatio float64 `json:"audio_ratio" gorm:"default:0"`
  41. AudioCompletionRatio float64 `json:"audio_completion_ratio" gorm:"default:0"`
  42. }
  43. func (cp *ChannelPricing) Insert() error {
  44. now := common.GetTimestamp()
  45. cp.CreatedTime = now
  46. cp.UpdatedTime = now
  47. err := DB.Create(cp).Error
  48. if err == nil {
  49. key := getChannelPricingCacheKey(cp.ModelName, cp.ChannelId)
  50. channelPricingCacheLock.Lock()
  51. channelPricingCache[key] = cp
  52. channelPricingCacheLock.Unlock()
  53. }
  54. return err
  55. }
  56. func (cp *ChannelPricing) Update() error {
  57. cp.UpdatedTime = common.GetTimestamp()
  58. err := DB.Model(&ChannelPricing{}).Where("id = ?", cp.Id).
  59. Select("quota_type", "model_ratio", "completion_ratio", "model_price",
  60. "tag_ids", "cache_ratio", "cache_creation_ratio", "image_ratio",
  61. "audio_ratio", "audio_completion_ratio", "updated_time").
  62. Updates(cp).Error
  63. if err == nil {
  64. key := getChannelPricingCacheKey(cp.ModelName, cp.ChannelId)
  65. channelPricingCacheLock.Lock()
  66. channelPricingCache[key] = cp
  67. channelPricingCacheLock.Unlock()
  68. }
  69. return err
  70. }
  71. func (cp *ChannelPricing) Delete() error {
  72. var existing ChannelPricing
  73. if err := DB.First(&existing, cp.Id).Error; err != nil {
  74. return err
  75. }
  76. err := DB.Delete(cp).Error
  77. if err == nil {
  78. key := getChannelPricingCacheKey(existing.ModelName, existing.ChannelId)
  79. channelPricingCacheLock.Lock()
  80. delete(channelPricingCache, key)
  81. channelPricingCacheLock.Unlock()
  82. }
  83. return err
  84. }
  85. // GetChannelPricing 获取指定模型在指定渠道的定价
  86. func GetChannelPricing(modelName string, channelId int) (*ChannelPricing, error) {
  87. var cp ChannelPricing
  88. err := DB.Where("model_name = ? AND channel_id = ?", modelName, channelId).First(&cp).Error
  89. if err != nil {
  90. return nil, err
  91. }
  92. return &cp, nil
  93. }
  94. // GetChannelPricingByModel 获取指定模型的所有渠道定价
  95. func GetChannelPricingByModel(modelName string) ([]*ChannelPricing, error) {
  96. var list []*ChannelPricing
  97. err := DB.Where("model_name = ?", modelName).Find(&list).Error
  98. return list, err
  99. }
  100. // GetAllChannelPricing 获取所有渠道定价(分页)
  101. func GetAllChannelPricing(offset int, limit int) ([]*ChannelPricing, int64, error) {
  102. var list []*ChannelPricing
  103. var total int64
  104. if err := DB.Model(&ChannelPricing{}).Count(&total).Error; err != nil {
  105. return nil, 0, err
  106. }
  107. err := DB.Order("id DESC").Offset(offset).Limit(limit).Find(&list).Error
  108. return list, total, err
  109. }
  110. // BatchUpsertChannelPricing 批量创建或更新渠道定价
  111. func BatchUpsertChannelPricing(pricings []*ChannelPricing) error {
  112. if len(pricings) == 0 {
  113. return nil
  114. }
  115. now := common.GetTimestamp()
  116. for _, cp := range pricings {
  117. cp.UpdatedTime = now
  118. // 仅在 CreatedTime 为空时设置(新记录)
  119. if cp.CreatedTime == 0 {
  120. cp.CreatedTime = now
  121. }
  122. }
  123. // 使用 GORM 的 OnConflict 实现 upsert
  124. // 唯一索引为 idx_model_channel (model_name, channel_id)
  125. return DB.Clauses(clause.OnConflict{
  126. Columns: []clause.Column{
  127. {Name: "model_name"},
  128. {Name: "channel_id"},
  129. },
  130. DoUpdates: clause.AssignmentColumns([]string{
  131. "quota_type",
  132. "model_ratio",
  133. "completion_ratio",
  134. "model_price",
  135. "tag_ids",
  136. "cache_ratio",
  137. "cache_creation_ratio",
  138. "image_ratio",
  139. "audio_ratio",
  140. "audio_completion_ratio",
  141. "updated_time",
  142. }),
  143. }).Create(&pricings).Error
  144. }
  145. // getChannelPricingCacheKey 生成缓存键
  146. func getChannelPricingCacheKey(modelName string, channelId int) string {
  147. return fmt.Sprintf("%s:%d", modelName, channelId)
  148. }
  149. // GetEffectivePricing 获取有效定价(纯内存查找)
  150. func GetEffectivePricing(modelName string, channelId int) (*ChannelPricing, bool) {
  151. key := getChannelPricingCacheKey(modelName, channelId)
  152. channelPricingCacheLock.RLock()
  153. cp, ok := channelPricingCache[key]
  154. channelPricingCacheLock.RUnlock()
  155. if !ok {
  156. return nil, false
  157. }
  158. return cp, true
  159. }
  160. // LoadChannelPricingCache 全量加载渠道定价到内存(启动时调用)
  161. func LoadChannelPricingCache() {
  162. var pricings []*ChannelPricing
  163. if err := DB.Find(&pricings).Error; err != nil {
  164. common.SysError("[ChannelPricing] LoadChannelPricingCache failed: " + err.Error())
  165. return
  166. }
  167. channelPricingCacheLock.Lock()
  168. channelPricingCache = make(map[string]*ChannelPricing, len(pricings))
  169. for _, cp := range pricings {
  170. key := getChannelPricingCacheKey(cp.ModelName, cp.ChannelId)
  171. channelPricingCache[key] = cp
  172. }
  173. channelPricingCacheLock.Unlock()
  174. common.SysLog(fmt.Sprintf("[ChannelPricing] cache loaded %d records", len(pricings)))
  175. }
  176. // ChannelPricingWithChannel 带渠道信息的定价响应
  177. type ChannelPricingWithChannel struct {
  178. Id int `json:"id"`
  179. ChannelId int `json:"channel_id"`
  180. ChannelName string `json:"channel_name"`
  181. ChannelType int `json:"channel_type"`
  182. TagIds string `json:"tag_ids" gorm:"column:tag_ids"` // 渠道定价的标签ID列表(逗号分隔)
  183. Tags []*PricingTag `json:"tags" gorm:"-"` // 渠道定价的标签详情(不参与数据库扫描)
  184. QuotaType int `json:"quota_type"` // 0=按量, 1=按次
  185. ModelRatio float64 `json:"model_ratio"`
  186. CompletionRatio float64 `json:"completion_ratio"`
  187. ModelPrice float64 `json:"model_price"`
  188. HasCustomPricing bool `json:"has_custom_pricing"` // 是否有自定义定价
  189. CacheRatio float64 `json:"cache_ratio"`
  190. CacheCreationRatio float64 `json:"cache_creation_ratio"`
  191. ImageRatio float64 `json:"image_ratio"`
  192. AudioRatio float64 `json:"audio_ratio"`
  193. AudioCompletionRatio float64 `json:"audio_completion_ratio"`
  194. }
  195. // GetChannelPricingByModelWithChannelInfo 获取指定模型的渠道定价(带渠道信息)
  196. // 返回所有支持该模型的渠道,对于没有渠道定价的渠道使用全局默认价格
  197. func GetChannelPricingByModelWithChannelInfo(modelName string) ([]*ChannelPricingWithChannel, error) {
  198. var results []*ChannelPricingWithChannel
  199. // 获取全局默认价格
  200. globalModelRatio, hasRatio, _ := ratio_setting.GetModelRatio(modelName)
  201. globalModelPrice, hasPrice := ratio_setting.GetModelPrice(modelName, false)
  202. globalCompletionRatio := ratio_setting.GetCompletionRatio(modelName)
  203. // 确定默认计费类型
  204. var defaultQuotaType int
  205. if hasPrice {
  206. defaultQuotaType = QuotaTypeByCall
  207. } else {
  208. defaultQuotaType = QuotaTypeByTokens
  209. }
  210. // 如果没有全局价格,设置默认值
  211. if !hasRatio {
  212. globalModelRatio = 0
  213. }
  214. if !hasPrice {
  215. globalModelPrice = 0
  216. }
  217. // 查询所有支持该模型的渠道,左连接渠道定价表
  218. err := DB.Table("abilities").
  219. Select(`abilities.channel_id, channels.name as channel_name, channels.type as channel_type,
  220. COALESCE(channel_pricings.quota_type, ?) as quota_type,
  221. COALESCE(channel_pricings.model_ratio, ?) as model_ratio,
  222. COALESCE(channel_pricings.completion_ratio, ?) as completion_ratio,
  223. COALESCE(channel_pricings.model_price, ?) as model_price,
  224. channel_pricings.id as id,
  225. channel_pricings.tag_ids as tag_ids,
  226. (channel_pricings.id IS NOT NULL) as has_custom_pricing`,
  227. defaultQuotaType, globalModelRatio, globalCompletionRatio, globalModelPrice).
  228. Joins("LEFT JOIN channels ON abilities.channel_id = channels.id").
  229. Joins("LEFT JOIN channel_pricings ON abilities.channel_id = channel_pricings.channel_id AND channel_pricings.model_name = ? AND channel_pricings.deleted_at IS NULL", modelName).
  230. Where("abilities.model = ?", modelName).
  231. Where("abilities.enabled = ?", true).
  232. Where("channels.status = ?", 1). // 只显示启用的渠道
  233. Group("abilities.channel_id, channels.name, channels.type, channel_pricings.quota_type, channel_pricings.model_ratio, channel_pricings.completion_ratio, channel_pricings.model_price, channel_pricings.id, channel_pricings.tag_ids").
  234. Scan(&results).Error
  235. if err != nil {
  236. return nil, err
  237. }
  238. // 获取所有定价标签
  239. allTags, err := GetAllPricingTags()
  240. if err != nil {
  241. return results, nil // 如果获取标签失败,仍然返回基础结果
  242. }
  243. // 建立标签ID到标签的映射
  244. tagMap := make(map[int]*PricingTag)
  245. for _, tag := range allTags {
  246. tagMap[tag.Id] = tag
  247. }
  248. // 为每个渠道定价填充标签
  249. for _, result := range results {
  250. if result.TagIds != "" {
  251. result.Tags = make([]*PricingTag, 0)
  252. for _, idStr := range strings.Split(result.TagIds, ",") {
  253. if id, err := strconv.Atoi(strings.TrimSpace(idStr)); err == nil {
  254. if tag, ok := tagMap[id]; ok {
  255. result.Tags = append(result.Tags, tag)
  256. }
  257. }
  258. }
  259. }
  260. }
  261. return results, nil
  262. }