channel.go 15 KB

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