adaptor.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. //TODO implement me
  34. return nil, errors.New("not implemented")
  35. }
  36. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  37. switch info.RelayMode {
  38. case constant.RelayModeImagesGenerations:
  39. return request, nil
  40. case constant.RelayModeImagesEdits:
  41. var requestBody bytes.Buffer
  42. writer := multipart.NewWriter(&requestBody)
  43. writer.WriteField("model", request.Model)
  44. // 获取所有表单字段
  45. formData := c.Request.PostForm
  46. // 遍历表单字段并打印输出
  47. for key, values := range formData {
  48. if key == "model" {
  49. continue
  50. }
  51. for _, value := range values {
  52. writer.WriteField(key, value)
  53. }
  54. }
  55. // Parse the multipart form to handle both single image and multiple images
  56. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  57. return nil, errors.New("failed to parse multipart form")
  58. }
  59. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  60. // Check if "image" field exists in any form, including array notation
  61. var imageFiles []*multipart.FileHeader
  62. var exists bool
  63. // First check for standard "image" field
  64. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  65. // If not found, check for "image[]" field
  66. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  67. // If still not found, iterate through all fields to find any that start with "image["
  68. foundArrayImages := false
  69. for fieldName, files := range c.Request.MultipartForm.File {
  70. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  71. foundArrayImages = true
  72. for _, file := range files {
  73. imageFiles = append(imageFiles, file)
  74. }
  75. }
  76. }
  77. // If no image fields found at all
  78. if !foundArrayImages && (len(imageFiles) == 0) {
  79. return nil, errors.New("image is required")
  80. }
  81. }
  82. }
  83. // Process all image files
  84. for i, fileHeader := range imageFiles {
  85. file, err := fileHeader.Open()
  86. if err != nil {
  87. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  88. }
  89. defer file.Close()
  90. // If multiple images, use image[] as the field name
  91. fieldName := "image"
  92. if len(imageFiles) > 1 {
  93. fieldName = "image[]"
  94. }
  95. // Determine MIME type based on file extension
  96. mimeType := detectImageMimeType(fileHeader.Filename)
  97. // Create a form file with the appropriate content type
  98. h := make(textproto.MIMEHeader)
  99. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  100. h.Set("Content-Type", mimeType)
  101. part, err := writer.CreatePart(h)
  102. if err != nil {
  103. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  104. }
  105. if _, err := io.Copy(part, file); err != nil {
  106. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  107. }
  108. }
  109. // Handle mask file if present
  110. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  111. maskFile, err := maskFiles[0].Open()
  112. if err != nil {
  113. return nil, errors.New("failed to open mask file")
  114. }
  115. defer maskFile.Close()
  116. // Determine MIME type for mask file
  117. mimeType := detectImageMimeType(maskFiles[0].Filename)
  118. // Create a form file with the appropriate content type
  119. h := make(textproto.MIMEHeader)
  120. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  121. h.Set("Content-Type", mimeType)
  122. maskPart, err := writer.CreatePart(h)
  123. if err != nil {
  124. return nil, errors.New("create form file failed for mask")
  125. }
  126. if _, err := io.Copy(maskPart, maskFile); err != nil {
  127. return nil, errors.New("copy mask file failed")
  128. }
  129. }
  130. } else {
  131. return nil, errors.New("no multipart form data found")
  132. }
  133. // 关闭 multipart 编写器以设置分界线
  134. writer.Close()
  135. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  136. return bytes.NewReader(requestBody.Bytes()), nil
  137. default:
  138. return request, nil
  139. }
  140. }
  141. // detectImageMimeType determines the MIME type based on the file extension
  142. func detectImageMimeType(filename string) string {
  143. ext := strings.ToLower(filepath.Ext(filename))
  144. switch ext {
  145. case ".jpg", ".jpeg":
  146. return "image/jpeg"
  147. case ".png":
  148. return "image/png"
  149. case ".webp":
  150. return "image/webp"
  151. default:
  152. // Try to detect from extension if possible
  153. if strings.HasPrefix(ext, ".jp") {
  154. return "image/jpeg"
  155. }
  156. // Default to png as a fallback
  157. return "image/png"
  158. }
  159. }
  160. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  161. }
  162. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  163. // 支持自定义域名,如果未设置则使用默认域名
  164. baseUrl := info.ChannelBaseUrl
  165. if baseUrl == "" {
  166. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  167. }
  168. switch info.RelayFormat {
  169. case types.RelayFormatClaude:
  170. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  171. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  172. }
  173. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  174. default:
  175. switch info.RelayMode {
  176. case constant.RelayModeChatCompletions:
  177. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  178. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  179. }
  180. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  181. case constant.RelayModeEmbeddings:
  182. return fmt.Sprintf("%s/api/v3/embeddings", baseUrl), nil
  183. case constant.RelayModeImagesGenerations:
  184. return fmt.Sprintf("%s/api/v3/images/generations", baseUrl), nil
  185. case constant.RelayModeImagesEdits:
  186. return fmt.Sprintf("%s/api/v3/images/edits", baseUrl), nil
  187. case constant.RelayModeRerank:
  188. return fmt.Sprintf("%s/api/v3/rerank", baseUrl), nil
  189. default:
  190. }
  191. }
  192. return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
  193. }
  194. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  195. channel.SetupApiRequestHeader(info, c, req)
  196. req.Set("Authorization", "Bearer "+info.ApiKey)
  197. return nil
  198. }
  199. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  200. if request == nil {
  201. return nil, errors.New("request is nil")
  202. }
  203. // 适配 方舟deepseek混合模型 的 thinking 后缀
  204. if strings.HasSuffix(info.UpstreamModelName, "-thinking") && strings.HasPrefix(info.UpstreamModelName, "deepseek") {
  205. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  206. request.Model = info.UpstreamModelName
  207. request.THINKING = json.RawMessage(`{"type": "enabled"}`)
  208. }
  209. return request, nil
  210. }
  211. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  212. return nil, nil
  213. }
  214. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  215. return request, nil
  216. }
  217. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  218. // TODO implement me
  219. return nil, errors.New("not implemented")
  220. }
  221. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  222. return channel.DoApiRequest(a, c, info, requestBody)
  223. }
  224. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  225. adaptor := openai.Adaptor{}
  226. usage, err = adaptor.DoResponse(c, resp, info)
  227. return
  228. }
  229. func (a *Adaptor) GetModelList() []string {
  230. return ModelList
  231. }
  232. func (a *Adaptor) GetChannelName() string {
  233. return ChannelName
  234. }