channel.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 != "" && group != "null" {
  98. var groupCondition string
  99. if common.UsingPostgreSQL {
  100. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  101. } else {
  102. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  103. }
  104. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  105. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  106. } else {
  107. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  108. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  109. }
  110. // 执行查询
  111. err := baseQuery.Where(whereClause, args...).Find(&channels).Error
  112. if err != nil {
  113. return nil, err
  114. }
  115. return channels, nil
  116. }
  117. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  118. channel := Channel{Id: id}
  119. var err error = nil
  120. if selectAll {
  121. err = DB.First(&channel, "id = ?", id).Error
  122. } else {
  123. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  124. }
  125. return &channel, err
  126. }
  127. func BatchInsertChannels(channels []Channel) error {
  128. var err error
  129. err = DB.Create(&channels).Error
  130. if err != nil {
  131. return err
  132. }
  133. for _, channel_ := range channels {
  134. err = channel_.AddAbilities()
  135. if err != nil {
  136. return err
  137. }
  138. }
  139. return nil
  140. }
  141. func BatchDeleteChannels(ids []int) error {
  142. //使用事务 删除channel表和channel_ability表
  143. tx := DB.Begin()
  144. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  145. if err != nil {
  146. // 回滚事务
  147. tx.Rollback()
  148. return err
  149. }
  150. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  151. if err != nil {
  152. // 回滚事务
  153. tx.Rollback()
  154. return err
  155. }
  156. // 提交事务
  157. tx.Commit()
  158. return err
  159. }
  160. func (channel *Channel) GetPriority() int64 {
  161. if channel.Priority == nil {
  162. return 0
  163. }
  164. return *channel.Priority
  165. }
  166. func (channel *Channel) GetWeight() int {
  167. if channel.Weight == nil {
  168. return 0
  169. }
  170. return int(*channel.Weight)
  171. }
  172. func (channel *Channel) GetBaseURL() string {
  173. if channel.BaseURL == nil {
  174. return ""
  175. }
  176. return *channel.BaseURL
  177. }
  178. func (channel *Channel) GetModelMapping() string {
  179. if channel.ModelMapping == nil {
  180. return ""
  181. }
  182. return *channel.ModelMapping
  183. }
  184. func (channel *Channel) GetStatusCodeMapping() string {
  185. if channel.StatusCodeMapping == nil {
  186. return ""
  187. }
  188. return *channel.StatusCodeMapping
  189. }
  190. func (channel *Channel) Insert() error {
  191. var err error
  192. err = DB.Create(channel).Error
  193. if err != nil {
  194. return err
  195. }
  196. err = channel.AddAbilities()
  197. return err
  198. }
  199. func (channel *Channel) Update() error {
  200. var err error
  201. err = DB.Model(channel).Updates(channel).Error
  202. if err != nil {
  203. return err
  204. }
  205. DB.Model(channel).First(channel, "id = ?", channel.Id)
  206. err = channel.UpdateAbilities()
  207. return err
  208. }
  209. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  210. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  211. TestTime: common.GetTimestamp(),
  212. ResponseTime: int(responseTime),
  213. }).Error
  214. if err != nil {
  215. common.SysError("failed to update response time: " + err.Error())
  216. }
  217. }
  218. func (channel *Channel) UpdateBalance(balance float64) {
  219. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  220. BalanceUpdatedTime: common.GetTimestamp(),
  221. Balance: balance,
  222. }).Error
  223. if err != nil {
  224. common.SysError("failed to update balance: " + err.Error())
  225. }
  226. }
  227. func (channel *Channel) Delete() error {
  228. var err error
  229. err = DB.Delete(channel).Error
  230. if err != nil {
  231. return err
  232. }
  233. err = channel.DeleteAbilities()
  234. return err
  235. }
  236. func UpdateChannelStatusById(id int, status int, reason string) {
  237. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  238. if err != nil {
  239. common.SysError("failed to update ability status: " + err.Error())
  240. }
  241. channel, err := GetChannelById(id, true)
  242. if err != nil {
  243. // find channel by id error, directly update status
  244. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  245. if err != nil {
  246. common.SysError("failed to update channel status: " + err.Error())
  247. }
  248. } else {
  249. // find channel by id success, update status and other info
  250. info := channel.GetOtherInfo()
  251. info["status_reason"] = reason
  252. info["status_time"] = common.GetTimestamp()
  253. channel.SetOtherInfo(info)
  254. channel.Status = status
  255. err = channel.Save()
  256. if err != nil {
  257. common.SysError("failed to update channel status: " + err.Error())
  258. }
  259. }
  260. }
  261. func UpdateChannelUsedQuota(id int, quota int) {
  262. if common.BatchUpdateEnabled {
  263. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  264. return
  265. }
  266. updateChannelUsedQuota(id, quota)
  267. }
  268. func updateChannelUsedQuota(id int, quota int) {
  269. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  270. if err != nil {
  271. common.SysError("failed to update channel used quota: " + err.Error())
  272. }
  273. }
  274. func DeleteChannelByStatus(status int64) (int64, error) {
  275. result := DB.Where("status = ?", status).Delete(&Channel{})
  276. return result.RowsAffected, result.Error
  277. }
  278. func DeleteDisabledChannel() (int64, error) {
  279. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  280. return result.RowsAffected, result.Error
  281. }