adaptor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package volcengine
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "path/filepath"
  10. "strings"
  11. channelconstant "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/relay/channel"
  14. "github.com/QuantumNous/new-api/relay/channel/openai"
  15. relaycommon "github.com/QuantumNous/new-api/relay/common"
  16. "github.com/QuantumNous/new-api/relay/constant"
  17. "github.com/QuantumNous/new-api/setting/model_setting"
  18. "github.com/QuantumNous/new-api/types"
  19. "github.com/gin-gonic/gin"
  20. )
  21. const (
  22. contextKeyTTSRequest = "volcengine_tts_request"
  23. contextKeyResponseFormat = "response_format"
  24. )
  25. type Adaptor struct {
  26. }
  27. func (a *Adaptor) ConvertGeminiRequest(*gin.Context, *relaycommon.RelayInfo, *dto.GeminiChatRequest) (any, error) {
  28. //TODO implement me
  29. return nil, errors.New("not implemented")
  30. }
  31. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, req *dto.ClaudeRequest) (any, error) {
  32. adaptor := openai.Adaptor{}
  33. return adaptor.ConvertClaudeRequest(c, info, req)
  34. }
  35. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  36. if info.RelayMode != constant.RelayModeAudioSpeech {
  37. return nil, errors.New("unsupported audio relay mode")
  38. }
  39. appID, token, err := parseVolcengineAuth(info.ApiKey)
  40. if err != nil {
  41. return nil, err
  42. }
  43. voiceType := mapVoiceType(request.Voice)
  44. speedRatio := request.Speed
  45. encoding := mapEncoding(request.ResponseFormat)
  46. c.Set(contextKeyResponseFormat, encoding)
  47. volcRequest := VolcengineTTSRequest{
  48. App: VolcengineTTSApp{
  49. AppID: appID,
  50. Token: token,
  51. Cluster: "volcano_tts",
  52. },
  53. User: VolcengineTTSUser{
  54. UID: "openai_relay_user",
  55. },
  56. Audio: VolcengineTTSAudio{
  57. VoiceType: voiceType,
  58. Encoding: encoding,
  59. SpeedRatio: speedRatio,
  60. Rate: 24000,
  61. },
  62. Request: VolcengineTTSReqInfo{
  63. ReqID: generateRequestID(),
  64. Text: request.Input,
  65. Operation: "submit",
  66. Model: info.OriginModelName,
  67. },
  68. }
  69. if len(request.Metadata) > 0 {
  70. if err = json.Unmarshal(request.Metadata, &volcRequest); err != nil {
  71. return nil, fmt.Errorf("error unmarshalling metadata to volcengine request: %w", err)
  72. }
  73. }
  74. c.Set(contextKeyTTSRequest, volcRequest)
  75. if volcRequest.Request.Operation == "submit" {
  76. info.IsStream = true
  77. }
  78. jsonData, err := json.Marshal(volcRequest)
  79. if err != nil {
  80. return nil, fmt.Errorf("error marshalling volcengine request: %w", err)
  81. }
  82. return bytes.NewReader(jsonData), nil
  83. }
  84. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  85. switch info.RelayMode {
  86. case constant.RelayModeImagesGenerations:
  87. return request, nil
  88. // 根据官方文档,并没有发现豆包生图支持表单请求:https://www.volcengine.com/docs/82379/1824121
  89. //case constant.RelayModeImagesEdits:
  90. //
  91. // var requestBody bytes.Buffer
  92. // writer := multipart.NewWriter(&requestBody)
  93. //
  94. // writer.WriteField("model", request.Model)
  95. //
  96. // formData := c.Request.PostForm
  97. // for key, values := range formData {
  98. // if key == "model" {
  99. // continue
  100. // }
  101. // for _, value := range values {
  102. // writer.WriteField(key, value)
  103. // }
  104. // }
  105. //
  106. // if err := c.Request.ParseMultipartForm(32 << 20); err != nil {
  107. // return nil, errors.New("failed to parse multipart form")
  108. // }
  109. //
  110. // if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  111. // var imageFiles []*multipart.FileHeader
  112. // var exists bool
  113. //
  114. // if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  115. // if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  116. // foundArrayImages := false
  117. // for fieldName, files := range c.Request.MultipartForm.File {
  118. // if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  119. // foundArrayImages = true
  120. // for _, file := range files {
  121. // imageFiles = append(imageFiles, file)
  122. // }
  123. // }
  124. // }
  125. //
  126. // if !foundArrayImages && (len(imageFiles) == 0) {
  127. // return nil, errors.New("image is required")
  128. // }
  129. // }
  130. // }
  131. //
  132. // for i, fileHeader := range imageFiles {
  133. // file, err := fileHeader.Open()
  134. // if err != nil {
  135. // return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  136. // }
  137. // defer file.Close()
  138. //
  139. // fieldName := "image"
  140. // if len(imageFiles) > 1 {
  141. // fieldName = "image[]"
  142. // }
  143. //
  144. // mimeType := detectImageMimeType(fileHeader.Filename)
  145. //
  146. // h := make(textproto.MIMEHeader)
  147. // h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  148. // h.Set("Content-Type", mimeType)
  149. //
  150. // part, err := writer.CreatePart(h)
  151. // if err != nil {
  152. // return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  153. // }
  154. //
  155. // if _, err := io.Copy(part, file); err != nil {
  156. // return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  157. // }
  158. // }
  159. //
  160. // if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  161. // maskFile, err := maskFiles[0].Open()
  162. // if err != nil {
  163. // return nil, errors.New("failed to open mask file")
  164. // }
  165. // defer maskFile.Close()
  166. //
  167. // mimeType := detectImageMimeType(maskFiles[0].Filename)
  168. //
  169. // h := make(textproto.MIMEHeader)
  170. // h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  171. // h.Set("Content-Type", mimeType)
  172. //
  173. // maskPart, err := writer.CreatePart(h)
  174. // if err != nil {
  175. // return nil, errors.New("create form file failed for mask")
  176. // }
  177. //
  178. // if _, err := io.Copy(maskPart, maskFile); err != nil {
  179. // return nil, errors.New("copy mask file failed")
  180. // }
  181. // }
  182. // } else {
  183. // return nil, errors.New("no multipart form data found")
  184. // }
  185. //
  186. // writer.Close()
  187. // c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  188. // return bytes.NewReader(requestBody.Bytes()), nil
  189. default:
  190. return request, nil
  191. }
  192. }
  193. func detectImageMimeType(filename string) string {
  194. ext := strings.ToLower(filepath.Ext(filename))
  195. switch ext {
  196. case ".jpg", ".jpeg":
  197. return "image/jpeg"
  198. case ".png":
  199. return "image/png"
  200. case ".webp":
  201. return "image/webp"
  202. default:
  203. if strings.HasPrefix(ext, ".jp") {
  204. return "image/jpeg"
  205. }
  206. return "image/png"
  207. }
  208. }
  209. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  210. }
  211. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  212. baseUrl := info.ChannelBaseUrl
  213. if baseUrl == "" {
  214. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  215. }
  216. switch info.RelayFormat {
  217. case types.RelayFormatClaude:
  218. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  219. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  220. }
  221. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  222. default:
  223. switch info.RelayMode {
  224. case constant.RelayModeChatCompletions:
  225. if strings.HasPrefix(info.UpstreamModelName, "bot") {
  226. return fmt.Sprintf("%s/api/v3/bots/chat/completions", baseUrl), nil
  227. }
  228. return fmt.Sprintf("%s/api/v3/chat/completions", baseUrl), nil
  229. case constant.RelayModeEmbeddings:
  230. return fmt.Sprintf("%s/api/v3/embeddings", baseUrl), nil
  231. //豆包的图生图也走generations接口: https://www.volcengine.com/docs/82379/1824121
  232. case constant.RelayModeImagesGenerations, constant.RelayModeImagesEdits:
  233. return fmt.Sprintf("%s/api/v3/images/generations", baseUrl), nil
  234. //case constant.RelayModeImagesEdits:
  235. // return fmt.Sprintf("%s/api/v3/images/edits", baseUrl), nil
  236. case constant.RelayModeRerank:
  237. return fmt.Sprintf("%s/api/v3/rerank", baseUrl), nil
  238. case constant.RelayModeAudioSpeech:
  239. if baseUrl == channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine] {
  240. return "wss://openspeech.bytedance.com/api/v1/tts/ws_binary", nil
  241. }
  242. return fmt.Sprintf("%s/v1/audio/speech", baseUrl), nil
  243. default:
  244. }
  245. }
  246. return "", fmt.Errorf("unsupported relay mode: %d", info.RelayMode)
  247. }
  248. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  249. channel.SetupApiRequestHeader(info, c, req)
  250. if info.RelayMode == constant.RelayModeAudioSpeech {
  251. parts := strings.Split(info.ApiKey, "|")
  252. if len(parts) == 2 {
  253. req.Set("Authorization", "Bearer;"+parts[1])
  254. }
  255. req.Set("Content-Type", "application/json")
  256. return nil
  257. } else if info.RelayMode == constant.RelayModeImagesEdits {
  258. req.Set("Content-Type", gin.MIMEJSON)
  259. }
  260. req.Set("Authorization", "Bearer "+info.ApiKey)
  261. return nil
  262. }
  263. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  264. if request == nil {
  265. return nil, errors.New("request is nil")
  266. }
  267. if !model_setting.ShouldPreserveThinkingSuffix(info.OriginModelName) &&
  268. strings.HasSuffix(info.UpstreamModelName, "-thinking") &&
  269. strings.HasPrefix(info.UpstreamModelName, "deepseek") {
  270. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  271. request.Model = info.UpstreamModelName
  272. request.THINKING = json.RawMessage(`{"type": "enabled"}`)
  273. }
  274. return request, nil
  275. }
  276. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  277. return nil, nil
  278. }
  279. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  280. return request, nil
  281. }
  282. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  283. return nil, errors.New("not implemented")
  284. }
  285. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  286. if info.RelayMode == constant.RelayModeAudioSpeech {
  287. baseUrl := info.ChannelBaseUrl
  288. if baseUrl == "" {
  289. baseUrl = channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine]
  290. }
  291. if baseUrl == channelconstant.ChannelBaseURLs[channelconstant.ChannelTypeVolcEngine] {
  292. if info.IsStream {
  293. return nil, nil
  294. }
  295. }
  296. }
  297. return channel.DoApiRequest(a, c, info, requestBody)
  298. }
  299. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  300. if info.RelayMode == constant.RelayModeAudioSpeech {
  301. encoding := mapEncoding(c.GetString(contextKeyResponseFormat))
  302. if info.IsStream {
  303. volcRequestInterface, exists := c.Get(contextKeyTTSRequest)
  304. if !exists {
  305. return nil, types.NewErrorWithStatusCode(
  306. errors.New("volcengine TTS request not found in context"),
  307. types.ErrorCodeBadRequestBody,
  308. http.StatusInternalServerError,
  309. )
  310. }
  311. volcRequest, ok := volcRequestInterface.(VolcengineTTSRequest)
  312. if !ok {
  313. return nil, types.NewErrorWithStatusCode(
  314. errors.New("invalid volcengine TTS request type"),
  315. types.ErrorCodeBadRequestBody,
  316. http.StatusInternalServerError,
  317. )
  318. }
  319. // Get the WebSocket URL
  320. requestURL, urlErr := a.GetRequestURL(info)
  321. if urlErr != nil {
  322. return nil, types.NewErrorWithStatusCode(
  323. urlErr,
  324. types.ErrorCodeBadRequestBody,
  325. http.StatusInternalServerError,
  326. )
  327. }
  328. return handleTTSWebSocketResponse(c, requestURL, volcRequest, info, encoding)
  329. }
  330. return handleTTSResponse(c, resp, info, encoding)
  331. }
  332. adaptor := openai.Adaptor{}
  333. usage, err = adaptor.DoResponse(c, resp, info)
  334. return
  335. }
  336. func (a *Adaptor) GetModelList() []string {
  337. return ModelList
  338. }
  339. func (a *Adaptor) GetChannelName() string {
  340. return ChannelName
  341. }