channel.go 15 KB

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