channel.go 16 KB

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