image_handler.go 4.4 KB

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