channel.go 8.3 KB

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