channel.go 18 KB

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