channel.go 14 KB

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