relay-image.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package relay
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "io"
  9. "net/http"
  10. "one-api/common"
  11. "one-api/constant"
  12. "one-api/dto"
  13. "one-api/model"
  14. relaycommon "one-api/relay/common"
  15. "one-api/service"
  16. "strings"
  17. )
  18. func getAndValidImageRequest(c *gin.Context, info *relaycommon.RelayInfo) (*dto.ImageRequest, error) {
  19. imageRequest := &dto.ImageRequest{}
  20. err := common.UnmarshalBodyReusable(c, imageRequest)
  21. if err != nil {
  22. return nil, err
  23. }
  24. if imageRequest.Prompt == "" {
  25. return nil, errors.New("prompt is required")
  26. }
  27. if strings.Contains(imageRequest.Size, "×") {
  28. return nil, errors.New("size an unexpected error occurred in the parameter, please use 'x' instead of the multiplication sign '×'")
  29. }
  30. if imageRequest.N == 0 {
  31. imageRequest.N = 1
  32. }
  33. if imageRequest.Size == "" {
  34. imageRequest.Size = "1024x1024"
  35. }
  36. if imageRequest.Model == "" {
  37. imageRequest.Model = "dall-e-2"
  38. }
  39. if imageRequest.Quality == "" {
  40. imageRequest.Quality = "standard"
  41. }
  42. // Not "256x256", "512x512", or "1024x1024"
  43. if imageRequest.Model == "dall-e-2" || imageRequest.Model == "dall-e" {
  44. if imageRequest.Size != "" && imageRequest.Size != "256x256" && imageRequest.Size != "512x512" && imageRequest.Size != "1024x1024" {
  45. return nil, errors.New("size must be one of 256x256, 512x512, or 1024x1024, dall-e-3 1024x1792 or 1792x1024")
  46. }
  47. } else if imageRequest.Model == "dall-e-3" {
  48. if imageRequest.Size != "" && imageRequest.Size != "1024x1024" && imageRequest.Size != "1024x1792" && imageRequest.Size != "1792x1024" {
  49. return nil, errors.New("size must be one of 256x256, 512x512, or 1024x1024, dall-e-3 1024x1792 or 1792x1024")
  50. }
  51. //if imageRequest.N != 1 {
  52. // return nil, errors.New("n must be 1")
  53. //}
  54. }
  55. // N should between 1 and 10
  56. //if imageRequest.N != 0 && (imageRequest.N < 1 || imageRequest.N > 10) {
  57. // return service.OpenAIErrorWrapper(errors.New("n must be between 1 and 10"), "invalid_field_value", http.StatusBadRequest)
  58. //}
  59. if constant.ShouldCheckPromptSensitive() {
  60. err := service.CheckSensitiveInput(imageRequest.Prompt)
  61. if err != nil {
  62. return nil, err
  63. }
  64. }
  65. return imageRequest, nil
  66. }
  67. func ImageHelper(c *gin.Context, relayMode int) *dto.OpenAIErrorWithStatusCode {
  68. relayInfo := relaycommon.GenRelayInfo(c)
  69. imageRequest, err := getAndValidImageRequest(c, relayInfo)
  70. if err != nil {
  71. common.LogError(c, fmt.Sprintf("getAndValidImageRequest failed: %s", err.Error()))
  72. return service.OpenAIErrorWrapper(err, "invalid_image_request", http.StatusBadRequest)
  73. }
  74. // map model name
  75. modelMapping := c.GetString("model_mapping")
  76. if modelMapping != "" {
  77. modelMap := make(map[string]string)
  78. err := json.Unmarshal([]byte(modelMapping), &modelMap)
  79. if err != nil {
  80. return service.OpenAIErrorWrapper(err, "unmarshal_model_mapping_failed", http.StatusInternalServerError)
  81. }
  82. if modelMap[imageRequest.Model] != "" {
  83. imageRequest.Model = modelMap[imageRequest.Model]
  84. }
  85. }
  86. relayInfo.UpstreamModelName = imageRequest.Model
  87. modelPrice, success := common.GetModelPrice(imageRequest.Model, true)
  88. if !success {
  89. modelRatio := common.GetModelRatio(imageRequest.Model)
  90. // modelRatio 16 = modelPrice $0.04
  91. // per 1 modelRatio = $0.04 / 16
  92. modelPrice = 0.0025 * modelRatio
  93. }
  94. groupRatio := common.GetGroupRatio(relayInfo.Group)
  95. userQuota, err := model.CacheGetUserQuota(relayInfo.UserId)
  96. sizeRatio := 1.0
  97. // Size
  98. if imageRequest.Size == "256x256" {
  99. sizeRatio = 0.4
  100. } else if imageRequest.Size == "512x512" {
  101. sizeRatio = 0.45
  102. } else if imageRequest.Size == "1024x1024" {
  103. sizeRatio = 1
  104. } else if imageRequest.Size == "1024x1792" || imageRequest.Size == "1792x1024" {
  105. sizeRatio = 2
  106. }
  107. qualityRatio := 1.0
  108. if imageRequest.Model == "dall-e-3" && imageRequest.Quality == "hd" {
  109. qualityRatio = 2.0
  110. if imageRequest.Size == "1024x1792" || imageRequest.Size == "1792x1024" {
  111. qualityRatio = 1.5
  112. }
  113. }
  114. imageRatio := modelPrice * sizeRatio * qualityRatio * float64(imageRequest.N)
  115. quota := int(imageRatio * groupRatio * common.QuotaPerUnit)
  116. if userQuota-quota < 0 {
  117. return service.OpenAIErrorWrapperLocal(errors.New("user quota is not enough"), "insufficient_user_quota", http.StatusForbidden)
  118. }
  119. adaptor := GetAdaptor(relayInfo.ApiType)
  120. if adaptor == nil {
  121. return service.OpenAIErrorWrapperLocal(fmt.Errorf("invalid api type: %d", relayInfo.ApiType), "invalid_api_type", http.StatusBadRequest)
  122. }
  123. adaptor.Init(relayInfo)
  124. var requestBody io.Reader
  125. convertedRequest, err := adaptor.ConvertImageRequest(c, relayInfo, *imageRequest)
  126. if err != nil {
  127. return service.OpenAIErrorWrapperLocal(err, "convert_request_failed", http.StatusInternalServerError)
  128. }
  129. jsonData, err := json.Marshal(convertedRequest)
  130. if err != nil {
  131. return service.OpenAIErrorWrapperLocal(err, "json_marshal_failed", http.StatusInternalServerError)
  132. }
  133. requestBody = bytes.NewBuffer(jsonData)
  134. statusCodeMappingStr := c.GetString("status_code_mapping")
  135. resp, err := adaptor.DoRequest(c, relayInfo, requestBody)
  136. if err != nil {
  137. return service.OpenAIErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
  138. }
  139. if resp != nil {
  140. relayInfo.IsStream = relayInfo.IsStream || strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream")
  141. if resp.StatusCode != http.StatusOK {
  142. openaiErr := service.RelayErrorHandler(resp)
  143. // reset status code 重置状态码
  144. service.ResetStatusCode(openaiErr, statusCodeMappingStr)
  145. return openaiErr
  146. }
  147. }
  148. _, openaiErr := adaptor.DoResponse(c, resp, relayInfo)
  149. if openaiErr != nil {
  150. // reset status code 重置状态码
  151. service.ResetStatusCode(openaiErr, statusCodeMappingStr)
  152. return openaiErr
  153. }
  154. usage := &dto.Usage{
  155. PromptTokens: imageRequest.N,
  156. TotalTokens: imageRequest.N,
  157. }
  158. quality := "standard"
  159. if imageRequest.Quality == "hd" {
  160. quality = "hd"
  161. }
  162. logContent := fmt.Sprintf("大小 %s, 品质 %s", imageRequest.Size, quality)
  163. postConsumeQuota(c, relayInfo, imageRequest.Model, usage, 0, 0, userQuota, 0, groupRatio, imageRatio, true, logContent)
  164. return nil
  165. }