channel.go 16 KB

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