adaptor.go 8.1 KB

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