Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

745 wiersze
25 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. RequireMatrixUsageBilling: relayInfo.RequireMatrixUsageBilling,
  175. }
  176. for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
  177. channel, channelErr := getChannel(c, relayInfo, retryParam)
  178. if channelErr != nil {
  179. logger.LogError(c, channelErr.Error())
  180. newAPIError = channelErr
  181. break
  182. }
  183. addUsedChannel(c, channel.Id)
  184. bodyStorage, bodyErr := common.GetBodyStorage(c)
  185. if bodyErr != nil {
  186. // Ensure consistent 413 for oversized bodies even when error occurs later (e.g., retry path)
  187. if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
  188. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusRequestEntityTooLarge, types.ErrOptionWithSkipRetry())
  189. } else {
  190. newAPIError = types.NewErrorWithStatusCode(bodyErr, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  191. }
  192. break
  193. }
  194. c.Request.Body = io.NopCloser(bodyStorage)
  195. switch relayFormat {
  196. case types.RelayFormatOpenAIRealtime:
  197. newAPIError = relay.WssHelper(c, relayInfo)
  198. case types.RelayFormatClaude:
  199. newAPIError = relay.ClaudeHelper(c, relayInfo)
  200. case types.RelayFormatGemini:
  201. newAPIError = geminiRelayHandler(c, relayInfo)
  202. default:
  203. newAPIError = relayHandler(c, relayInfo)
  204. }
  205. if newAPIError == nil {
  206. return
  207. }
  208. newAPIError = service.NormalizeViolationFeeError(newAPIError)
  209. processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  210. if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) {
  211. break
  212. }
  213. // Prometheus: 重试计数
  214. if metrics.IsEnabled() {
  215. channelIdStr := strconv.Itoa(channel.Id)
  216. metrics.GetMetrics().RequestRetriesTotal.WithLabelValues(channelIdStr, relayInfo.OriginModelName).Inc()
  217. }
  218. }
  219. useChannel := c.GetStringSlice("use_channel")
  220. if len(useChannel) > 1 {
  221. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  222. logger.LogInfo(c, retryLogStr)
  223. }
  224. }
  225. var upgrader = websocket.Upgrader{
  226. Subprotocols: []string{"realtime"}, // WS 握手支持的协议,如果有使用 Sec-WebSocket-Protocol,则必须在此声明对应的 Protocol TODO add other protocol
  227. CheckOrigin: func(r *http.Request) bool {
  228. return true // 允许跨域
  229. },
  230. }
  231. func addUsedChannel(c *gin.Context, channelId int) {
  232. useChannel := c.GetStringSlice("use_channel")
  233. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  234. c.Set("use_channel", useChannel)
  235. }
  236. func fastTokenCountMetaForPricing(request dto.Request) *types.TokenCountMeta {
  237. if request == nil {
  238. return &types.TokenCountMeta{}
  239. }
  240. meta := &types.TokenCountMeta{
  241. TokenType: types.TokenTypeTokenizer,
  242. }
  243. switch r := request.(type) {
  244. case *dto.GeneralOpenAIRequest:
  245. if r.MaxCompletionTokens > r.MaxTokens {
  246. meta.MaxTokens = int(r.MaxCompletionTokens)
  247. } else {
  248. meta.MaxTokens = int(r.MaxTokens)
  249. }
  250. case *dto.OpenAIResponsesRequest:
  251. meta.MaxTokens = int(r.MaxOutputTokens)
  252. case *dto.ClaudeRequest:
  253. meta.MaxTokens = int(r.MaxTokens)
  254. case *dto.ImageRequest:
  255. // Pricing for image requests depends on ImagePriceRatio; safe to compute even when CountToken is disabled.
  256. return r.GetTokenCountMeta()
  257. default:
  258. // Best-effort: leave CombineText empty to avoid large allocations.
  259. }
  260. return meta
  261. }
  262. func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service.RetryParam) (*model.Channel, *types.NewAPIError) {
  263. if info.ChannelMeta == nil {
  264. autoBan := c.GetBool("auto_ban")
  265. autoBanInt := 1
  266. if !autoBan {
  267. autoBanInt = 0
  268. }
  269. return &model.Channel{
  270. Id: c.GetInt("channel_id"),
  271. Type: c.GetInt("channel_type"),
  272. Name: c.GetString("channel_name"),
  273. AutoBan: &autoBanInt,
  274. }, nil
  275. }
  276. channel, selectGroup, err := service.CacheGetRandomSatisfiedChannel(retryParam)
  277. info.PriceData.GroupRatioInfo = helper.HandleGroupRatio(c, info)
  278. if err != nil {
  279. if apiErr, ok := err.(*types.NewAPIError); ok {
  280. return nil, apiErr
  281. }
  282. return nil, types.NewError(fmt.Errorf("获取分组 %s 下模型 %s 的可用渠道失败(retry): %s", selectGroup, info.OriginModelName, err.Error()), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  283. }
  284. if channel == nil {
  285. return nil, types.NewError(fmt.Errorf("分组 %s 下模型 %s 的可用渠道不存在(retry)", selectGroup, info.OriginModelName), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  286. }
  287. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, info.OriginModelName)
  288. if newAPIError != nil {
  289. return nil, newAPIError
  290. }
  291. return channel, nil
  292. }
  293. func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
  294. if openaiErr == nil {
  295. return false
  296. }
  297. if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
  298. return false
  299. }
  300. if types.IsChannelError(openaiErr) {
  301. return true
  302. }
  303. if types.IsSkipRetryError(openaiErr) {
  304. return false
  305. }
  306. if retryTimes <= 0 {
  307. return false
  308. }
  309. code := openaiErr.StatusCode
  310. if code >= 200 && code < 300 {
  311. return false
  312. }
  313. if code < 100 || code > 599 {
  314. return true
  315. }
  316. return operation_setting.ShouldRetryByStatusCode(code)
  317. }
  318. func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError) {
  319. logger.LogError(c, fmt.Sprintf("channel error (channel #%d, status code: %d): %s", channelError.ChannelId, err.StatusCode, err.Error()))
  320. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  321. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  322. if service.ShouldDisableChannel(channelError.ChannelType, err) && channelError.AutoBan {
  323. gopool.Go(func() {
  324. service.DisableChannel(channelError, err.ErrorWithStatusCode())
  325. })
  326. }
  327. if constant.ErrorLogEnabled && types.IsRecordErrorLog(err) {
  328. // 保存错误日志到mysql中
  329. userId := c.GetInt("id")
  330. tokenName := c.GetString("token_name")
  331. modelName := c.GetString("original_model")
  332. tokenId := c.GetInt("token_id")
  333. userGroup := c.GetString("group")
  334. channelId := c.GetInt("channel_id")
  335. other := make(map[string]interface{})
  336. if c.Request != nil && c.Request.URL != nil {
  337. other["request_path"] = c.Request.URL.Path
  338. }
  339. other["error_type"] = err.GetErrorType()
  340. other["error_code"] = err.GetErrorCode()
  341. other["status_code"] = err.StatusCode
  342. other["channel_id"] = channelId
  343. other["channel_name"] = c.GetString("channel_name")
  344. other["channel_type"] = c.GetInt("channel_type")
  345. if err.UpstreamRequestId != "" {
  346. other["upstream_request_id"] = err.UpstreamRequestId
  347. }
  348. if err.UpstreamBody != "" {
  349. other["upstream_body"] = err.UpstreamBody
  350. }
  351. adminInfo := make(map[string]interface{})
  352. adminInfo["use_channel"] = c.GetStringSlice("use_channel")
  353. isMultiKey := common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey)
  354. if isMultiKey {
  355. adminInfo["is_multi_key"] = true
  356. adminInfo["multi_key_index"] = common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex)
  357. }
  358. service.AppendChannelAffinityAdminInfo(c, adminInfo)
  359. other["admin_info"] = adminInfo
  360. startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
  361. if startTime.IsZero() {
  362. startTime = time.Now()
  363. }
  364. useTimeSeconds := int(time.Since(startTime).Seconds())
  365. model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveErrorWithStatusCode(), tokenId, useTimeSeconds, false, userGroup, other)
  366. }
  367. }
  368. func RelayMidjourney(c *gin.Context) {
  369. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatMjProxy, nil, nil)
  370. if err != nil {
  371. c.JSON(http.StatusInternalServerError, gin.H{
  372. "description": fmt.Sprintf("failed to generate relay info: %s", err.Error()),
  373. "type": "upstream_error",
  374. "code": 4,
  375. })
  376. return
  377. }
  378. var mjErr *dto.MidjourneyResponse
  379. switch relayInfo.RelayMode {
  380. case relayconstant.RelayModeMidjourneyNotify:
  381. mjErr = relay.RelayMidjourneyNotify(c)
  382. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  383. mjErr = relay.RelayMidjourneyTask(c, relayInfo.RelayMode)
  384. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  385. mjErr = relay.RelayMidjourneyTaskImageSeed(c)
  386. case relayconstant.RelayModeSwapFace:
  387. mjErr = relay.RelaySwapFace(c, relayInfo)
  388. default:
  389. mjErr = relay.RelayMidjourneySubmit(c, relayInfo)
  390. }
  391. //err = relayMidjourneySubmit(c, relayMode)
  392. log.Println(mjErr)
  393. if mjErr != nil {
  394. statusCode := http.StatusBadRequest
  395. if mjErr.Code == 30 {
  396. mjErr.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  397. statusCode = http.StatusTooManyRequests
  398. }
  399. c.JSON(statusCode, gin.H{
  400. "description": fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result),
  401. "type": "upstream_error",
  402. "code": mjErr.Code,
  403. })
  404. channelId := c.GetInt("channel_id")
  405. logger.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", mjErr.Description, mjErr.Result)))
  406. }
  407. }
  408. func RelayNotImplemented(c *gin.Context) {
  409. err := types.OpenAIError{
  410. Message: "API not implemented",
  411. Type: "new_api_error",
  412. Param: "",
  413. Code: "api_not_implemented",
  414. }
  415. c.JSON(http.StatusNotImplemented, gin.H{
  416. "error": err,
  417. })
  418. }
  419. func RelayNotFound(c *gin.Context) {
  420. err := types.OpenAIError{
  421. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  422. Type: "invalid_request_error",
  423. Param: "",
  424. Code: "",
  425. }
  426. c.JSON(http.StatusNotFound, gin.H{
  427. "error": err,
  428. })
  429. }
  430. func RelayTaskFetch(c *gin.Context) {
  431. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
  432. if err != nil {
  433. c.JSON(http.StatusInternalServerError, &dto.TaskError{
  434. Code: "gen_relay_info_failed",
  435. Message: err.Error(),
  436. StatusCode: http.StatusInternalServerError,
  437. })
  438. return
  439. }
  440. if taskErr := relay.RelayTaskFetch(c, relayInfo.RelayMode); taskErr != nil {
  441. respondTaskError(c, taskErr)
  442. }
  443. }
  444. func preloadTaskPricingConfig(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
  445. modelName := strings.TrimSpace(info.OriginModelName)
  446. action := strings.TrimSpace(info.Action)
  447. contentType := c.Request.Header.Get("Content-Type")
  448. storage, err := common.GetBodyStorage(c)
  449. if err != nil {
  450. status := http.StatusBadRequest
  451. if common.IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge) {
  452. status = http.StatusRequestEntityTooLarge
  453. }
  454. return service.TaskErrorWrapperLocal(err, "read_request_body_failed", status)
  455. }
  456. defer func() {
  457. _, _ = storage.Seek(0, io.SeekStart)
  458. c.Request.Body = io.NopCloser(storage)
  459. }()
  460. switch {
  461. case strings.HasPrefix(contentType, "application/json"):
  462. body, err := storage.Bytes()
  463. if err != nil {
  464. return service.TaskErrorWrapperLocal(err, "read_request_body_failed", http.StatusBadRequest)
  465. }
  466. if strings.TrimSpace(string(body)) != "" {
  467. var payload map[string]any
  468. if err := common.Unmarshal(body, &payload); err != nil {
  469. return service.TaskErrorWrapperLocal(err, "invalid_json", http.StatusBadRequest)
  470. }
  471. if raw, ok := payload["model"].(string); ok && strings.TrimSpace(raw) != "" {
  472. modelName = strings.TrimSpace(raw)
  473. }
  474. if raw, ok := payload["action"].(string); ok && strings.TrimSpace(raw) != "" {
  475. action = strings.TrimSpace(raw)
  476. }
  477. }
  478. case strings.Contains(contentType, gin.MIMEMultipartPOSTForm):
  479. form, err := common.ParseMultipartFormReusable(c)
  480. if err != nil {
  481. return service.TaskErrorWrapperLocal(err, "invalid_multipart_form", http.StatusBadRequest)
  482. }
  483. if vals := form.Value["model"]; len(vals) > 0 && strings.TrimSpace(vals[0]) != "" {
  484. modelName = strings.TrimSpace(vals[0])
  485. }
  486. if vals := form.Value["action"]; len(vals) > 0 && strings.TrimSpace(vals[0]) != "" {
  487. action = strings.TrimSpace(vals[0])
  488. }
  489. }
  490. if modelName == "" && action != "" {
  491. platform := constant.TaskPlatform(c.GetString("platform"))
  492. modelName = service.CoverTaskActionToModelName(platform, action)
  493. }
  494. if modelName != "" {
  495. info.OriginModelName = modelName
  496. }
  497. if action != "" {
  498. info.Action = action
  499. }
  500. info.PricingConfigSnapshotLoaded = true
  501. info.PricingConfigSnapshot = ratio_setting.GetPricingConfig(info.OriginModelName)
  502. info.RequireMatrixUsageBilling = info.PricingConfigSnapshot != nil &&
  503. info.PricingConfigSnapshot.BillingUnit == types.BillingUnitPer1MTokens
  504. return nil
  505. }
  506. func buildTaskBillingContext(info *relaycommon.RelayInfo) *model.TaskBillingContext {
  507. bc := &model.TaskBillingContext{
  508. ModelPrice: info.PriceData.ModelPrice,
  509. GroupRatio: info.PriceData.GroupRatioInfo.GroupRatio,
  510. ModelRatio: info.PriceData.ModelRatio,
  511. OtherRatios: info.PriceData.OtherRatios,
  512. OriginModelName: info.OriginModelName,
  513. PerCallBilling: common.StringsContains(constant.TaskPricePatches, info.OriginModelName),
  514. }
  515. if decision := info.PricingDecisionFrozen; decision != nil && decision.BillingMode == types.BillingModeMatrix {
  516. bc.BillingMode = decision.BillingMode
  517. bc.PricingSnapshot = types.CloneMapAny(decision.Snapshot)
  518. bc.BillingUnit = decision.BillingUnit
  519. bc.TokenUnitPriceUSD = decision.TokenUnitPriceUSD
  520. bc.PerCallBilling = decision.PerCallBilling
  521. bc.ModelPrice = decision.PriceUSD
  522. bc.GroupRatio = decision.GroupRatioInfo.GroupRatio
  523. bc.OtherRatios = types.CloneRatios(decision.OtherRatios)
  524. }
  525. return bc
  526. }
  527. func RelayTask(c *gin.Context) {
  528. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil)
  529. if err != nil {
  530. c.JSON(http.StatusInternalServerError, &dto.TaskError{
  531. Code: "gen_relay_info_failed",
  532. Message: err.Error(),
  533. StatusCode: http.StatusInternalServerError,
  534. })
  535. return
  536. }
  537. if taskErr := relay.ResolveOriginTask(c, relayInfo); taskErr != nil {
  538. respondTaskError(c, taskErr)
  539. return
  540. }
  541. if taskErr := preloadTaskPricingConfig(c, relayInfo); taskErr != nil {
  542. respondTaskError(c, taskErr)
  543. return
  544. }
  545. var result *relay.TaskSubmitResult
  546. var taskErr *dto.TaskError
  547. defer func() {
  548. if taskErr != nil && relayInfo.Billing != nil {
  549. relayInfo.Billing.Refund(c)
  550. }
  551. }()
  552. retryParam := &service.RetryParam{
  553. Ctx: c,
  554. TokenGroup: relayInfo.TokenGroup,
  555. ModelName: relayInfo.OriginModelName,
  556. Retry: common.GetPointer(0),
  557. }
  558. for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
  559. var channel *model.Channel
  560. if lockedCh, ok := relayInfo.LockedChannel.(*model.Channel); ok && lockedCh != nil {
  561. channel = lockedCh
  562. if setupErr := middleware.SetupContextForSelectedChannel(c, channel, relayInfo.OriginModelName); setupErr != nil {
  563. taskErr = service.TaskErrorWrapperLocal(setupErr.Err, "setup_locked_channel_failed", http.StatusInternalServerError)
  564. break
  565. }
  566. } else {
  567. var channelErr *types.NewAPIError
  568. channel, channelErr = getChannel(c, relayInfo, retryParam)
  569. if channelErr != nil {
  570. logger.LogError(c, channelErr.Error())
  571. taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", http.StatusInternalServerError)
  572. break
  573. }
  574. }
  575. addUsedChannel(c, channel.Id)
  576. bodyStorage, bodyErr := common.GetBodyStorage(c)
  577. if bodyErr != nil {
  578. if common.IsRequestBodyTooLargeError(bodyErr) || errors.Is(bodyErr, common.ErrRequestBodyTooLarge) {
  579. taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusRequestEntityTooLarge)
  580. } else {
  581. taskErr = service.TaskErrorWrapperLocal(bodyErr, "read_request_body_failed", http.StatusBadRequest)
  582. }
  583. break
  584. }
  585. c.Request.Body = io.NopCloser(bodyStorage)
  586. result, taskErr = relay.RelayTaskSubmit(c, relayInfo)
  587. if taskErr == nil {
  588. break
  589. }
  590. if !taskErr.LocalError {
  591. processChannelError(c,
  592. *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey,
  593. common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()),
  594. types.NewOpenAIError(taskErr.Error, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode))
  595. }
  596. if !shouldRetryTaskRelay(c, channel.Id, taskErr, common.RetryTimes-retryParam.GetRetry()) {
  597. break
  598. }
  599. }
  600. useChannel := c.GetStringSlice("use_channel")
  601. if len(useChannel) > 1 {
  602. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  603. logger.LogInfo(c, retryLogStr)
  604. }
  605. // ── 成功:结算 + 日志 + 插入任务 ──
  606. if taskErr == nil {
  607. if settleErr := service.SettleBilling(c, relayInfo, result.Quota); settleErr != nil {
  608. common.SysError("settle task billing error: " + settleErr.Error())
  609. }
  610. service.LogTaskConsumption(c, relayInfo)
  611. task := model.InitTask(result.Platform, relayInfo)
  612. task.PrivateData.UpstreamTaskID = result.UpstreamTaskID
  613. task.PrivateData.BillingSource = relayInfo.BillingSource
  614. task.PrivateData.SubscriptionId = relayInfo.SubscriptionId
  615. task.PrivateData.TokenId = relayInfo.TokenId
  616. task.PrivateData.BillingContext = buildTaskBillingContext(relayInfo)
  617. task.Quota = result.Quota
  618. task.Data = result.TaskData
  619. task.Action = relayInfo.Action
  620. if insertErr := task.Insert(); insertErr != nil {
  621. common.SysError("insert task error: " + insertErr.Error())
  622. }
  623. }
  624. if taskErr != nil {
  625. respondTaskError(c, taskErr)
  626. }
  627. }
  628. // respondTaskError 统一输出 Task 错误响应(含 429 限流提示改写)
  629. func respondTaskError(c *gin.Context, taskErr *dto.TaskError) {
  630. if taskErr.StatusCode == http.StatusTooManyRequests {
  631. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  632. }
  633. c.JSON(taskErr.StatusCode, taskErr)
  634. }
  635. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  636. if taskErr == nil {
  637. return false
  638. }
  639. if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
  640. return false
  641. }
  642. if retryTimes <= 0 {
  643. return false
  644. }
  645. if taskErr.StatusCode == http.StatusTooManyRequests {
  646. return true
  647. }
  648. if taskErr.StatusCode == 307 {
  649. return true
  650. }
  651. if taskErr.StatusCode/100 == 5 {
  652. // 超时不重试
  653. if operation_setting.IsAlwaysSkipRetryStatusCode(taskErr.StatusCode) {
  654. return false
  655. }
  656. return true
  657. }
  658. if taskErr.StatusCode == http.StatusBadRequest {
  659. return false
  660. }
  661. if taskErr.StatusCode == 408 {
  662. // azure处理超时不重试
  663. return false
  664. }
  665. if taskErr.LocalError {
  666. return false
  667. }
  668. if taskErr.StatusCode/100 == 2 {
  669. return false
  670. }
  671. return true
  672. }