channel.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. type AddChannelRequest struct {
  324. Mode string `json:"mode"`
  325. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  326. Channel *model.Channel `json:"channel"`
  327. }
  328. func getVertexArrayKeys(keys string) ([]string, error) {
  329. if keys == "" {
  330. return nil, nil
  331. }
  332. var keyArray []interface{}
  333. err := common.Unmarshal([]byte(keys), &keyArray)
  334. if err != nil {
  335. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  336. }
  337. cleanKeys := make([]string, 0, len(keyArray))
  338. for _, key := range keyArray {
  339. var keyStr string
  340. switch v := key.(type) {
  341. case string:
  342. keyStr = strings.TrimSpace(v)
  343. default:
  344. bytes, err := json.Marshal(v)
  345. if err != nil {
  346. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  347. }
  348. keyStr = string(bytes)
  349. }
  350. if keyStr != "" {
  351. cleanKeys = append(cleanKeys, keyStr)
  352. }
  353. }
  354. if len(cleanKeys) == 0 {
  355. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  356. }
  357. return cleanKeys, nil
  358. }
  359. func AddChannel(c *gin.Context) {
  360. addChannelRequest := AddChannelRequest{}
  361. err := c.ShouldBindJSON(&addChannelRequest)
  362. if err != nil {
  363. common.ApiError(c, err)
  364. return
  365. }
  366. err = addChannelRequest.Channel.ValidateSettings()
  367. if err != nil {
  368. c.JSON(http.StatusOK, gin.H{
  369. "success": false,
  370. "message": "channel setting 格式错误:" + err.Error(),
  371. })
  372. return
  373. }
  374. if addChannelRequest.Channel == nil || addChannelRequest.Channel.Key == "" {
  375. c.JSON(http.StatusOK, gin.H{
  376. "success": false,
  377. "message": "channel cannot be empty",
  378. })
  379. return
  380. }
  381. // Validate the length of the model name
  382. for _, m := range addChannelRequest.Channel.GetModels() {
  383. if len(m) > 255 {
  384. c.JSON(http.StatusOK, gin.H{
  385. "success": false,
  386. "message": fmt.Sprintf("模型名称过长: %s", m),
  387. })
  388. return
  389. }
  390. }
  391. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  392. if addChannelRequest.Channel.Other == "" {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "部署地区不能为空",
  396. })
  397. return
  398. } else {
  399. regionMap, err := common.StrToMap(addChannelRequest.Channel.Other)
  400. if err != nil {
  401. c.JSON(http.StatusOK, gin.H{
  402. "success": false,
  403. "message": "部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}",
  404. })
  405. return
  406. }
  407. if regionMap["default"] == nil {
  408. c.JSON(http.StatusOK, gin.H{
  409. "success": false,
  410. "message": "部署地区必须包含default字段",
  411. })
  412. return
  413. }
  414. }
  415. }
  416. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  417. keys := make([]string, 0)
  418. switch addChannelRequest.Mode {
  419. case "multi_to_single":
  420. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  421. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  422. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  423. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  424. if err != nil {
  425. c.JSON(http.StatusOK, gin.H{
  426. "success": false,
  427. "message": err.Error(),
  428. })
  429. return
  430. }
  431. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  432. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  433. } else {
  434. cleanKeys := make([]string, 0)
  435. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  436. if key == "" {
  437. continue
  438. }
  439. key = strings.TrimSpace(key)
  440. cleanKeys = append(cleanKeys, key)
  441. }
  442. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  443. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  444. }
  445. keys = []string{addChannelRequest.Channel.Key}
  446. case "batch":
  447. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi {
  448. // multi json
  449. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  450. if err != nil {
  451. c.JSON(http.StatusOK, gin.H{
  452. "success": false,
  453. "message": err.Error(),
  454. })
  455. return
  456. }
  457. } else {
  458. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  459. }
  460. case "single":
  461. keys = []string{addChannelRequest.Channel.Key}
  462. default:
  463. c.JSON(http.StatusOK, gin.H{
  464. "success": false,
  465. "message": "不支持的添加模式",
  466. })
  467. return
  468. }
  469. channels := make([]model.Channel, 0, len(keys))
  470. for _, key := range keys {
  471. if key == "" {
  472. continue
  473. }
  474. localChannel := addChannelRequest.Channel
  475. localChannel.Key = key
  476. channels = append(channels, *localChannel)
  477. }
  478. err = model.BatchInsertChannels(channels)
  479. if err != nil {
  480. common.ApiError(c, err)
  481. return
  482. }
  483. c.JSON(http.StatusOK, gin.H{
  484. "success": true,
  485. "message": "",
  486. })
  487. return
  488. }
  489. func DeleteChannel(c *gin.Context) {
  490. id, _ := strconv.Atoi(c.Param("id"))
  491. channel := model.Channel{Id: id}
  492. err := channel.Delete()
  493. if err != nil {
  494. common.ApiError(c, err)
  495. return
  496. }
  497. c.JSON(http.StatusOK, gin.H{
  498. "success": true,
  499. "message": "",
  500. })
  501. return
  502. }
  503. func DeleteDisabledChannel(c *gin.Context) {
  504. rows, err := model.DeleteDisabledChannel()
  505. if err != nil {
  506. common.ApiError(c, err)
  507. return
  508. }
  509. c.JSON(http.StatusOK, gin.H{
  510. "success": true,
  511. "message": "",
  512. "data": rows,
  513. })
  514. return
  515. }
  516. type ChannelTag struct {
  517. Tag string `json:"tag"`
  518. NewTag *string `json:"new_tag"`
  519. Priority *int64 `json:"priority"`
  520. Weight *uint `json:"weight"`
  521. ModelMapping *string `json:"model_mapping"`
  522. Models *string `json:"models"`
  523. Groups *string `json:"groups"`
  524. }
  525. func DisableTagChannels(c *gin.Context) {
  526. channelTag := ChannelTag{}
  527. err := c.ShouldBindJSON(&channelTag)
  528. if err != nil || channelTag.Tag == "" {
  529. c.JSON(http.StatusOK, gin.H{
  530. "success": false,
  531. "message": "参数错误",
  532. })
  533. return
  534. }
  535. err = model.DisableChannelByTag(channelTag.Tag)
  536. if err != nil {
  537. common.ApiError(c, err)
  538. return
  539. }
  540. c.JSON(http.StatusOK, gin.H{
  541. "success": true,
  542. "message": "",
  543. })
  544. return
  545. }
  546. func EnableTagChannels(c *gin.Context) {
  547. channelTag := ChannelTag{}
  548. err := c.ShouldBindJSON(&channelTag)
  549. if err != nil || channelTag.Tag == "" {
  550. c.JSON(http.StatusOK, gin.H{
  551. "success": false,
  552. "message": "参数错误",
  553. })
  554. return
  555. }
  556. err = model.EnableChannelByTag(channelTag.Tag)
  557. if err != nil {
  558. common.ApiError(c, err)
  559. return
  560. }
  561. c.JSON(http.StatusOK, gin.H{
  562. "success": true,
  563. "message": "",
  564. })
  565. return
  566. }
  567. func EditTagChannels(c *gin.Context) {
  568. channelTag := ChannelTag{}
  569. err := c.ShouldBindJSON(&channelTag)
  570. if err != nil {
  571. c.JSON(http.StatusOK, gin.H{
  572. "success": false,
  573. "message": "参数错误",
  574. })
  575. return
  576. }
  577. if channelTag.Tag == "" {
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": false,
  580. "message": "tag不能为空",
  581. })
  582. return
  583. }
  584. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  585. if err != nil {
  586. common.ApiError(c, err)
  587. return
  588. }
  589. c.JSON(http.StatusOK, gin.H{
  590. "success": true,
  591. "message": "",
  592. })
  593. return
  594. }
  595. type ChannelBatch struct {
  596. Ids []int `json:"ids"`
  597. Tag *string `json:"tag"`
  598. }
  599. func DeleteChannelBatch(c *gin.Context) {
  600. channelBatch := ChannelBatch{}
  601. err := c.ShouldBindJSON(&channelBatch)
  602. if err != nil || len(channelBatch.Ids) == 0 {
  603. c.JSON(http.StatusOK, gin.H{
  604. "success": false,
  605. "message": "参数错误",
  606. })
  607. return
  608. }
  609. err = model.BatchDeleteChannels(channelBatch.Ids)
  610. if err != nil {
  611. common.ApiError(c, err)
  612. return
  613. }
  614. c.JSON(http.StatusOK, gin.H{
  615. "success": true,
  616. "message": "",
  617. "data": len(channelBatch.Ids),
  618. })
  619. return
  620. }
  621. type PatchChannel struct {
  622. model.Channel
  623. MultiKeyMode *string `json:"multi_key_mode"`
  624. }
  625. func UpdateChannel(c *gin.Context) {
  626. channel := PatchChannel{}
  627. err := c.ShouldBindJSON(&channel)
  628. if err != nil {
  629. common.ApiError(c, err)
  630. return
  631. }
  632. err = channel.ValidateSettings()
  633. if err != nil {
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": false,
  636. "message": "channel setting 格式错误:" + err.Error(),
  637. })
  638. return
  639. }
  640. if channel.Type == constant.ChannelTypeVertexAi {
  641. if channel.Other == "" {
  642. c.JSON(http.StatusOK, gin.H{
  643. "success": false,
  644. "message": "部署地区不能为空",
  645. })
  646. return
  647. } else {
  648. regionMap, err := common.StrToMap(channel.Other)
  649. if err != nil {
  650. c.JSON(http.StatusOK, gin.H{
  651. "success": false,
  652. "message": "部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}",
  653. })
  654. return
  655. }
  656. if regionMap["default"] == nil {
  657. c.JSON(http.StatusOK, gin.H{
  658. "success": false,
  659. "message": "部署地区必须包含default字段",
  660. })
  661. return
  662. }
  663. }
  664. }
  665. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  666. originChannel, err := model.GetChannelById(channel.Id, false)
  667. if err != nil {
  668. c.JSON(http.StatusOK, gin.H{
  669. "success": false,
  670. "message": err.Error(),
  671. })
  672. }
  673. if originChannel.ChannelInfo.IsMultiKey {
  674. channel.ChannelInfo = originChannel.ChannelInfo
  675. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  676. }
  677. }
  678. err = channel.Update()
  679. if err != nil {
  680. common.ApiError(c, err)
  681. return
  682. }
  683. channel.Key = ""
  684. c.JSON(http.StatusOK, gin.H{
  685. "success": true,
  686. "message": "",
  687. "data": channel,
  688. })
  689. return
  690. }
  691. func FetchModels(c *gin.Context) {
  692. var req struct {
  693. BaseURL string `json:"base_url"`
  694. Type int `json:"type"`
  695. Key string `json:"key"`
  696. }
  697. if err := c.ShouldBindJSON(&req); err != nil {
  698. c.JSON(http.StatusBadRequest, gin.H{
  699. "success": false,
  700. "message": "Invalid request",
  701. })
  702. return
  703. }
  704. baseURL := req.BaseURL
  705. if baseURL == "" {
  706. baseURL = constant.ChannelBaseURLs[req.Type]
  707. }
  708. client := &http.Client{}
  709. url := fmt.Sprintf("%s/v1/models", baseURL)
  710. request, err := http.NewRequest("GET", url, nil)
  711. if err != nil {
  712. c.JSON(http.StatusInternalServerError, gin.H{
  713. "success": false,
  714. "message": err.Error(),
  715. })
  716. return
  717. }
  718. // remove line breaks and extra spaces.
  719. key := strings.TrimSpace(req.Key)
  720. // If the key contains a line break, only take the first part.
  721. key = strings.Split(key, "\n")[0]
  722. request.Header.Set("Authorization", "Bearer "+key)
  723. response, err := client.Do(request)
  724. if err != nil {
  725. c.JSON(http.StatusInternalServerError, gin.H{
  726. "success": false,
  727. "message": err.Error(),
  728. })
  729. return
  730. }
  731. //check status code
  732. if response.StatusCode != http.StatusOK {
  733. c.JSON(http.StatusInternalServerError, gin.H{
  734. "success": false,
  735. "message": "Failed to fetch models",
  736. })
  737. return
  738. }
  739. defer response.Body.Close()
  740. var result struct {
  741. Data []struct {
  742. ID string `json:"id"`
  743. } `json:"data"`
  744. }
  745. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  746. c.JSON(http.StatusInternalServerError, gin.H{
  747. "success": false,
  748. "message": err.Error(),
  749. })
  750. return
  751. }
  752. var models []string
  753. for _, model := range result.Data {
  754. models = append(models, model.ID)
  755. }
  756. c.JSON(http.StatusOK, gin.H{
  757. "success": true,
  758. "data": models,
  759. })
  760. }
  761. func BatchSetChannelTag(c *gin.Context) {
  762. channelBatch := ChannelBatch{}
  763. err := c.ShouldBindJSON(&channelBatch)
  764. if err != nil || len(channelBatch.Ids) == 0 {
  765. c.JSON(http.StatusOK, gin.H{
  766. "success": false,
  767. "message": "参数错误",
  768. })
  769. return
  770. }
  771. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  772. if err != nil {
  773. common.ApiError(c, err)
  774. return
  775. }
  776. c.JSON(http.StatusOK, gin.H{
  777. "success": true,
  778. "message": "",
  779. "data": len(channelBatch.Ids),
  780. })
  781. return
  782. }
  783. func GetTagModels(c *gin.Context) {
  784. tag := c.Query("tag")
  785. if tag == "" {
  786. c.JSON(http.StatusBadRequest, gin.H{
  787. "success": false,
  788. "message": "tag不能为空",
  789. })
  790. return
  791. }
  792. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  793. if err != nil {
  794. c.JSON(http.StatusInternalServerError, gin.H{
  795. "success": false,
  796. "message": err.Error(),
  797. })
  798. return
  799. }
  800. var longestModels string
  801. maxLength := 0
  802. // Find the longest models string among all channels with the given tag
  803. for _, channel := range channels {
  804. if channel.Models != "" {
  805. currentModels := strings.Split(channel.Models, ",")
  806. if len(currentModels) > maxLength {
  807. maxLength = len(currentModels)
  808. longestModels = channel.Models
  809. }
  810. }
  811. }
  812. c.JSON(http.StatusOK, gin.H{
  813. "success": true,
  814. "message": "",
  815. "data": longestModels,
  816. })
  817. return
  818. }
  819. // CopyChannel handles cloning an existing channel with its key.
  820. // POST /api/channel/copy/:id
  821. // Optional query params:
  822. // suffix - string appended to the original name (default "_复制")
  823. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  824. func CopyChannel(c *gin.Context) {
  825. id, err := strconv.Atoi(c.Param("id"))
  826. if err != nil {
  827. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  828. return
  829. }
  830. suffix := c.DefaultQuery("suffix", "_复制")
  831. resetBalance := true
  832. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  833. if v, err := strconv.ParseBool(rbStr); err == nil {
  834. resetBalance = v
  835. }
  836. }
  837. // fetch original channel with key
  838. origin, err := model.GetChannelById(id, true)
  839. if err != nil {
  840. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  841. return
  842. }
  843. // clone channel
  844. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  845. clone.Id = 0 // let DB auto-generate
  846. clone.CreatedTime = common.GetTimestamp()
  847. clone.Name = origin.Name + suffix
  848. clone.TestTime = 0
  849. clone.ResponseTime = 0
  850. if resetBalance {
  851. clone.Balance = 0
  852. clone.UsedQuota = 0
  853. }
  854. // insert
  855. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  856. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  857. return
  858. }
  859. // success
  860. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  861. }