adaptor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package volcengine
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net/http"
  10. "net/textproto"
  11. "path/filepath"
  12. "strings"
  13. channelconstant "github.com/QuantumNous/new-api/constant"
  14. "github.com/QuantumNous/new-api/dto"
  15. "github.com/QuantumNous/new-api/relay/channel"
  16. "github.com/QuantumNous/new-api/relay/channel/openai"
  17. relaycommon "github.com/QuantumNous/new-api/relay/common"
  18. "github.com/QuantumNous/new-api/relay/constant"
  19. "github.com/QuantumNous/new-api/types"
  20. "github.com/gin-gonic/gin"
  21. )
  22. type Adaptor struct {
  23. }
  24. func (a *Adaptor) ConvertGeminiRequest(*gin.Context, *relaycommon.RelayInfo, *dto.GeminiChatRequest) (any, error) {
  25. //TODO implement me
  26. return nil, errors.New("not implemented")
  27. }
  28. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, req *dto.ClaudeRequest) (any, error) {
  29. adaptor := openai.Adaptor{}
  30. return adaptor.ConvertClaudeRequest(c, info, req)
  31. }
  32. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  33. if info.RelayMode != constant.RelayModeAudioSpeech {
  34. return nil, errors.New("unsupported audio relay mode")
  35. }
  36. appID, token, err := parseVolcengineAuth(info.ApiKey)
  37. if err != nil {
  38. return nil, err
  39. }
  40. voiceType := mapVoiceType(request.Voice)
  41. speedRatio := mapSpeedRatio(request.Speed)
  42. encoding := mapEncoding(request.ResponseFormat)
  43. c.Set("response_format", encoding)
  44. volcRequest := VolcengineTTSRequest{
  45. App: VolcengineTTSApp{
  46. AppID: appID,
  47. Token: token,
  48. Cluster: "volcano_tts",
  49. },
  50. User: VolcengineTTSUser{
  51. UID: "openai_relay_user",
  52. },
  53. Audio: VolcengineTTSAudio{
  54. VoiceType: voiceType,
  55. Encoding: encoding,
  56. SpeedRatio: speedRatio,
  57. Rate: 24000,
  58. },
  59. Request: VolcengineTTSReqInfo{
  60. ReqID: generateRequestID(),
  61. Text: request.Input,
  62. Operation: "query",
  63. Model: info.OriginModelName,
  64. },
  65. }
  66. // 同步扩展字段的厂商自定义metadata
  67. if len(request.Metadata) > 0 {
  68. if err = json.Unmarshal(request.Metadata, &volcRequest); err != nil {
  69. return nil, fmt.Errorf("error unmarshalling metadata to volcengine request: %w", err)
  70. }
  71. }
  72. jsonData, err := json.Marshal(volcRequest)
  73. if err != nil {
  74. return nil, fmt.Errorf("error marshalling volcengine request: %w", err)
  75. }
  76. return bytes.NewReader(jsonData), nil
  77. }
  78. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  79. switch info.RelayMode {
  80. case constant.RelayModeImagesGenerations:
  81. return request, nil
  82. case constant.RelayModeImagesEdits:
  83. var requestBody bytes.Buffer
  84. writer := multipart.NewWriter(&requestBody)
  85. writer.WriteField("model", request.Model)
  86. // 获取所有表单字段
  87. formData := c.Request.PostForm
  88. // 遍历表单字段并打印输出
  89. for key, values := range formData {
  90. if key == "model" {
  91. continue
  92. }
  93. for _, value := range values {
  94. writer.WriteField(key, value)
  95. }
  96. }
  97. // Parse the multipart form to handle both single image and multiple images
  98. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  99. return nil, errors.New("failed to parse multipart form")
  100. }
  101. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  102. // Check if "image" field exists in any form, including array notation
  103. var imageFiles []*multipart.FileHeader
  104. var exists bool
  105. // First check for standard "image" field
  106. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  107. // If not found, check for "image[]" field
  108. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  109. // If still not found, iterate through all fields to find any that start with "image["
  110. foundArrayImages := false
  111. for fieldName, files := range c.Request.MultipartForm.File {
  112. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  113. foundArrayImages = true
  114. for _, file := range files {
  115. imageFiles = append(imageFiles, file)
  116. }
  117. }
  118. }
  119. // If no image fields found at all
  120. if !foundArrayImages && (len(imageFiles) == 0) {
  121. return nil, errors.New("image is required")
  122. }
  123. }
  124. }
  125. // Process all image files
  126. for i, fileHeader := range imageFiles {
  127. file, err := fileHeader.Open()
  128. if err != nil {
  129. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  130. }
  131. defer file.Close()
  132. // If multiple images, use image[] as the field name
  133. fieldName := "image"
  134. if len(imageFiles) > 1 {
  135. fieldName = "image[]"
  136. }
  137. // Determine MIME type based on file extension
  138. mimeType := detectImageMimeType(fileHeader.Filename)
  139. // Create a form file with the appropriate content type
  140. h := make(textproto.MIMEHeader)
  141. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  142. h.Set("Content-Type", mimeType)
  143. part, err := writer.CreatePart(h)
  144. if err != nil {
  145. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  146. }
  147. if _, err := io.Copy(part, file); err != nil {
  148. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  149. }
  150. }
  151. // Handle mask file if present
  152. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  153. maskFile, err := maskFiles[0].Open()
  154. if err != nil {
  155. return nil, errors.New("failed to open mask file")
  156. }
  157. defer maskFile.Close()
  158. // Determine MIME type for mask file
  159. mimeType := detectImageMimeType(maskFiles[0].Filename)
  160. // Create a form file with the appropriate content type
  161. h := make(textproto.MIMEHeader)
  162. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  163. h.Set("Content-Type", mimeType)
  164. maskPart, err := writer.CreatePart(h)
  165. if err != nil {
  166. return nil, errors.New("create form file failed for mask")
  167. }
  168. if _, err := io.Copy(maskPart, maskFile); err != nil {
  169. return nil, errors.New("copy mask file failed")
  170. }
  171. }
  172. } else {
  173. return nil, errors.New("no multipart form data found")
  174. }
  175. // 关闭 multipart 编写器以设置分界线
  176. writer.Close()
  177. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  178. return bytes.NewReader(requestBody.Bytes()), nil
  179. default:
  180. return request, nil
  181. }
  182. }
  183. // detectImageMimeType determines the MIME type based on the file extension
  184. func detectImageMimeType(filename string) string {
  185. ext := strings.ToLower(filepath.Ext(filename))
  186. switch ext {
  187. case ".jpg", ".jpeg":
  188. return "image/jpeg"
  189. case ".png":
  190. return "image/png"
  191. case ".webp":
  192. return "image/webp"
  193. default:
  194. // Try to detect from extension if possible
  195. if strings.HasPrefix(ext, ".jp") {
  196. return "image/jpeg"
  197. }
  198. // Default to png as a fallback
  199. return "image/png"
  200. }
  201. }
  202. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  203. }
  204. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  205. baseUrl := info.ChannelBaseUrl
  206. if baseUrl == "" {
  207. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  208. }
  209. switch info.RelayFormat {
  210. case types.RelayFormatClaude:
  211. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  212. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  213. }
  214. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  215. default:
  216. switch info.RelayMode {
  217. case constant.RelayModeChatCompletions:
  218. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  219. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  220. }
  221. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  222. case constant.RelayModeEmbeddings:
  223. return fmt.Sprintf("%s/api/v3/embeddings", baseUrl), nil
  224. case constant.RelayModeImagesGenerations:
  225. return fmt.Sprintf("%s/api/v3/images/generations", baseUrl), nil
  226. case constant.RelayModeImagesEdits:
  227. return fmt.Sprintf("%s/api/v3/images/edits", baseUrl), nil
  228. case constant.RelayModeRerank:
  229. return fmt.Sprintf("%s/api/v3/rerank", baseUrl), nil
  230. case constant.RelayModeAudioSpeech:
  231. // 只有当 baseUrl 是火山默认的官方Url时才改为官方的的TTS接口,否则走透传的New接口
  232. if baseUrl == channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine] {
  233. return "https://openspeech.bytedance.com/api/v1/tts", nil
  234. }
  235. return fmt.Sprintf("%s/v1/audio/speech", baseUrl), nil
  236. default:
  237. }
  238. }
  239. return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
  240. }
  241. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  242. channel.SetupApiRequestHeader(info, c, req)
  243. if info.RelayMode == constant.RelayModeAudioSpeech {
  244. parts := strings.Split(info.ApiKey, "|")
  245. if len(parts) == 2 {
  246. req.Set("Authorization", "Bearer;"+parts[1])
  247. }
  248. req.Set("Content-Type", "application/json")
  249. return nil
  250. }
  251. req.Set("Authorization", "Bearer "+info.ApiKey)
  252. return nil
  253. }
  254. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  255. if request == nil {
  256. return nil, errors.New("request is nil")
  257. }
  258. // 适配 方舟deepseek混合模型 的 thinking 后缀
  259. if strings.HasSuffix(info.UpstreamModelName, "-thinking") && strings.HasPrefix(info.UpstreamModelName, "deepseek") {
  260. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  261. request.Model = info.UpstreamModelName
  262. request.THINKING = json.RawMessage(`{"type": "enabled"}`)
  263. }
  264. return request, nil
  265. }
  266. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  267. return nil, nil
  268. }
  269. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  270. return request, nil
  271. }
  272. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  273. // TODO implement me
  274. return nil, errors.New("not implemented")
  275. }
  276. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  277. return channel.DoApiRequest(a, c, info, requestBody)
  278. }
  279. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  280. if info.RelayMode == constant.RelayModeAudioSpeech {
  281. encoding := mapEncoding(c.GetString("response_format"))
  282. return handleTTSResponse(c, resp, info, encoding)
  283. }
  284. adaptor := openai.Adaptor{}
  285. usage, err = adaptor.DoResponse(c, resp, info)
  286. return
  287. }
  288. func (a *Adaptor) GetModelList() []string {
  289. return ModelList
  290. }
  291. func (a *Adaptor) GetChannelName() string {
  292. return ChannelName
  293. }