adaptor.go 9.1 KB

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