2023-06-19 02:28:55 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
2023-07-15 04:30:06 +00:00
|
|
|
"bytes"
|
2023-09-17 07:39:46 +00:00
|
|
|
"context"
|
2023-07-15 04:30:06 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2024-01-28 11:38:58 +00:00
|
|
|
"github.com/songquanpeng/one-api/common"
|
|
|
|
"github.com/songquanpeng/one-api/common/logger"
|
|
|
|
"github.com/songquanpeng/one-api/model"
|
|
|
|
"github.com/songquanpeng/one-api/relay/channel/openai"
|
2024-03-03 11:30:11 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/constant"
|
2024-02-17 16:15:31 +00:00
|
|
|
relaymodel "github.com/songquanpeng/one-api/relay/model"
|
2024-01-28 11:38:58 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/util"
|
2023-06-19 02:28:55 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
2023-12-03 09:34:59 +00:00
|
|
|
"strings"
|
2023-11-17 12:03:16 +00:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-06-19 02:28:55 +00:00
|
|
|
)
|
|
|
|
|
2023-11-17 12:03:16 +00:00
|
|
|
func isWithinRange(element string, value int) bool {
|
2024-03-03 11:30:11 +00:00
|
|
|
if _, ok := constant.DalleGenerationImageAmounts[element]; !ok {
|
2023-11-17 12:03:16 +00:00
|
|
|
return false
|
|
|
|
}
|
2024-03-03 11:30:11 +00:00
|
|
|
min := constant.DalleGenerationImageAmounts[element][0]
|
|
|
|
max := constant.DalleGenerationImageAmounts[element][1]
|
2023-11-17 12:03:16 +00:00
|
|
|
|
|
|
|
return value >= min && value <= max
|
|
|
|
}
|
|
|
|
|
2024-02-17 16:15:31 +00:00
|
|
|
func RelayImageHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatusCode {
|
2024-03-03 11:30:11 +00:00
|
|
|
ctx := c.Request.Context()
|
|
|
|
meta := util.GetRelayMeta(c)
|
|
|
|
imageRequest, err := getImageRequest(c, meta.Mode)
|
2023-11-24 12:42:29 +00:00
|
|
|
if err != nil {
|
2024-03-03 11:30:11 +00:00
|
|
|
logger.Errorf(ctx, "getImageRequest failed: %s", err.Error())
|
|
|
|
return openai.ErrorWrapper(err, "invalid_image_request", http.StatusBadRequest)
|
2023-11-17 12:03:16 +00:00
|
|
|
}
|
|
|
|
|
2024-03-03 11:30:11 +00:00
|
|
|
// map model name
|
|
|
|
var isModelMapped bool
|
|
|
|
meta.OriginModelName = imageRequest.Model
|
|
|
|
imageRequest.Model, isModelMapped = util.GetMappedModelName(imageRequest.Model, meta.ModelMapping)
|
|
|
|
meta.ActualModelName = imageRequest.Model
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2024-03-03 11:30:11 +00:00
|
|
|
// model validation
|
|
|
|
bizErr := validateImageRequest(imageRequest, meta)
|
|
|
|
if bizErr != nil {
|
|
|
|
return bizErr
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
|
2024-03-03 11:30:11 +00:00
|
|
|
imageCostRatio, err := getImageCostRatio(imageRequest)
|
|
|
|
if err != nil {
|
|
|
|
return openai.ErrorWrapper(err, "get_image_cost_ratio_failed", http.StatusInternalServerError)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
requestURL := c.Request.URL.String()
|
2024-03-03 11:30:11 +00:00
|
|
|
fullRequestURL := util.GetFullRequestURL(meta.BaseURL, requestURL, meta.ChannelType)
|
|
|
|
if meta.ChannelType == common.ChannelTypeAzure {
|
2023-12-03 09:34:59 +00:00
|
|
|
// https://learn.microsoft.com/en-us/azure/ai-services/openai/dall-e-quickstart?tabs=dalle3%2Ccommand-line&pivots=rest-api
|
2024-01-21 15:21:42 +00:00
|
|
|
apiVersion := util.GetAzureAPIVersion(c)
|
2024-03-17 11:34:21 +00:00
|
|
|
// https://{resource_name}.openai.azure.com/openai/deployments/dall-e-3/images/generations?api-version=2024-03-01-preview
|
2024-03-03 11:30:11 +00:00
|
|
|
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/images/generations?api-version=%s", meta.BaseURL, imageRequest.Model, apiVersion)
|
2023-12-03 09:34:59 +00:00
|
|
|
}
|
|
|
|
|
2023-07-15 04:30:06 +00:00
|
|
|
var requestBody io.Reader
|
2024-03-03 11:30:11 +00:00
|
|
|
if isModelMapped || meta.ChannelType == common.ChannelTypeAzure { // make Azure channel request body
|
2023-07-15 04:30:06 +00:00
|
|
|
jsonStr, err := json.Marshal(imageRequest)
|
|
|
|
if err != nil {
|
2024-03-03 11:30:11 +00:00
|
|
|
return openai.ErrorWrapper(err, "marshal_image_request_failed", http.StatusInternalServerError)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
requestBody = bytes.NewBuffer(jsonStr)
|
|
|
|
} else {
|
|
|
|
requestBody = c.Request.Body
|
|
|
|
}
|
|
|
|
|
2024-03-03 11:30:11 +00:00
|
|
|
modelRatio := common.GetModelRatio(imageRequest.Model)
|
|
|
|
groupRatio := common.GetGroupRatio(meta.Group)
|
2023-07-15 04:30:06 +00:00
|
|
|
ratio := modelRatio * groupRatio
|
2024-03-13 11:38:44 +00:00
|
|
|
userQuota, err := model.CacheGetUserQuota(ctx, meta.UserId)
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2024-03-13 12:00:51 +00:00
|
|
|
quota := int64(ratio*imageCostRatio*1000) * int64(imageRequest.N)
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-11-24 12:42:29 +00:00
|
|
|
if userQuota-quota < 0 {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(errors.New("user quota is not enough"), "insufficient_user_quota", http.StatusForbidden)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "new_request_failed", http.StatusInternalServerError)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
2023-12-03 09:34:59 +00:00
|
|
|
token := c.Request.Header.Get("Authorization")
|
2024-03-03 11:30:11 +00:00
|
|
|
if meta.ChannelType == common.ChannelTypeAzure { // Azure authentication
|
2023-12-03 09:34:59 +00:00
|
|
|
token = strings.TrimPrefix(token, "Bearer ")
|
|
|
|
req.Header.Set("api-key", token)
|
|
|
|
} else {
|
|
|
|
req.Header.Set("Authorization", token)
|
|
|
|
}
|
2023-07-15 04:30:06 +00:00
|
|
|
|
|
|
|
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
|
|
|
req.Header.Set("Accept", c.Request.Header.Get("Accept"))
|
|
|
|
|
2024-01-14 11:21:03 +00:00
|
|
|
resp, err := util.HTTPClient.Do(req)
|
2023-06-19 02:28:55 +00:00
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-06-19 02:28:55 +00:00
|
|
|
err = req.Body.Close()
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
2024-03-03 11:30:11 +00:00
|
|
|
var imageResponse openai.ImageResponse
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-09-17 07:39:46 +00:00
|
|
|
defer func(ctx context.Context) {
|
2024-01-01 08:18:50 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return
|
|
|
|
}
|
2024-03-03 11:30:11 +00:00
|
|
|
err := model.PostConsumeTokenQuota(meta.TokenId, quota)
|
2023-07-15 04:30:06 +00:00
|
|
|
if err != nil {
|
2024-01-21 15:21:42 +00:00
|
|
|
logger.SysError("error consuming token remain quota: " + err.Error())
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
2024-03-13 11:38:44 +00:00
|
|
|
err = model.CacheUpdateUserQuota(ctx, meta.UserId)
|
2023-07-15 04:30:06 +00:00
|
|
|
if err != nil {
|
2024-01-21 15:21:42 +00:00
|
|
|
logger.SysError("error update user quota cache: " + err.Error())
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
2023-11-24 12:42:29 +00:00
|
|
|
if quota != 0 {
|
|
|
|
tokenName := c.GetString("token_name")
|
|
|
|
logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f", modelRatio, groupRatio)
|
2024-03-03 11:30:11 +00:00
|
|
|
model.RecordConsumeLog(ctx, meta.UserId, meta.ChannelId, 0, 0, imageRequest.Model, tokenName, quota, logContent)
|
|
|
|
model.UpdateUserUsedQuotaAndRequestCount(meta.UserId, quota)
|
2023-11-24 12:42:29 +00:00
|
|
|
channelId := c.GetInt("channel_id")
|
|
|
|
model.UpdateChannelUsedQuota(channelId, quota)
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
2023-11-24 12:42:29 +00:00
|
|
|
}(c.Request.Context())
|
|
|
|
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-11-24 12:42:29 +00:00
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
|
2023-11-24 12:42:29 +00:00
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2024-03-03 11:30:11 +00:00
|
|
|
err = json.Unmarshal(responseBody, &imageResponse)
|
2023-11-24 12:42:29 +00:00
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError)
|
2023-11-24 12:42:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-06-19 02:28:55 +00:00
|
|
|
for k, v := range resp.Header {
|
|
|
|
c.Writer.Header().Set(k, v[0])
|
|
|
|
}
|
|
|
|
c.Writer.WriteHeader(resp.StatusCode)
|
2023-07-15 04:30:06 +00:00
|
|
|
|
2023-06-19 02:28:55 +00:00
|
|
|
_, err = io.Copy(c.Writer, resp.Body)
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "copy_response_body_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|