channel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. modelsCol = `"models"`
  109. }
  110. order := "priority desc"
  111. if idSort {
  112. order = "id desc"
  113. }
  114. // 构造基础查询
  115. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  116. // 构造WHERE子句
  117. var whereClause string
  118. var args []interface{}
  119. if group != "" && group != "null" {
  120. var groupCondition string
  121. if common.UsingMySQL {
  122. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  123. } else {
  124. // sqlite, PostgreSQL
  125. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  126. }
  127. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  128. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  129. } else {
  130. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  131. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  132. }
  133. // 执行查询
  134. err := baseQuery.Where(whereClause, args...).Order(order).Find(&channels).Error
  135. if err != nil {
  136. return nil, err
  137. }
  138. return channels, nil
  139. }
  140. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  141. channel := Channel{Id: id}
  142. var err error = nil
  143. if selectAll {
  144. err = DB.First(&channel, "id = ?", id).Error
  145. } else {
  146. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  147. }
  148. return &channel, err
  149. }
  150. func BatchInsertChannels(channels []Channel) error {
  151. var err error
  152. err = DB.Create(&channels).Error
  153. if err != nil {
  154. return err
  155. }
  156. for _, channel_ := range channels {
  157. err = channel_.AddAbilities()
  158. if err != nil {
  159. return err
  160. }
  161. }
  162. return nil
  163. }
  164. func BatchDeleteChannels(ids []int) error {
  165. //使用事务 删除channel表和channel_ability表
  166. tx := DB.Begin()
  167. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  168. if err != nil {
  169. // 回滚事务
  170. tx.Rollback()
  171. return err
  172. }
  173. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  174. if err != nil {
  175. // 回滚事务
  176. tx.Rollback()
  177. return err
  178. }
  179. // 提交事务
  180. tx.Commit()
  181. return err
  182. }
  183. func (channel *Channel) GetPriority() int64 {
  184. if channel.Priority == nil {
  185. return 0
  186. }
  187. return *channel.Priority
  188. }
  189. func (channel *Channel) GetWeight() int {
  190. if channel.Weight == nil {
  191. return 0
  192. }
  193. return int(*channel.Weight)
  194. }
  195. func (channel *Channel) GetBaseURL() string {
  196. if channel.BaseURL == nil {
  197. return ""
  198. }
  199. return *channel.BaseURL
  200. }
  201. func (channel *Channel) GetModelMapping() string {
  202. if channel.ModelMapping == nil {
  203. return ""
  204. }
  205. return *channel.ModelMapping
  206. }
  207. func (channel *Channel) GetStatusCodeMapping() string {
  208. if channel.StatusCodeMapping == nil {
  209. return ""
  210. }
  211. return *channel.StatusCodeMapping
  212. }
  213. func (channel *Channel) Insert() error {
  214. var err error
  215. err = DB.Create(channel).Error
  216. if err != nil {
  217. return err
  218. }
  219. err = channel.AddAbilities()
  220. return err
  221. }
  222. func (channel *Channel) Update() error {
  223. var err error
  224. err = DB.Model(channel).Updates(channel).Error
  225. if err != nil {
  226. return err
  227. }
  228. DB.Model(channel).First(channel, "id = ?", channel.Id)
  229. err = channel.UpdateAbilities(nil)
  230. return err
  231. }
  232. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  233. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  234. TestTime: common.GetTimestamp(),
  235. ResponseTime: int(responseTime),
  236. }).Error
  237. if err != nil {
  238. common.SysError("failed to update response time: " + err.Error())
  239. }
  240. }
  241. func (channel *Channel) UpdateBalance(balance float64) {
  242. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  243. BalanceUpdatedTime: common.GetTimestamp(),
  244. Balance: balance,
  245. }).Error
  246. if err != nil {
  247. common.SysError("failed to update balance: " + err.Error())
  248. }
  249. }
  250. func (channel *Channel) Delete() error {
  251. var err error
  252. err = DB.Delete(channel).Error
  253. if err != nil {
  254. return err
  255. }
  256. err = channel.DeleteAbilities()
  257. return err
  258. }
  259. var channelStatusLock sync.Mutex
  260. func UpdateChannelStatusById(id int, status int, reason string) {
  261. if common.MemoryCacheEnabled {
  262. channelStatusLock.Lock()
  263. channelCache, _ := CacheGetChannel(id)
  264. // 如果缓存渠道存在,且状态已是目标状态,直接返回
  265. if channelCache != nil && channelCache.Status == status {
  266. channelStatusLock.Unlock()
  267. return
  268. }
  269. // 如果缓存渠道不存在(说明已经被禁用),且要设置的状态不为启用,直接返回
  270. if channelCache == nil && status != common.ChannelStatusEnabled {
  271. channelStatusLock.Unlock()
  272. return
  273. }
  274. CacheUpdateChannelStatus(id, status)
  275. channelStatusLock.Unlock()
  276. }
  277. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  278. if err != nil {
  279. common.SysError("failed to update ability status: " + err.Error())
  280. }
  281. channel, err := GetChannelById(id, true)
  282. if err != nil {
  283. // find channel by id error, directly update status
  284. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  285. if err != nil {
  286. common.SysError("failed to update channel status: " + err.Error())
  287. }
  288. } else {
  289. // find channel by id success, update status and other info
  290. info := channel.GetOtherInfo()
  291. info["status_reason"] = reason
  292. info["status_time"] = common.GetTimestamp()
  293. channel.SetOtherInfo(info)
  294. channel.Status = status
  295. err = channel.Save()
  296. if err != nil {
  297. common.SysError("failed to update channel status: " + err.Error())
  298. }
  299. }
  300. }
  301. func EnableChannelByTag(tag string) error {
  302. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  303. if err != nil {
  304. return err
  305. }
  306. err = UpdateAbilityStatusByTag(tag, true)
  307. return err
  308. }
  309. func DisableChannelByTag(tag string) error {
  310. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  311. if err != nil {
  312. return err
  313. }
  314. err = UpdateAbilityStatusByTag(tag, false)
  315. return err
  316. }
  317. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  318. updateData := Channel{}
  319. shouldReCreateAbilities := false
  320. updatedTag := tag
  321. // 如果 newTag 不为空且不等于 tag,则更新 tag
  322. if newTag != nil && *newTag != tag {
  323. updateData.Tag = newTag
  324. updatedTag = *newTag
  325. }
  326. if modelMapping != nil && *modelMapping != "" {
  327. updateData.ModelMapping = modelMapping
  328. }
  329. if models != nil && *models != "" {
  330. shouldReCreateAbilities = true
  331. updateData.Models = *models
  332. }
  333. if group != nil && *group != "" {
  334. shouldReCreateAbilities = true
  335. updateData.Group = *group
  336. }
  337. if priority != nil {
  338. updateData.Priority = priority
  339. }
  340. if weight != nil {
  341. updateData.Weight = weight
  342. }
  343. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  344. if err != nil {
  345. return err
  346. }
  347. if shouldReCreateAbilities {
  348. channels, err := GetChannelsByTag(updatedTag, false)
  349. if err == nil {
  350. for _, channel := range channels {
  351. err = channel.UpdateAbilities(nil)
  352. if err != nil {
  353. common.SysError("failed to update abilities: " + err.Error())
  354. }
  355. }
  356. }
  357. } else {
  358. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  359. if err != nil {
  360. return err
  361. }
  362. }
  363. return nil
  364. }
  365. func UpdateChannelUsedQuota(id int, quota int) {
  366. if common.BatchUpdateEnabled {
  367. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  368. return
  369. }
  370. updateChannelUsedQuota(id, quota)
  371. }
  372. func updateChannelUsedQuota(id int, quota int) {
  373. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  374. if err != nil {
  375. common.SysError("failed to update channel used quota: " + err.Error())
  376. }
  377. }
  378. func DeleteChannelByStatus(status int64) (int64, error) {
  379. result := DB.Where("status = ?", status).Delete(&Channel{})
  380. return result.RowsAffected, result.Error
  381. }
  382. func DeleteDisabledChannel() (int64, error) {
  383. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  384. return result.RowsAffected, result.Error
  385. }
  386. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  387. var tags []*string
  388. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  389. return tags, err
  390. }
  391. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  392. var tags []*string
  393. modelsCol := "`models`"
  394. // 如果是 PostgreSQL,使用双引号
  395. if common.UsingPostgreSQL {
  396. modelsCol = `"models"`
  397. }
  398. order := "priority desc"
  399. if idSort {
  400. order = "id desc"
  401. }
  402. // 构造基础查询
  403. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  404. // 构造WHERE子句
  405. var whereClause string
  406. var args []interface{}
  407. if group != "" && group != "null" {
  408. var groupCondition string
  409. if common.UsingMySQL {
  410. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  411. } else {
  412. // sqlite, PostgreSQL
  413. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  414. }
  415. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  416. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  417. } else {
  418. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  419. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  420. }
  421. subQuery := baseQuery.Where(whereClause, args...).
  422. Select("tag").
  423. Where("tag != ''").
  424. Order(order)
  425. err := DB.Table("(?) as sub", subQuery).
  426. Select("DISTINCT tag").
  427. Find(&tags).Error
  428. if err != nil {
  429. return nil, err
  430. }
  431. return tags, nil
  432. }
  433. func (channel *Channel) GetSetting() map[string]interface{} {
  434. setting := make(map[string]interface{})
  435. if channel.Setting != "" {
  436. err := json.Unmarshal([]byte(channel.Setting), &setting)
  437. if err != nil {
  438. common.SysError("failed to unmarshal setting: " + err.Error())
  439. }
  440. }
  441. return setting
  442. }
  443. func (channel *Channel) SetSetting(setting map[string]interface{}) {
  444. settingBytes, err := json.Marshal(setting)
  445. if err != nil {
  446. common.SysError("failed to marshal setting: " + err.Error())
  447. return
  448. }
  449. channel.Setting = string(settingBytes)
  450. }
  451. func GetChannelsByIds(ids []int) ([]*Channel, error) {
  452. var channels []*Channel
  453. err := DB.Where("id in (?)", ids).Find(&channels).Error
  454. return channels, err
  455. }
  456. func BatchSetChannelTag(ids []int, tag *string) error {
  457. // 开启事务
  458. tx := DB.Begin()
  459. if tx.Error != nil {
  460. return tx.Error
  461. }
  462. // 更新标签
  463. err := tx.Model(&Channel{}).Where("id in (?)", ids).Update("tag", tag).Error
  464. if err != nil {
  465. tx.Rollback()
  466. return err
  467. }
  468. // update ability status
  469. channels, err := GetChannelsByIds(ids)
  470. if err != nil {
  471. tx.Rollback()
  472. return err
  473. }
  474. for _, channel := range channels {
  475. err = channel.UpdateAbilities(tx)
  476. if err != nil {
  477. tx.Rollback()
  478. return err
  479. }
  480. }
  481. // 提交事务
  482. return tx.Commit().Error
  483. }