channel.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. baseURL := common.ChannelBaseURLs[channel.Type]
  126. if channel.GetBaseURL() != "" {
  127. baseURL = channel.GetBaseURL()
  128. }
  129. url := fmt.Sprintf("%s/v1/models", baseURL)
  130. switch channel.Type {
  131. case common.ChannelTypeGemini:
  132. url = fmt.Sprintf("%s/v1beta/openai/models", baseURL)
  133. case common.ChannelTypeAli:
  134. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  135. }
  136. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  137. if err != nil {
  138. c.JSON(http.StatusOK, gin.H{
  139. "success": false,
  140. "message": err.Error(),
  141. })
  142. return
  143. }
  144. var result OpenAIModelsResponse
  145. if err = json.Unmarshal(body, &result); err != nil {
  146. c.JSON(http.StatusOK, gin.H{
  147. "success": false,
  148. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  149. })
  150. return
  151. }
  152. var ids []string
  153. for _, model := range result.Data {
  154. id := model.ID
  155. if channel.Type == common.ChannelTypeGemini {
  156. id = strings.TrimPrefix(id, "models/")
  157. }
  158. ids = append(ids, id)
  159. }
  160. c.JSON(http.StatusOK, gin.H{
  161. "success": true,
  162. "message": "",
  163. "data": ids,
  164. })
  165. }
  166. func FixChannelsAbilities(c *gin.Context) {
  167. count, err := model.FixAbility()
  168. if err != nil {
  169. c.JSON(http.StatusOK, gin.H{
  170. "success": false,
  171. "message": err.Error(),
  172. })
  173. return
  174. }
  175. c.JSON(http.StatusOK, gin.H{
  176. "success": true,
  177. "message": "",
  178. "data": count,
  179. })
  180. }
  181. func SearchChannels(c *gin.Context) {
  182. keyword := c.Query("keyword")
  183. group := c.Query("group")
  184. modelKeyword := c.Query("model")
  185. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  186. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  187. channelData := make([]*model.Channel, 0)
  188. if enableTagMode {
  189. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  190. if err != nil {
  191. c.JSON(http.StatusOK, gin.H{
  192. "success": false,
  193. "message": err.Error(),
  194. })
  195. return
  196. }
  197. for _, tag := range tags {
  198. if tag != nil && *tag != "" {
  199. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  200. if err == nil {
  201. channelData = append(channelData, tagChannel...)
  202. }
  203. }
  204. }
  205. } else {
  206. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  207. if err != nil {
  208. c.JSON(http.StatusOK, gin.H{
  209. "success": false,
  210. "message": err.Error(),
  211. })
  212. return
  213. }
  214. channelData = channels
  215. }
  216. // calculate type counts for search results
  217. typeCounts := make(map[int64]int64)
  218. for _, channel := range channelData {
  219. typeCounts[int64(channel.Type)]++
  220. }
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": true,
  223. "message": "",
  224. "data": gin.H{
  225. "items": channelData,
  226. "type_counts": typeCounts,
  227. },
  228. })
  229. return
  230. }
  231. func GetChannel(c *gin.Context) {
  232. id, err := strconv.Atoi(c.Param("id"))
  233. if err != nil {
  234. c.JSON(http.StatusOK, gin.H{
  235. "success": false,
  236. "message": err.Error(),
  237. })
  238. return
  239. }
  240. channel, err := model.GetChannelById(id, false)
  241. if err != nil {
  242. c.JSON(http.StatusOK, gin.H{
  243. "success": false,
  244. "message": err.Error(),
  245. })
  246. return
  247. }
  248. c.JSON(http.StatusOK, gin.H{
  249. "success": true,
  250. "message": "",
  251. "data": channel,
  252. })
  253. return
  254. }
  255. func AddChannel(c *gin.Context) {
  256. channel := model.Channel{}
  257. err := c.ShouldBindJSON(&channel)
  258. if err != nil {
  259. c.JSON(http.StatusOK, gin.H{
  260. "success": false,
  261. "message": err.Error(),
  262. })
  263. return
  264. }
  265. channel.CreatedTime = common.GetTimestamp()
  266. keys := strings.Split(channel.Key, "\n")
  267. if channel.Type == common.ChannelTypeVertexAi {
  268. if channel.Other == "" {
  269. c.JSON(http.StatusOK, gin.H{
  270. "success": false,
  271. "message": "部署地区不能为空",
  272. })
  273. return
  274. } else {
  275. if common.IsJsonStr(channel.Other) {
  276. // must have default
  277. regionMap := common.StrToMap(channel.Other)
  278. if regionMap["default"] == nil {
  279. c.JSON(http.StatusOK, gin.H{
  280. "success": false,
  281. "message": "部署地区必须包含default字段",
  282. })
  283. return
  284. }
  285. }
  286. }
  287. keys = []string{channel.Key}
  288. }
  289. channels := make([]model.Channel, 0, len(keys))
  290. for _, key := range keys {
  291. if key == "" {
  292. continue
  293. }
  294. localChannel := channel
  295. localChannel.Key = key
  296. // Validate the length of the model name
  297. models := strings.Split(localChannel.Models, ",")
  298. for _, model := range models {
  299. if len(model) > 255 {
  300. c.JSON(http.StatusOK, gin.H{
  301. "success": false,
  302. "message": fmt.Sprintf("模型名称过长: %s", model),
  303. })
  304. return
  305. }
  306. }
  307. channels = append(channels, localChannel)
  308. }
  309. err = model.BatchInsertChannels(channels)
  310. if err != nil {
  311. c.JSON(http.StatusOK, gin.H{
  312. "success": false,
  313. "message": err.Error(),
  314. })
  315. return
  316. }
  317. c.JSON(http.StatusOK, gin.H{
  318. "success": true,
  319. "message": "",
  320. })
  321. return
  322. }
  323. func DeleteChannel(c *gin.Context) {
  324. id, _ := strconv.Atoi(c.Param("id"))
  325. channel := model.Channel{Id: id}
  326. err := channel.Delete()
  327. if err != nil {
  328. c.JSON(http.StatusOK, gin.H{
  329. "success": false,
  330. "message": err.Error(),
  331. })
  332. return
  333. }
  334. c.JSON(http.StatusOK, gin.H{
  335. "success": true,
  336. "message": "",
  337. })
  338. return
  339. }
  340. func DeleteDisabledChannel(c *gin.Context) {
  341. rows, err := model.DeleteDisabledChannel()
  342. if err != nil {
  343. c.JSON(http.StatusOK, gin.H{
  344. "success": false,
  345. "message": err.Error(),
  346. })
  347. return
  348. }
  349. c.JSON(http.StatusOK, gin.H{
  350. "success": true,
  351. "message": "",
  352. "data": rows,
  353. })
  354. return
  355. }
  356. type ChannelTag struct {
  357. Tag string `json:"tag"`
  358. NewTag *string `json:"new_tag"`
  359. Priority *int64 `json:"priority"`
  360. Weight *uint `json:"weight"`
  361. ModelMapping *string `json:"model_mapping"`
  362. Models *string `json:"models"`
  363. Groups *string `json:"groups"`
  364. }
  365. func DisableTagChannels(c *gin.Context) {
  366. channelTag := ChannelTag{}
  367. err := c.ShouldBindJSON(&channelTag)
  368. if err != nil || channelTag.Tag == "" {
  369. c.JSON(http.StatusOK, gin.H{
  370. "success": false,
  371. "message": "参数错误",
  372. })
  373. return
  374. }
  375. err = model.DisableChannelByTag(channelTag.Tag)
  376. if err != nil {
  377. c.JSON(http.StatusOK, gin.H{
  378. "success": false,
  379. "message": err.Error(),
  380. })
  381. return
  382. }
  383. c.JSON(http.StatusOK, gin.H{
  384. "success": true,
  385. "message": "",
  386. })
  387. return
  388. }
  389. func EnableTagChannels(c *gin.Context) {
  390. channelTag := ChannelTag{}
  391. err := c.ShouldBindJSON(&channelTag)
  392. if err != nil || channelTag.Tag == "" {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "参数错误",
  396. })
  397. return
  398. }
  399. err = model.EnableChannelByTag(channelTag.Tag)
  400. if err != nil {
  401. c.JSON(http.StatusOK, gin.H{
  402. "success": false,
  403. "message": err.Error(),
  404. })
  405. return
  406. }
  407. c.JSON(http.StatusOK, gin.H{
  408. "success": true,
  409. "message": "",
  410. })
  411. return
  412. }
  413. func EditTagChannels(c *gin.Context) {
  414. channelTag := ChannelTag{}
  415. err := c.ShouldBindJSON(&channelTag)
  416. if err != nil {
  417. c.JSON(http.StatusOK, gin.H{
  418. "success": false,
  419. "message": "参数错误",
  420. })
  421. return
  422. }
  423. if channelTag.Tag == "" {
  424. c.JSON(http.StatusOK, gin.H{
  425. "success": false,
  426. "message": "tag不能为空",
  427. })
  428. return
  429. }
  430. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  431. if err != nil {
  432. c.JSON(http.StatusOK, gin.H{
  433. "success": false,
  434. "message": err.Error(),
  435. })
  436. return
  437. }
  438. c.JSON(http.StatusOK, gin.H{
  439. "success": true,
  440. "message": "",
  441. })
  442. return
  443. }
  444. type ChannelBatch struct {
  445. Ids []int `json:"ids"`
  446. Tag *string `json:"tag"`
  447. }
  448. func DeleteChannelBatch(c *gin.Context) {
  449. channelBatch := ChannelBatch{}
  450. err := c.ShouldBindJSON(&channelBatch)
  451. if err != nil || len(channelBatch.Ids) == 0 {
  452. c.JSON(http.StatusOK, gin.H{
  453. "success": false,
  454. "message": "参数错误",
  455. })
  456. return
  457. }
  458. err = model.BatchDeleteChannels(channelBatch.Ids)
  459. if err != nil {
  460. c.JSON(http.StatusOK, gin.H{
  461. "success": false,
  462. "message": err.Error(),
  463. })
  464. return
  465. }
  466. c.JSON(http.StatusOK, gin.H{
  467. "success": true,
  468. "message": "",
  469. "data": len(channelBatch.Ids),
  470. })
  471. return
  472. }
  473. func UpdateChannel(c *gin.Context) {
  474. channel := model.Channel{}
  475. err := c.ShouldBindJSON(&channel)
  476. if err != nil {
  477. c.JSON(http.StatusOK, gin.H{
  478. "success": false,
  479. "message": err.Error(),
  480. })
  481. return
  482. }
  483. if channel.Type == common.ChannelTypeVertexAi {
  484. if channel.Other == "" {
  485. c.JSON(http.StatusOK, gin.H{
  486. "success": false,
  487. "message": "部署地区不能为空",
  488. })
  489. return
  490. } else {
  491. if common.IsJsonStr(channel.Other) {
  492. // must have default
  493. regionMap := common.StrToMap(channel.Other)
  494. if regionMap["default"] == nil {
  495. c.JSON(http.StatusOK, gin.H{
  496. "success": false,
  497. "message": "部署地区必须包含default字段",
  498. })
  499. return
  500. }
  501. }
  502. }
  503. }
  504. err = channel.Update()
  505. if err != nil {
  506. c.JSON(http.StatusOK, gin.H{
  507. "success": false,
  508. "message": err.Error(),
  509. })
  510. return
  511. }
  512. channel.Key = ""
  513. c.JSON(http.StatusOK, gin.H{
  514. "success": true,
  515. "message": "",
  516. "data": channel,
  517. })
  518. return
  519. }
  520. func FetchModels(c *gin.Context) {
  521. var req struct {
  522. BaseURL string `json:"base_url"`
  523. Type int `json:"type"`
  524. Key string `json:"key"`
  525. }
  526. if err := c.ShouldBindJSON(&req); err != nil {
  527. c.JSON(http.StatusBadRequest, gin.H{
  528. "success": false,
  529. "message": "Invalid request",
  530. })
  531. return
  532. }
  533. baseURL := req.BaseURL
  534. if baseURL == "" {
  535. baseURL = common.ChannelBaseURLs[req.Type]
  536. }
  537. client := &http.Client{}
  538. url := fmt.Sprintf("%s/v1/models", baseURL)
  539. request, err := http.NewRequest("GET", url, nil)
  540. if err != nil {
  541. c.JSON(http.StatusInternalServerError, gin.H{
  542. "success": false,
  543. "message": err.Error(),
  544. })
  545. return
  546. }
  547. // remove line breaks and extra spaces.
  548. key := strings.TrimSpace(req.Key)
  549. // If the key contains a line break, only take the first part.
  550. key = strings.Split(key, "\n")[0]
  551. request.Header.Set("Authorization", "Bearer "+key)
  552. response, err := client.Do(request)
  553. if err != nil {
  554. c.JSON(http.StatusInternalServerError, gin.H{
  555. "success": false,
  556. "message": err.Error(),
  557. })
  558. return
  559. }
  560. //check status code
  561. if response.StatusCode != http.StatusOK {
  562. c.JSON(http.StatusInternalServerError, gin.H{
  563. "success": false,
  564. "message": "Failed to fetch models",
  565. })
  566. return
  567. }
  568. defer response.Body.Close()
  569. var result struct {
  570. Data []struct {
  571. ID string `json:"id"`
  572. } `json:"data"`
  573. }
  574. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  575. c.JSON(http.StatusInternalServerError, gin.H{
  576. "success": false,
  577. "message": err.Error(),
  578. })
  579. return
  580. }
  581. var models []string
  582. for _, model := range result.Data {
  583. models = append(models, model.ID)
  584. }
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": true,
  587. "data": models,
  588. })
  589. }
  590. func BatchSetChannelTag(c *gin.Context) {
  591. channelBatch := ChannelBatch{}
  592. err := c.ShouldBindJSON(&channelBatch)
  593. if err != nil || len(channelBatch.Ids) == 0 {
  594. c.JSON(http.StatusOK, gin.H{
  595. "success": false,
  596. "message": "参数错误",
  597. })
  598. return
  599. }
  600. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.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. "data": len(channelBatch.Ids),
  612. })
  613. return
  614. }
  615. func GetTagModels(c *gin.Context) {
  616. tag := c.Query("tag")
  617. if tag == "" {
  618. c.JSON(http.StatusBadRequest, gin.H{
  619. "success": false,
  620. "message": "tag不能为空",
  621. })
  622. return
  623. }
  624. channels, err := model.GetChannelsByTag(tag, false) // Assuming false for idSort is fine here
  625. if err != nil {
  626. c.JSON(http.StatusInternalServerError, gin.H{
  627. "success": false,
  628. "message": err.Error(),
  629. })
  630. return
  631. }
  632. var longestModels string
  633. maxLength := 0
  634. // Find the longest models string among all channels with the given tag
  635. for _, channel := range channels {
  636. if channel.Models != "" {
  637. currentModels := strings.Split(channel.Models, ",")
  638. if len(currentModels) > maxLength {
  639. maxLength = len(currentModels)
  640. longestModels = channel.Models
  641. }
  642. }
  643. }
  644. c.JSON(http.StatusOK, gin.H{
  645. "success": true,
  646. "message": "",
  647. "data": longestModels,
  648. })
  649. return
  650. }