adaptor.go 12 KB

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