claude_handler.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package relay
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/constant"
  11. "github.com/QuantumNous/new-api/dto"
  12. relaycommon "github.com/QuantumNous/new-api/relay/common"
  13. "github.com/QuantumNous/new-api/relay/helper"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/QuantumNous/new-api/setting/model_setting"
  16. "github.com/QuantumNous/new-api/setting/reasoning"
  17. "github.com/QuantumNous/new-api/types"
  18. "github.com/gin-gonic/gin"
  19. )
  20. func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types.NewAPIError) {
  21. info.InitChannelMeta(c)
  22. claudeReq, ok := info.Request.(*dto.ClaudeRequest)
  23. if !ok {
  24. return types.NewErrorWithStatusCode(fmt.Errorf("invalid request type, expected *dto.ClaudeRequest, got %T", info.Request), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  25. }
  26. request, err := common.DeepCopy(claudeReq)
  27. if err != nil {
  28. return types.NewError(fmt.Errorf("failed to copy request to ClaudeRequest: %w", err), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
  29. }
  30. err = helper.ModelMappedHelper(c, info, request)
  31. if err != nil {
  32. return types.NewError(err, types.ErrorCodeChannelModelMappedError, types.ErrOptionWithSkipRetry())
  33. }
  34. adaptor := GetAdaptor(info.ApiType)
  35. if adaptor == nil {
  36. return types.NewError(fmt.Errorf("invalid api type: %d", info.ApiType), types.ErrorCodeInvalidApiType, types.ErrOptionWithSkipRetry())
  37. }
  38. adaptor.Init(info)
  39. if request.MaxTokens == 0 {
  40. request.MaxTokens = uint(model_setting.GetClaudeSettings().GetDefaultMaxTokens(request.Model))
  41. }
  42. if baseModel, effortLevel, ok := reasoning.TrimEffortSuffix(request.Model); ok && effortLevel != "" &&
  43. strings.HasPrefix(request.Model, "claude-opus-4-6") {
  44. request.Model = baseModel
  45. request.Thinking = &dto.Thinking{
  46. Type: "adaptive",
  47. }
  48. request.OutputConfig = json.RawMessage(fmt.Sprintf(`{"effort":"%s"}`, effortLevel))
  49. request.TopP = 0
  50. request.Temperature = common.GetPointer[float64](1.0)
  51. info.UpstreamModelName = request.Model
  52. } else if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
  53. strings.HasSuffix(request.Model, "-thinking") {
  54. if request.Thinking == nil {
  55. // 因为BudgetTokens 必须大于1024
  56. if request.MaxTokens < 1280 {
  57. request.MaxTokens = 1280
  58. }
  59. // BudgetTokens 为 max_tokens 的 80%
  60. request.Thinking = &dto.Thinking{
  61. Type: "enabled",
  62. BudgetTokens: common.GetPointer[int](int(float64(request.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage)),
  63. }
  64. // TODO: 临时处理
  65. // https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#important-considerations-when-using-extended-thinking
  66. request.TopP = 0
  67. request.Temperature = common.GetPointer[float64](1.0)
  68. }
  69. if !model_setting.ShouldPreserveThinkingSuffix(info.OriginModelName) {
  70. request.Model = strings.TrimSuffix(request.Model, "-thinking")
  71. }
  72. info.UpstreamModelName = request.Model
  73. }
  74. if info.ChannelSetting.SystemPrompt != "" {
  75. if request.System == nil {
  76. request.SetStringSystem(info.ChannelSetting.SystemPrompt)
  77. } else if info.ChannelSetting.SystemPromptOverride {
  78. common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true)
  79. if request.IsStringSystem() {
  80. existing := strings.TrimSpace(request.GetStringSystem())
  81. if existing == "" {
  82. request.SetStringSystem(info.ChannelSetting.SystemPrompt)
  83. } else {
  84. request.SetStringSystem(info.ChannelSetting.SystemPrompt + "\n" + existing)
  85. }
  86. } else {
  87. systemContents := request.ParseSystem()
  88. newSystem := dto.ClaudeMediaMessage{Type: dto.ContentTypeText}
  89. newSystem.SetText(info.ChannelSetting.SystemPrompt)
  90. if len(systemContents) == 0 {
  91. request.System = []dto.ClaudeMediaMessage{newSystem}
  92. } else {
  93. request.System = append([]dto.ClaudeMediaMessage{newSystem}, systemContents...)
  94. }
  95. }
  96. }
  97. }
  98. if !model_setting.GetGlobalSettings().PassThroughRequestEnabled &&
  99. !info.ChannelSetting.PassThroughBodyEnabled &&
  100. service.ShouldChatCompletionsUseResponsesGlobal(info.ChannelId, info.ChannelType, info.OriginModelName) {
  101. openAIRequest, convErr := service.ClaudeToOpenAIRequest(*request, info)
  102. if convErr != nil {
  103. return types.NewError(convErr, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  104. }
  105. usage, newApiErr := chatCompletionsViaResponses(c, info, adaptor, openAIRequest)
  106. if newApiErr != nil {
  107. return newApiErr
  108. }
  109. service.PostClaudeConsumeQuota(c, info, usage)
  110. return nil
  111. }
  112. var requestBody io.Reader
  113. if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
  114. body, err := common.GetRequestBody(c)
  115. if err != nil {
  116. return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  117. }
  118. requestBody = bytes.NewBuffer(body)
  119. } else {
  120. convertedRequest, err := adaptor.ConvertClaudeRequest(c, info, request)
  121. if err != nil {
  122. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  123. }
  124. relaycommon.AppendRequestConversionFromRequest(info, convertedRequest)
  125. jsonData, err := common.Marshal(convertedRequest)
  126. if err != nil {
  127. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  128. }
  129. // remove disabled fields for Claude API
  130. jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
  131. if err != nil {
  132. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  133. }
  134. // apply param override
  135. if len(info.ParamOverride) > 0 {
  136. jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
  137. if err != nil {
  138. return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
  139. }
  140. }
  141. if common.DebugEnabled {
  142. println("requestBody: ", string(jsonData))
  143. }
  144. requestBody = bytes.NewBuffer(jsonData)
  145. }
  146. statusCodeMappingStr := c.GetString("status_code_mapping")
  147. var httpResp *http.Response
  148. resp, err := adaptor.DoRequest(c, info, requestBody)
  149. if err != nil {
  150. return types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError)
  151. }
  152. if resp != nil {
  153. httpResp = resp.(*http.Response)
  154. info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  155. if httpResp.StatusCode != http.StatusOK {
  156. newAPIError = service.RelayErrorHandler(c.Request.Context(), httpResp, false)
  157. // reset status code 重置状态码
  158. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  159. return newAPIError
  160. }
  161. }
  162. usage, newAPIError := adaptor.DoResponse(c, httpResp, info)
  163. //log.Printf("usage: %v", usage)
  164. if newAPIError != nil {
  165. // reset status code 重置状态码
  166. service.ResetStatusCode(newAPIError, statusCodeMappingStr)
  167. return newAPIError
  168. }
  169. service.PostClaudeConsumeQuota(c, info, usage.(*dto.Usage))
  170. return nil
  171. }