relay-audio.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package relay
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/gin-gonic/gin"
  9. "io"
  10. "net/http"
  11. "one-api/common"
  12. "one-api/dto"
  13. "one-api/model"
  14. relaycommon "one-api/relay/common"
  15. relayconstant "one-api/relay/constant"
  16. "one-api/service"
  17. "strings"
  18. "time"
  19. )
  20. var availableVoices = []string{
  21. "alloy",
  22. "echo",
  23. "fable",
  24. "onyx",
  25. "nova",
  26. "shimmer",
  27. }
  28. func AudioHelper(c *gin.Context, relayMode int) *dto.OpenAIErrorWithStatusCode {
  29. tokenId := c.GetInt("token_id")
  30. channelType := c.GetInt("channel")
  31. channelId := c.GetInt("channel_id")
  32. userId := c.GetInt("id")
  33. group := c.GetString("group")
  34. startTime := time.Now()
  35. var audioRequest dto.TextToSpeechRequest
  36. if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  37. err := common.UnmarshalBodyReusable(c, &audioRequest)
  38. if err != nil {
  39. return service.OpenAIErrorWrapper(err, "bind_request_body_failed", http.StatusBadRequest)
  40. }
  41. } else {
  42. audioRequest = dto.TextToSpeechRequest{
  43. Model: "whisper-1",
  44. }
  45. }
  46. //err := common.UnmarshalBodyReusable(c, &audioRequest)
  47. // request validation
  48. if audioRequest.Model == "" {
  49. return service.OpenAIErrorWrapper(errors.New("model is required"), "required_field_missing", http.StatusBadRequest)
  50. }
  51. if strings.HasPrefix(audioRequest.Model, "tts-1") {
  52. if audioRequest.Voice == "" {
  53. return service.OpenAIErrorWrapper(errors.New("voice is required"), "required_field_missing", http.StatusBadRequest)
  54. }
  55. if !common.StringsContains(availableVoices, audioRequest.Voice) {
  56. return service.OpenAIErrorWrapper(errors.New("voice must be one of "+strings.Join(availableVoices, ", ")), "invalid_field_value", http.StatusBadRequest)
  57. }
  58. }
  59. preConsumedTokens := common.PreConsumedQuota
  60. modelRatio := common.GetModelRatio(audioRequest.Model)
  61. groupRatio := common.GetGroupRatio(group)
  62. ratio := modelRatio * groupRatio
  63. preConsumedQuota := int(float64(preConsumedTokens) * ratio)
  64. userQuota, err := model.CacheGetUserQuota(userId)
  65. if err != nil {
  66. return service.OpenAIErrorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
  67. }
  68. if userQuota-preConsumedQuota < 0 {
  69. return service.OpenAIErrorWrapper(errors.New("user quota is not enough"), "insufficient_user_quota", http.StatusForbidden)
  70. }
  71. err = model.CacheDecreaseUserQuota(userId, preConsumedQuota)
  72. if err != nil {
  73. return service.OpenAIErrorWrapper(err, "decrease_user_quota_failed", http.StatusInternalServerError)
  74. }
  75. if userQuota > 100*preConsumedQuota {
  76. // in this case, we do not pre-consume quota
  77. // because the user has enough quota
  78. preConsumedQuota = 0
  79. }
  80. if preConsumedQuota > 0 {
  81. userQuota, err = model.PreConsumeTokenQuota(tokenId, preConsumedQuota)
  82. if err != nil {
  83. return service.OpenAIErrorWrapper(err, "pre_consume_token_quota_failed", http.StatusForbidden)
  84. }
  85. }
  86. // map model name
  87. modelMapping := c.GetString("model_mapping")
  88. if modelMapping != "" {
  89. modelMap := make(map[string]string)
  90. err := json.Unmarshal([]byte(modelMapping), &modelMap)
  91. if err != nil {
  92. return service.OpenAIErrorWrapper(err, "unmarshal_model_mapping_failed", http.StatusInternalServerError)
  93. }
  94. if modelMap[audioRequest.Model] != "" {
  95. audioRequest.Model = modelMap[audioRequest.Model]
  96. }
  97. }
  98. baseURL := common.ChannelBaseURLs[channelType]
  99. requestURL := c.Request.URL.String()
  100. if c.GetString("base_url") != "" {
  101. baseURL = c.GetString("base_url")
  102. }
  103. fullRequestURL := relaycommon.GetFullRequestURL(baseURL, requestURL, channelType)
  104. if relayMode == relayconstant.RelayModeAudioTranscription && channelType == common.ChannelTypeAzure {
  105. // https://learn.microsoft.com/en-us/azure/ai-services/openai/whisper-quickstart?tabs=command-line#rest-api
  106. apiVersion := relaycommon.GetAzureAPIVersion(c)
  107. fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/audio/transcriptions?api-version=%s", baseURL, audioRequest.Model, apiVersion)
  108. }
  109. requestBody := c.Request.Body
  110. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  111. if err != nil {
  112. return service.OpenAIErrorWrapper(err, "new_request_failed", http.StatusInternalServerError)
  113. }
  114. if relayMode == relayconstant.RelayModeAudioTranscription && channelType == common.ChannelTypeAzure {
  115. // https://learn.microsoft.com/en-us/azure/ai-services/openai/whisper-quickstart?tabs=command-line#rest-api
  116. apiKey := c.Request.Header.Get("Authorization")
  117. apiKey = strings.TrimPrefix(apiKey, "Bearer ")
  118. req.Header.Set("api-key", apiKey)
  119. req.ContentLength = c.Request.ContentLength
  120. } else {
  121. req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
  122. }
  123. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  124. req.Header.Set("Accept", c.Request.Header.Get("Accept"))
  125. resp, err := service.GetHttpClient().Do(req)
  126. if err != nil {
  127. return service.OpenAIErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
  128. }
  129. err = req.Body.Close()
  130. if err != nil {
  131. return service.OpenAIErrorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
  132. }
  133. err = c.Request.Body.Close()
  134. if err != nil {
  135. return service.OpenAIErrorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
  136. }
  137. if resp.StatusCode != http.StatusOK {
  138. return relaycommon.RelayErrorHandler(resp)
  139. }
  140. var audioResponse dto.AudioResponse
  141. defer func(ctx context.Context) {
  142. go func() {
  143. useTimeSeconds := time.Now().Unix() - startTime.Unix()
  144. quota := 0
  145. var promptTokens = 0
  146. if strings.HasPrefix(audioRequest.Model, "tts-1") {
  147. quota = service.CountAudioToken(audioRequest.Input, audioRequest.Model)
  148. promptTokens = quota
  149. } else {
  150. quota = service.CountAudioToken(audioResponse.Text, audioRequest.Model)
  151. }
  152. quota = int(float64(quota) * ratio)
  153. if ratio != 0 && quota <= 0 {
  154. quota = 1
  155. }
  156. quotaDelta := quota - preConsumedQuota
  157. err := model.PostConsumeTokenQuota(tokenId, userQuota, quotaDelta, preConsumedQuota, true)
  158. if err != nil {
  159. common.SysError("error consuming token remain quota: " + err.Error())
  160. }
  161. err = model.CacheUpdateUserQuota(userId)
  162. if err != nil {
  163. common.SysError("error update user quota cache: " + err.Error())
  164. }
  165. if quota != 0 {
  166. tokenName := c.GetString("token_name")
  167. logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f", modelRatio, groupRatio)
  168. model.RecordConsumeLog(ctx, userId, channelId, promptTokens, 0, audioRequest.Model, tokenName, quota, logContent, tokenId, userQuota, int(useTimeSeconds), false)
  169. model.UpdateUserUsedQuotaAndRequestCount(userId, quota)
  170. channelId := c.GetInt("channel_id")
  171. model.UpdateChannelUsedQuota(channelId, quota)
  172. }
  173. }()
  174. }(c.Request.Context())
  175. responseBody, err := io.ReadAll(resp.Body)
  176. if err != nil {
  177. return service.OpenAIErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  178. }
  179. err = resp.Body.Close()
  180. if err != nil {
  181. return service.OpenAIErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError)
  182. }
  183. if strings.HasPrefix(audioRequest.Model, "tts-1") {
  184. } else {
  185. err = json.Unmarshal(responseBody, &audioResponse)
  186. if err != nil {
  187. return service.OpenAIErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError)
  188. }
  189. }
  190. resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
  191. for k, v := range resp.Header {
  192. c.Writer.Header().Set(k, v[0])
  193. }
  194. c.Writer.WriteHeader(resp.StatusCode)
  195. _, err = io.Copy(c.Writer, resp.Body)
  196. if err != nil {
  197. return service.OpenAIErrorWrapper(err, "copy_response_body_failed", http.StatusInternalServerError)
  198. }
  199. err = resp.Body.Close()
  200. if err != nil {
  201. return service.OpenAIErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError)
  202. }
  203. return nil
  204. }