channel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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, err := CacheGetChannel(id)
  267. // 如果缓存渠道不存在或渠道已是目标状态,直接返回
  268. if err != nil || channelCache.Status == status {
  269. channelStatusLock.Unlock()
  270. return
  271. }
  272. CacheUpdateChannelStatus(id, status)
  273. channelStatusLock.Unlock()
  274. }
  275. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  276. if err != nil {
  277. common.SysError("failed to update ability status: " + err.Error())
  278. }
  279. channel, err := GetChannelById(id, true)
  280. if err != nil {
  281. // find channel by id error, directly update status
  282. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  283. if err != nil {
  284. common.SysError("failed to update channel status: " + err.Error())
  285. }
  286. } else {
  287. // find channel by id success, update status and other info
  288. info := channel.GetOtherInfo()
  289. info["status_reason"] = reason
  290. info["status_time"] = common.GetTimestamp()
  291. channel.SetOtherInfo(info)
  292. channel.Status = status
  293. err = channel.Save()
  294. if err != nil {
  295. common.SysError("failed to update channel status: " + err.Error())
  296. }
  297. }
  298. }
  299. func EnableChannelByTag(tag string) error {
  300. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  301. if err != nil {
  302. return err
  303. }
  304. err = UpdateAbilityStatusByTag(tag, true)
  305. return err
  306. }
  307. func DisableChannelByTag(tag string) error {
  308. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  309. if err != nil {
  310. return err
  311. }
  312. err = UpdateAbilityStatusByTag(tag, false)
  313. return err
  314. }
  315. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  316. updateData := Channel{}
  317. shouldReCreateAbilities := false
  318. updatedTag := tag
  319. // 如果 newTag 不为空且不等于 tag,则更新 tag
  320. if newTag != nil && *newTag != tag {
  321. updateData.Tag = newTag
  322. updatedTag = *newTag
  323. }
  324. if modelMapping != nil && *modelMapping != "" {
  325. updateData.ModelMapping = modelMapping
  326. }
  327. if models != nil && *models != "" {
  328. shouldReCreateAbilities = true
  329. updateData.Models = *models
  330. }
  331. if group != nil && *group != "" {
  332. shouldReCreateAbilities = true
  333. updateData.Group = *group
  334. }
  335. if priority != nil {
  336. updateData.Priority = priority
  337. }
  338. if weight != nil {
  339. updateData.Weight = weight
  340. }
  341. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  342. if err != nil {
  343. return err
  344. }
  345. if shouldReCreateAbilities {
  346. channels, err := GetChannelsByTag(updatedTag, false)
  347. if err == nil {
  348. for _, channel := range channels {
  349. err = channel.UpdateAbilities()
  350. if err != nil {
  351. common.SysError("failed to update abilities: " + err.Error())
  352. }
  353. }
  354. }
  355. } else {
  356. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  357. if err != nil {
  358. return err
  359. }
  360. }
  361. return nil
  362. }
  363. func UpdateChannelUsedQuota(id int, quota int) {
  364. if common.BatchUpdateEnabled {
  365. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  366. return
  367. }
  368. updateChannelUsedQuota(id, quota)
  369. }
  370. func updateChannelUsedQuota(id int, quota int) {
  371. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  372. if err != nil {
  373. common.SysError("failed to update channel used quota: " + err.Error())
  374. }
  375. }
  376. func DeleteChannelByStatus(status int64) (int64, error) {
  377. result := DB.Where("status = ?", status).Delete(&Channel{})
  378. return result.RowsAffected, result.Error
  379. }
  380. func DeleteDisabledChannel() (int64, error) {
  381. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  382. return result.RowsAffected, result.Error
  383. }
  384. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  385. var tags []*string
  386. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  387. return tags, err
  388. }
  389. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  390. var tags []*string
  391. keyCol := "`key`"
  392. groupCol := "`group`"
  393. modelsCol := "`models`"
  394. // 如果是 PostgreSQL,使用双引号
  395. if common.UsingPostgreSQL {
  396. keyCol = `"key"`
  397. groupCol = `"group"`
  398. modelsCol = `"models"`
  399. }
  400. order := "priority desc"
  401. if idSort {
  402. order = "id desc"
  403. }
  404. // 构造基础查询
  405. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  406. // 构造WHERE子句
  407. var whereClause string
  408. var args []interface{}
  409. if group != "" && group != "null" {
  410. var groupCondition string
  411. if common.UsingMySQL {
  412. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  413. } else {
  414. // sqlite, PostgreSQL
  415. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  416. }
  417. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  418. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  419. } else {
  420. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  421. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  422. }
  423. subQuery := baseQuery.Where(whereClause, args...).
  424. Select("tag").
  425. Where("tag != ''").
  426. Order(order)
  427. err := DB.Table("(?) as sub", subQuery).
  428. Select("DISTINCT tag").
  429. Find(&tags).Error
  430. if err != nil {
  431. return nil, err
  432. }
  433. return tags, nil
  434. }
  435. func (channel *Channel) GetSetting() map[string]interface{} {
  436. setting := make(map[string]interface{})
  437. if channel.Setting != "" {
  438. err := json.Unmarshal([]byte(channel.Setting), &setting)
  439. if err != nil {
  440. common.SysError("failed to unmarshal setting: " + err.Error())
  441. }
  442. }
  443. return setting
  444. }
  445. func (channel *Channel) SetSetting(setting map[string]interface{}) {
  446. settingBytes, err := json.Marshal(setting)
  447. if err != nil {
  448. common.SysError("failed to marshal setting: " + err.Error())
  449. return
  450. }
  451. channel.Setting = string(settingBytes)
  452. }