adaptor.go 7.7 KB

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