channel.go 8.3 KB

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