adaptor.go 11 KB

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