adaptor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 := 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: "submit", // WebSocket uses "submit"
  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. // Store the request in context for WebSocket handler
  73. c.Set("volcengine_tts_request", volcRequest)
  74. // Return nil as WebSocket doesn't use traditional request body
  75. return nil, nil
  76. }
  77. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  78. switch info.RelayMode {
  79. case constant.RelayModeImagesGenerations:
  80. return request, nil
  81. case constant.RelayModeImagesEdits:
  82. var requestBody bytes.Buffer
  83. writer := multipart.NewWriter(&requestBody)
  84. writer.WriteField("model", request.Model)
  85. // 获取所有表单字段
  86. formData := c.Request.PostForm
  87. // 遍历表单字段并打印输出
  88. for key, values := range formData {
  89. if key == "model" {
  90. continue
  91. }
  92. for _, value := range values {
  93. writer.WriteField(key, value)
  94. }
  95. }
  96. // Parse the multipart form to handle both single image and multiple images
  97. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  98. return nil, errors.New("failed to parse multipart form")
  99. }
  100. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  101. // Check if "image" field exists in any form, including array notation
  102. var imageFiles []*multipart.FileHeader
  103. var exists bool
  104. // First check for standard "image" field
  105. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  106. // If not found, check for "image[]" field
  107. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  108. // If still not found, iterate through all fields to find any that start with "image["
  109. foundArrayImages := false
  110. for fieldName, files := range c.Request.MultipartForm.File {
  111. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  112. foundArrayImages = true
  113. for _, file := range files {
  114. imageFiles = append(imageFiles, file)
  115. }
  116. }
  117. }
  118. // If no image fields found at all
  119. if !foundArrayImages && (len(imageFiles) == 0) {
  120. return nil, errors.New("image is required")
  121. }
  122. }
  123. }
  124. // Process all image files
  125. for i, fileHeader := range imageFiles {
  126. file, err := fileHeader.Open()
  127. if err != nil {
  128. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  129. }
  130. defer file.Close()
  131. // If multiple images, use image[] as the field name
  132. fieldName := "image"
  133. if len(imageFiles) > 1 {
  134. fieldName = "image[]"
  135. }
  136. // Determine MIME type based on file extension
  137. mimeType := detectImageMimeType(fileHeader.Filename)
  138. // Create a form file with the appropriate content type
  139. h := make(textproto.MIMEHeader)
  140. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  141. h.Set("Content-Type", mimeType)
  142. part, err := writer.CreatePart(h)
  143. if err != nil {
  144. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  145. }
  146. if _, err := io.Copy(part, file); err != nil {
  147. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  148. }
  149. }
  150. // Handle mask file if present
  151. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  152. maskFile, err := maskFiles[0].Open()
  153. if err != nil {
  154. return nil, errors.New("failed to open mask file")
  155. }
  156. defer maskFile.Close()
  157. // Determine MIME type for mask file
  158. mimeType := detectImageMimeType(maskFiles[0].Filename)
  159. // Create a form file with the appropriate content type
  160. h := make(textproto.MIMEHeader)
  161. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  162. h.Set("Content-Type", mimeType)
  163. maskPart, err := writer.CreatePart(h)
  164. if err != nil {
  165. return nil, errors.New("create form file failed for mask")
  166. }
  167. if _, err := io.Copy(maskPart, maskFile); err != nil {
  168. return nil, errors.New("copy mask file failed")
  169. }
  170. }
  171. } else {
  172. return nil, errors.New("no multipart form data found")
  173. }
  174. // 关闭 multipart 编写器以设置分界线
  175. writer.Close()
  176. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  177. return bytes.NewReader(requestBody.Bytes()), nil
  178. default:
  179. return request, nil
  180. }
  181. }
  182. // detectImageMimeType determines the MIME type based on the file extension
  183. func detectImageMimeType(filename string) string {
  184. ext := strings.ToLower(filepath.Ext(filename))
  185. switch ext {
  186. case ".jpg", ".jpeg":
  187. return "image/jpeg"
  188. case ".png":
  189. return "image/png"
  190. case ".webp":
  191. return "image/webp"
  192. default:
  193. // Try to detect from extension if possible
  194. if strings.HasPrefix(ext, ".jp") {
  195. return "image/jpeg"
  196. }
  197. // Default to png as a fallback
  198. return "image/png"
  199. }
  200. }
  201. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  202. }
  203. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  204. baseUrl := info.ChannelBaseUrl
  205. if baseUrl == "" {
  206. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  207. }
  208. switch info.RelayFormat {
  209. case types.RelayFormatClaude:
  210. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  211. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  212. }
  213. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  214. default:
  215. switch info.RelayMode {
  216. case constant.RelayModeChatCompletions:
  217. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  218. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  219. }
  220. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  221. case constant.RelayModeEmbeddings:
  222. return fmt.Sprintf("%s/api/v3/embeddings", baseUrl), nil
  223. case constant.RelayModeImagesGenerations:
  224. return fmt.Sprintf("%s/api/v3/images/generations", baseUrl), nil
  225. case constant.RelayModeImagesEdits:
  226. return fmt.Sprintf("%s/api/v3/images/edits", baseUrl), nil
  227. case constant.RelayModeRerank:
  228. return fmt.Sprintf("%s/api/v3/rerank", baseUrl), nil
  229. case constant.RelayModeAudioSpeech:
  230. // 只有当 baseUrl 是火山默认的官方Url时才改为官方的的TTS接口,否则走透传的New接口
  231. if baseUrl == channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine] {
  232. return "wss://openspeech.bytedance.com/api/v1/tts/ws_binary", nil
  233. }
  234. return fmt.Sprintf("%s/v1/audio/speech", baseUrl), nil
  235. default:
  236. }
  237. }
  238. return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
  239. }
  240. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  241. channel.SetupApiRequestHeader(info, c, req)
  242. if info.RelayMode == constant.RelayModeAudioSpeech {
  243. parts := strings.Split(info.ApiKey, "|")
  244. if len(parts) == 2 {
  245. req.Set("Authorization", "Bearer;"+parts[1])
  246. }
  247. req.Set("Content-Type", "application/json")
  248. return nil
  249. }
  250. req.Set("Authorization", "Bearer "+info.ApiKey)
  251. return nil
  252. }
  253. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  254. if request == nil {
  255. return nil, errors.New("request is nil")
  256. }
  257. // 适配 方舟deepseek混合模型 的 thinking 后缀
  258. if strings.HasSuffix(info.UpstreamModelName, "-thinking") && strings.HasPrefix(info.UpstreamModelName, "deepseek") {
  259. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  260. request.Model = info.UpstreamModelName
  261. request.THINKING = json.RawMessage(`{"type": "enabled"}`)
  262. }
  263. return request, nil
  264. }
  265. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  266. return nil, nil
  267. }
  268. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  269. return request, nil
  270. }
  271. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  272. // TODO implement me
  273. return nil, errors.New("not implemented")
  274. }
  275. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  276. // For TTS with WebSocket, skip traditional HTTP request
  277. if info.RelayMode == constant.RelayModeAudioSpeech {
  278. baseUrl := info.ChannelBaseUrl
  279. if baseUrl == "" {
  280. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  281. }
  282. // Only use WebSocket for official Volcengine endpoint
  283. if baseUrl == channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine] {
  284. return nil, nil // WebSocket handling will be done in DoResponse
  285. }
  286. }
  287. return channel.DoApiRequest(a, c, info, requestBody)
  288. }
  289. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  290. if info.RelayMode == constant.RelayModeAudioSpeech {
  291. encoding := mapEncoding(c.GetString("response_format"))
  292. // Check if this is WebSocket mode (resp will be nil for WebSocket)
  293. if resp == nil {
  294. // Get the WebSocket URL
  295. requestURL, urlErr := a.GetRequestURL(info)
  296. if urlErr != nil {
  297. return nil, types.NewErrorWithStatusCode(
  298. urlErr,
  299. types.ErrorCodeBadRequestBody,
  300. http.StatusInternalServerError,
  301. )
  302. }
  303. // Retrieve the volcengine request from context
  304. volcRequestInterface, exists := c.Get("volcengine_tts_request")
  305. if !exists {
  306. return nil, types.NewErrorWithStatusCode(
  307. errors.New("volcengine TTS request not found in context"),
  308. types.ErrorCodeBadRequestBody,
  309. http.StatusInternalServerError,
  310. )
  311. }
  312. volcRequest, ok := volcRequestInterface.(VolcengineTTSRequest)
  313. if !ok {
  314. return nil, types.NewErrorWithStatusCode(
  315. errors.New("invalid volcengine TTS request type"),
  316. types.ErrorCodeBadRequestBody,
  317. http.StatusInternalServerError,
  318. )
  319. }
  320. // Handle WebSocket streaming
  321. return handleTTSWebSocketResponse(c, requestURL, volcRequest, info, encoding)
  322. }
  323. // Handle traditional HTTP response
  324. return handleTTSResponse(c, resp, info, encoding)
  325. }
  326. adaptor := openai.Adaptor{}
  327. usage, err = adaptor.DoResponse(c, resp, info)
  328. return
  329. }
  330. func (a *Adaptor) GetModelList() []string {
  331. return ModelList
  332. }
  333. func (a *Adaptor) GetChannelName() string {
  334. return ChannelName
  335. }