channel.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. count, 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": count,
  223. })
  224. }
  225. func SearchChannels(c *gin.Context) {
  226. keyword := c.Query("keyword")
  227. group := c.Query("group")
  228. modelKeyword := c.Query("model")
  229. statusParam := c.Query("status")
  230. statusFilter := parseStatusFilter(statusParam)
  231. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  232. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  233. channelData := make([]*model.Channel, 0)
  234. if enableTagMode {
  235. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  236. if err != nil {
  237. c.JSON(http.StatusOK, gin.H{
  238. "success": false,
  239. "message": err.Error(),
  240. })
  241. return
  242. }
  243. for _, tag := range tags {
  244. if tag != nil && *tag != "" {
  245. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  246. if err == nil {
  247. channelData = append(channelData, tagChannel...)
  248. }
  249. }
  250. }
  251. } else {
  252. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  253. if err != nil {
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": false,
  256. "message": err.Error(),
  257. })
  258. return
  259. }
  260. channelData = channels
  261. }
  262. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  263. filtered := make([]*model.Channel, 0, len(channelData))
  264. for _, ch := range channelData {
  265. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  266. continue
  267. }
  268. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  269. continue
  270. }
  271. filtered = append(filtered, ch)
  272. }
  273. channelData = filtered
  274. }
  275. // calculate type counts for search results
  276. typeCounts := make(map[int64]int64)
  277. for _, channel := range channelData {
  278. typeCounts[int64(channel.Type)]++
  279. }
  280. typeParam := c.Query("type")
  281. typeFilter := -1
  282. if typeParam != "" {
  283. if tp, err := strconv.Atoi(typeParam); err == nil {
  284. typeFilter = tp
  285. }
  286. }
  287. if typeFilter >= 0 {
  288. filtered := make([]*model.Channel, 0, len(channelData))
  289. for _, ch := range channelData {
  290. if ch.Type == typeFilter {
  291. filtered = append(filtered, ch)
  292. }
  293. }
  294. channelData = filtered
  295. }
  296. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  297. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  298. if page < 1 {
  299. page = 1
  300. }
  301. if pageSize <= 0 {
  302. pageSize = 20
  303. }
  304. total := len(channelData)
  305. startIdx := (page - 1) * pageSize
  306. if startIdx > total {
  307. startIdx = total
  308. }
  309. endIdx := startIdx + pageSize
  310. if endIdx > total {
  311. endIdx = total
  312. }
  313. pagedData := channelData[startIdx:endIdx]
  314. c.JSON(http.StatusOK, gin.H{
  315. "success": true,
  316. "message": "",
  317. "data": gin.H{
  318. "items": pagedData,
  319. "total": total,
  320. "type_counts": typeCounts,
  321. },
  322. })
  323. return
  324. }
  325. func GetChannel(c *gin.Context) {
  326. id, err := strconv.Atoi(c.Param("id"))
  327. if err != nil {
  328. c.JSON(http.StatusOK, gin.H{
  329. "success": false,
  330. "message": err.Error(),
  331. })
  332. return
  333. }
  334. channel, err := model.GetChannelById(id, false)
  335. if err != nil {
  336. c.JSON(http.StatusOK, gin.H{
  337. "success": false,
  338. "message": err.Error(),
  339. })
  340. return
  341. }
  342. c.JSON(http.StatusOK, gin.H{
  343. "success": true,
  344. "message": "",
  345. "data": channel,
  346. })
  347. return
  348. }
  349. type AddChannelRequest struct {
  350. Mode string `json:"mode"`
  351. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  352. Channel *model.Channel `json:"channel"`
  353. }
  354. func getVertexArrayKeys(keys string) ([]string, error) {
  355. if keys == "" {
  356. return nil, nil
  357. }
  358. var keyArray []interface{}
  359. err := common.UnmarshalJson([]byte(keys), &keyArray)
  360. if err != nil {
  361. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  362. }
  363. cleanKeys := make([]string, 0, len(keyArray))
  364. for _, key := range keyArray {
  365. keyStr := fmt.Sprintf("%v", key)
  366. if keyStr != "" {
  367. cleanKeys = append(cleanKeys, strings.TrimSpace(keyStr))
  368. }
  369. }
  370. if len(cleanKeys) == 0 {
  371. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  372. }
  373. return cleanKeys, nil
  374. }
  375. func AddChannel(c *gin.Context) {
  376. addChannelRequest := AddChannelRequest{}
  377. err := c.ShouldBindJSON(&addChannelRequest)
  378. if err != nil {
  379. c.JSON(http.StatusOK, gin.H{
  380. "success": false,
  381. "message": err.Error(),
  382. })
  383. return
  384. }
  385. if addChannelRequest.Channel == nil || addChannelRequest.Channel.Key == "" {
  386. c.JSON(http.StatusOK, gin.H{
  387. "success": false,
  388. "message": "channel cannot be empty",
  389. })
  390. return
  391. }
  392. // Validate the length of the model name
  393. for _, m := range addChannelRequest.Channel.GetModels() {
  394. if len(m) > 255 {
  395. c.JSON(http.StatusOK, gin.H{
  396. "success": false,
  397. "message": fmt.Sprintf("模型名称过长: %s", m),
  398. })
  399. return
  400. }
  401. }
  402. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  403. if addChannelRequest.Channel.Other == "" {
  404. c.JSON(http.StatusOK, gin.H{
  405. "success": false,
  406. "message": "部署地区不能为空",
  407. })
  408. return
  409. } else {
  410. regionMap, err := common.StrToMap(addChannelRequest.Channel.Other)
  411. if err != nil {
  412. c.JSON(http.StatusOK, gin.H{
  413. "success": false,
  414. "message": "部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}",
  415. })
  416. return
  417. }
  418. if regionMap["default"] == nil {
  419. c.JSON(http.StatusOK, gin.H{
  420. "success": false,
  421. "message": "部署地区必须包含default字段",
  422. })
  423. return
  424. }
  425. }
  426. }
  427. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  428. keys := make([]string, 0)
  429. switch addChannelRequest.Mode {
  430. case "multi_to_single":
  431. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  432. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  433. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  434. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  435. if err != nil {
  436. c.JSON(http.StatusOK, gin.H{
  437. "success": false,
  438. "message": err.Error(),
  439. })
  440. return
  441. }
  442. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  443. } else {
  444. cleanKeys := make([]string, 0)
  445. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  446. if key == "" {
  447. continue
  448. }
  449. key = strings.TrimSpace(key)
  450. cleanKeys = append(cleanKeys, key)
  451. }
  452. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  453. }
  454. keys = []string{addChannelRequest.Channel.Key}
  455. case "batch":
  456. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  457. // multi json
  458. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  459. if err != nil {
  460. c.JSON(http.StatusOK, gin.H{
  461. "success": false,
  462. "message": err.Error(),
  463. })
  464. return
  465. }
  466. } else {
  467. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  468. }
  469. case "single":
  470. keys = []string{addChannelRequest.Channel.Key}
  471. default:
  472. c.JSON(http.StatusOK, gin.H{
  473. "success": false,
  474. "message": "不支持的添加模式",
  475. })
  476. return
  477. }
  478. channels := make([]model.Channel, 0, len(keys))
  479. for _, key := range keys {
  480. if key == "" {
  481. continue
  482. }
  483. localChannel := addChannelRequest.Channel
  484. localChannel.Key = key
  485. channels = append(channels, *localChannel)
  486. }
  487. err = model.BatchInsertChannels(channels)
  488. if err != nil {
  489. c.JSON(http.StatusOK, gin.H{
  490. "success": false,
  491. "message": err.Error(),
  492. })
  493. return
  494. }
  495. c.JSON(http.StatusOK, gin.H{
  496. "success": true,
  497. "message": "",
  498. })
  499. return
  500. }
  501. func DeleteChannel(c *gin.Context) {
  502. id, _ := strconv.Atoi(c.Param("id"))
  503. channel := model.Channel{Id: id}
  504. err := channel.Delete()
  505. if err != nil {
  506. c.JSON(http.StatusOK, gin.H{
  507. "success": false,
  508. "message": err.Error(),
  509. })
  510. return
  511. }
  512. c.JSON(http.StatusOK, gin.H{
  513. "success": true,
  514. "message": "",
  515. })
  516. return
  517. }
  518. func DeleteDisabledChannel(c *gin.Context) {
  519. rows, err := model.DeleteDisabledChannel()
  520. if err != nil {
  521. c.JSON(http.StatusOK, gin.H{
  522. "success": false,
  523. "message": err.Error(),
  524. })
  525. return
  526. }
  527. c.JSON(http.StatusOK, gin.H{
  528. "success": true,
  529. "message": "",
  530. "data": rows,
  531. })
  532. return
  533. }
  534. type ChannelTag struct {
  535. Tag string `json:"tag"`
  536. NewTag *string `json:"new_tag"`
  537. Priority *int64 `json:"priority"`
  538. Weight *uint `json:"weight"`
  539. ModelMapping *string `json:"model_mapping"`
  540. Models *string `json:"models"`
  541. Groups *string `json:"groups"`
  542. }
  543. func DisableTagChannels(c *gin.Context) {
  544. channelTag := ChannelTag{}
  545. err := c.ShouldBindJSON(&channelTag)
  546. if err != nil || channelTag.Tag == "" {
  547. c.JSON(http.StatusOK, gin.H{
  548. "success": false,
  549. "message": "参数错误",
  550. })
  551. return
  552. }
  553. err = model.DisableChannelByTag(channelTag.Tag)
  554. if err != nil {
  555. c.JSON(http.StatusOK, gin.H{
  556. "success": false,
  557. "message": err.Error(),
  558. })
  559. return
  560. }
  561. c.JSON(http.StatusOK, gin.H{
  562. "success": true,
  563. "message": "",
  564. })
  565. return
  566. }
  567. func EnableTagChannels(c *gin.Context) {
  568. channelTag := ChannelTag{}
  569. err := c.ShouldBindJSON(&channelTag)
  570. if err != nil || channelTag.Tag == "" {
  571. c.JSON(http.StatusOK, gin.H{
  572. "success": false,
  573. "message": "参数错误",
  574. })
  575. return
  576. }
  577. err = model.EnableChannelByTag(channelTag.Tag)
  578. if err != nil {
  579. c.JSON(http.StatusOK, gin.H{
  580. "success": false,
  581. "message": err.Error(),
  582. })
  583. return
  584. }
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "message": "",
  588. })
  589. return
  590. }
  591. func EditTagChannels(c *gin.Context) {
  592. channelTag := ChannelTag{}
  593. err := c.ShouldBindJSON(&channelTag)
  594. if err != nil {
  595. c.JSON(http.StatusOK, gin.H{
  596. "success": false,
  597. "message": "参数错误",
  598. })
  599. return
  600. }
  601. if channelTag.Tag == "" {
  602. c.JSON(http.StatusOK, gin.H{
  603. "success": false,
  604. "message": "tag不能为空",
  605. })
  606. return
  607. }
  608. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  609. if err != nil {
  610. c.JSON(http.StatusOK, gin.H{
  611. "success": false,
  612. "message": err.Error(),
  613. })
  614. return
  615. }
  616. c.JSON(http.StatusOK, gin.H{
  617. "success": true,
  618. "message": "",
  619. })
  620. return
  621. }
  622. type ChannelBatch struct {
  623. Ids []int `json:"ids"`
  624. Tag *string `json:"tag"`
  625. }
  626. func DeleteChannelBatch(c *gin.Context) {
  627. channelBatch := ChannelBatch{}
  628. err := c.ShouldBindJSON(&channelBatch)
  629. if err != nil || len(channelBatch.Ids) == 0 {
  630. c.JSON(http.StatusOK, gin.H{
  631. "success": false,
  632. "message": "参数错误",
  633. })
  634. return
  635. }
  636. err = model.BatchDeleteChannels(channelBatch.Ids)
  637. if err != nil {
  638. c.JSON(http.StatusOK, gin.H{
  639. "success": false,
  640. "message": err.Error(),
  641. })
  642. return
  643. }
  644. c.JSON(http.StatusOK, gin.H{
  645. "success": true,
  646. "message": "",
  647. "data": len(channelBatch.Ids),
  648. })
  649. return
  650. }
  651. func UpdateChannel(c *gin.Context) {
  652. channel := model.Channel{}
  653. err := c.ShouldBindJSON(&channel)
  654. if err != nil {
  655. c.JSON(http.StatusOK, gin.H{
  656. "success": false,
  657. "message": err.Error(),
  658. })
  659. return
  660. }
  661. if channel.Type == constant.ChannelTypeVertexAi {
  662. if channel.Other == "" {
  663. c.JSON(http.StatusOK, gin.H{
  664. "success": false,
  665. "message": "部署地区不能为空",
  666. })
  667. return
  668. } else {
  669. regionMap, err := common.StrToMap(channel.Other)
  670. if err != nil {
  671. c.JSON(http.StatusOK, gin.H{
  672. "success": false,
  673. "message": "部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}",
  674. })
  675. return
  676. }
  677. if regionMap["default"] == nil {
  678. c.JSON(http.StatusOK, gin.H{
  679. "success": false,
  680. "message": "部署地区必须包含default字段",
  681. })
  682. return
  683. }
  684. }
  685. }
  686. err = channel.Update()
  687. if err != nil {
  688. c.JSON(http.StatusOK, gin.H{
  689. "success": false,
  690. "message": err.Error(),
  691. })
  692. return
  693. }
  694. channel.Key = ""
  695. c.JSON(http.StatusOK, gin.H{
  696. "success": true,
  697. "message": "",
  698. "data": channel,
  699. })
  700. return
  701. }
  702. func FetchModels(c *gin.Context) {
  703. var req struct {
  704. BaseURL string `json:"base_url"`
  705. Type int `json:"type"`
  706. Key string `json:"key"`
  707. }
  708. if err := c.ShouldBindJSON(&req); err != nil {
  709. c.JSON(http.StatusBadRequest, gin.H{
  710. "success": false,
  711. "message": "Invalid request",
  712. })
  713. return
  714. }
  715. baseURL := req.BaseURL
  716. if baseURL == "" {
  717. baseURL = constant.ChannelBaseURLs[req.Type]
  718. }
  719. client := &http.Client{}
  720. url := fmt.Sprintf("%s/v1/models", baseURL)
  721. request, err := http.NewRequest("GET", url, nil)
  722. if err != nil {
  723. c.JSON(http.StatusInternalServerError, gin.H{
  724. "success": false,
  725. "message": err.Error(),
  726. })
  727. return
  728. }
  729. // remove line breaks and extra spaces.
  730. key := strings.TrimSpace(req.Key)
  731. // If the key contains a line break, only take the first part.
  732. key = strings.Split(key, "\n")[0]
  733. request.Header.Set("Authorization", "Bearer "+key)
  734. response, err := client.Do(request)
  735. if err != nil {
  736. c.JSON(http.StatusInternalServerError, gin.H{
  737. "success": false,
  738. "message": err.Error(),
  739. })
  740. return
  741. }
  742. //check status code
  743. if response.StatusCode != http.StatusOK {
  744. c.JSON(http.StatusInternalServerError, gin.H{
  745. "success": false,
  746. "message": "Failed to fetch models",
  747. })
  748. return
  749. }
  750. defer response.Body.Close()
  751. var result struct {
  752. Data []struct {
  753. ID string `json:"id"`
  754. } `json:"data"`
  755. }
  756. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  757. c.JSON(http.StatusInternalServerError, gin.H{
  758. "success": false,
  759. "message": err.Error(),
  760. })
  761. return
  762. }
  763. var models []string
  764. for _, model := range result.Data {
  765. models = append(models, model.ID)
  766. }
  767. c.JSON(http.StatusOK, gin.H{
  768. "success": true,
  769. "data": models,
  770. })
  771. }
  772. func BatchSetChannelTag(c *gin.Context) {
  773. channelBatch := ChannelBatch{}
  774. err := c.ShouldBindJSON(&channelBatch)
  775. if err != nil || len(channelBatch.Ids) == 0 {
  776. c.JSON(http.StatusOK, gin.H{
  777. "success": false,
  778. "message": "参数错误",
  779. })
  780. return
  781. }
  782. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  783. if err != nil {
  784. c.JSON(http.StatusOK, gin.H{
  785. "success": false,
  786. "message": err.Error(),
  787. })
  788. return
  789. }
  790. c.JSON(http.StatusOK, gin.H{
  791. "success": true,
  792. "message": "",
  793. "data": len(channelBatch.Ids),
  794. })
  795. return
  796. }
  797. func GetTagModels(c *gin.Context) {
  798. tag := c.Query("tag")
  799. if tag == "" {
  800. c.JSON(http.StatusBadRequest, gin.H{
  801. "success": false,
  802. "message": "tag不能为空",
  803. })
  804. return
  805. }
  806. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  807. if err != nil {
  808. c.JSON(http.StatusInternalServerError, gin.H{
  809. "success": false,
  810. "message": err.Error(),
  811. })
  812. return
  813. }
  814. var longestModels string
  815. maxLength := 0
  816. // Find the longest models string among all channels with the given tag
  817. for _, channel := range channels {
  818. if channel.Models != "" {
  819. currentModels := strings.Split(channel.Models, ",")
  820. if len(currentModels) > maxLength {
  821. maxLength = len(currentModels)
  822. longestModels = channel.Models
  823. }
  824. }
  825. }
  826. c.JSON(http.StatusOK, gin.H{
  827. "success": true,
  828. "message": "",
  829. "data": longestModels,
  830. })
  831. return
  832. }