adaptor.go 12 KB

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