channel.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/model"
  9. "strconv"
  10. "strings"
  11. "github.com/gin-gonic/gin"
  12. )
  13. type OpenAIModel struct {
  14. ID string `json:"id"`
  15. Object string `json:"object"`
  16. Created int64 `json:"created"`
  17. OwnedBy string `json:"owned_by"`
  18. Permission []struct {
  19. ID string `json:"id"`
  20. Object string `json:"object"`
  21. Created int64 `json:"created"`
  22. AllowCreateEngine bool `json:"allow_create_engine"`
  23. AllowSampling bool `json:"allow_sampling"`
  24. AllowLogprobs bool `json:"allow_logprobs"`
  25. AllowSearchIndices bool `json:"allow_search_indices"`
  26. AllowView bool `json:"allow_view"`
  27. AllowFineTuning bool `json:"allow_fine_tuning"`
  28. Organization string `json:"organization"`
  29. Group string `json:"group"`
  30. IsBlocking bool `json:"is_blocking"`
  31. } `json:"permission"`
  32. Root string `json:"root"`
  33. Parent string `json:"parent"`
  34. }
  35. type OpenAIModelsResponse struct {
  36. Data []OpenAIModel `json:"data"`
  37. Success bool `json:"success"`
  38. }
  39. func parseStatusFilter(statusParam string) int {
  40. switch strings.ToLower(statusParam) {
  41. case "enabled", "1":
  42. return common.ChannelStatusEnabled
  43. case "disabled", "0":
  44. return 0
  45. default:
  46. return -1
  47. }
  48. }
  49. func GetAllChannels(c *gin.Context) {
  50. pageInfo := common.GetPageQuery(c)
  51. channelData := make([]*model.Channel, 0)
  52. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  53. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  54. statusParam := c.Query("status")
  55. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  56. statusFilter := parseStatusFilter(statusParam)
  57. // type filter
  58. typeStr := c.Query("type")
  59. typeFilter := -1
  60. if typeStr != "" {
  61. if t, err := strconv.Atoi(typeStr); err == nil {
  62. typeFilter = t
  63. }
  64. }
  65. var total int64
  66. if enableTagMode {
  67. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  68. if err != nil {
  69. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  70. return
  71. }
  72. for _, tag := range tags {
  73. if tag == nil || *tag == "" {
  74. continue
  75. }
  76. tagChannels, err := model.GetChannelsByTag(*tag, idSort)
  77. if err != nil {
  78. continue
  79. }
  80. filtered := make([]*model.Channel, 0)
  81. for _, ch := range tagChannels {
  82. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  83. continue
  84. }
  85. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  86. continue
  87. }
  88. if typeFilter >= 0 && ch.Type != typeFilter {
  89. continue
  90. }
  91. filtered = append(filtered, ch)
  92. }
  93. channelData = append(channelData, filtered...)
  94. }
  95. total, _ = model.CountAllTags()
  96. } else {
  97. baseQuery := model.DB.Model(&model.Channel{})
  98. if typeFilter >= 0 {
  99. baseQuery = baseQuery.Where("type = ?", typeFilter)
  100. }
  101. if statusFilter == common.ChannelStatusEnabled {
  102. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  103. } else if statusFilter == 0 {
  104. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  105. }
  106. baseQuery.Count(&total)
  107. order := "priority desc"
  108. if idSort {
  109. order = "id desc"
  110. }
  111. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  112. if err != nil {
  113. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  114. return
  115. }
  116. }
  117. countQuery := model.DB.Model(&model.Channel{})
  118. if statusFilter == common.ChannelStatusEnabled {
  119. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  120. } else if statusFilter == 0 {
  121. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  122. }
  123. var results []struct {
  124. Type int64
  125. Count int64
  126. }
  127. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  128. typeCounts := make(map[int64]int64)
  129. for _, r := range results {
  130. typeCounts[r.Type] = r.Count
  131. }
  132. common.ApiSuccess(c, gin.H{
  133. "items": channelData,
  134. "total": total,
  135. "page": pageInfo.GetPage(),
  136. "page_size": pageInfo.GetPageSize(),
  137. "type_counts": typeCounts,
  138. })
  139. return
  140. }
  141. func FetchUpstreamModels(c *gin.Context) {
  142. id, err := strconv.Atoi(c.Param("id"))
  143. if err != nil {
  144. common.ApiError(c, err)
  145. return
  146. }
  147. channel, err := model.GetChannelById(id, true)
  148. if err != nil {
  149. common.ApiError(c, err)
  150. return
  151. }
  152. baseURL := constant.ChannelBaseURLs[channel.Type]
  153. if channel.GetBaseURL() != "" {
  154. baseURL = channel.GetBaseURL()
  155. }
  156. url := fmt.Sprintf("%s/v1/models", baseURL)
  157. switch channel.Type {
  158. case constant.ChannelTypeGemini:
  159. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  160. case constant.ChannelTypeAli:
  161. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  162. }
  163. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  164. if err != nil {
  165. common.ApiError(c, err)
  166. return
  167. }
  168. var result OpenAIModelsResponse
  169. if err = json.Unmarshal(body, &result); err != nil {
  170. c.JSON(http.StatusOK, gin.H{
  171. "success": false,
  172. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  173. })
  174. return
  175. }
  176. var ids []string
  177. for _, model := range result.Data {
  178. id := model.ID
  179. if channel.Type == constant.ChannelTypeGemini {
  180. id = strings.TrimPrefix(id, "models/")
  181. }
  182. ids = append(ids, id)
  183. }
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": true,
  186. "message": "",
  187. "data": ids,
  188. })
  189. }
  190. func FixChannelsAbilities(c *gin.Context) {
  191. success, fails, err := model.FixAbility()
  192. if err != nil {
  193. common.ApiError(c, err)
  194. return
  195. }
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": true,
  198. "message": "",
  199. "data": gin.H{
  200. "success": success,
  201. "fails": fails,
  202. },
  203. })
  204. }
  205. func SearchChannels(c *gin.Context) {
  206. keyword := c.Query("keyword")
  207. group := c.Query("group")
  208. modelKeyword := c.Query("model")
  209. statusParam := c.Query("status")
  210. statusFilter := parseStatusFilter(statusParam)
  211. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  212. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  213. channelData := make([]*model.Channel, 0)
  214. if enableTagMode {
  215. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  216. if err != nil {
  217. c.JSON(http.StatusOK, gin.H{
  218. "success": false,
  219. "message": err.Error(),
  220. })
  221. return
  222. }
  223. for _, tag := range tags {
  224. if tag != nil && *tag != "" {
  225. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  226. if err == nil {
  227. channelData = append(channelData, tagChannel...)
  228. }
  229. }
  230. }
  231. } else {
  232. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  233. if err != nil {
  234. c.JSON(http.StatusOK, gin.H{
  235. "success": false,
  236. "message": err.Error(),
  237. })
  238. return
  239. }
  240. channelData = channels
  241. }
  242. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  243. filtered := make([]*model.Channel, 0, len(channelData))
  244. for _, ch := range channelData {
  245. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  246. continue
  247. }
  248. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  249. continue
  250. }
  251. filtered = append(filtered, ch)
  252. }
  253. channelData = filtered
  254. }
  255. // calculate type counts for search results
  256. typeCounts := make(map[int64]int64)
  257. for _, channel := range channelData {
  258. typeCounts[int64(channel.Type)]++
  259. }
  260. typeParam := c.Query("type")
  261. typeFilter := -1
  262. if typeParam != "" {
  263. if tp, err := strconv.Atoi(typeParam); err == nil {
  264. typeFilter = tp
  265. }
  266. }
  267. if typeFilter >= 0 {
  268. filtered := make([]*model.Channel, 0, len(channelData))
  269. for _, ch := range channelData {
  270. if ch.Type == typeFilter {
  271. filtered = append(filtered, ch)
  272. }
  273. }
  274. channelData = filtered
  275. }
  276. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  277. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  278. if page < 1 {
  279. page = 1
  280. }
  281. if pageSize <= 0 {
  282. pageSize = 20
  283. }
  284. total := len(channelData)
  285. startIdx := (page - 1) * pageSize
  286. if startIdx > total {
  287. startIdx = total
  288. }
  289. endIdx := startIdx + pageSize
  290. if endIdx > total {
  291. endIdx = total
  292. }
  293. pagedData := channelData[startIdx:endIdx]
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": true,
  296. "message": "",
  297. "data": gin.H{
  298. "items": pagedData,
  299. "total": total,
  300. "type_counts": typeCounts,
  301. },
  302. })
  303. return
  304. }
  305. func GetChannel(c *gin.Context) {
  306. id, err := strconv.Atoi(c.Param("id"))
  307. if err != nil {
  308. common.ApiError(c, err)
  309. return
  310. }
  311. channel, err := model.GetChannelById(id, false)
  312. if err != nil {
  313. common.ApiError(c, err)
  314. return
  315. }
  316. c.JSON(http.StatusOK, gin.H{
  317. "success": true,
  318. "message": "",
  319. "data": channel,
  320. })
  321. return
  322. }
  323. // validateChannel 通用的渠道校验函数
  324. func validateChannel(channel *model.Channel, isAdd bool) error {
  325. // 校验 channel settings
  326. if err := channel.ValidateSettings(); err != nil {
  327. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  328. }
  329. // 如果是添加操作,检查 channel 和 key 是否为空
  330. if isAdd {
  331. if channel == nil || channel.Key == "" {
  332. return fmt.Errorf("channel cannot be empty")
  333. }
  334. // 检查模型名称长度是否超过 255
  335. for _, m := range channel.GetModels() {
  336. if len(m) > 255 {
  337. return fmt.Errorf("模型名称过长: %s", m)
  338. }
  339. }
  340. }
  341. // VertexAI 特殊校验
  342. if channel.Type == constant.ChannelTypeVertexAi {
  343. if channel.Other == "" {
  344. return fmt.Errorf("部署地区不能为空")
  345. }
  346. regionMap, err := common.StrToMap(channel.Other)
  347. if err != nil {
  348. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  349. }
  350. if regionMap["default"] == nil {
  351. return fmt.Errorf("部署地区必须包含default字段")
  352. }
  353. }
  354. return nil
  355. }
  356. type AddChannelRequest struct {
  357. Mode string `json:"mode"`
  358. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  359. Channel *model.Channel `json:"channel"`
  360. }
  361. func getVertexArrayKeys(keys string) ([]string, error) {
  362. if keys == "" {
  363. return nil, nil
  364. }
  365. var keyArray []interface{}
  366. err := common.Unmarshal([]byte(keys), &keyArray)
  367. if err != nil {
  368. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  369. }
  370. cleanKeys := make([]string, 0, len(keyArray))
  371. for _, key := range keyArray {
  372. var keyStr string
  373. switch v := key.(type) {
  374. case string:
  375. keyStr = strings.TrimSpace(v)
  376. default:
  377. bytes, err := json.Marshal(v)
  378. if err != nil {
  379. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  380. }
  381. keyStr = string(bytes)
  382. }
  383. if keyStr != "" {
  384. cleanKeys = append(cleanKeys, keyStr)
  385. }
  386. }
  387. if len(cleanKeys) == 0 {
  388. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  389. }
  390. return cleanKeys, nil
  391. }
  392. func AddChannel(c *gin.Context) {
  393. addChannelRequest := AddChannelRequest{}
  394. err := c.ShouldBindJSON(&addChannelRequest)
  395. if err != nil {
  396. common.ApiError(c, err)
  397. return
  398. }
  399. // 使用统一的校验函数
  400. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  401. c.JSON(http.StatusOK, gin.H{
  402. "success": false,
  403. "message": err.Error(),
  404. })
  405. return
  406. }
  407. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  408. keys := make([]string, 0)
  409. switch addChannelRequest.Mode {
  410. case "multi_to_single":
  411. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  412. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  413. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  414. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  415. if err != nil {
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": false,
  418. "message": err.Error(),
  419. })
  420. return
  421. }
  422. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  423. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  424. } else {
  425. cleanKeys := make([]string, 0)
  426. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  427. if key == "" {
  428. continue
  429. }
  430. key = strings.TrimSpace(key)
  431. cleanKeys = append(cleanKeys, key)
  432. }
  433. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  434. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  435. }
  436. keys = []string{addChannelRequest.Channel.Key}
  437. case "batch":
  438. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  439. // multi json
  440. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  441. if err != nil {
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": false,
  444. "message": err.Error(),
  445. })
  446. return
  447. }
  448. } else {
  449. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  450. }
  451. case "single":
  452. keys = []string{addChannelRequest.Channel.Key}
  453. default:
  454. c.JSON(http.StatusOK, gin.H{
  455. "success": false,
  456. "message": "不支持的添加模式",
  457. })
  458. return
  459. }
  460. channels := make([]model.Channel, 0, len(keys))
  461. for _, key := range keys {
  462. if key == "" {
  463. continue
  464. }
  465. localChannel := addChannelRequest.Channel
  466. localChannel.Key = key
  467. channels = append(channels, *localChannel)
  468. }
  469. err = model.BatchInsertChannels(channels)
  470. if err != nil {
  471. common.ApiError(c, err)
  472. return
  473. }
  474. c.JSON(http.StatusOK, gin.H{
  475. "success": true,
  476. "message": "",
  477. })
  478. return
  479. }
  480. func DeleteChannel(c *gin.Context) {
  481. id, _ := strconv.Atoi(c.Param("id"))
  482. channel := model.Channel{Id: id}
  483. err := channel.Delete()
  484. if err != nil {
  485. common.ApiError(c, err)
  486. return
  487. }
  488. model.InitChannelCache()
  489. c.JSON(http.StatusOK, gin.H{
  490. "success": true,
  491. "message": "",
  492. })
  493. return
  494. }
  495. func DeleteDisabledChannel(c *gin.Context) {
  496. rows, err := model.DeleteDisabledChannel()
  497. if err != nil {
  498. common.ApiError(c, err)
  499. return
  500. }
  501. model.InitChannelCache()
  502. c.JSON(http.StatusOK, gin.H{
  503. "success": true,
  504. "message": "",
  505. "data": rows,
  506. })
  507. return
  508. }
  509. type ChannelTag struct {
  510. Tag string `json:"tag"`
  511. NewTag *string `json:"new_tag"`
  512. Priority *int64 `json:"priority"`
  513. Weight *uint `json:"weight"`
  514. ModelMapping *string `json:"model_mapping"`
  515. Models *string `json:"models"`
  516. Groups *string `json:"groups"`
  517. }
  518. func DisableTagChannels(c *gin.Context) {
  519. channelTag := ChannelTag{}
  520. err := c.ShouldBindJSON(&channelTag)
  521. if err != nil || channelTag.Tag == "" {
  522. c.JSON(http.StatusOK, gin.H{
  523. "success": false,
  524. "message": "参数错误",
  525. })
  526. return
  527. }
  528. err = model.DisableChannelByTag(channelTag.Tag)
  529. if err != nil {
  530. common.ApiError(c, err)
  531. return
  532. }
  533. model.InitChannelCache()
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "message": "",
  537. })
  538. return
  539. }
  540. func EnableTagChannels(c *gin.Context) {
  541. channelTag := ChannelTag{}
  542. err := c.ShouldBindJSON(&channelTag)
  543. if err != nil || channelTag.Tag == "" {
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": false,
  546. "message": "参数错误",
  547. })
  548. return
  549. }
  550. err = model.EnableChannelByTag(channelTag.Tag)
  551. if err != nil {
  552. common.ApiError(c, err)
  553. return
  554. }
  555. model.InitChannelCache()
  556. c.JSON(http.StatusOK, gin.H{
  557. "success": true,
  558. "message": "",
  559. })
  560. return
  561. }
  562. func EditTagChannels(c *gin.Context) {
  563. channelTag := ChannelTag{}
  564. err := c.ShouldBindJSON(&channelTag)
  565. if err != nil {
  566. c.JSON(http.StatusOK, gin.H{
  567. "success": false,
  568. "message": "参数错误",
  569. })
  570. return
  571. }
  572. if channelTag.Tag == "" {
  573. c.JSON(http.StatusOK, gin.H{
  574. "success": false,
  575. "message": "tag不能为空",
  576. })
  577. return
  578. }
  579. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  580. if err != nil {
  581. common.ApiError(c, err)
  582. return
  583. }
  584. model.InitChannelCache()
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "message": "",
  588. })
  589. return
  590. }
  591. type ChannelBatch struct {
  592. Ids []int `json:"ids"`
  593. Tag *string `json:"tag"`
  594. }
  595. func DeleteChannelBatch(c *gin.Context) {
  596. channelBatch := ChannelBatch{}
  597. err := c.ShouldBindJSON(&channelBatch)
  598. if err != nil || len(channelBatch.Ids) == 0 {
  599. c.JSON(http.StatusOK, gin.H{
  600. "success": false,
  601. "message": "参数错误",
  602. })
  603. return
  604. }
  605. err = model.BatchDeleteChannels(channelBatch.Ids)
  606. if err != nil {
  607. common.ApiError(c, err)
  608. return
  609. }
  610. model.InitChannelCache()
  611. c.JSON(http.StatusOK, gin.H{
  612. "success": true,
  613. "message": "",
  614. "data": len(channelBatch.Ids),
  615. })
  616. return
  617. }
  618. type PatchChannel struct {
  619. model.Channel
  620. MultiKeyMode *string `json:"multi_key_mode"`
  621. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  622. }
  623. func UpdateChannel(c *gin.Context) {
  624. channel := PatchChannel{}
  625. err := c.ShouldBindJSON(&channel)
  626. if err != nil {
  627. common.ApiError(c, err)
  628. return
  629. }
  630. // 使用统一的校验函数
  631. if err := validateChannel(&channel.Channel, false); err != nil {
  632. c.JSON(http.StatusOK, gin.H{
  633. "success": false,
  634. "message": err.Error(),
  635. })
  636. return
  637. }
  638. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  639. originChannel, err := model.GetChannelById(channel.Id, true)
  640. if err != nil {
  641. c.JSON(http.StatusOK, gin.H{
  642. "success": false,
  643. "message": err.Error(),
  644. })
  645. return
  646. }
  647. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  648. channel.ChannelInfo = originChannel.ChannelInfo
  649. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  650. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  651. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  652. }
  653. // 处理多key模式下的密钥追加/覆盖逻辑
  654. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  655. switch *channel.KeyMode {
  656. case "append":
  657. // 追加模式:将新密钥添加到现有密钥列表
  658. if originChannel.Key != "" {
  659. var newKeys []string
  660. var existingKeys []string
  661. // 解析现有密钥
  662. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  663. // JSON数组格式
  664. var arr []json.RawMessage
  665. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  666. existingKeys = make([]string, len(arr))
  667. for i, v := range arr {
  668. existingKeys[i] = string(v)
  669. }
  670. }
  671. } else {
  672. // 换行分隔格式
  673. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  674. }
  675. // 处理 Vertex AI 的特殊情况
  676. if channel.Type == constant.ChannelTypeVertexAi {
  677. // 尝试解析新密钥为JSON数组
  678. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  679. array, err := getVertexArrayKeys(channel.Key)
  680. if err != nil {
  681. c.JSON(http.StatusOK, gin.H{
  682. "success": false,
  683. "message": "追加密钥解析失败: " + err.Error(),
  684. })
  685. return
  686. }
  687. newKeys = array
  688. } else {
  689. // 单个JSON密钥
  690. newKeys = []string{channel.Key}
  691. }
  692. // 合并密钥
  693. allKeys := append(existingKeys, newKeys...)
  694. channel.Key = strings.Join(allKeys, "\n")
  695. } else {
  696. // 普通渠道的处理
  697. inputKeys := strings.Split(channel.Key, "\n")
  698. for _, key := range inputKeys {
  699. key = strings.TrimSpace(key)
  700. if key != "" {
  701. newKeys = append(newKeys, key)
  702. }
  703. }
  704. // 合并密钥
  705. allKeys := append(existingKeys, newKeys...)
  706. channel.Key = strings.Join(allKeys, "\n")
  707. }
  708. }
  709. case "replace":
  710. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  711. }
  712. }
  713. err = channel.Update()
  714. if err != nil {
  715. common.ApiError(c, err)
  716. return
  717. }
  718. model.InitChannelCache()
  719. channel.Key = ""
  720. c.JSON(http.StatusOK, gin.H{
  721. "success": true,
  722. "message": "",
  723. "data": channel,
  724. })
  725. return
  726. }
  727. func FetchModels(c *gin.Context) {
  728. var req struct {
  729. BaseURL string `json:"base_url"`
  730. Type int `json:"type"`
  731. Key string `json:"key"`
  732. }
  733. if err := c.ShouldBindJSON(&req); err != nil {
  734. c.JSON(http.StatusBadRequest, gin.H{
  735. "success": false,
  736. "message": "Invalid request",
  737. })
  738. return
  739. }
  740. baseURL := req.BaseURL
  741. if baseURL == "" {
  742. baseURL = constant.ChannelBaseURLs[req.Type]
  743. }
  744. client := &http.Client{}
  745. url := fmt.Sprintf("%s/v1/models", baseURL)
  746. request, err := http.NewRequest("GET", url, nil)
  747. if err != nil {
  748. c.JSON(http.StatusInternalServerError, gin.H{
  749. "success": false,
  750. "message": err.Error(),
  751. })
  752. return
  753. }
  754. // remove line breaks and extra spaces.
  755. key := strings.TrimSpace(req.Key)
  756. // If the key contains a line break, only take the first part.
  757. key = strings.Split(key, "\n")[0]
  758. request.Header.Set("Authorization", "Bearer "+key)
  759. response, err := client.Do(request)
  760. if err != nil {
  761. c.JSON(http.StatusInternalServerError, gin.H{
  762. "success": false,
  763. "message": err.Error(),
  764. })
  765. return
  766. }
  767. //check status code
  768. if response.StatusCode != http.StatusOK {
  769. c.JSON(http.StatusInternalServerError, gin.H{
  770. "success": false,
  771. "message": "Failed to fetch models",
  772. })
  773. return
  774. }
  775. defer response.Body.Close()
  776. var result struct {
  777. Data []struct {
  778. ID string `json:"id"`
  779. } `json:"data"`
  780. }
  781. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  782. c.JSON(http.StatusInternalServerError, gin.H{
  783. "success": false,
  784. "message": err.Error(),
  785. })
  786. return
  787. }
  788. var models []string
  789. for _, model := range result.Data {
  790. models = append(models, model.ID)
  791. }
  792. c.JSON(http.StatusOK, gin.H{
  793. "success": true,
  794. "data": models,
  795. })
  796. }
  797. func BatchSetChannelTag(c *gin.Context) {
  798. channelBatch := ChannelBatch{}
  799. err := c.ShouldBindJSON(&channelBatch)
  800. if err != nil || len(channelBatch.Ids) == 0 {
  801. c.JSON(http.StatusOK, gin.H{
  802. "success": false,
  803. "message": "参数错误",
  804. })
  805. return
  806. }
  807. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  808. if err != nil {
  809. common.ApiError(c, err)
  810. return
  811. }
  812. model.InitChannelCache()
  813. c.JSON(http.StatusOK, gin.H{
  814. "success": true,
  815. "message": "",
  816. "data": len(channelBatch.Ids),
  817. })
  818. return
  819. }
  820. func GetTagModels(c *gin.Context) {
  821. tag := c.Query("tag")
  822. if tag == "" {
  823. c.JSON(http.StatusBadRequest, gin.H{
  824. "success": false,
  825. "message": "tag不能为空",
  826. })
  827. return
  828. }
  829. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  830. if err != nil {
  831. c.JSON(http.StatusInternalServerError, gin.H{
  832. "success": false,
  833. "message": err.Error(),
  834. })
  835. return
  836. }
  837. var longestModels string
  838. maxLength := 0
  839. // Find the longest models string among all channels with the given tag
  840. for _, channel := range channels {
  841. if channel.Models != "" {
  842. currentModels := strings.Split(channel.Models, ",")
  843. if len(currentModels) > maxLength {
  844. maxLength = len(currentModels)
  845. longestModels = channel.Models
  846. }
  847. }
  848. }
  849. c.JSON(http.StatusOK, gin.H{
  850. "success": true,
  851. "message": "",
  852. "data": longestModels,
  853. })
  854. return
  855. }
  856. // CopyChannel handles cloning an existing channel with its key.
  857. // POST /api/channel/copy/:id
  858. // Optional query params:
  859. //
  860. // suffix - string appended to the original name (default "_复制")
  861. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  862. func CopyChannel(c *gin.Context) {
  863. id, err := strconv.Atoi(c.Param("id"))
  864. if err != nil {
  865. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  866. return
  867. }
  868. suffix := c.DefaultQuery("suffix", "_复制")
  869. resetBalance := true
  870. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  871. if v, err := strconv.ParseBool(rbStr); err == nil {
  872. resetBalance = v
  873. }
  874. }
  875. // fetch original channel with key
  876. origin, err := model.GetChannelById(id, true)
  877. if err != nil {
  878. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  879. return
  880. }
  881. // clone channel
  882. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  883. clone.Id = 0 // let DB auto-generate
  884. clone.CreatedTime = common.GetTimestamp()
  885. clone.Name = origin.Name + suffix
  886. clone.TestTime = 0
  887. clone.ResponseTime = 0
  888. if resetBalance {
  889. clone.Balance = 0
  890. clone.UsedQuota = 0
  891. }
  892. // insert
  893. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  894. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  895. return
  896. }
  897. model.InitChannelCache()
  898. // success
  899. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  900. }