adaptor.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package ali
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "github.com/QuantumNous/new-api/dto"
  9. "github.com/QuantumNous/new-api/relay/channel"
  10. "github.com/QuantumNous/new-api/relay/channel/claude"
  11. "github.com/QuantumNous/new-api/relay/channel/openai"
  12. relaycommon "github.com/QuantumNous/new-api/relay/common"
  13. "github.com/QuantumNous/new-api/relay/constant"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/QuantumNous/new-api/types"
  16. "github.com/gin-gonic/gin"
  17. )
  18. type Adaptor struct {
  19. IsSyncImageModel bool
  20. }
  21. func supportsAliAnthropicMessages(modelName string) bool {
  22. // Only models with the "qwen" designation can use the Claude-compatible interface; others require conversion.
  23. return strings.Contains(strings.ToLower(modelName), "qwen")
  24. }
  25. var syncModels = []string{
  26. "z-image",
  27. "qwen-image",
  28. "wan2.6",
  29. }
  30. func isSyncImageModel(modelName string) bool {
  31. for _, m := range syncModels {
  32. if strings.Contains(modelName, m) {
  33. return true
  34. }
  35. }
  36. return false
  37. }
  38. func (a *Adaptor) ConvertGeminiRequest(*gin.Context, *relaycommon.RelayInfo, *dto.GeminiChatRequest) (any, error) {
  39. //TODO implement me
  40. return nil, errors.New("not implemented")
  41. }
  42. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, req *dto.ClaudeRequest) (any, error) {
  43. if supportsAliAnthropicMessages(info.UpstreamModelName) {
  44. return req, nil
  45. }
  46. oaiReq, err := service.ClaudeToOpenAIRequest(*req, info)
  47. if err != nil {
  48. return nil, err
  49. }
  50. if info.SupportStreamOptions && info.IsStream {
  51. oaiReq.StreamOptions = &dto.StreamOptions{IncludeUsage: true}
  52. }
  53. return a.ConvertOpenAIRequest(c, info, oaiReq)
  54. }
  55. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  56. }
  57. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  58. var fullRequestURL string
  59. switch info.RelayFormat {
  60. case types.RelayFormatClaude:
  61. if supportsAliAnthropicMessages(info.UpstreamModelName) {
  62. fullRequestURL = fmt.Sprintf("%s/apps/anthropic/v1/messages", info.ChannelBaseUrl)
  63. } else {
  64. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/chat/completions", info.ChannelBaseUrl)
  65. }
  66. default:
  67. switch info.RelayMode {
  68. case constant.RelayModeEmbeddings:
  69. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/embeddings", info.ChannelBaseUrl)
  70. case constant.RelayModeRerank:
  71. fullRequestURL = fmt.Sprintf("%s/api/v1/services/rerank/text-rerank/text-rerank", info.ChannelBaseUrl)
  72. case constant.RelayModeImagesGenerations:
  73. if isSyncImageModel(info.OriginModelName) {
  74. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/multimodal-generation/generation", info.ChannelBaseUrl)
  75. } else {
  76. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/text2image/image-synthesis", info.ChannelBaseUrl)
  77. }
  78. case constant.RelayModeImagesEdits:
  79. if isOldWanModel(info.OriginModelName) {
  80. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/image2image/image-synthesis", info.ChannelBaseUrl)
  81. } else if isWanModel(info.OriginModelName) {
  82. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/image-generation/generation", info.ChannelBaseUrl)
  83. } else {
  84. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/multimodal-generation/generation", info.ChannelBaseUrl)
  85. }
  86. case constant.RelayModeCompletions:
  87. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/completions", info.ChannelBaseUrl)
  88. default:
  89. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/chat/completions", info.ChannelBaseUrl)
  90. }
  91. }
  92. return fullRequestURL, nil
  93. }
  94. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  95. channel.SetupApiRequestHeader(info, c, req)
  96. req.Set("Authorization", "Bearer "+info.ApiKey)
  97. if info.IsStream {
  98. req.Set("X-DashScope-SSE", "enable")
  99. }
  100. if c.GetString("plugin") != "" {
  101. req.Set("X-DashScope-Plugin", c.GetString("plugin"))
  102. }
  103. if info.RelayMode == constant.RelayModeImagesGenerations {
  104. if isSyncImageModel(info.OriginModelName) {
  105. } else {
  106. req.Set("X-DashScope-Async", "enable")
  107. }
  108. }
  109. if info.RelayMode == constant.RelayModeImagesEdits {
  110. if isWanModel(info.OriginModelName) {
  111. req.Set("X-DashScope-Async", "enable")
  112. }
  113. req.Set("Content-Type", "application/json")
  114. }
  115. return nil
  116. }
  117. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  118. if request == nil {
  119. return nil, errors.New("request is nil")
  120. }
  121. // docs: https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712216
  122. // fix: InternalError.Algo.InvalidParameter: The value of the enable_thinking parameter is restricted to True.
  123. //if strings.Contains(request.Model, "thinking") {
  124. // request.EnableThinking = true
  125. // request.Stream = true
  126. // info.IsStream = true
  127. //}
  128. //// fix: ali parameter.enable_thinking must be set to false for non-streaming calls
  129. //if !info.IsStream {
  130. // request.EnableThinking = false
  131. //}
  132. switch info.RelayMode {
  133. default:
  134. aliReq := requestOpenAI2Ali(*request)
  135. return aliReq, nil
  136. }
  137. }
  138. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  139. if info.RelayMode == constant.RelayModeImagesGenerations {
  140. if isSyncImageModel(info.OriginModelName) {
  141. a.IsSyncImageModel = true
  142. }
  143. aliRequest, err := oaiImage2AliImageRequest(info, request, a.IsSyncImageModel)
  144. if err != nil {
  145. return nil, fmt.Errorf("convert image request to async ali image request failed: %w", err)
  146. }
  147. return aliRequest, nil
  148. } else if info.RelayMode == constant.RelayModeImagesEdits {
  149. if isOldWanModel(info.OriginModelName) {
  150. return oaiFormEdit2WanxImageEdit(c, info, request)
  151. }
  152. if isSyncImageModel(info.OriginModelName) {
  153. if isWanModel(info.OriginModelName) {
  154. a.IsSyncImageModel = false
  155. } else {
  156. a.IsSyncImageModel = true
  157. }
  158. }
  159. // ali image edit https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2976416
  160. // 如果用户使用表单,则需要解析表单数据
  161. if strings.Contains(c.Request.Header.Get("Content-Type"), "multipart/form-data") {
  162. aliRequest, err := oaiFormEdit2AliImageEdit(c, info, request)
  163. if err != nil {
  164. return nil, fmt.Errorf("convert image edit form request failed: %w", err)
  165. }
  166. return aliRequest, nil
  167. } else {
  168. aliRequest, err := oaiImage2AliImageRequest(info, request, a.IsSyncImageModel)
  169. if err != nil {
  170. return nil, fmt.Errorf("convert image request to async ali image request failed: %w", err)
  171. }
  172. return aliRequest, nil
  173. }
  174. }
  175. return nil, fmt.Errorf("unsupported image relay mode: %d", info.RelayMode)
  176. }
  177. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  178. return ConvertRerankRequest(request), nil
  179. }
  180. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  181. return request, nil
  182. }
  183. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  184. //TODO implement me
  185. return nil, errors.New("not implemented")
  186. }
  187. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  188. //TODO implement me
  189. return nil, errors.New("not implemented")
  190. }
  191. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  192. return channel.DoApiRequest(a, c, info, requestBody)
  193. }
  194. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  195. switch info.RelayFormat {
  196. case types.RelayFormatClaude:
  197. if supportsAliAnthropicMessages(info.UpstreamModelName) {
  198. if info.IsStream {
  199. return claude.ClaudeStreamHandler(c, resp, info, claude.RequestModeMessage)
  200. }
  201. return claude.ClaudeHandler(c, resp, info, claude.RequestModeMessage)
  202. }
  203. adaptor := openai.Adaptor{}
  204. return adaptor.DoResponse(c, resp, info)
  205. default:
  206. switch info.RelayMode {
  207. case constant.RelayModeImagesGenerations:
  208. err, usage = aliImageHandler(a, c, resp, info)
  209. case constant.RelayModeImagesEdits:
  210. err, usage = aliImageHandler(a, c, resp, info)
  211. case constant.RelayModeRerank:
  212. err, usage = RerankHandler(c, resp, info)
  213. default:
  214. adaptor := openai.Adaptor{}
  215. usage, err = adaptor.DoResponse(c, resp, info)
  216. }
  217. return usage, err
  218. }
  219. }
  220. func (a *Adaptor) GetModelList() []string {
  221. return ModelList
  222. }
  223. func (a *Adaptor) GetChannelName() string {
  224. return ChannelName
  225. }