channel.go 8.2 KB

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