channel.go 21 KB

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