Browse Source

feat: 添加SiliconFlow图像生成接口自动转换支持

1. 将对SiliconFlow渠道的RelayModeImagesGenerations请求,转发至v1/images/generations端点。
2. SiliconFlow图像生成接口额外参数适配。
etnAtker 4 months ago
parent
commit
3172c956f7
2 changed files with 37 additions and 2 deletions
  1. 22 2
      relay/channel/siliconflow/adaptor.go
  2. 15 0
      relay/channel/siliconflow/dto.go

+ 22 - 2
relay/channel/siliconflow/adaptor.go

@@ -6,6 +6,7 @@ import (
 	"io"
 	"net/http"
 
+	"github.com/QuantumNous/new-api/common"
 	"github.com/QuantumNous/new-api/dto"
 	"github.com/QuantumNous/new-api/relay/channel"
 	"github.com/QuantumNous/new-api/relay/channel/openai"
@@ -35,8 +36,25 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
 }
 
 func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
-	adaptor := openai.Adaptor{}
-	return adaptor.ConvertImageRequest(c, info, request)
+	// 解析extra到SFImageRequest里,以填入SiliconFlow特殊字段。若失败重建一个空的。
+	extra, _ := common.Marshal(request.Extra)
+	sfRequest := &SFImageRequest{}
+	err := common.Unmarshal(extra, sfRequest)
+	if err != nil {
+		sfRequest = &SFImageRequest{}
+	}
+
+	sfRequest.Model = request.Model
+	sfRequest.Prompt = request.Prompt
+	// 优先使用image_size/batch_size,否则使用OpenAI标准的size/n
+	if sfRequest.ImageSize == "" {
+		sfRequest.ImageSize = request.Size
+	}
+	if sfRequest.BatchSize == 0 {
+		sfRequest.BatchSize = request.N
+	}
+
+	return sfRequest, nil
 }
 
 func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
@@ -51,6 +69,8 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
 		return fmt.Sprintf("%s/v1/chat/completions", info.ChannelBaseUrl), nil
 	} else if info.RelayMode == constant.RelayModeCompletions {
 		return fmt.Sprintf("%s/v1/completions", info.ChannelBaseUrl), nil
+	} else if info.RelayMode == constant.RelayModeImagesGenerations {
+		return fmt.Sprintf("%s/v1/images/generations", info.ChannelBaseUrl), nil
 	}
 	return fmt.Sprintf("%s/v1/chat/completions", info.ChannelBaseUrl), nil
 }

+ 15 - 0
relay/channel/siliconflow/dto.go

@@ -15,3 +15,18 @@ type SFRerankResponse struct {
 	Results []dto.RerankResponseResult `json:"results"`
 	Meta    SFMeta                     `json:"meta"`
 }
+
+type SFImageRequest struct {
+	Model             string  `json:"model"`
+	Prompt            string  `json:"prompt"`
+	NegativePrompt    string  `json:"negative_prompt,omitempty"`
+	ImageSize         string  `json:"image_size,omitempty"`
+	BatchSize         uint    `json:"batch_size,omitempty"`
+	Seed              uint64  `json:"seed,omitempty"`
+	NumInferenceSteps uint    `json:"num_inference_steps,omitempty"`
+	GuidanceScale     float64 `json:"guidance_scale,omitempty"`
+	Cfg               float64 `json:"cfg,omitempty"`
+	Image             string  `json:"image,omitempty"`
+	Image2            string  `json:"image2,omitempty"`
+	Image3            string  `json:"image3,omitempty"`
+}