adaptor.go 8.1 KB

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