adaptor.go 8.4 KB

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