image_handler.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. relaycommon.AppendRequestConversionFromRequest(info, convertedRequest)
  51. switch convertedRequest.(type) {
  52. case *bytes.Buffer:
  53. requestBody = convertedRequest.(io.Reader)
  54. default:
  55. jsonData, err := common.Marshal(convertedRequest)
  56. if err != nil {
  57. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  58. }
  59. // apply param override
  60. if len(info.ParamOverride) > 0 {
  61. jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
  62. if err != nil {
  63. return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
  64. }
  65. }
  66. if common.DebugEnabled {
  67. logger.LogDebug(c, fmt.Sprintf("image request body: %s", string(jsonData)))
  68. }
  69. requestBody = bytes.NewBuffer(jsonData)
  70. }
  71. }
  72. statusCodeMappingStr := c.GetString("status_code_mapping")
  73. resp, err := adaptor.DoRequest(c, info, requestBody)
  74. if err != nil {
  75. return types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError)
  76. }
  77. var httpResp *http.Response
  78. if resp != nil {
  79. httpResp = resp.(*http.Response)
  80. info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  81. if httpResp.StatusCode != http.StatusOK {
  82. if httpResp.StatusCode == http.StatusCreated && info.ApiType == constant.APITypeReplicate {
  83. // replicate channel returns 201 Created when using Prefer: wait, treat it as success.
  84. httpResp.StatusCode = http.StatusOK
  85. } else {
  86. newAPIError = service.RelayErrorHandler(c.Request.Context(), httpResp, false)
  87. // reset status code 重置状态码
  88. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  89. return newAPIError
  90. }
  91. }
  92. }
  93. usage, newAPIError := adaptor.DoResponse(c, httpResp, info)
  94. if newAPIError != nil {
  95. // reset status code 重置状态码
  96. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  97. return newAPIError
  98. }
  99. if usage.(*dto.Usage).TotalTokens == 0 {
  100. usage.(*dto.Usage).TotalTokens = int(request.N)
  101. }
  102. if usage.(*dto.Usage).PromptTokens == 0 {
  103. usage.(*dto.Usage).PromptTokens = int(request.N)
  104. }
  105. quality := "standard"
  106. if request.Quality == "hd" {
  107. quality = "hd"
  108. }
  109. var logContent []string
  110. if len(request.Size) > 0 {
  111. logContent = append(logContent, fmt.Sprintf("大小 %s", request.Size))
  112. }
  113. if len(quality) > 0 {
  114. logContent = append(logContent, fmt.Sprintf("品质 %s", quality))
  115. }
  116. if request.N > 0 {
  117. logContent = append(logContent, fmt.Sprintf("生成数量 %d", request.N))
  118. }
  119. postConsumeQuota(c, info, usage.(*dto.Usage), logContent...)
  120. return nil
  121. }