channel.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. }
  35. func (channel *Channel) GetModels() []string {
  36. if channel.Models == "" {
  37. return []string{}
  38. }
  39. return strings.Split(strings.Trim(channel.Models, ","), ",")
  40. }
  41. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  42. otherInfo := make(map[string]interface{})
  43. if channel.OtherInfo != "" {
  44. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  45. if err != nil {
  46. common.SysError("failed to unmarshal other info: " + err.Error())
  47. }
  48. }
  49. return otherInfo
  50. }
  51. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  52. otherInfoBytes, err := json.Marshal(otherInfo)
  53. if err != nil {
  54. common.SysError("failed to marshal other info: " + err.Error())
  55. return
  56. }
  57. channel.OtherInfo = string(otherInfoBytes)
  58. }
  59. func (channel *Channel) GetTag() string {
  60. if channel.Tag == nil {
  61. return ""
  62. }
  63. return *channel.Tag
  64. }
  65. func (channel *Channel) SetTag(tag string) {
  66. channel.Tag = &tag
  67. }
  68. func (channel *Channel) GetAutoBan() bool {
  69. if channel.AutoBan == nil {
  70. return false
  71. }
  72. return *channel.AutoBan == 1
  73. }
  74. func (channel *Channel) Save() error {
  75. return DB.Save(channel).Error
  76. }
  77. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  78. var channels []*Channel
  79. var err error
  80. order := "priority desc"
  81. if idSort {
  82. order = "id desc"
  83. }
  84. if selectAll {
  85. err = DB.Order(order).Find(&channels).Error
  86. } else {
  87. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  88. }
  89. return channels, err
  90. }
  91. func GetChannelsByTag(tag string, idSort bool) ([]*Channel, error) {
  92. var channels []*Channel
  93. order := "priority desc"
  94. if idSort {
  95. order = "id desc"
  96. }
  97. err := DB.Where("tag = ?", tag).Order(order).Find(&channels).Error
  98. return channels, err
  99. }
  100. func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error) {
  101. var channels []*Channel
  102. keyCol := "`key`"
  103. groupCol := "`group`"
  104. modelsCol := "`models`"
  105. // 如果是 PostgreSQL,使用双引号
  106. if common.UsingPostgreSQL {
  107. keyCol = `"key"`
  108. groupCol = `"group"`
  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()
  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. func UpdateChannelStatusById(id int, status int, reason string) {
  261. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  262. if err != nil {
  263. common.SysError("failed to update ability status: " + err.Error())
  264. }
  265. channel, err := GetChannelById(id, true)
  266. if err != nil {
  267. // find channel by id error, directly update status
  268. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  269. if err != nil {
  270. common.SysError("failed to update channel status: " + err.Error())
  271. }
  272. } else {
  273. // find channel by id success, update status and other info
  274. info := channel.GetOtherInfo()
  275. info["status_reason"] = reason
  276. info["status_time"] = common.GetTimestamp()
  277. channel.SetOtherInfo(info)
  278. channel.Status = status
  279. err = channel.Save()
  280. if err != nil {
  281. common.SysError("failed to update channel status: " + err.Error())
  282. }
  283. }
  284. }
  285. func EnableChannelByTag(tag string) error {
  286. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  287. if err != nil {
  288. return err
  289. }
  290. err = UpdateAbilityStatusByTag(tag, true)
  291. return err
  292. }
  293. func DisableChannelByTag(tag string) error {
  294. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  295. if err != nil {
  296. return err
  297. }
  298. err = UpdateAbilityStatusByTag(tag, false)
  299. return err
  300. }
  301. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  302. updateData := Channel{}
  303. shouldReCreateAbilities := false
  304. updatedTag := tag
  305. // 如果 newTag 不为空且不等于 tag,则更新 tag
  306. if newTag != nil && *newTag != tag {
  307. updateData.Tag = newTag
  308. updatedTag = *newTag
  309. }
  310. if modelMapping != nil && *modelMapping != "" {
  311. updateData.ModelMapping = modelMapping
  312. }
  313. if models != nil && *models != "" {
  314. shouldReCreateAbilities = true
  315. updateData.Models = *models
  316. }
  317. if group != nil && *group != "" {
  318. shouldReCreateAbilities = true
  319. updateData.Group = *group
  320. }
  321. if priority != nil {
  322. updateData.Priority = priority
  323. }
  324. if weight != nil {
  325. updateData.Weight = weight
  326. }
  327. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  328. if err != nil {
  329. return err
  330. }
  331. if shouldReCreateAbilities {
  332. channels, err := GetChannelsByTag(updatedTag, false)
  333. if err == nil {
  334. for _, channel := range channels {
  335. err = channel.UpdateAbilities()
  336. if err != nil {
  337. common.SysError("failed to update abilities: " + err.Error())
  338. }
  339. }
  340. }
  341. } else {
  342. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  343. if err != nil {
  344. return err
  345. }
  346. }
  347. return nil
  348. }
  349. func UpdateChannelUsedQuota(id int, quota int) {
  350. if common.BatchUpdateEnabled {
  351. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  352. return
  353. }
  354. updateChannelUsedQuota(id, quota)
  355. }
  356. func updateChannelUsedQuota(id int, quota int) {
  357. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  358. if err != nil {
  359. common.SysError("failed to update channel used quota: " + err.Error())
  360. }
  361. }
  362. func DeleteChannelByStatus(status int64) (int64, error) {
  363. result := DB.Where("status = ?", status).Delete(&Channel{})
  364. return result.RowsAffected, result.Error
  365. }
  366. func DeleteDisabledChannel() (int64, error) {
  367. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  368. return result.RowsAffected, result.Error
  369. }
  370. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  371. var tags []*string
  372. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  373. return tags, err
  374. }
  375. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  376. var tags []*string
  377. keyCol := "`key`"
  378. groupCol := "`group`"
  379. modelsCol := "`models`"
  380. // 如果是 PostgreSQL,使用双引号
  381. if common.UsingPostgreSQL {
  382. keyCol = `"key"`
  383. groupCol = `"group"`
  384. modelsCol = `"models"`
  385. }
  386. order := "priority desc"
  387. if idSort {
  388. order = "id desc"
  389. }
  390. // 构造基础查询
  391. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  392. // 构造WHERE子句
  393. var whereClause string
  394. var args []interface{}
  395. if group != "" && group != "null" {
  396. var groupCondition string
  397. if common.UsingMySQL {
  398. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  399. } else {
  400. // sqlite, PostgreSQL
  401. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  402. }
  403. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  404. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  405. } else {
  406. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  407. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  408. }
  409. subQuery := baseQuery.Where(whereClause, args...).
  410. Select("tag").
  411. Where("tag != ''").
  412. Order(order)
  413. err := DB.Table("(?) as sub", subQuery).
  414. Select("DISTINCT tag").
  415. Find(&tags).Error
  416. if err != nil {
  417. return nil, err
  418. }
  419. return tags, nil
  420. }