channel.go 17 KB

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