channel.go 16 KB

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