channel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package model
  2. import (
  3. "encoding/json"
  4. "one-api/common"
  5. "strings"
  6. "sync"
  7. "gorm.io/gorm"
  8. )
  9. type Channel struct {
  10. Id int `json:"id"`
  11. Type int `json:"type" gorm:"default:0"`
  12. Key string `json:"key" gorm:"not null"`
  13. OpenAIOrganization *string `json:"openai_organization"`
  14. TestModel *string `json:"test_model"`
  15. Status int `json:"status" gorm:"default:1"`
  16. Name string `json:"name" gorm:"index"`
  17. Weight *uint `json:"weight" gorm:"default:0"`
  18. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  19. TestTime int64 `json:"test_time" gorm:"bigint"`
  20. ResponseTime int `json:"response_time"` // in milliseconds
  21. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  22. Other string `json:"other"`
  23. Balance float64 `json:"balance"` // in USD
  24. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  25. Models string `json:"models"`
  26. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  27. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  28. ModelMapping *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
  29. //MaxInputTokens *int `json:"max_input_tokens" gorm:"default:0"`
  30. StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
  31. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  32. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  33. OtherInfo string `json:"other_info"`
  34. Tag *string `json:"tag" gorm:"index"`
  35. Setting string `json:"setting" gorm:"type:text"`
  36. }
  37. func (channel *Channel) GetModels() []string {
  38. if channel.Models == "" {
  39. return []string{}
  40. }
  41. return strings.Split(strings.Trim(channel.Models, ","), ",")
  42. }
  43. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  44. otherInfo := make(map[string]interface{})
  45. if channel.OtherInfo != "" {
  46. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  47. if err != nil {
  48. common.SysError("failed to unmarshal other info: " + err.Error())
  49. }
  50. }
  51. return otherInfo
  52. }
  53. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  54. otherInfoBytes, err := json.Marshal(otherInfo)
  55. if err != nil {
  56. common.SysError("failed to marshal other info: " + err.Error())
  57. return
  58. }
  59. channel.OtherInfo = string(otherInfoBytes)
  60. }
  61. func (channel *Channel) GetTag() string {
  62. if channel.Tag == nil {
  63. return ""
  64. }
  65. return *channel.Tag
  66. }
  67. func (channel *Channel) SetTag(tag string) {
  68. channel.Tag = &tag
  69. }
  70. func (channel *Channel) GetAutoBan() bool {
  71. if channel.AutoBan == nil {
  72. return false
  73. }
  74. return *channel.AutoBan == 1
  75. }
  76. func (channel *Channel) Save() error {
  77. return DB.Save(channel).Error
  78. }
  79. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  80. var channels []*Channel
  81. var err error
  82. order := "priority desc"
  83. if idSort {
  84. order = "id desc"
  85. }
  86. if selectAll {
  87. err = DB.Order(order).Find(&channels).Error
  88. } else {
  89. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  90. }
  91. return channels, err
  92. }
  93. func GetChannelsByTag(tag string, idSort bool) ([]*Channel, error) {
  94. var channels []*Channel
  95. order := "priority desc"
  96. if idSort {
  97. order = "id desc"
  98. }
  99. err := DB.Where("tag = ?", tag).Order(order).Find(&channels).Error
  100. return channels, err
  101. }
  102. func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error) {
  103. var channels []*Channel
  104. modelsCol := "`models`"
  105. // 如果是 PostgreSQL,使用双引号
  106. if common.UsingPostgreSQL {
  107. keyCol = `"key"`
  108. }
  109. order := "priority desc"
  110. if idSort {
  111. order = "id desc"
  112. }
  113. // 构造基础查询
  114. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  115. // 构造WHERE子句
  116. var whereClause string
  117. var args []interface{}
  118. if group != "" && group != "null" {
  119. var groupCondition string
  120. if common.UsingMySQL {
  121. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  122. } else {
  123. // sqlite, PostgreSQL
  124. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  125. }
  126. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  127. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  128. } else {
  129. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  130. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  131. }
  132. // 执行查询
  133. err := baseQuery.Where(whereClause, args...).Order(order).Find(&channels).Error
  134. if err != nil {
  135. return nil, err
  136. }
  137. return channels, nil
  138. }
  139. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  140. channel := Channel{Id: id}
  141. var err error = nil
  142. if selectAll {
  143. err = DB.First(&channel, "id = ?", id).Error
  144. } else {
  145. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  146. }
  147. return &channel, err
  148. }
  149. func BatchInsertChannels(channels []Channel) error {
  150. var err error
  151. err = DB.Create(&channels).Error
  152. if err != nil {
  153. return err
  154. }
  155. for _, channel_ := range channels {
  156. err = channel_.AddAbilities()
  157. if err != nil {
  158. return err
  159. }
  160. }
  161. return nil
  162. }
  163. func BatchDeleteChannels(ids []int) error {
  164. //使用事务 删除channel表和channel_ability表
  165. tx := DB.Begin()
  166. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  167. if err != nil {
  168. // 回滚事务
  169. tx.Rollback()
  170. return err
  171. }
  172. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  173. if err != nil {
  174. // 回滚事务
  175. tx.Rollback()
  176. return err
  177. }
  178. // 提交事务
  179. tx.Commit()
  180. return err
  181. }
  182. func (channel *Channel) GetPriority() int64 {
  183. if channel.Priority == nil {
  184. return 0
  185. }
  186. return *channel.Priority
  187. }
  188. func (channel *Channel) GetWeight() int {
  189. if channel.Weight == nil {
  190. return 0
  191. }
  192. return int(*channel.Weight)
  193. }
  194. func (channel *Channel) GetBaseURL() string {
  195. if channel.BaseURL == nil {
  196. return ""
  197. }
  198. return *channel.BaseURL
  199. }
  200. func (channel *Channel) GetModelMapping() string {
  201. if channel.ModelMapping == nil {
  202. return ""
  203. }
  204. return *channel.ModelMapping
  205. }
  206. func (channel *Channel) GetStatusCodeMapping() string {
  207. if channel.StatusCodeMapping == nil {
  208. return ""
  209. }
  210. return *channel.StatusCodeMapping
  211. }
  212. func (channel *Channel) Insert() error {
  213. var err error
  214. err = DB.Create(channel).Error
  215. if err != nil {
  216. return err
  217. }
  218. err = channel.AddAbilities()
  219. return err
  220. }
  221. func (channel *Channel) Update() error {
  222. var err error
  223. err = DB.Model(channel).Updates(channel).Error
  224. if err != nil {
  225. return err
  226. }
  227. DB.Model(channel).First(channel, "id = ?", channel.Id)
  228. err = channel.UpdateAbilities(nil)
  229. return err
  230. }
  231. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  232. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  233. TestTime: common.GetTimestamp(),
  234. ResponseTime: int(responseTime),
  235. }).Error
  236. if err != nil {
  237. common.SysError("failed to update response time: " + err.Error())
  238. }
  239. }
  240. func (channel *Channel) UpdateBalance(balance float64) {
  241. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  242. BalanceUpdatedTime: common.GetTimestamp(),
  243. Balance: balance,
  244. }).Error
  245. if err != nil {
  246. common.SysError("failed to update balance: " + err.Error())
  247. }
  248. }
  249. func (channel *Channel) Delete() error {
  250. var err error
  251. err = DB.Delete(channel).Error
  252. if err != nil {
  253. return err
  254. }
  255. err = channel.DeleteAbilities()
  256. return err
  257. }
  258. var channelStatusLock sync.Mutex
  259. func UpdateChannelStatusById(id int, status int, reason string) {
  260. if common.MemoryCacheEnabled {
  261. channelStatusLock.Lock()
  262. channelCache, _ := CacheGetChannel(id)
  263. // 如果缓存渠道存在,且状态已是目标状态,直接返回
  264. if channelCache != nil && channelCache.Status == status {
  265. channelStatusLock.Unlock()
  266. return
  267. }
  268. // 如果缓存渠道不存在(说明已经被禁用),且要设置的状态不为启用,直接返回
  269. if channelCache == nil && status != common.ChannelStatusEnabled {
  270. channelStatusLock.Unlock()
  271. return
  272. }
  273. CacheUpdateChannelStatus(id, status)
  274. channelStatusLock.Unlock()
  275. }
  276. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  277. if err != nil {
  278. common.SysError("failed to update ability status: " + err.Error())
  279. }
  280. channel, err := GetChannelById(id, true)
  281. if err != nil {
  282. // find channel by id error, directly update status
  283. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  284. if err != nil {
  285. common.SysError("failed to update channel status: " + err.Error())
  286. }
  287. } else {
  288. // find channel by id success, update status and other info
  289. info := channel.GetOtherInfo()
  290. info["status_reason"] = reason
  291. info["status_time"] = common.GetTimestamp()
  292. channel.SetOtherInfo(info)
  293. channel.Status = status
  294. err = channel.Save()
  295. if err != nil {
  296. common.SysError("failed to update channel status: " + err.Error())
  297. }
  298. }
  299. }
  300. func EnableChannelByTag(tag string) error {
  301. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  302. if err != nil {
  303. return err
  304. }
  305. err = UpdateAbilityStatusByTag(tag, true)
  306. return err
  307. }
  308. func DisableChannelByTag(tag string) error {
  309. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  310. if err != nil {
  311. return err
  312. }
  313. err = UpdateAbilityStatusByTag(tag, false)
  314. return err
  315. }
  316. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  317. updateData := Channel{}
  318. shouldReCreateAbilities := false
  319. updatedTag := tag
  320. // 如果 newTag 不为空且不等于 tag,则更新 tag
  321. if newTag != nil && *newTag != tag {
  322. updateData.Tag = newTag
  323. updatedTag = *newTag
  324. }
  325. if modelMapping != nil && *modelMapping != "" {
  326. updateData.ModelMapping = modelMapping
  327. }
  328. if models != nil && *models != "" {
  329. shouldReCreateAbilities = true
  330. updateData.Models = *models
  331. }
  332. if group != nil && *group != "" {
  333. shouldReCreateAbilities = true
  334. updateData.Group = *group
  335. }
  336. if priority != nil {
  337. updateData.Priority = priority
  338. }
  339. if weight != nil {
  340. updateData.Weight = weight
  341. }
  342. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  343. if err != nil {
  344. return err
  345. }
  346. if shouldReCreateAbilities {
  347. channels, err := GetChannelsByTag(updatedTag, false)
  348. if err == nil {
  349. for _, channel := range channels {
  350. err = channel.UpdateAbilities(nil)
  351. if err != nil {
  352. common.SysError("failed to update abilities: " + err.Error())
  353. }
  354. }
  355. }
  356. } else {
  357. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  358. if err != nil {
  359. return err
  360. }
  361. }
  362. return nil
  363. }
  364. func UpdateChannelUsedQuota(id int, quota int) {
  365. if common.BatchUpdateEnabled {
  366. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  367. return
  368. }
  369. updateChannelUsedQuota(id, quota)
  370. }
  371. func updateChannelUsedQuota(id int, quota int) {
  372. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  373. if err != nil {
  374. common.SysError("failed to update channel used quota: " + err.Error())
  375. }
  376. }
  377. func DeleteChannelByStatus(status int64) (int64, error) {
  378. result := DB.Where("status = ?", status).Delete(&Channel{})
  379. return result.RowsAffected, result.Error
  380. }
  381. func DeleteDisabledChannel() (int64, error) {
  382. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  383. return result.RowsAffected, result.Error
  384. }
  385. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  386. var tags []*string
  387. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  388. return tags, err
  389. }
  390. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  391. var tags []*string
  392. modelsCol := "`models`"
  393. // 如果是 PostgreSQL,使用双引号
  394. if common.UsingPostgreSQL {
  395. modelsCol = `"models"`
  396. }
  397. order := "priority desc"
  398. if idSort {
  399. order = "id desc"
  400. }
  401. // 构造基础查询
  402. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  403. // 构造WHERE子句
  404. var whereClause string
  405. var args []interface{}
  406. if group != "" && group != "null" {
  407. var groupCondition string
  408. if common.UsingMySQL {
  409. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  410. } else {
  411. // sqlite, PostgreSQL
  412. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  413. }
  414. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  415. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  416. } else {
  417. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  418. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  419. }
  420. subQuery := baseQuery.Where(whereClause, args...).
  421. Select("tag").
  422. Where("tag != ''").
  423. Order(order)
  424. err := DB.Table("(?) as sub", subQuery).
  425. Select("DISTINCT tag").
  426. Find(&tags).Error
  427. if err != nil {
  428. return nil, err
  429. }
  430. return tags, nil
  431. }
  432. func (channel *Channel) GetSetting() map[string]interface{} {
  433. setting := make(map[string]interface{})
  434. if channel.Setting != "" {
  435. err := json.Unmarshal([]byte(channel.Setting), &setting)
  436. if err != nil {
  437. common.SysError("failed to unmarshal setting: " + err.Error())
  438. }
  439. }
  440. return setting
  441. }
  442. func (channel *Channel) SetSetting(setting map[string]interface{}) {
  443. settingBytes, err := json.Marshal(setting)
  444. if err != nil {
  445. common.SysError("failed to marshal setting: " + err.Error())
  446. return
  447. }
  448. channel.Setting = string(settingBytes)
  449. }
  450. func GetChannelsByIds(ids []int) ([]*Channel, error) {
  451. var channels []*Channel
  452. err := DB.Where("id in (?)", ids).Find(&channels).Error
  453. return channels, err
  454. }
  455. func BatchSetChannelTag(ids []int, tag *string) error {
  456. // 开启事务
  457. tx := DB.Begin()
  458. if tx.Error != nil {
  459. return tx.Error
  460. }
  461. // 更新标签
  462. err := tx.Model(&Channel{}).Where("id in (?)", ids).Update("tag", tag).Error
  463. if err != nil {
  464. tx.Rollback()
  465. return err
  466. }
  467. // update ability status
  468. channels, err := GetChannelsByIds(ids)
  469. if err != nil {
  470. tx.Rollback()
  471. return err
  472. }
  473. for _, channel := range channels {
  474. err = channel.UpdateAbilities(tx)
  475. if err != nil {
  476. tx.Rollback()
  477. return err
  478. }
  479. }
  480. // 提交事务
  481. return tx.Commit().Error
  482. }