adaptor.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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/setting/model_setting"
  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.RelayModeResponses:
  76. fullRequestURL = fmt.Sprintf("%s/api/v2/apps/protocols/compatible-mode/v1/responses", info.ChannelBaseUrl)
  77. case constant.RelayModeImagesGenerations:
  78. if isSyncImageModel(info.OriginModelName) {
  79. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/multimodal-generation/generation", info.ChannelBaseUrl)
  80. } else {
  81. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/text2image/image-synthesis", info.ChannelBaseUrl)
  82. }
  83. case constant.RelayModeImagesEdits:
  84. if isOldWanModel(info.OriginModelName) {
  85. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/image2image/image-synthesis", info.ChannelBaseUrl)
  86. } else if isWanModel(info.OriginModelName) {
  87. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/image-generation/generation", info.ChannelBaseUrl)
  88. } else {
  89. fullRequestURL = fmt.Sprintf("%s/api/v1/services/aigc/multimodal-generation/generation", info.ChannelBaseUrl)
  90. }
  91. case constant.RelayModeCompletions:
  92. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/completions", info.ChannelBaseUrl)
  93. default:
  94. fullRequestURL = fmt.Sprintf("%s/compatible-mode/v1/chat/completions", info.ChannelBaseUrl)
  95. }
  96. }
  97. return fullRequestURL, nil
  98. }
  99. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  100. channel.SetupApiRequestHeader(info, c, req)
  101. req.Set("Authorization", "Bearer "+info.ApiKey)
  102. if info.IsStream {
  103. req.Set("X-DashScope-SSE", "enable")
  104. }
  105. if c.GetString("plugin") != "" {
  106. req.Set("X-DashScope-Plugin", c.GetString("plugin"))
  107. }
  108. if info.RelayMode == constant.RelayModeImagesGenerations {
  109. if isSyncImageModel(info.OriginModelName) {
  110. } else {
  111. req.Set("X-DashScope-Async", "enable")
  112. }
  113. }
  114. if info.RelayMode == constant.RelayModeImagesEdits {
  115. if isWanModel(info.OriginModelName) {
  116. req.Set("X-DashScope-Async", "enable")
  117. }
  118. req.Set("Content-Type", "application/json")
  119. }
  120. return nil
  121. }
  122. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  123. if request == nil {
  124. return nil, errors.New("request is nil")
  125. }
  126. // docs: https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712216
  127. // fix: InternalError.Algo.InvalidParameter: The value of the enable_thinking parameter is restricted to True.
  128. //if strings.Contains(request.Model, "thinking") {
  129. // request.EnableThinking = true
  130. // request.Stream = true
  131. // info.IsStream = true
  132. //}
  133. //// fix: ali parameter.enable_thinking must be set to false for non-streaming calls
  134. //if !info.IsStream {
  135. // request.EnableThinking = false
  136. //}
  137. switch info.RelayMode {
  138. default:
  139. aliReq := requestOpenAI2Ali(*request)
  140. return aliReq, nil
  141. }
  142. }
  143. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  144. if info.RelayMode == constant.RelayModeImagesGenerations {
  145. if isSyncImageModel(info.OriginModelName) {
  146. a.IsSyncImageModel = true
  147. }
  148. aliRequest, err := oaiImage2AliImageRequest(info, request, a.IsSyncImageModel)
  149. if err != nil {
  150. return nil, fmt.Errorf("convert image request to async ali image request failed: %w", err)
  151. }
  152. return aliRequest, nil
  153. } else if info.RelayMode == constant.RelayModeImagesEdits {
  154. if isOldWanModel(info.OriginModelName) {
  155. return oaiFormEdit2WanxImageEdit(c, info, request)
  156. }
  157. if isSyncImageModel(info.OriginModelName) {
  158. if isWanModel(info.OriginModelName) {
  159. a.IsSyncImageModel = false
  160. } else {
  161. a.IsSyncImageModel = true
  162. }
  163. }
  164. // ali image edit https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2976416
  165. // 如果用户使用表单,则需要解析表单数据
  166. if strings.Contains(c.Request.Header.Get("Content-Type"), "multipart/form-data") {
  167. aliRequest, err := oaiFormEdit2AliImageEdit(c, info, request)
  168. if err != nil {
  169. return nil, fmt.Errorf("convert image edit form request failed: %w", err)
  170. }
  171. return aliRequest, nil
  172. } else {
  173. aliRequest, err := oaiImage2AliImageRequest(info, request, a.IsSyncImageModel)
  174. if err != nil {
  175. return nil, fmt.Errorf("convert image request to async ali image request failed: %w", err)
  176. }
  177. return aliRequest, nil
  178. }
  179. }
  180. return nil, fmt.Errorf("unsupported image relay mode: %d", info.RelayMode)
  181. }
  182. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  183. return ConvertRerankRequest(request), nil
  184. }
  185. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  186. return request, nil
  187. }
  188. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  189. //TODO implement me
  190. return nil, errors.New("not implemented")
  191. }
  192. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  193. return request, nil
  194. }
  195. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  196. return channel.DoApiRequest(a, c, info, requestBody)
  197. }
  198. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  199. switch info.RelayFormat {
  200. case types.RelayFormatClaude:
  201. if supportsAliAnthropicMessages(info.UpstreamModelName) {
  202. adaptor := claude.Adaptor{}
  203. return adaptor.DoResponse(c, resp, info)
  204. }
  205. adaptor := openai.Adaptor{}
  206. return adaptor.DoResponse(c, resp, info)
  207. default:
  208. switch info.RelayMode {
  209. case constant.RelayModeImagesGenerations:
  210. err, usage = aliImageHandler(a, c, resp, info)
  211. case constant.RelayModeImagesEdits:
  212. err, usage = aliImageHandler(a, c, resp, info)
  213. case constant.RelayModeRerank:
  214. err, usage = RerankHandler(c, resp, info)
  215. default:
  216. adaptor := openai.Adaptor{}
  217. usage, err = adaptor.DoResponse(c, resp, info)
  218. }
  219. return usage, err
  220. }
  221. }
  222. func (a *Adaptor) GetModelList() []string {
  223. return ModelList
  224. }
  225. func (a *Adaptor) GetChannelName() string {
  226. return ChannelName
  227. }