image_handler.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package relay
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/dto"
  10. "github.com/QuantumNous/new-api/logger"
  11. relaycommon "github.com/QuantumNous/new-api/relay/common"
  12. "github.com/QuantumNous/new-api/relay/helper"
  13. "github.com/QuantumNous/new-api/service"
  14. "github.com/QuantumNous/new-api/setting/model_setting"
  15. "github.com/QuantumNous/new-api/types"
  16. "github.com/gin-gonic/gin"
  17. )
  18. func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types.NewAPIError) {
  19. info.InitChannelMeta(c)
  20. imageReq, ok := info.Request.(*dto.ImageRequest)
  21. if !ok {
  22. return types.NewErrorWithStatusCode(fmt.Errorf("invalid request type, expected dto.ImageRequest, got %T", info.Request), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  23. }
  24. request, err := common.DeepCopy(imageReq)
  25. if err != nil {
  26. return types.NewError(fmt.Errorf("failed to copy request to ImageRequest: %w", err), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
  27. }
  28. err = helper.ModelMappedHelper(c, info, request)
  29. if err != nil {
  30. return types.NewError(err, types.ErrorCodeChannelModelMappedError, types.ErrOptionWithSkipRetry())
  31. }
  32. adaptor := GetAdaptor(info.ApiType)
  33. if adaptor == nil {
  34. return types.NewError(fmt.Errorf("invalid api type: %d", info.ApiType), types.ErrorCodeInvalidApiType, types.ErrOptionWithSkipRetry())
  35. }
  36. adaptor.Init(info)
  37. var requestBody io.Reader
  38. if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
  39. body, err := common.GetRequestBody(c)
  40. if err != nil {
  41. return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  42. }
  43. requestBody = bytes.NewBuffer(body)
  44. } else {
  45. convertedRequest, err := adaptor.ConvertImageRequest(c, info, *request)
  46. if err != nil {
  47. return types.NewError(err, types.ErrorCodeConvertRequestFailed)
  48. }
  49. switch convertedRequest.(type) {
  50. case *bytes.Buffer:
  51. requestBody = convertedRequest.(io.Reader)
  52. default:
  53. jsonData, err := common.Marshal(convertedRequest)
  54. if err != nil {
  55. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  56. }
  57. // apply param override
  58. if len(info.ParamOverride) > 0 {
  59. jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride)
  60. if err != nil {
  61. return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
  62. }
  63. }
  64. if common.DebugEnabled {
  65. logger.LogDebug(c, fmt.Sprintf("image request body: %s", string(jsonData)))
  66. }
  67. requestBody = bytes.NewBuffer(jsonData)
  68. }
  69. }
  70. statusCodeMappingStr := c.GetString("status_code_mapping")
  71. resp, err := adaptor.DoRequest(c, info, requestBody)
  72. if err != nil {
  73. return types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError)
  74. }
  75. var httpResp *http.Response
  76. if resp != nil {
  77. httpResp = resp.(*http.Response)
  78. info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  79. if httpResp.StatusCode != http.StatusOK {
  80. newAPIError = service.RelayErrorHandler(c.Request.Context(), httpResp, false)
  81. // reset status code 重置状态码
  82. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  83. return newAPIError
  84. }
  85. }
  86. usage, newAPIError := adaptor.DoResponse(c, httpResp, info)
  87. if newAPIError != nil {
  88. // reset status code 重置状态码
  89. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  90. return newAPIError
  91. }
  92. if usage.(*dto.Usage).TotalTokens == 0 {
  93. usage.(*dto.Usage).TotalTokens = int(request.N)
  94. }
  95. if usage.(*dto.Usage).PromptTokens == 0 {
  96. usage.(*dto.Usage).PromptTokens = int(request.N)
  97. }
  98. quality := "standard"
  99. if request.Quality == "hd" {
  100. quality = "hd"
  101. }
  102. var logContent string
  103. if len(request.Size) > 0 {
  104. logContent = fmt.Sprintf("大小 %s, 品质 %s, 张数 %d", request.Size, quality, request.N)
  105. }
  106. postConsumeQuota(c, info, usage.(*dto.Usage), logContent)
  107. return nil
  108. }