channel.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "strconv"
  9. "strings"
  10. "github.com/gin-gonic/gin"
  11. )
  12. type OpenAIModel struct {
  13. ID string `json:"id"`
  14. Object string `json:"object"`
  15. Created int64 `json:"created"`
  16. OwnedBy string `json:"owned_by"`
  17. Permission []struct {
  18. ID string `json:"id"`
  19. Object string `json:"object"`
  20. Created int64 `json:"created"`
  21. AllowCreateEngine bool `json:"allow_create_engine"`
  22. AllowSampling bool `json:"allow_sampling"`
  23. AllowLogprobs bool `json:"allow_logprobs"`
  24. AllowSearchIndices bool `json:"allow_search_indices"`
  25. AllowView bool `json:"allow_view"`
  26. AllowFineTuning bool `json:"allow_fine_tuning"`
  27. Organization string `json:"organization"`
  28. Group string `json:"group"`
  29. IsBlocking bool `json:"is_blocking"`
  30. } `json:"permission"`
  31. Root string `json:"root"`
  32. Parent string `json:"parent"`
  33. }
  34. type OpenAIModelsResponse struct {
  35. Data []OpenAIModel `json:"data"`
  36. Success bool `json:"success"`
  37. }
  38. func GetAllChannels(c *gin.Context) {
  39. p, _ := strconv.Atoi(c.Query("p"))
  40. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  41. if p < 1 {
  42. p = 1
  43. }
  44. if pageSize < 1 {
  45. pageSize = common.ItemsPerPage
  46. }
  47. channelData := make([]*model.Channel, 0)
  48. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  49. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  50. // type filter
  51. typeStr := c.Query("type")
  52. typeFilter := -1
  53. if typeStr != "" {
  54. if t, err := strconv.Atoi(typeStr); err == nil {
  55. typeFilter = t
  56. }
  57. }
  58. var total int64
  59. if enableTagMode {
  60. // tag 分页:先分页 tag,再取各 tag 下 channels
  61. tags, err := model.GetPaginatedTags((p-1)*pageSize, pageSize)
  62. if err != nil {
  63. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  64. return
  65. }
  66. for _, tag := range tags {
  67. if tag != nil && *tag != "" {
  68. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  69. if err == nil {
  70. channelData = append(channelData, tagChannel...)
  71. }
  72. }
  73. }
  74. // 计算 tag 总数用于分页
  75. total, _ = model.CountAllTags()
  76. } else if typeFilter >= 0 {
  77. channels, err := model.GetChannelsByType((p-1)*pageSize, pageSize, idSort, typeFilter)
  78. if err != nil {
  79. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  80. return
  81. }
  82. channelData = channels
  83. total, _ = model.CountChannelsByType(typeFilter)
  84. } else {
  85. channels, err := model.GetAllChannels((p-1)*pageSize, pageSize, false, idSort)
  86. if err != nil {
  87. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  88. return
  89. }
  90. channelData = channels
  91. total, _ = model.CountAllChannels()
  92. }
  93. // calculate type counts
  94. typeCounts, _ := model.CountChannelsGroupByType()
  95. c.JSON(http.StatusOK, gin.H{
  96. "success": true,
  97. "message": "",
  98. "data": gin.H{
  99. "items": channelData,
  100. "total": total,
  101. "page": p,
  102. "page_size": pageSize,
  103. "type_counts": typeCounts,
  104. },
  105. })
  106. return
  107. }
  108. func FetchUpstreamModels(c *gin.Context) {
  109. id, err := strconv.Atoi(c.Param("id"))
  110. if err != nil {
  111. c.JSON(http.StatusOK, gin.H{
  112. "success": false,
  113. "message": err.Error(),
  114. })
  115. return
  116. }
  117. channel, err := model.GetChannelById(id, true)
  118. if err != nil {
  119. c.JSON(http.StatusOK, gin.H{
  120. "success": false,
  121. "message": err.Error(),
  122. })
  123. return
  124. }
  125. //if channel.Type != common.ChannelTypeOpenAI {
  126. // c.JSON(http.StatusOK, gin.H{
  127. // "success": false,
  128. // "message": "仅支持 OpenAI 类型渠道",
  129. // })
  130. // return
  131. //}
  132. baseURL := common.ChannelBaseURLs[channel.Type]
  133. if channel.GetBaseURL() != "" {
  134. baseURL = channel.GetBaseURL()
  135. }
  136. url := fmt.Sprintf("%s/v1/models", baseURL)
  137. switch channel.Type {
  138. case common.ChannelTypeGemini:
  139. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  140. case common.ChannelTypeAli:
  141. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  142. }
  143. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  144. if err != nil {
  145. c.JSON(http.StatusOK, gin.H{
  146. "success": false,
  147. "message": err.Error(),
  148. })
  149. return
  150. }
  151. var result OpenAIModelsResponse
  152. if err = json.Unmarshal(body, &result); err != nil {
  153. c.JSON(http.StatusOK, gin.H{
  154. "success": false,
  155. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  156. })
  157. return
  158. }
  159. var ids []string
  160. for _, model := range result.Data {
  161. id := model.ID
  162. if channel.Type == common.ChannelTypeGemini {
  163. id = strings.TrimPrefix(id, "models/")
  164. }
  165. ids = append(ids, id)
  166. }
  167. c.JSON(http.StatusOK, gin.H{
  168. "success": true,
  169. "message": "",
  170. "data": ids,
  171. })
  172. }
  173. func FixChannelsAbilities(c *gin.Context) {
  174. count, err := model.FixAbility()
  175. if err != nil {
  176. c.JSON(http.StatusOK, gin.H{
  177. "success": false,
  178. "message": err.Error(),
  179. })
  180. return
  181. }
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": true,
  184. "message": "",
  185. "data": count,
  186. })
  187. }
  188. func SearchChannels(c *gin.Context) {
  189. keyword := c.Query("keyword")
  190. group := c.Query("group")
  191. modelKeyword := c.Query("model")
  192. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  193. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  194. channelData := make([]*model.Channel, 0)
  195. if enableTagMode {
  196. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  197. if err != nil {
  198. c.JSON(http.StatusOK, gin.H{
  199. "success": false,
  200. "message": err.Error(),
  201. })
  202. return
  203. }
  204. for _, tag := range tags {
  205. if tag != nil && *tag != "" {
  206. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  207. if err == nil {
  208. channelData = append(channelData, tagChannel...)
  209. }
  210. }
  211. }
  212. } else {
  213. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  214. if err != nil {
  215. c.JSON(http.StatusOK, gin.H{
  216. "success": false,
  217. "message": err.Error(),
  218. })
  219. return
  220. }
  221. channelData = channels
  222. }
  223. c.JSON(http.StatusOK, gin.H{
  224. "success": true,
  225. "message": "",
  226. "data": channelData,
  227. })
  228. return
  229. }
  230. func GetChannel(c *gin.Context) {
  231. id, err := strconv.Atoi(c.Param("id"))
  232. if err != nil {
  233. c.JSON(http.StatusOK, gin.H{
  234. "success": false,
  235. "message": err.Error(),
  236. })
  237. return
  238. }
  239. channel, err := model.GetChannelById(id, false)
  240. if err != nil {
  241. c.JSON(http.StatusOK, gin.H{
  242. "success": false,
  243. "message": err.Error(),
  244. })
  245. return
  246. }
  247. c.JSON(http.StatusOK, gin.H{
  248. "success": true,
  249. "message": "",
  250. "data": channel,
  251. })
  252. return
  253. }
  254. func AddChannel(c *gin.Context) {
  255. channel := model.Channel{}
  256. err := c.ShouldBindJSON(&channel)
  257. if err != nil {
  258. c.JSON(http.StatusOK, gin.H{
  259. "success": false,
  260. "message": err.Error(),
  261. })
  262. return
  263. }
  264. channel.CreatedTime = common.GetTimestamp()
  265. keys := strings.Split(channel.Key, "\n")
  266. if channel.Type == common.ChannelTypeVertexAi {
  267. if channel.Other == "" {
  268. c.JSON(http.StatusOK, gin.H{
  269. "success": false,
  270. "message": "部署地区不能为空",
  271. })
  272. return
  273. } else {
  274. if common.IsJsonStr(channel.Other) {
  275. // must have default
  276. regionMap := common.StrToMap(channel.Other)
  277. if regionMap["default"] == nil {
  278. c.JSON(http.StatusOK, gin.H{
  279. "success": false,
  280. "message": "部署地区必须包含default字段",
  281. })
  282. return
  283. }
  284. }
  285. }
  286. keys = []string{channel.Key}
  287. }
  288. channels := make([]model.Channel, 0, len(keys))
  289. for _, key := range keys {
  290. if key == "" {
  291. continue
  292. }
  293. localChannel := channel
  294. localChannel.Key = key
  295. // Validate the length of the model name
  296. models := strings.Split(localChannel.Models, ",")
  297. for _, model := range models {
  298. if len(model) > 255 {
  299. c.JSON(http.StatusOK, gin.H{
  300. "success": false,
  301. "message": fmt.Sprintf("模型名称过长: %s", model),
  302. })
  303. return
  304. }
  305. }
  306. channels = append(channels, localChannel)
  307. }
  308. err = model.BatchInsertChannels(channels)
  309. if err != nil {
  310. c.JSON(http.StatusOK, gin.H{
  311. "success": false,
  312. "message": err.Error(),
  313. })
  314. return
  315. }
  316. c.JSON(http.StatusOK, gin.H{
  317. "success": true,
  318. "message": "",
  319. })
  320. return
  321. }
  322. func DeleteChannel(c *gin.Context) {
  323. id, _ := strconv.Atoi(c.Param("id"))
  324. channel := model.Channel{Id: id}
  325. err := channel.Delete()
  326. if err != nil {
  327. c.JSON(http.StatusOK, gin.H{
  328. "success": false,
  329. "message": err.Error(),
  330. })
  331. return
  332. }
  333. c.JSON(http.StatusOK, gin.H{
  334. "success": true,
  335. "message": "",
  336. })
  337. return
  338. }
  339. func DeleteDisabledChannel(c *gin.Context) {
  340. rows, err := model.DeleteDisabledChannel()
  341. if err != nil {
  342. c.JSON(http.StatusOK, gin.H{
  343. "success": false,
  344. "message": err.Error(),
  345. })
  346. return
  347. }
  348. c.JSON(http.StatusOK, gin.H{
  349. "success": true,
  350. "message": "",
  351. "data": rows,
  352. })
  353. return
  354. }
  355. type ChannelTag struct {
  356. Tag string `json:"tag"`
  357. NewTag *string `json:"new_tag"`
  358. Priority *int64 `json:"priority"`
  359. Weight *uint `json:"weight"`
  360. ModelMapping *string `json:"model_mapping"`
  361. Models *string `json:"models"`
  362. Groups *string `json:"groups"`
  363. }
  364. func DisableTagChannels(c *gin.Context) {
  365. channelTag := ChannelTag{}
  366. err := c.ShouldBindJSON(&channelTag)
  367. if err != nil || channelTag.Tag == "" {
  368. c.JSON(http.StatusOK, gin.H{
  369. "success": false,
  370. "message": "参数错误",
  371. })
  372. return
  373. }
  374. err = model.DisableChannelByTag(channelTag.Tag)
  375. if err != nil {
  376. c.JSON(http.StatusOK, gin.H{
  377. "success": false,
  378. "message": err.Error(),
  379. })
  380. return
  381. }
  382. c.JSON(http.StatusOK, gin.H{
  383. "success": true,
  384. "message": "",
  385. })
  386. return
  387. }
  388. func EnableTagChannels(c *gin.Context) {
  389. channelTag := ChannelTag{}
  390. err := c.ShouldBindJSON(&channelTag)
  391. if err != nil || channelTag.Tag == "" {
  392. c.JSON(http.StatusOK, gin.H{
  393. "success": false,
  394. "message": "参数错误",
  395. })
  396. return
  397. }
  398. err = model.EnableChannelByTag(channelTag.Tag)
  399. if err != nil {
  400. c.JSON(http.StatusOK, gin.H{
  401. "success": false,
  402. "message": err.Error(),
  403. })
  404. return
  405. }
  406. c.JSON(http.StatusOK, gin.H{
  407. "success": true,
  408. "message": "",
  409. })
  410. return
  411. }
  412. func EditTagChannels(c *gin.Context) {
  413. channelTag := ChannelTag{}
  414. err := c.ShouldBindJSON(&channelTag)
  415. if err != nil {
  416. c.JSON(http.StatusOK, gin.H{
  417. "success": false,
  418. "message": "参数错误",
  419. })
  420. return
  421. }
  422. if channelTag.Tag == "" {
  423. c.JSON(http.StatusOK, gin.H{
  424. "success": false,
  425. "message": "tag不能为空",
  426. })
  427. return
  428. }
  429. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  430. if err != nil {
  431. c.JSON(http.StatusOK, gin.H{
  432. "success": false,
  433. "message": err.Error(),
  434. })
  435. return
  436. }
  437. c.JSON(http.StatusOK, gin.H{
  438. "success": true,
  439. "message": "",
  440. })
  441. return
  442. }
  443. type ChannelBatch struct {
  444. Ids []int `json:"ids"`
  445. Tag *string `json:"tag"`
  446. }
  447. func DeleteChannelBatch(c *gin.Context) {
  448. channelBatch := ChannelBatch{}
  449. err := c.ShouldBindJSON(&channelBatch)
  450. if err != nil || len(channelBatch.Ids) == 0 {
  451. c.JSON(http.StatusOK, gin.H{
  452. "success": false,
  453. "message": "参数错误",
  454. })
  455. return
  456. }
  457. err = model.BatchDeleteChannels(channelBatch.Ids)
  458. if err != nil {
  459. c.JSON(http.StatusOK, gin.H{
  460. "success": false,
  461. "message": err.Error(),
  462. })
  463. return
  464. }
  465. c.JSON(http.StatusOK, gin.H{
  466. "success": true,
  467. "message": "",
  468. "data": len(channelBatch.Ids),
  469. })
  470. return
  471. }
  472. func UpdateChannel(c *gin.Context) {
  473. channel := model.Channel{}
  474. err := c.ShouldBindJSON(&channel)
  475. if err != nil {
  476. c.JSON(http.StatusOK, gin.H{
  477. "success": false,
  478. "message": err.Error(),
  479. })
  480. return
  481. }
  482. if channel.Type == common.ChannelTypeVertexAi {
  483. if channel.Other == "" {
  484. c.JSON(http.StatusOK, gin.H{
  485. "success": false,
  486. "message": "部署地区不能为空",
  487. })
  488. return
  489. } else {
  490. if common.IsJsonStr(channel.Other) {
  491. // must have default
  492. regionMap := common.StrToMap(channel.Other)
  493. if regionMap["default"] == nil {
  494. c.JSON(http.StatusOK, gin.H{
  495. "success": false,
  496. "message": "部署地区必须包含default字段",
  497. })
  498. return
  499. }
  500. }
  501. }
  502. }
  503. err = channel.Update()
  504. if err != nil {
  505. c.JSON(http.StatusOK, gin.H{
  506. "success": false,
  507. "message": err.Error(),
  508. })
  509. return
  510. }
  511. c.JSON(http.StatusOK, gin.H{
  512. "success": true,
  513. "message": "",
  514. "data": channel,
  515. })
  516. return
  517. }
  518. func FetchModels(c *gin.Context) {
  519. var req struct {
  520. BaseURL string `json:"base_url"`
  521. Type int `json:"type"`
  522. Key string `json:"key"`
  523. }
  524. if err := c.ShouldBindJSON(&req); err != nil {
  525. c.JSON(http.StatusBadRequest, gin.H{
  526. "success": false,
  527. "message": "Invalid request",
  528. })
  529. return
  530. }
  531. baseURL := req.BaseURL
  532. if baseURL == "" {
  533. baseURL = common.ChannelBaseURLs[req.Type]
  534. }
  535. client := &http.Client{}
  536. url := fmt.Sprintf("%s/v1/models", baseURL)
  537. request, err := http.NewRequest("GET", url, nil)
  538. if err != nil {
  539. c.JSON(http.StatusInternalServerError, gin.H{
  540. "success": false,
  541. "message": err.Error(),
  542. })
  543. return
  544. }
  545. // remove line breaks and extra spaces.
  546. key := strings.TrimSpace(req.Key)
  547. // If the key contains a line break, only take the first part.
  548. key = strings.Split(key, "\n")[0]
  549. request.Header.Set("Authorization", "Bearer "+key)
  550. response, err := client.Do(request)
  551. if err != nil {
  552. c.JSON(http.StatusInternalServerError, gin.H{
  553. "success": false,
  554. "message": err.Error(),
  555. })
  556. return
  557. }
  558. //check status code
  559. if response.StatusCode != http.StatusOK {
  560. c.JSON(http.StatusInternalServerError, gin.H{
  561. "success": false,
  562. "message": "Failed to fetch models",
  563. })
  564. return
  565. }
  566. defer response.Body.Close()
  567. var result struct {
  568. Data []struct {
  569. ID string `json:"id"`
  570. } `json:"data"`
  571. }
  572. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  573. c.JSON(http.StatusInternalServerError, gin.H{
  574. "success": false,
  575. "message": err.Error(),
  576. })
  577. return
  578. }
  579. var models []string
  580. for _, model := range result.Data {
  581. models = append(models, model.ID)
  582. }
  583. c.JSON(http.StatusOK, gin.H{
  584. "success": true,
  585. "data": models,
  586. })
  587. }
  588. func BatchSetChannelTag(c *gin.Context) {
  589. channelBatch := ChannelBatch{}
  590. err := c.ShouldBindJSON(&channelBatch)
  591. if err != nil || len(channelBatch.Ids) == 0 {
  592. c.JSON(http.StatusOK, gin.H{
  593. "success": false,
  594. "message": "参数错误",
  595. })
  596. return
  597. }
  598. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  599. if err != nil {
  600. c.JSON(http.StatusOK, gin.H{
  601. "success": false,
  602. "message": err.Error(),
  603. })
  604. return
  605. }
  606. c.JSON(http.StatusOK, gin.H{
  607. "success": true,
  608. "message": "",
  609. "data": len(channelBatch.Ids),
  610. })
  611. return
  612. }
  613. func GetTagModels(c *gin.Context) {
  614. tag := c.Query("tag")
  615. if tag == "" {
  616. c.JSON(http.StatusBadRequest, gin.H{
  617. "success": false,
  618. "message": "tag不能为空",
  619. })
  620. return
  621. }
  622. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  623. if err != nil {
  624. c.JSON(http.StatusInternalServerError, gin.H{
  625. "success": false,
  626. "message": err.Error(),
  627. })
  628. return
  629. }
  630. var longestModels string
  631. maxLength := 0
  632. // Find the longest models string among all channels with the given tag
  633. for _, channel := range channels {
  634. if channel.Models != "" {
  635. currentModels := strings.Split(channel.Models, ",")
  636. if len(currentModels) > maxLength {
  637. maxLength = len(currentModels)
  638. longestModels = channel.Models
  639. }
  640. }
  641. }
  642. c.JSON(http.StatusOK, gin.H{
  643. "success": true,
  644. "message": "",
  645. "data": longestModels,
  646. })
  647. return
  648. }