distributor.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "strconv"
  9. "strings"
  10. )
  11. type ModelRequest struct {
  12. Model string `json:"model"`
  13. }
  14. func Distribute() func(c *gin.Context) {
  15. return func(c *gin.Context) {
  16. userId := c.GetInt("id")
  17. userGroup, _ := model.CacheGetUserGroup(userId)
  18. c.Set("group", userGroup)
  19. var channel *model.Channel
  20. channelId, ok := c.Get("channelId")
  21. if ok {
  22. id, err := strconv.Atoi(channelId.(string))
  23. if err != nil {
  24. c.JSON(http.StatusBadRequest, gin.H{
  25. "error": gin.H{
  26. "message": "无效的渠道 ID",
  27. "type": "one_api_error",
  28. },
  29. })
  30. c.Abort()
  31. return
  32. }
  33. channel, err = model.GetChannelById(id, true)
  34. if err != nil {
  35. c.JSON(http.StatusBadRequest, gin.H{
  36. "error": gin.H{
  37. "message": "无效的渠道 ID",
  38. "type": "one_api_error",
  39. },
  40. })
  41. c.Abort()
  42. return
  43. }
  44. if channel.Status != common.ChannelStatusEnabled {
  45. c.JSON(http.StatusForbidden, gin.H{
  46. "error": gin.H{
  47. "message": "该渠道已被禁用",
  48. "type": "one_api_error",
  49. },
  50. })
  51. c.Abort()
  52. return
  53. }
  54. } else {
  55. // Select a channel for the user
  56. var modelRequest ModelRequest
  57. err := common.UnmarshalBodyReusable(c, &modelRequest)
  58. if err != nil {
  59. c.JSON(http.StatusBadRequest, gin.H{
  60. "error": gin.H{
  61. "message": "无效的请求",
  62. "type": "one_api_error",
  63. },
  64. })
  65. c.Abort()
  66. return
  67. }
  68. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  69. if modelRequest.Model == "" {
  70. modelRequest.Model = "text-moderation-stable"
  71. }
  72. }
  73. channel, err = model.CacheGetRandomSatisfiedChannel(userGroup, modelRequest.Model)
  74. if err != nil {
  75. c.JSON(http.StatusServiceUnavailable, gin.H{
  76. "error": gin.H{
  77. "message": "无可用渠道",
  78. "type": "one_api_error",
  79. },
  80. })
  81. c.Abort()
  82. return
  83. }
  84. }
  85. c.Set("channel", channel.Type)
  86. c.Set("channel_id", channel.Id)
  87. c.Set("channel_name", channel.Name)
  88. c.Set("model_mapping", channel.ModelMapping)
  89. c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
  90. c.Set("base_url", channel.BaseURL)
  91. if channel.Type == common.ChannelTypeAzure {
  92. c.Set("api_version", channel.Other)
  93. }
  94. c.Next()
  95. }
  96. }