No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

559 líneas
18 KiB

  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "sort"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/constant"
  13. "github.com/QuantumNous/new-api/dto"
  14. "github.com/QuantumNous/new-api/logger"
  15. "github.com/QuantumNous/new-api/model"
  16. "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  17. relaycommon "github.com/QuantumNous/new-api/relay/common"
  18. "github.com/QuantumNous/new-api/types"
  19. "github.com/samber/lo"
  20. )
  21. // TaskPollingAdaptor 定义轮询所需的最小适配器接口,避免 service -> relay 的循环依赖
  22. type TaskPollingAdaptor interface {
  23. Init(info *relaycommon.RelayInfo)
  24. FetchTask(baseURL string, key string, body map[string]any, proxy string) (*http.Response, error)
  25. ParseTaskResult(body []byte) (*relaycommon.TaskInfo, error)
  26. // AdjustBillingOnComplete 在任务到达终态(成功/失败)时由轮询循环调用。
  27. // 返回正数触发差额结算(补扣/退还),返回 0 保持预扣费金额不变。
  28. AdjustBillingOnComplete(task *model.Task, taskResult *relaycommon.TaskInfo) int
  29. }
  30. // GetTaskAdaptorFunc 由 main 包注入,用于获取指定平台的任务适配器。
  31. // 打破 service -> relay -> relay/channel -> service 的循环依赖。
  32. var GetTaskAdaptorFunc func(platform constant.TaskPlatform) TaskPollingAdaptor
  33. // sweepTimedOutTasks 在主轮询之前独立清理超时任务。
  34. // 每次最多处理 100 条,剩余的下个周期继续处理。
  35. // 使用 per-task CAS (UpdateWithStatus) 防止覆盖被正常轮询已推进的任务。
  36. func sweepTimedOutTasks(ctx context.Context) {
  37. if constant.TaskTimeoutMinutes <= 0 {
  38. return
  39. }
  40. cutoff := time.Now().Unix() - int64(constant.TaskTimeoutMinutes)*60
  41. tasks := model.GetTimedOutUnfinishedTasks(cutoff, 100)
  42. if len(tasks) == 0 {
  43. return
  44. }
  45. const legacyTaskCutoff int64 = 1740182400 // 2026-02-22 00:00:00 UTC
  46. reason := fmt.Sprintf("任务超时(%d分钟)", constant.TaskTimeoutMinutes)
  47. legacyReason := "任务超时(旧系统遗留任务,不进行退款,请联系管理员)"
  48. now := time.Now().Unix()
  49. timedOutCount := 0
  50. for _, task := range tasks {
  51. isLegacy := task.SubmitTime > 0 && task.SubmitTime < legacyTaskCutoff
  52. oldStatus := task.Status
  53. task.Status = model.TaskStatusFailure
  54. task.Progress = "100%"
  55. task.FinishTime = now
  56. if isLegacy {
  57. task.FailReason = legacyReason
  58. } else {
  59. task.FailReason = reason
  60. }
  61. won, err := task.UpdateWithStatus(oldStatus)
  62. if err != nil {
  63. logger.LogError(ctx, fmt.Sprintf("sweepTimedOutTasks CAS update error for task %s: %v", task.TaskID, err))
  64. continue
  65. }
  66. if !won {
  67. logger.LogInfo(ctx, fmt.Sprintf("sweepTimedOutTasks: task %s already transitioned, skip", task.TaskID))
  68. continue
  69. }
  70. timedOutCount++
  71. if !isLegacy && task.Quota != 0 {
  72. RefundTaskQuota(ctx, task, reason)
  73. }
  74. }
  75. if timedOutCount > 0 {
  76. logger.LogInfo(ctx, fmt.Sprintf("sweepTimedOutTasks: timed out %d tasks", timedOutCount))
  77. }
  78. }
  79. // TaskPollingLoop 主轮询循环,每 15 秒检查一次未完成的任务
  80. func TaskPollingLoop() {
  81. for {
  82. time.Sleep(time.Duration(15) * time.Second)
  83. common.SysLog("任务进度轮询开始")
  84. ctx := context.TODO()
  85. sweepTimedOutTasks(ctx)
  86. allTasks := model.GetAllUnFinishSyncTasks(constant.TaskQueryLimit)
  87. platformTask := make(map[constant.TaskPlatform][]*model.Task)
  88. for _, t := range allTasks {
  89. platformTask[t.Platform] = append(platformTask[t.Platform], t)
  90. }
  91. for platform, tasks := range platformTask {
  92. if len(tasks) == 0 {
  93. continue
  94. }
  95. taskChannelM := make(map[int][]string)
  96. taskM := make(map[string]*model.Task)
  97. nullTaskIds := make([]int64, 0)
  98. for _, task := range tasks {
  99. upstreamID := task.GetUpstreamTaskID()
  100. if upstreamID == "" {
  101. // 统计失败的未完成任务
  102. nullTaskIds = append(nullTaskIds, task.ID)
  103. continue
  104. }
  105. taskM[upstreamID] = task
  106. taskChannelM[task.ChannelId] = append(taskChannelM[task.ChannelId], upstreamID)
  107. }
  108. if len(nullTaskIds) > 0 {
  109. err := model.TaskBulkUpdateByID(nullTaskIds, map[string]any{
  110. "status": "FAILURE",
  111. "progress": "100%",
  112. })
  113. if err != nil {
  114. logger.LogError(ctx, fmt.Sprintf("Fix null task_id task error: %v", err))
  115. } else {
  116. logger.LogInfo(ctx, fmt.Sprintf("Fix null task_id task success: %v", nullTaskIds))
  117. }
  118. }
  119. if len(taskChannelM) == 0 {
  120. continue
  121. }
  122. DispatchPlatformUpdate(platform, taskChannelM, taskM)
  123. }
  124. common.SysLog("任务进度轮询完成")
  125. }
  126. }
  127. // DispatchPlatformUpdate 按平台分发轮询更新
  128. func DispatchPlatformUpdate(platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) {
  129. switch platform {
  130. case constant.TaskPlatformMidjourney:
  131. // MJ 轮询由其自身处理,这里预留入口
  132. case constant.TaskPlatformSuno:
  133. _ = UpdateSunoTasks(context.Background(), taskChannelM, taskM)
  134. default:
  135. if err := UpdateVideoTasks(context.Background(), platform, taskChannelM, taskM); err != nil {
  136. common.SysLog(fmt.Sprintf("UpdateVideoTasks fail: %s", err))
  137. }
  138. }
  139. }
  140. // UpdateSunoTasks 按渠道更新所有 Suno 任务
  141. func UpdateSunoTasks(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
  142. for channelId, taskIds := range taskChannelM {
  143. err := updateSunoTasks(ctx, channelId, taskIds, taskM)
  144. if err != nil {
  145. logger.LogError(ctx, fmt.Sprintf("渠道 #%d 更新异步任务失败: %s", channelId, err.Error()))
  146. }
  147. }
  148. return nil
  149. }
  150. func updateSunoTasks(ctx context.Context, channelId int, taskIds []string, taskM map[string]*model.Task) error {
  151. logger.LogInfo(ctx, fmt.Sprintf("渠道 #%d 未完成的任务有: %d", channelId, len(taskIds)))
  152. if len(taskIds) == 0 {
  153. return nil
  154. }
  155. ch, err := model.CacheGetChannel(channelId)
  156. if err != nil {
  157. common.SysLog(fmt.Sprintf("CacheGetChannel: %v", err))
  158. // Collect DB primary key IDs for bulk update (taskIds are upstream IDs, not task_id column values)
  159. var failedIDs []int64
  160. for _, upstreamID := range taskIds {
  161. if t, ok := taskM[upstreamID]; ok {
  162. failedIDs = append(failedIDs, t.ID)
  163. }
  164. }
  165. err = model.TaskBulkUpdateByID(failedIDs, map[string]any{
  166. "fail_reason": fmt.Sprintf("获取渠道信息失败,请联系管理员,渠道ID:%d", channelId),
  167. "status": "FAILURE",
  168. "progress": "100%",
  169. })
  170. if err != nil {
  171. common.SysLog(fmt.Sprintf("UpdateSunoTask error: %v", err))
  172. }
  173. return err
  174. }
  175. adaptor := GetTaskAdaptorFunc(constant.TaskPlatformSuno)
  176. if adaptor == nil {
  177. return errors.New("adaptor not found")
  178. }
  179. proxy := ch.GetSetting().Proxy
  180. resp, err := adaptor.FetchTask(*ch.BaseURL, ch.Key, map[string]any{
  181. "ids": taskIds,
  182. }, proxy)
  183. if err != nil {
  184. common.SysLog(fmt.Sprintf("Get Task Do req error: %v", err))
  185. return err
  186. }
  187. if resp.StatusCode != http.StatusOK {
  188. logger.LogError(ctx, fmt.Sprintf("Get Task status code: %d", resp.StatusCode))
  189. return fmt.Errorf("Get Task status code: %d", resp.StatusCode)
  190. }
  191. defer resp.Body.Close()
  192. responseBody, err := io.ReadAll(resp.Body)
  193. if err != nil {
  194. common.SysLog(fmt.Sprintf("Get Suno Task parse body error: %v", err))
  195. return err
  196. }
  197. var responseItems dto.TaskResponse[[]dto.SunoDataResponse]
  198. err = common.Unmarshal(responseBody, &responseItems)
  199. if err != nil {
  200. logger.LogError(ctx, fmt.Sprintf("Get Suno Task parse body error2: %v, body: %s", err, string(responseBody)))
  201. return err
  202. }
  203. if !responseItems.IsSuccess() {
  204. common.SysLog(fmt.Sprintf("渠道 #%d 未完成的任务有: %d, 成功获取到任务数: %s", channelId, len(taskIds), string(responseBody)))
  205. return err
  206. }
  207. for _, responseItem := range responseItems.Data {
  208. task := taskM[responseItem.TaskID]
  209. if !taskNeedsUpdate(task, responseItem) {
  210. continue
  211. }
  212. task.Status = lo.If(model.TaskStatus(responseItem.Status) != "", model.TaskStatus(responseItem.Status)).Else(task.Status)
  213. task.FailReason = lo.If(responseItem.FailReason != "", responseItem.FailReason).Else(task.FailReason)
  214. task.SubmitTime = lo.If(responseItem.SubmitTime != 0, responseItem.SubmitTime).Else(task.SubmitTime)
  215. task.StartTime = lo.If(responseItem.StartTime != 0, responseItem.StartTime).Else(task.StartTime)
  216. task.FinishTime = lo.If(responseItem.FinishTime != 0, responseItem.FinishTime).Else(task.FinishTime)
  217. if responseItem.FailReason != "" || task.Status == model.TaskStatusFailure {
  218. logger.LogInfo(ctx, task.TaskID+" 构建失败,"+task.FailReason)
  219. task.Progress = "100%"
  220. RefundTaskQuota(ctx, task, task.FailReason)
  221. }
  222. if responseItem.Status == model.TaskStatusSuccess {
  223. task.Progress = "100%"
  224. }
  225. task.Data = responseItem.Data
  226. err = task.Update()
  227. if err != nil {
  228. common.SysLog("UpdateSunoTask task error: " + err.Error())
  229. }
  230. }
  231. return nil
  232. }
  233. // taskNeedsUpdate 检查 Suno 任务是否需要更新
  234. func taskNeedsUpdate(oldTask *model.Task, newTask dto.SunoDataResponse) bool {
  235. if oldTask.SubmitTime != newTask.SubmitTime {
  236. return true
  237. }
  238. if oldTask.StartTime != newTask.StartTime {
  239. return true
  240. }
  241. if oldTask.FinishTime != newTask.FinishTime {
  242. return true
  243. }
  244. if string(oldTask.Status) != newTask.Status {
  245. return true
  246. }
  247. if oldTask.FailReason != newTask.FailReason {
  248. return true
  249. }
  250. if (oldTask.Status == model.TaskStatusFailure || oldTask.Status == model.TaskStatusSuccess) && oldTask.Progress != "100%" {
  251. return true
  252. }
  253. oldData, _ := common.Marshal(oldTask.Data)
  254. newData, _ := common.Marshal(newTask.Data)
  255. sort.Slice(oldData, func(i, j int) bool {
  256. return oldData[i] < oldData[j]
  257. })
  258. sort.Slice(newData, func(i, j int) bool {
  259. return newData[i] < newData[j]
  260. })
  261. if string(oldData) != string(newData) {
  262. return true
  263. }
  264. return false
  265. }
  266. // UpdateVideoTasks 按渠道更新所有视频任务
  267. func UpdateVideoTasks(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) error {
  268. for channelId, taskIds := range taskChannelM {
  269. if err := updateVideoTasks(ctx, platform, channelId, taskIds, taskM); err != nil {
  270. logger.LogError(ctx, fmt.Sprintf("Channel #%d failed to update video async tasks: %s", channelId, err.Error()))
  271. }
  272. }
  273. return nil
  274. }
  275. func updateVideoTasks(ctx context.Context, platform constant.TaskPlatform, channelId int, taskIds []string, taskM map[string]*model.Task) error {
  276. logger.LogInfo(ctx, fmt.Sprintf("Channel #%d pending video tasks: %d", channelId, len(taskIds)))
  277. if len(taskIds) == 0 {
  278. return nil
  279. }
  280. cacheGetChannel, err := model.CacheGetChannel(channelId)
  281. if err != nil {
  282. // Collect DB primary key IDs for bulk update (taskIds are upstream IDs, not task_id column values)
  283. var failedIDs []int64
  284. for _, upstreamID := range taskIds {
  285. if t, ok := taskM[upstreamID]; ok {
  286. failedIDs = append(failedIDs, t.ID)
  287. }
  288. }
  289. errUpdate := model.TaskBulkUpdateByID(failedIDs, map[string]any{
  290. "fail_reason": fmt.Sprintf("Failed to get channel info, channel ID: %d", channelId),
  291. "status": "FAILURE",
  292. "progress": "100%",
  293. })
  294. if errUpdate != nil {
  295. common.SysLog(fmt.Sprintf("UpdateVideoTask error: %v", errUpdate))
  296. }
  297. return fmt.Errorf("CacheGetChannel failed: %w", err)
  298. }
  299. adaptor := GetTaskAdaptorFunc(platform)
  300. if adaptor == nil {
  301. return fmt.Errorf("video adaptor not found")
  302. }
  303. info := &relaycommon.RelayInfo{}
  304. info.ChannelMeta = &relaycommon.ChannelMeta{
  305. ChannelBaseUrl: cacheGetChannel.GetBaseURL(),
  306. }
  307. info.ApiKey = cacheGetChannel.Key
  308. adaptor.Init(info)
  309. for _, taskId := range taskIds {
  310. if err := updateVideoSingleTask(ctx, adaptor, cacheGetChannel, taskId, taskM); err != nil {
  311. logger.LogError(ctx, fmt.Sprintf("Failed to update video task %s: %s", taskId, err.Error()))
  312. }
  313. }
  314. return nil
  315. }
  316. func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *model.Channel, taskId string, taskM map[string]*model.Task) error {
  317. baseURL := constant.ChannelBaseURLs[ch.Type]
  318. if ch.GetBaseURL() != "" {
  319. baseURL = ch.GetBaseURL()
  320. }
  321. proxy := ch.GetSetting().Proxy
  322. task := taskM[taskId]
  323. if task == nil {
  324. logger.LogError(ctx, fmt.Sprintf("Task %s not found in taskM", taskId))
  325. return fmt.Errorf("task %s not found", taskId)
  326. }
  327. key := ch.Key
  328. privateData := task.PrivateData
  329. if privateData.Key != "" {
  330. key = privateData.Key
  331. }
  332. resp, err := adaptor.FetchTask(baseURL, key, map[string]any{
  333. "task_id": task.GetUpstreamTaskID(),
  334. "action": task.Action,
  335. }, proxy)
  336. if err != nil {
  337. return fmt.Errorf("fetchTask failed for task %s: %w", taskId, err)
  338. }
  339. defer resp.Body.Close()
  340. responseBody, err := io.ReadAll(resp.Body)
  341. if err != nil {
  342. return fmt.Errorf("readAll failed for task %s: %w", taskId, err)
  343. }
  344. logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask response: %s", string(responseBody)))
  345. snap := task.Snapshot()
  346. taskResult := &relaycommon.TaskInfo{}
  347. // try parse as New API response format
  348. var responseItems dto.TaskResponse[model.Task]
  349. if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() {
  350. logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask parsed as new api response format: %+v", responseItems))
  351. t := responseItems.Data
  352. taskResult.TaskID = t.TaskID
  353. taskResult.Status = string(t.Status)
  354. taskResult.Url = t.GetResultURL()
  355. taskResult.Progress = t.Progress
  356. taskResult.Reason = t.FailReason
  357. task.Data = t.Data
  358. } else if taskResult, err = adaptor.ParseTaskResult(responseBody); err != nil {
  359. return fmt.Errorf("parseTaskResult failed for task %s: %w", taskId, err)
  360. } else {
  361. task.Data = redactVideoResponseBody(responseBody)
  362. }
  363. logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask taskResult: %+v", taskResult))
  364. now := time.Now().Unix()
  365. if taskResult.Status == "" {
  366. taskResult = relaycommon.FailTaskInfo("upstream returned empty status")
  367. }
  368. shouldRefund := false
  369. shouldSettle := false
  370. quota := task.Quota
  371. task.Status = model.TaskStatus(taskResult.Status)
  372. switch taskResult.Status {
  373. case model.TaskStatusSubmitted:
  374. task.Progress = taskcommon.ProgressSubmitted
  375. case model.TaskStatusQueued:
  376. task.Progress = taskcommon.ProgressQueued
  377. case model.TaskStatusInProgress:
  378. task.Progress = taskcommon.ProgressInProgress
  379. if task.StartTime == 0 {
  380. task.StartTime = now
  381. }
  382. case model.TaskStatusSuccess:
  383. task.Progress = taskcommon.ProgressComplete
  384. if task.FinishTime == 0 {
  385. task.FinishTime = now
  386. }
  387. if strings.HasPrefix(taskResult.Url, "data:") {
  388. // data: URI (e.g. Vertex base64 encoded video) — keep in Data, not in ResultURL
  389. } else if taskResult.Url != "" {
  390. // Direct upstream URL (e.g. Kling, Ali, Doubao, etc.)
  391. task.PrivateData.ResultURL = taskResult.Url
  392. } else {
  393. // No URL from adaptor — construct proxy URL using public task ID
  394. task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
  395. }
  396. shouldSettle = true
  397. case model.TaskStatusFailure:
  398. logger.LogJson(ctx, fmt.Sprintf("Task %s failed", taskId), task)
  399. task.Status = model.TaskStatusFailure
  400. task.Progress = taskcommon.ProgressComplete
  401. if task.FinishTime == 0 {
  402. task.FinishTime = now
  403. }
  404. task.FailReason = taskResult.Reason
  405. logger.LogInfo(ctx, fmt.Sprintf("Task %s failed: %s", task.TaskID, task.FailReason))
  406. taskResult.Progress = taskcommon.ProgressComplete
  407. if quota != 0 {
  408. shouldRefund = true
  409. }
  410. default:
  411. return fmt.Errorf("unknown task status %s for task %s", taskResult.Status, task.TaskID)
  412. }
  413. if taskResult.Progress != "" {
  414. task.Progress = taskResult.Progress
  415. }
  416. isDone := task.Status == model.TaskStatusSuccess || task.Status == model.TaskStatusFailure
  417. if isDone && snap.Status != task.Status {
  418. won, err := task.UpdateWithStatus(snap.Status)
  419. if err != nil {
  420. logger.LogError(ctx, fmt.Sprintf("UpdateWithStatus failed for task %s: %s", task.TaskID, err.Error()))
  421. shouldRefund = false
  422. shouldSettle = false
  423. } else if !won {
  424. logger.LogWarn(ctx, fmt.Sprintf("Task %s already transitioned by another process, skip billing", task.TaskID))
  425. shouldRefund = false
  426. shouldSettle = false
  427. }
  428. } else if !snap.Equal(task.Snapshot()) {
  429. if _, err := task.UpdateWithStatus(snap.Status); err != nil {
  430. logger.LogError(ctx, fmt.Sprintf("Failed to update task %s: %s", task.TaskID, err.Error()))
  431. }
  432. } else {
  433. // No changes, skip update
  434. logger.LogDebug(ctx, fmt.Sprintf("No update needed for task %s", task.TaskID))
  435. }
  436. if shouldSettle {
  437. settleTaskBillingOnComplete(ctx, adaptor, task, taskResult)
  438. }
  439. if shouldRefund {
  440. RefundTaskQuota(ctx, task, task.FailReason)
  441. }
  442. return nil
  443. }
  444. func redactVideoResponseBody(body []byte) []byte {
  445. var m map[string]any
  446. if err := common.Unmarshal(body, &m); err != nil {
  447. return body
  448. }
  449. resp, _ := m["response"].(map[string]any)
  450. if resp != nil {
  451. delete(resp, "bytesBase64Encoded")
  452. if v, ok := resp["video"].(string); ok {
  453. resp["video"] = truncateBase64(v)
  454. }
  455. if vs, ok := resp["videos"].([]any); ok {
  456. for i := range vs {
  457. if vm, ok := vs[i].(map[string]any); ok {
  458. delete(vm, "bytesBase64Encoded")
  459. }
  460. }
  461. }
  462. }
  463. b, err := common.Marshal(m)
  464. if err != nil {
  465. return body
  466. }
  467. return b
  468. }
  469. func truncateBase64(s string) string {
  470. const maxKeep = 256
  471. if len(s) <= maxKeep {
  472. return s
  473. }
  474. return s[:maxKeep] + "..."
  475. }
  476. // settleTaskBillingOnComplete 任务完成时的统一计费调整。
  477. // 优先级:1. adaptor.AdjustBillingOnComplete 返回正数 → 使用 adaptor 计算的额度
  478. //
  479. // 2. taskResult.TotalTokens > 0 → 按 token 重算
  480. // 3. 都不满足 → 保持预扣额度不变
  481. func settleTaskBillingOnComplete(ctx context.Context, adaptor TaskPollingAdaptor, task *model.Task, taskResult *relaycommon.TaskInfo) {
  482. if bc := task.PrivateData.BillingContext; bc != nil && bc.BillingMode == types.BillingModeMatrix {
  483. _, billingUnit, _, err := types.ResolveMatrixPricingSnapshot(bc.BillingUnit, bc.PricingSnapshot)
  484. if err != nil {
  485. logger.LogError(ctx, fmt.Sprintf("task %s matrix pricing snapshot invalid: %s", task.TaskID, err.Error()))
  486. return
  487. }
  488. if billingUnit == types.BillingUnitPerCall {
  489. logger.LogInfo(ctx, fmt.Sprintf("task %s matrix per_call billing, skip settlement", task.TaskID))
  490. return
  491. }
  492. if billingUnit == types.BillingUnitPer1MTokens {
  493. RecalculateMatrixUsageTaskQuota(ctx, task, taskResult.TotalTokens)
  494. return
  495. }
  496. logger.LogError(ctx, fmt.Sprintf("task %s unknown matrix billing_unit: %s", task.TaskID, billingUnit))
  497. return
  498. }
  499. // 0. 按次计费的任务不做差额结算
  500. if bc := task.PrivateData.BillingContext; bc != nil && bc.PerCallBilling {
  501. logger.LogInfo(ctx, fmt.Sprintf("任务 %s 按次计费,跳过差额结算", task.TaskID))
  502. return
  503. }
  504. // 1. 优先让 adaptor 决定最终额度
  505. if actualQuota := adaptor.AdjustBillingOnComplete(task, taskResult); actualQuota > 0 {
  506. RecalculateTaskQuota(ctx, task, actualQuota, "adaptor计费调整")
  507. return
  508. }
  509. // 2. 回退到 token 重算
  510. if taskResult.TotalTokens > 0 {
  511. RecalculateTaskQuotaByTokens(ctx, task, taskResult.TotalTokens)
  512. return
  513. }
  514. // 3. 无调整,保持预扣额度
  515. }