channel.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package model
  2. import (
  3. "encoding/json"
  4. "gorm.io/gorm"
  5. "one-api/common"
  6. )
  7. type Channel struct {
  8. Id int `json:"id"`
  9. Type int `json:"type" gorm:"default:0"`
  10. Key string `json:"key" gorm:"not null"`
  11. OpenAIOrganization *string `json:"openai_organization"`
  12. TestModel *string `json:"test_model"`
  13. Status int `json:"status" gorm:"default:1"`
  14. Name string `json:"name" gorm:"index"`
  15. Weight *uint `json:"weight" gorm:"default:0"`
  16. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  17. TestTime int64 `json:"test_time" gorm:"bigint"`
  18. ResponseTime int `json:"response_time"` // in milliseconds
  19. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  20. Other string `json:"other"`
  21. Balance float64 `json:"balance"` // in USD
  22. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  23. Models string `json:"models"`
  24. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  25. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  26. ModelMapping *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
  27. //MaxInputTokens *int `json:"max_input_tokens" gorm:"default:0"`
  28. StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
  29. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  30. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  31. OtherInfo string `json:"other_info"`
  32. }
  33. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  34. otherInfo := make(map[string]interface{})
  35. if channel.OtherInfo != "" {
  36. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  37. if err != nil {
  38. common.SysError("failed to unmarshal other info: " + err.Error())
  39. }
  40. }
  41. return otherInfo
  42. }
  43. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  44. otherInfoBytes, err := json.Marshal(otherInfo)
  45. if err != nil {
  46. common.SysError("failed to marshal other info: " + err.Error())
  47. return
  48. }
  49. channel.OtherInfo = string(otherInfoBytes)
  50. }
  51. func (channel *Channel) Save() error {
  52. return DB.Save(channel).Error
  53. }
  54. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  55. var channels []*Channel
  56. var err error
  57. order := "priority desc"
  58. if idSort {
  59. order = "id desc"
  60. }
  61. if selectAll {
  62. err = DB.Order(order).Find(&channels).Error
  63. } else {
  64. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  65. }
  66. return channels, err
  67. }
  68. func SearchChannels(keyword string, group string, model string) ([]*Channel, error) {
  69. var channels []*Channel
  70. keyCol := "`key`"
  71. groupCol := "`group`"
  72. modelsCol := "`models`"
  73. // 如果是 PostgreSQL,使用双引号
  74. if common.UsingPostgreSQL {
  75. keyCol = `"key"`
  76. groupCol = `"group"`
  77. modelsCol = `"models"`
  78. }
  79. // 构造基础查询
  80. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  81. // 构造WHERE子句
  82. var whereClause string
  83. var args []interface{}
  84. if group != "" {
  85. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + groupCol + " LIKE ? AND " + modelsCol + " LIKE ?"
  86. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+group+"%", "%"+model+"%")
  87. } else {
  88. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  89. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  90. }
  91. // 执行查询
  92. err := baseQuery.Where(whereClause, args...).Find(&channels).Error
  93. if err != nil {
  94. return nil, err
  95. }
  96. return channels, nil
  97. }
  98. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  99. channel := Channel{Id: id}
  100. var err error = nil
  101. if selectAll {
  102. err = DB.First(&channel, "id = ?", id).Error
  103. } else {
  104. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  105. }
  106. return &channel, err
  107. }
  108. func BatchInsertChannels(channels []Channel) error {
  109. var err error
  110. err = DB.Create(&channels).Error
  111. if err != nil {
  112. return err
  113. }
  114. for _, channel_ := range channels {
  115. err = channel_.AddAbilities()
  116. if err != nil {
  117. return err
  118. }
  119. }
  120. return nil
  121. }
  122. func BatchDeleteChannels(ids []int) error {
  123. //使用事务 删除channel表和channel_ability表
  124. tx := DB.Begin()
  125. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  126. if err != nil {
  127. // 回滚事务
  128. tx.Rollback()
  129. return err
  130. }
  131. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  132. if err != nil {
  133. // 回滚事务
  134. tx.Rollback()
  135. return err
  136. }
  137. // 提交事务
  138. tx.Commit()
  139. return err
  140. }
  141. func (channel *Channel) GetPriority() int64 {
  142. if channel.Priority == nil {
  143. return 0
  144. }
  145. return *channel.Priority
  146. }
  147. func (channel *Channel) GetWeight() int {
  148. if channel.Weight == nil {
  149. return 0
  150. }
  151. return int(*channel.Weight)
  152. }
  153. func (channel *Channel) GetBaseURL() string {
  154. if channel.BaseURL == nil {
  155. return ""
  156. }
  157. return *channel.BaseURL
  158. }
  159. func (channel *Channel) GetModelMapping() string {
  160. if channel.ModelMapping == nil {
  161. return ""
  162. }
  163. return *channel.ModelMapping
  164. }
  165. func (channel *Channel) GetStatusCodeMapping() string {
  166. if channel.StatusCodeMapping == nil {
  167. return ""
  168. }
  169. return *channel.StatusCodeMapping
  170. }
  171. func (channel *Channel) Insert() error {
  172. var err error
  173. err = DB.Create(channel).Error
  174. if err != nil {
  175. return err
  176. }
  177. err = channel.AddAbilities()
  178. return err
  179. }
  180. func (channel *Channel) Update() error {
  181. var err error
  182. err = DB.Model(channel).Updates(channel).Error
  183. if err != nil {
  184. return err
  185. }
  186. DB.Model(channel).First(channel, "id = ?", channel.Id)
  187. err = channel.UpdateAbilities()
  188. return err
  189. }
  190. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  191. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  192. TestTime: common.GetTimestamp(),
  193. ResponseTime: int(responseTime),
  194. }).Error
  195. if err != nil {
  196. common.SysError("failed to update response time: " + err.Error())
  197. }
  198. }
  199. func (channel *Channel) UpdateBalance(balance float64) {
  200. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  201. BalanceUpdatedTime: common.GetTimestamp(),
  202. Balance: balance,
  203. }).Error
  204. if err != nil {
  205. common.SysError("failed to update balance: " + err.Error())
  206. }
  207. }
  208. func (channel *Channel) Delete() error {
  209. var err error
  210. err = DB.Delete(channel).Error
  211. if err != nil {
  212. return err
  213. }
  214. err = channel.DeleteAbilities()
  215. return err
  216. }
  217. func UpdateChannelStatusById(id int, status int, reason string) {
  218. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  219. if err != nil {
  220. common.SysError("failed to update ability status: " + err.Error())
  221. }
  222. channel, err := GetChannelById(id, true)
  223. if err != nil {
  224. // find channel by id error, directly update status
  225. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  226. if err != nil {
  227. common.SysError("failed to update channel status: " + err.Error())
  228. }
  229. } else {
  230. // find channel by id success, update status and other info
  231. info := channel.GetOtherInfo()
  232. info["status_reason"] = reason
  233. info["status_time"] = common.GetTimestamp()
  234. channel.SetOtherInfo(info)
  235. channel.Status = status
  236. err = channel.Save()
  237. if err != nil {
  238. common.SysError("failed to update channel status: " + err.Error())
  239. }
  240. }
  241. }
  242. func UpdateChannelUsedQuota(id int, quota int) {
  243. if common.BatchUpdateEnabled {
  244. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  245. return
  246. }
  247. updateChannelUsedQuota(id, quota)
  248. }
  249. func updateChannelUsedQuota(id int, quota int) {
  250. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  251. if err != nil {
  252. common.SysError("failed to update channel used quota: " + err.Error())
  253. }
  254. }
  255. func DeleteChannelByStatus(status int64) (int64, error) {
  256. result := DB.Where("status = ?", status).Delete(&Channel{})
  257. return result.RowsAffected, result.Error
  258. }
  259. func DeleteDisabledChannel() (int64, error) {
  260. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  261. return result.RowsAffected, result.Error
  262. }