channel.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. Tag *string `json:"tag" gorm:"index"`
  34. }
  35. func (channel *Channel) GetModels() []string {
  36. if channel.Models == "" {
  37. return []string{}
  38. }
  39. return strings.Split(strings.Trim(channel.Models, ","), ",")
  40. }
  41. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  42. otherInfo := make(map[string]interface{})
  43. if channel.OtherInfo != "" {
  44. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  45. if err != nil {
  46. common.SysError("failed to unmarshal other info: " + err.Error())
  47. }
  48. }
  49. return otherInfo
  50. }
  51. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  52. otherInfoBytes, err := json.Marshal(otherInfo)
  53. if err != nil {
  54. common.SysError("failed to marshal other info: " + err.Error())
  55. return
  56. }
  57. channel.OtherInfo = string(otherInfoBytes)
  58. }
  59. func (channel *Channel) GetTag() string {
  60. if channel.Tag == nil {
  61. return ""
  62. }
  63. return *channel.Tag
  64. }
  65. func (channel *Channel) SetTag(tag string) {
  66. channel.Tag = &tag
  67. }
  68. func (channel *Channel) GetAutoBan() bool {
  69. if channel.AutoBan == nil {
  70. return false
  71. }
  72. return *channel.AutoBan == 1
  73. }
  74. func (channel *Channel) Save() error {
  75. return DB.Save(channel).Error
  76. }
  77. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  78. var channels []*Channel
  79. var err error
  80. order := "priority desc"
  81. if idSort {
  82. order = "id desc"
  83. }
  84. if selectAll {
  85. err = DB.Order(order).Find(&channels).Error
  86. } else {
  87. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  88. }
  89. return channels, err
  90. }
  91. func GetChannelsByTag(tag string) ([]*Channel, error) {
  92. var channels []*Channel
  93. err := DB.Where("tag = ?", tag).Find(&channels).Error
  94. return channels, err
  95. }
  96. func SearchChannels(keyword string, group string, model string) ([]*Channel, error) {
  97. var channels []*Channel
  98. keyCol := "`key`"
  99. groupCol := "`group`"
  100. modelsCol := "`models`"
  101. // 如果是 PostgreSQL,使用双引号
  102. if common.UsingPostgreSQL {
  103. keyCol = `"key"`
  104. groupCol = `"group"`
  105. modelsCol = `"models"`
  106. }
  107. // 构造基础查询
  108. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  109. // 构造WHERE子句
  110. var whereClause string
  111. var args []interface{}
  112. if group != "" && group != "null" {
  113. var groupCondition string
  114. if common.UsingMySQL {
  115. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  116. } else {
  117. // sqlite, PostgreSQL
  118. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  119. }
  120. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  121. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  122. } else {
  123. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  124. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  125. }
  126. // 执行查询
  127. err := baseQuery.Where(whereClause, args...).Order("priority desc").Find(&channels).Error
  128. if err != nil {
  129. return nil, err
  130. }
  131. return channels, nil
  132. }
  133. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  134. channel := Channel{Id: id}
  135. var err error = nil
  136. if selectAll {
  137. err = DB.First(&channel, "id = ?", id).Error
  138. } else {
  139. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  140. }
  141. return &channel, err
  142. }
  143. func BatchInsertChannels(channels []Channel) error {
  144. var err error
  145. err = DB.Create(&channels).Error
  146. if err != nil {
  147. return err
  148. }
  149. for _, channel_ := range channels {
  150. err = channel_.AddAbilities()
  151. if err != nil {
  152. return err
  153. }
  154. }
  155. return nil
  156. }
  157. func BatchDeleteChannels(ids []int) error {
  158. //使用事务 删除channel表和channel_ability表
  159. tx := DB.Begin()
  160. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  161. if err != nil {
  162. // 回滚事务
  163. tx.Rollback()
  164. return err
  165. }
  166. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  167. if err != nil {
  168. // 回滚事务
  169. tx.Rollback()
  170. return err
  171. }
  172. // 提交事务
  173. tx.Commit()
  174. return err
  175. }
  176. func (channel *Channel) GetPriority() int64 {
  177. if channel.Priority == nil {
  178. return 0
  179. }
  180. return *channel.Priority
  181. }
  182. func (channel *Channel) GetWeight() int {
  183. if channel.Weight == nil {
  184. return 0
  185. }
  186. return int(*channel.Weight)
  187. }
  188. func (channel *Channel) GetBaseURL() string {
  189. if channel.BaseURL == nil {
  190. return ""
  191. }
  192. return *channel.BaseURL
  193. }
  194. func (channel *Channel) GetModelMapping() string {
  195. if channel.ModelMapping == nil {
  196. return ""
  197. }
  198. return *channel.ModelMapping
  199. }
  200. func (channel *Channel) GetStatusCodeMapping() string {
  201. if channel.StatusCodeMapping == nil {
  202. return ""
  203. }
  204. return *channel.StatusCodeMapping
  205. }
  206. func (channel *Channel) Insert() error {
  207. var err error
  208. err = DB.Create(channel).Error
  209. if err != nil {
  210. return err
  211. }
  212. err = channel.AddAbilities()
  213. return err
  214. }
  215. func (channel *Channel) Update() error {
  216. var err error
  217. err = DB.Model(channel).Updates(channel).Error
  218. if err != nil {
  219. return err
  220. }
  221. DB.Model(channel).First(channel, "id = ?", channel.Id)
  222. err = channel.UpdateAbilities()
  223. return err
  224. }
  225. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  226. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  227. TestTime: common.GetTimestamp(),
  228. ResponseTime: int(responseTime),
  229. }).Error
  230. if err != nil {
  231. common.SysError("failed to update response time: " + err.Error())
  232. }
  233. }
  234. func (channel *Channel) UpdateBalance(balance float64) {
  235. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  236. BalanceUpdatedTime: common.GetTimestamp(),
  237. Balance: balance,
  238. }).Error
  239. if err != nil {
  240. common.SysError("failed to update balance: " + err.Error())
  241. }
  242. }
  243. func (channel *Channel) Delete() error {
  244. var err error
  245. err = DB.Delete(channel).Error
  246. if err != nil {
  247. return err
  248. }
  249. err = channel.DeleteAbilities()
  250. return err
  251. }
  252. func UpdateChannelStatusById(id int, status int, reason string) {
  253. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  254. if err != nil {
  255. common.SysError("failed to update ability status: " + err.Error())
  256. }
  257. channel, err := GetChannelById(id, true)
  258. if err != nil {
  259. // find channel by id error, directly update status
  260. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  261. if err != nil {
  262. common.SysError("failed to update channel status: " + err.Error())
  263. }
  264. } else {
  265. // find channel by id success, update status and other info
  266. info := channel.GetOtherInfo()
  267. info["status_reason"] = reason
  268. info["status_time"] = common.GetTimestamp()
  269. channel.SetOtherInfo(info)
  270. channel.Status = status
  271. err = channel.Save()
  272. if err != nil {
  273. common.SysError("failed to update channel status: " + err.Error())
  274. }
  275. }
  276. }
  277. func EnableChannelByTag(tag string) error {
  278. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  279. if err != nil {
  280. return err
  281. }
  282. err = UpdateAbilityStatusByTag(tag, true)
  283. return err
  284. }
  285. func DisableChannelByTag(tag string) error {
  286. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  287. if err != nil {
  288. return err
  289. }
  290. err = UpdateAbilityStatusByTag(tag, false)
  291. return err
  292. }
  293. func EditChannelByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  294. updateData := Channel{}
  295. if newTag != nil {
  296. updateData.Tag = newTag
  297. }
  298. if priority != nil {
  299. updateData.Priority = priority
  300. }
  301. if weight != nil {
  302. updateData.Weight = weight
  303. }
  304. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  305. if err != nil {
  306. return err
  307. }
  308. return UpdateAbilityByTag(tag, newTag, priority, weight)
  309. }
  310. func UpdateChannelUsedQuota(id int, quota int) {
  311. if common.BatchUpdateEnabled {
  312. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  313. return
  314. }
  315. updateChannelUsedQuota(id, quota)
  316. }
  317. func updateChannelUsedQuota(id int, quota int) {
  318. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  319. if err != nil {
  320. common.SysError("failed to update channel used quota: " + err.Error())
  321. }
  322. }
  323. func DeleteChannelByStatus(status int64) (int64, error) {
  324. result := DB.Where("status = ?", status).Delete(&Channel{})
  325. return result.RowsAffected, result.Error
  326. }
  327. func DeleteDisabledChannel() (int64, error) {
  328. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  329. return result.RowsAffected, result.Error
  330. }