channel.go 13 KB

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