channel.go 14 KB

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