您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

741 行
24 KiB

  1. package controller
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/common/metrics"
  13. "github.com/QuantumNous/new-api/constant"
  14. "github.com/QuantumNous/new-api/dto"
  15. "github.com/QuantumNous/new-api/logger"
  16. "github.com/QuantumNous/new-api/middleware"
  17. "github.com/QuantumNous/new-api/model"
  18. "github.com/QuantumNous/new-api/relay"
  19. relaycommon "github.com/QuantumNous/new-api/relay/common"
  20. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  21. "github.com/QuantumNous/new-api/relay/helper"
  22. "github.com/QuantumNous/new-api/service"
  23. "github.com/QuantumNous/new-api/setting"
  24. "github.com/QuantumNous/new-api/setting/operation_setting"
  25. "github.com/QuantumNous/new-api/setting/ratio_setting"
  26. "github.com/QuantumNous/new-api/types"
  27. "github.com/bytedance/gopkg/util/gopool"
  28. "github.com/gin-gonic/gin"
  29. "github.com/gorilla/websocket"
  30. )
  31. func relayHandler(c *gin.Context, info *relaycommon.RelayInfo) *types.NewAPIError {
  32. var err *types.NewAPIError
  33. switch info.RelayMode {
  34. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  35. err = relay.ImageHelper(c, info)
  36. case relayconstant.RelayModeAudioSpeech:
  37. fallthrough
  38. case relayconstant.RelayModeAudioTranslation:
  39. fallthrough
  40. case relayconstant.RelayModeAudioTranscription:
  41. err = relay.AudioHelper(c, info)
  42. case relayconstant.RelayModeRerank:
  43. err = relay.RerankHelper(c, info)
  44. case relayconstant.RelayModeEmbeddings:
  45. err = relay.EmbeddingHelper(c, info)
  46. case relayconstant.RelayModeResponses, relayconstant.RelayModeResponsesCompact:
  47. err = relay.ResponsesHelper(c, info)
  48. default:
  49. err = relay.TextHelper(c, info)
  50. }
  51. return err
  52. }
  53. func geminiRelayHandler(c *gin.Context, info *relaycommon.RelayInfo) *types.NewAPIError {
  54. var err *types.NewAPIError
  55. if strings.Contains(c.Request.URL.Path, "embed") {
  56. err = relay.GeminiEmbeddingHandler(c, info)
  57. } else {
  58. err = relay.GeminiHelper(c, info)
  59. }
  60. return err
  61. }
  62. func Relay(c *gin.Context, relayFormat types.RelayFormat) {
  63. requestId := c.GetString(common.RequestIdKey)
  64. //group := common.GetContextKeyString(c, constant.ContextKeyUsingGroup)
  65. //originalModel := common.GetContextKeyString(c, constant.ContextKeyOriginalModel)
  66. var (
  67. newAPIError *types.NewAPIError
  68. ws *websocket.Conn
  69. )
  70. if relayFormat == types.RelayFormatOpenAIRealtime {
  71. var err error
  72. ws, err = upgrader.Upgrade(c.Writer, c.Request, nil)
  73. if err != nil {
  74. helper.WssError(c, ws, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry()).ToOpenAIError())
  75. return
  76. }
  77. defer ws.Close()
  78. }
  79. defer func() {
  80. if newAPIError != nil {
  81. logger.LogError(c, fmt.Sprintf("relay error: %s", newAPIError.Error()))
  82. // Prometheus: 错误计数
  83. if metrics.IsEnabled() {
  84. channelId := strconv.Itoa(c.GetInt("channel_id"))
  85. modelName := c.GetString("original_model")
  86. errorType, errorCode := metrics.ClassifyError(newAPIError.StatusCode, newAPIError.Error())
  87. metrics.GetMetrics().RequestErrorsTotal.WithLabelValues(channelId, modelName, errorType, errorCode).Inc()
  88. }
  89. newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
  90. switch relayFormat {
  91. case types.RelayFormatOpenAIRealtime:
  92. helper.WssError(c, ws, newAPIError.ToOpenAIError())
  93. case types.RelayFormatClaude:
  94. c.JSON(newAPIError.StatusCode, gin.H{
  95. "type": "error",
  96. "error": newAPIError.ToClaudeError(),
  97. })
  98. default:
  99. c.JSON(newAPIError.StatusCode, gin.H{
  100. "error": newAPIError.ToOpenAIError(),
  101. })
  102. }
  103. }
  104. }()
  105. request, err := helper.GetAndValidateRequest(c, relayFormat)
  106. if err != nil {
  107. // Map "request body too large" to 413 so clients can handle it correctly
  108. if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
  109. newAPIError = types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusRequestEntityTooLarge, types.ErrOptionWithSkipRetry())
  110. } else {
  111. newAPIError = types.NewError(err, types.ErrorCodeInvalidRequest)
  112. }
  113. return
  114. }
  115. relayInfo, err := relaycommon.GenRelayInfo(c, relayFormat, request, ws)
  116. if err != nil {
  117. newAPIError = types.NewError(err, types.ErrorCodeGenRelayInfoFailed)
  118. return
  119. }
  120. needSensitiveCheck := setting.ShouldCheckPromptSensitive()
  121. needCountToken := constant.CountToken
  122. // Avoid building huge CombineText (strings.Join) when token counting and sensitive check are both disabled.
  123. var meta *types.TokenCountMeta
  124. if needSensitiveCheck || needCountToken {
  125. meta = request.GetTokenCountMeta()
  126. } else {
  127. meta = fastTokenCountMetaForPricing(request)
  128. }
  129. if needSensitiveCheck && meta != nil {
  130. contains, words := service.CheckSensitiveText(meta.CombineText)
  131. if contains {
  132. logger.LogWarn(c, fmt.Sprintf("user sensitive words detected: %s", strings.Join(words, ", ")))
  133. newAPIError = types.NewError(err, types.ErrorCodeSensitiveWordsDetected)
  134. return
  135. }
  136. }
  137. tokens, err := service.EstimateRequestToken(c, meta, relayInfo)
  138. if err != nil {
  139. newAPIError = types.NewError(err, types.ErrorCodeCountTokenFailed)
  140. return
  141. }
  142. relayInfo.SetEstimatePromptTokens(tokens)
  143. priceData, err := helper.ModelPriceHelper(c, relayInfo, tokens, meta)
  144. if err != nil {
  145. newAPIError = types.NewError(err, types.ErrorCodeModelPriceError)
  146. return
  147. }
  148. // common.SetContextKey(c, constant.ContextKeyTokenCountMeta, meta)
  149. if priceData.FreeModel {
  150. logger.LogInfo(c, fmt.Sprintf("模型 %s 免费,跳过预扣费", relayInfo.OriginModelName))
  151. } else {
  152. common.SysLog(fmt.Sprintf("[RegionSync] relay PreConsumeBilling: userId=%d, QuotaToPreConsume=%d, FreeModel=%v, UsePrice=%v, ModelRatio=%.4f, GroupRatio=%.4f, ModelPrice=%.4f, model=%s",
  153. relayInfo.UserId, priceData.QuotaToPreConsume, priceData.FreeModel, priceData.UsePrice, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.ModelPrice, relayInfo.OriginModelName))
  154. newAPIError = service.PreConsumeBilling(c, priceData.QuotaToPreConsume, relayInfo)
  155. if newAPIError != nil {
  156. return
  157. }
  158. }
  159. defer func() {
  160. // Only return quota if downstream failed and quota was actually pre-consumed
  161. if newAPIError != nil {
  162. newAPIError = service.NormalizeViolationFeeError(newAPIError)
  163. if relayInfo.Billing != nil {
  164. relayInfo.Billing.Refund(c)
  165. }
  166. service.ChargeViolationFeeIfNeeded(c, relayInfo, newAPIError)
  167. }
  168. }()
  169. retryParam := &service.RetryParam{
  170. Ctx: c,
  171. TokenGroup: relayInfo.TokenGroup,
  172. ModelName: relayInfo.OriginModelName,
  173. Retry: common.GetPointer(0),
  174. }
  175. for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
  176. channel, channelErr := getChannel(c, relayInfo, retryParam)
  177. if channelErr != nil {
  178. logger.LogError(c, channelErr.Error())
  179. newAPIError = channelErr
  180. break
  181. }
  182. addUsedChannel(c, channel.Id)
  183. bodyStorage, bodyErr := common.GetBodyStorage(c)
  184. if bodyErr != nil {
  185. // Ensure consistent 413 for oversized bodies even when error occurs later (e.g., retry path)
  186. if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
  187. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusRequestEntityTooLarge, types.ErrOptionWithSkipRetry())
  188. } else {
  189. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  190. }
  191. break
  192. }
  193. c.Request.Body = io.NopCloser(bodyStorage)
  194. switch relayFormat {
  195. case types.RelayFormatOpenAIRealtime:
  196. newAPIError = relay.WssHelper(c, relayInfo)
  197. case types.RelayFormatClaude:
  198. newAPIError = relay.ClaudeHelper(c, relayInfo)
  199. case types.RelayFormatGemini:
  200. newAPIError = geminiRelayHandler(c, relayInfo)
  201. default:
  202. newAPIError = relayHandler(c, relayInfo)
  203. }
  204. if newAPIError == nil {
  205. return
  206. }
  207. newAPIError = service.NormalizeViolationFeeError(newAPIError)
  208. processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  209. if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) {
  210. break
  211. }
  212. // Prometheus: 重试计数
  213. if metrics.IsEnabled() {
  214. channelIdStr := strconv.Itoa(channel.Id)
  215. metrics.GetMetrics().RequestRetriesTotal.WithLabelValues(channelIdStr, relayInfo.OriginModelName).Inc()
  216. }
  217. }
  218. useChannel := c.GetStringSlice("use_channel")
  219. if len(useChannel) > 1 {
  220. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  221. logger.LogInfo(c, retryLogStr)
  222. }
  223. }
  224. var upgrader = websocket.Upgrader{
  225. Subprotocols: []string{"realtime"}, // WS 握手支持的协议,如果有使用 Sec-WebSocket-Protocol,则必须在此声明对应的 Protocol TODO add other protocol
  226. CheckOrigin: func(r *http.Request) bool {
  227. return true // 允许跨域
  228. },
  229. }
  230. func addUsedChannel(c *gin.Context, channelId int) {
  231. useChannel := c.GetStringSlice("use_channel")
  232. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  233. c.Set("use_channel", useChannel)
  234. }
  235. func fastTokenCountMetaForPricing(request dto.Request) *types.TokenCountMeta {
  236. if request == nil {
  237. return &types.TokenCountMeta{}
  238. }
  239. meta := &types.TokenCountMeta{
  240. TokenType: types.TokenTypeTokenizer,
  241. }
  242. switch r := request.(type) {
  243. case *dto.GeneralOpenAIRequest:
  244. if r.MaxCompletionTokens > r.MaxTokens {
  245. meta.MaxTokens = int(r.MaxCompletionTokens)
  246. } else {
  247. meta.MaxTokens = int(r.MaxTokens)
  248. }
  249. case *dto.OpenAIResponsesRequest:
  250. meta.MaxTokens = int(r.MaxOutputTokens)
  251. case *dto.ClaudeRequest:
  252. meta.MaxTokens = int(r.MaxTokens)
  253. case *dto.ImageRequest:
  254. // Pricing for image requests depends on ImagePriceRatio; safe to compute even when CountToken is disabled.
  255. return r.GetTokenCountMeta()
  256. default:
  257. // Best-effort: leave CombineText empty to avoid large allocations.
  258. }
  259. return meta
  260. }
  261. func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service.RetryParam) (*model.Channel, *types.NewAPIError) {
  262. if info.ChannelMeta == nil {
  263. autoBan := c.GetBool("auto_ban")
  264. autoBanInt := 1
  265. if !autoBan {
  266. autoBanInt = 0
  267. }
  268. return &model.Channel{
  269. Id: c.GetInt("channel_id"),
  270. Type: c.GetInt("channel_type"),
  271. Name: c.GetString("channel_name"),
  272. AutoBan: &autoBanInt,
  273. }, nil
  274. }
  275. channel, selectGroup, err := service.CacheGetRandomSatisfiedChannel(retryParam)
  276. info.PriceData.GroupRatioInfo = helper.HandleGroupRatio(c, info)
  277. if err != nil {
  278. return nil, types.NewError(fmt.Errorf("获取分组 %s 下模型 %s 的可用渠道失败(retry): %s", selectGroup, info.OriginModelName, err.Error()), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  279. }
  280. if channel == nil {
  281. return nil, types.NewError(fmt.Errorf("分组 %s 下模型 %s 的可用渠道不存在(retry)", selectGroup, info.OriginModelName), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  282. }
  283. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, info.OriginModelName)
  284. if newAPIError != nil {
  285. return nil, newAPIError
  286. }
  287. return channel, nil
  288. }
  289. func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
  290. if openaiErr == nil {
  291. return false
  292. }
  293. if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
  294. return false
  295. }
  296. if types.IsChannelError(openaiErr) {
  297. return true
  298. }
  299. if types.IsSkipRetryError(openaiErr) {
  300. return false
  301. }
  302. if retryTimes <= 0 {
  303. return false
  304. }
  305. code := openaiErr.StatusCode
  306. if code >= 200 && code < 300 {
  307. return false
  308. }
  309. if code < 100 || code > 599 {
  310. return true
  311. }
  312. return operation_setting.ShouldRetryByStatusCode(code)
  313. }
  314. func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError) {
  315. logger.LogError(c, fmt.Sprintf("channel error (channel #%d, status code: %d): %s", channelError.ChannelId, err.StatusCode, err.Error()))
  316. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  317. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  318. if service.ShouldDisableChannel(channelError.ChannelType, err) && channelError.AutoBan {
  319. gopool.Go(func() {
  320. service.DisableChannel(channelError, err.ErrorWithStatusCode())
  321. })
  322. }
  323. if constant.ErrorLogEnabled && types.IsRecordErrorLog(err) {
  324. // 保存错误日志到mysql中
  325. userId := c.GetInt("id")
  326. tokenName := c.GetString("token_name")
  327. modelName := c.GetString("original_model")
  328. tokenId := c.GetInt("token_id")
  329. userGroup := c.GetString("group")
  330. channelId := c.GetInt("channel_id")
  331. other := make(map[string]interface{})
  332. if c.Request != nil && c.Request.URL != nil {
  333. other["request_path"] = c.Request.URL.Path
  334. }
  335. other["error_type"] = err.GetErrorType()
  336. other["error_code"] = err.GetErrorCode()
  337. other["status_code"] = err.StatusCode
  338. other["channel_id"] = channelId
  339. other["channel_name"] = c.GetString("channel_name")
  340. other["channel_type"] = c.GetInt("channel_type")
  341. if err.UpstreamRequestId != "" {
  342. other["upstream_request_id"] = err.UpstreamRequestId
  343. }
  344. if err.UpstreamBody != "" {
  345. other["upstream_body"] = err.UpstreamBody
  346. }
  347. adminInfo := make(map[string]interface{})
  348. adminInfo["use_channel"] = c.GetStringSlice("use_channel")
  349. isMultiKey := common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey)
  350. if isMultiKey {
  351. adminInfo["is_multi_key"] = true
  352. adminInfo["multi_key_index"] = common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex)
  353. }
  354. service.AppendChannelAffinityAdminInfo(c, adminInfo)
  355. other["admin_info"] = adminInfo
  356. startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
  357. if startTime.IsZero() {
  358. startTime = time.Now()
  359. }
  360. useTimeSeconds := int(time.Since(startTime).Seconds())
  361. model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveErrorWithStatusCode(), tokenId, useTimeSeconds, false, userGroup, other)
  362. }
  363. }
  364. func RelayMidjourney(c *gin.Context) {
  365. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatMjProxy, nil, nil)
  366. if err != nil {
  367. c.JSON(http.StatusInternalServerError, gin.H{
  368. "description": fmt.Sprintf("failed to generate relay info: %s", err.Error()),
  369. "type": "upstream_error",
  370. "code": 4,
  371. })
  372. return
  373. }
  374. var mjErr *dto.MidjourneyResponse
  375. switch relayInfo.RelayMode {
  376. case relayconstant.RelayModeMidjourneyNotify:
  377. mjErr = relay.RelayMidjourneyNotify(c)
  378. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  379. mjErr = relay.RelayMidjourneyTask(c, relayInfo.RelayMode)
  380. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  381. mjErr = relay.RelayMidjourneyTaskImageSeed(c)
  382. case relayconstant.RelayModeSwapFace:
  383. mjErr = relay.RelaySwapFace(c, relayInfo)
  384. default:
  385. mjErr = relay.RelayMidjourneySubmit(c, relayInfo)
  386. }
  387. //err = relayMidjourneySubmit(c, relayMode)
  388. log.Println(mjErr)
  389. if mjErr != nil {
  390. statusCode := http.StatusBadRequest
  391. if mjErr.Code == 30 {
  392. mjErr.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  393. statusCode = http.StatusTooManyRequests
  394. }
  395. c.JSON(statusCode, gin.H{
  396. "description": fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result),
  397. "type": "upstream_error",
  398. "code": mjErr.Code,
  399. })
  400. channelId := c.GetInt("channel_id")
  401. logger.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result)))
  402. }
  403. }
  404. func RelayNotImplemented(c *gin.Context) {
  405. err := types.OpenAIError{
  406. Message: "API not implemented",
  407. Type: "new_api_error",
  408. Param: "",
  409. Code: "api_not_implemented",
  410. }
  411. c.JSON(http.StatusNotImplemented, gin.H{
  412. "error": err,
  413. })
  414. }
  415. func RelayNotFound(c *gin.Context) {
  416. err := types.OpenAIError{
  417. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  418. Type: "invalid_request_error",
  419. Param: "",
  420. Code: "",
  421. }
  422. c.JSON(http.StatusNotFound, gin.H{
  423. "error": err,
  424. })
  425. }
  426. func RelayTaskFetch(c *gin.Context) {
  427. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
  428. if err != nil {
  429. c.JSON(http.StatusInternalServerError, &dto.TaskError{
  430. Code: "gen_relay_info_failed",
  431. Message: err.Error(),
  432. StatusCode: http.StatusInternalServerError,
  433. })
  434. return
  435. }
  436. if taskErr := relay.RelayTaskFetch(c, relayInfo.RelayMode); taskErr != nil {
  437. respondTaskError(c, taskErr)
  438. }
  439. }
  440. func preloadTaskPricingConfig(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
  441. modelName := strings.TrimSpace(info.OriginModelName)
  442. action := strings.TrimSpace(info.Action)
  443. contentType := c.Request.Header.Get("Content-Type")
  444. storage, err := common.GetBodyStorage(c)
  445. if err != nil {
  446. status := http.StatusBadRequest
  447. if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
  448. status = http.StatusRequestEntityTooLarge
  449. }
  450. return service.TaskErrorWrapperLocal(err, "read_request_body_failed", status)
  451. }
  452. defer func() {
  453. _, _ = storage.Seek(0, io.SeekStart)
  454. c.Request.Body = io.NopCloser(storage)
  455. }()
  456. switch {
  457. case strings.HasPrefix(contentType, "application/json"):
  458. body, err := storage.Bytes()
  459. if err != nil {
  460. return service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusBadRequest)
  461. }
  462. if strings.TrimSpace(string(body)) != "" {
  463. var payload map[string]any
  464. if err := common.Unmarshal(body, &payload); err != nil {
  465. return service.TaskErrorWrapperLocal(err, "invalid_json", http.StatusBadRequest)
  466. }
  467. if raw, ok := payload["model"].(string); ok && strings.TrimSpace(raw) != "" {
  468. modelName = strings.TrimSpace(raw)
  469. }
  470. if raw, ok := payload["action"].(string); ok && strings.TrimSpace(raw) != "" {
  471. action = strings.TrimSpace(raw)
  472. }
  473. }
  474. case strings.Contains(contentType, gin.MIMEMultipartPOSTForm):
  475. form, err := common.ParseMultipartFormReusable(c)
  476. if err != nil {
  477. return service.TaskErrorWrapperLocal(err, "invalid_multipart_form", http.StatusBadRequest)
  478. }
  479. if vals := form.Value["model"]; len(vals) > 0 && strings.TrimSpace(vals[0]) != "" {
  480. modelName = strings.TrimSpace(vals[0])
  481. }
  482. if vals := form.Value["action"]; len(vals) > 0 && strings.TrimSpace(vals[0]) != "" {
  483. action = strings.TrimSpace(vals[0])
  484. }
  485. }
  486. if modelName == "" && action != "" {
  487. platform := constant.TaskPlatform(c.GetString("platform"))
  488. modelName = service.CoverTaskActionToModelName(platform, action)
  489. }
  490. if modelName != "" {
  491. info.OriginModelName = modelName
  492. }
  493. if action != "" {
  494. info.Action = action
  495. }
  496. info.PricingConfigSnapshotLoaded = true
  497. info.PricingConfigSnapshot = ratio_setting.GetPricingConfig(info.OriginModelName)
  498. info.RequireMatrixUsageBilling = info.PricingConfigSnapshot != nil &&
  499. info.PricingConfigSnapshot.BillingUnit == types.BillingUnitPer1MTokens
  500. return nil
  501. }
  502. func buildTaskBillingContext(info *relaycommon.RelayInfo) *model.TaskBillingContext {
  503. bc := &model.TaskBillingContext{
  504. ModelPrice: info.PriceData.ModelPrice,
  505. GroupRatio: info.PriceData.GroupRatioInfo.GroupRatio,
  506. ModelRatio: info.PriceData.ModelRatio,
  507. OtherRatios: info.PriceData.OtherRatios,
  508. OriginModelName: info.OriginModelName,
  509. PerCallBilling: common.StringsContains(constant.TaskPricePatches, info.OriginModelName),
  510. }
  511. if decision := info.PricingDecisionFrozen; decision != nil && decision.BillingMode == types.BillingModeMatrix {
  512. bc.BillingMode = decision.BillingMode
  513. bc.PricingSnapshot = types.CloneMapAny(decision.Snapshot)
  514. bc.BillingUnit = decision.BillingUnit
  515. bc.TokenUnitPriceUSD = decision.TokenUnitPriceUSD
  516. bc.PerCallBilling = decision.PerCallBilling
  517. bc.ModelPrice = decision.PriceUSD
  518. bc.GroupRatio = decision.GroupRatioInfo.GroupRatio
  519. bc.OtherRatios = types.CloneRatios(decision.OtherRatios)
  520. }
  521. return bc
  522. }
  523. func RelayTask(c *gin.Context) {
  524. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
  525. if err != nil {
  526. c.JSON(http.StatusInternalServerError, &dto.TaskError{
  527. Code: "gen_relay_info_failed",
  528. Message: err.Error(),
  529. StatusCode: http.StatusInternalServerError,
  530. })
  531. return
  532. }
  533. if taskErr := relay.ResolveOriginTask(c, relayInfo); taskErr != nil {
  534. respondTaskError(c, taskErr)
  535. return
  536. }
  537. if taskErr := preloadTaskPricingConfig(c, relayInfo); taskErr != nil {
  538. respondTaskError(c, taskErr)
  539. return
  540. }
  541. var result *relay.TaskSubmitResult
  542. var taskErr *dto.TaskError
  543. defer func() {
  544. if taskErr != nil && relayInfo.Billing != nil {
  545. relayInfo.Billing.Refund(c)
  546. }
  547. }()
  548. retryParam := &service.RetryParam{
  549. Ctx: c,
  550. TokenGroup: relayInfo.TokenGroup,
  551. ModelName: relayInfo.OriginModelName,
  552. Retry: common.GetPointer(0),
  553. }
  554. for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
  555. var channel *model.Channel
  556. if lockedCh, ok := relayInfo.LockedChannel.(*model.Channel); ok && lockedCh != nil {
  557. channel = lockedCh
  558. if setupErr := middleware.SetupContextForSelectedChannel(c, channel, relayInfo.OriginModelName); setupErr != nil {
  559. taskErr = service.TaskErrorWrapperLocal(setupErr.Err, "setup_locked_channel_failed", http.StatusInternalServerError)
  560. break
  561. }
  562. } else {
  563. var channelErr *types.NewAPIError
  564. channel, channelErr = getChannel(c, relayInfo, retryParam)
  565. if channelErr != nil {
  566. logger.LogError(c, channelErr.Error())
  567. taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", http.StatusInternalServerError)
  568. break
  569. }
  570. }
  571. addUsedChannel(c, channel.Id)
  572. bodyStorage, bodyErr := common.GetBodyStorage(c)
  573. if bodyErr != nil {
  574. if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
  575. taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusRequestEntityTooLarge)
  576. } else {
  577. taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusBadRequest)
  578. }
  579. break
  580. }
  581. c.Request.Body = io.NopCloser(bodyStorage)
  582. result, taskErr = relay.RelayTaskSubmit(c, relayInfo)
  583. if taskErr == nil {
  584. break
  585. }
  586. if !taskErr.LocalError {
  587. processChannelError(c,
  588. *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey,
  589. common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()),
  590. types.NewOpenAIError(taskErr.Error, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode))
  591. }
  592. if !shouldRetryTaskRelay(c, channel.Id, taskErr, common.RetryTimes-retryParam.GetRetry()) {
  593. break
  594. }
  595. }
  596. useChannel := c.GetStringSlice("use_channel")
  597. if len(useChannel) > 1 {
  598. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  599. logger.LogInfo(c, retryLogStr)
  600. }
  601. // ── 成功:结算 + 日志 + 插入任务 ──
  602. if taskErr == nil {
  603. if settleErr := service.SettleBilling(c, relayInfo, result.Quota); settleErr != nil {
  604. common.SysError("settle task billing error: " + settleErr.Error())
  605. }
  606. service.LogTaskConsumption(c, relayInfo)
  607. task := model.InitTask(result.Platform, relayInfo)
  608. task.PrivateData.UpstreamTaskID = result.UpstreamTaskID
  609. task.PrivateData.BillingSource = relayInfo.BillingSource
  610. task.PrivateData.SubscriptionId = relayInfo.SubscriptionId
  611. task.PrivateData.TokenId = relayInfo.TokenId
  612. task.PrivateData.BillingContext = buildTaskBillingContext(relayInfo)
  613. task.Quota = result.Quota
  614. task.Data = result.TaskData
  615. task.Action = relayInfo.Action
  616. if insertErr := task.Insert(); insertErr != nil {
  617. common.SysError("insert task error: " + insertErr.Error())
  618. }
  619. }
  620. if taskErr != nil {
  621. respondTaskError(c, taskErr)
  622. }
  623. }
  624. // respondTaskError 统一输出 Task 错误响应(含 429 限流提示改写)
  625. func respondTaskError(c *gin.Context, taskErr *dto.TaskError) {
  626. if taskErr.StatusCode == http.StatusTooManyRequests {
  627. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  628. }
  629. c.JSON(taskErr.StatusCode, taskErr)
  630. }
  631. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  632. if taskErr == nil {
  633. return false
  634. }
  635. if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
  636. return false
  637. }
  638. if retryTimes <= 0 {
  639. return false
  640. }
  641. if taskErr.StatusCode == http.StatusTooManyRequests {
  642. return true
  643. }
  644. if taskErr.StatusCode == 307 {
  645. return true
  646. }
  647. if taskErr.StatusCode/100 == 5 {
  648. // 超时不重试
  649. if operation_setting.IsAlwaysSkipRetryStatusCode(taskErr.StatusCode) {
  650. return false
  651. }
  652. return true
  653. }
  654. if taskErr.StatusCode == http.StatusBadRequest {
  655. return false
  656. }
  657. if taskErr.StatusCode == 408 {
  658. // azure处理超时不重试
  659. return false
  660. }
  661. if taskErr.LocalError {
  662. return false
  663. }
  664. if taskErr.StatusCode/100 == 2 {
  665. return false
  666. }
  667. return true
  668. }