channel.go 8.6 KB

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