relay_task.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. package relay
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/relay/channel"
  15. "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  16. relaycommon "github.com/QuantumNous/new-api/relay/common"
  17. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  18. "github.com/QuantumNous/new-api/relay/helper"
  19. "github.com/QuantumNous/new-api/service"
  20. "github.com/gin-gonic/gin"
  21. )
  22. type TaskSubmitResult struct {
  23. UpstreamTaskID string
  24. TaskData []byte
  25. Platform constant.TaskPlatform
  26. ModelName string
  27. Quota int
  28. //PerCallPrice types.PriceData
  29. }
  30. // ResolveOriginTask 处理基于已有任务的提交(remix / continuation):
  31. // 查找原始任务、从中提取模型名称、将渠道锁定到原始任务的渠道(并通过
  32. // specific_channel_id 禁止重试),以及提取 OtherRatios(时长、分辨率)。
  33. // 该函数在控制器的重试循环之前调用一次,其结果通过 info 字段和上下文持久化。
  34. func ResolveOriginTask(c *gin.Context, info *relaycommon.RelayInfo) *dto.TaskError {
  35. // 检测 remix action
  36. path := c.Request.URL.Path
  37. if strings.Contains(path, "/v1/videos/") && strings.HasSuffix(path, "/remix") {
  38. info.Action = constant.TaskActionRemix
  39. }
  40. if info.Action == constant.TaskActionRemix {
  41. videoID := c.Param("video_id")
  42. if strings.TrimSpace(videoID) == "" {
  43. return service.TaskErrorWrapperLocal(fmt.Errorf("video_id is required"), "invalid_request", http.StatusBadRequest)
  44. }
  45. info.OriginTaskID = videoID
  46. }
  47. if info.OriginTaskID == "" {
  48. return nil
  49. }
  50. // 查找原始任务
  51. originTask, exist, err := model.GetByTaskId(info.UserId, info.OriginTaskID)
  52. if err != nil {
  53. return service.TaskErrorWrapper(err, "get_origin_task_failed", http.StatusInternalServerError)
  54. }
  55. if !exist {
  56. return service.TaskErrorWrapperLocal(errors.New("task_origin_not_exist"), "task_not_exist", http.StatusBadRequest)
  57. }
  58. // 从原始任务推导模型名称
  59. if info.OriginModelName == "" {
  60. if originTask.Properties.OriginModelName != "" {
  61. info.OriginModelName = originTask.Properties.OriginModelName
  62. } else if originTask.Properties.UpstreamModelName != "" {
  63. info.OriginModelName = originTask.Properties.UpstreamModelName
  64. } else {
  65. var taskData map[string]interface{}
  66. _ = common.Unmarshal(originTask.Data, &taskData)
  67. if m, ok := taskData["model"].(string); ok && m != "" {
  68. info.OriginModelName = m
  69. }
  70. }
  71. }
  72. // 锁定到原始任务的渠道(如果与当前选中的不同)
  73. if originTask.ChannelId != info.ChannelId {
  74. ch, err := model.GetChannelById(originTask.ChannelId, true)
  75. if err != nil {
  76. return service.TaskErrorWrapperLocal(err, "channel_not_found", http.StatusBadRequest)
  77. }
  78. if ch.Status != common.ChannelStatusEnabled {
  79. return service.TaskErrorWrapperLocal(errors.New("the channel of the origin task is disabled"), "task_channel_disable", http.StatusBadRequest)
  80. }
  81. key, _, newAPIError := ch.GetNextEnabledKey()
  82. if newAPIError != nil {
  83. return service.TaskErrorWrapper(newAPIError, "channel_no_available_key", newAPIError.StatusCode)
  84. }
  85. common.SetContextKey(c, constant.ContextKeyChannelKey, key)
  86. common.SetContextKey(c, constant.ContextKeyChannelType, ch.Type)
  87. common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, ch.GetBaseURL())
  88. common.SetContextKey(c, constant.ContextKeyChannelId, originTask.ChannelId)
  89. info.ChannelBaseUrl = ch.GetBaseURL()
  90. info.ChannelId = originTask.ChannelId
  91. info.ChannelType = ch.Type
  92. info.ApiKey = key
  93. }
  94. // 渠道已锁定到原始任务 → 禁止重试切换到其他渠道
  95. c.Set("specific_channel_id", fmt.Sprintf("%d", originTask.ChannelId))
  96. // 提取 remix 参数(时长、分辨率 → OtherRatios)
  97. if info.Action == constant.TaskActionRemix {
  98. var taskData map[string]interface{}
  99. _ = common.Unmarshal(originTask.Data, &taskData)
  100. secondsStr, _ := taskData["seconds"].(string)
  101. seconds, _ := strconv.Atoi(secondsStr)
  102. if seconds <= 0 {
  103. seconds = 4
  104. }
  105. sizeStr, _ := taskData["size"].(string)
  106. if info.PriceData.OtherRatios == nil {
  107. info.PriceData.OtherRatios = map[string]float64{}
  108. }
  109. info.PriceData.OtherRatios["seconds"] = float64(seconds)
  110. info.PriceData.OtherRatios["size"] = 1
  111. if sizeStr == "1792x1024" || sizeStr == "1024x1792" {
  112. info.PriceData.OtherRatios["size"] = 1.666667
  113. }
  114. }
  115. return nil
  116. }
  117. // RelayTaskSubmit 完成 task 提交的全部流程(每次尝试调用一次):
  118. // 刷新渠道元数据 → 确定 platform/adaptor → 验证请求 →
  119. // 估算计费(EstimateBilling) → 计算价格 → 预扣费(仅首次)→
  120. // 构建/发送/解析上游请求 → 提交后计费调整(AdjustBillingOnSubmit)。
  121. // 控制器负责 defer Refund 和成功后 Settle。
  122. func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitResult, *dto.TaskError) {
  123. info.InitChannelMeta(c)
  124. // 1. 确定 platform → 创建适配器 → 验证请求
  125. platform := constant.TaskPlatform(c.GetString("platform"))
  126. if platform == "" {
  127. platform = GetTaskPlatform(c)
  128. }
  129. adaptor := GetTaskAdaptor(platform)
  130. if adaptor == nil {
  131. return nil, service.TaskErrorWrapperLocal(fmt.Errorf("invalid api platform: %s", platform), "invalid_api_platform", http.StatusBadRequest)
  132. }
  133. adaptor.Init(info)
  134. if taskErr := adaptor.ValidateRequestAndSetAction(c, info); taskErr != nil {
  135. return nil, taskErr
  136. }
  137. // 2. 确定模型名称
  138. modelName := info.OriginModelName
  139. if modelName == "" {
  140. modelName = service.CoverTaskActionToModelName(platform, info.Action)
  141. }
  142. // 3. 预生成公开 task ID(仅首次)
  143. if info.PublicTaskID == "" {
  144. info.PublicTaskID = model.GenerateTaskID()
  145. }
  146. // 4. 价格计算:基础模型价格
  147. info.OriginModelName = modelName
  148. info.PriceData = helper.ModelPriceHelperPerCall(c, info)
  149. // 5. 计费估算:让适配器根据用户请求提供 OtherRatios(时长、分辨率等)
  150. // 必须在 ModelPriceHelperPerCall 之后调用(它会重建 PriceData)。
  151. // ResolveOriginTask 可能已在 remix 路径中预设了 OtherRatios,此处合并。
  152. if estimatedRatios := adaptor.EstimateBilling(c, info); len(estimatedRatios) > 0 {
  153. for k, v := range estimatedRatios {
  154. info.PriceData.AddOtherRatio(k, v)
  155. }
  156. }
  157. // 6. 将 OtherRatios 应用到基础额度
  158. if !common.StringsContains(constant.TaskPricePatches, modelName) {
  159. for _, ra := range info.PriceData.OtherRatios {
  160. if ra != 1.0 {
  161. info.PriceData.Quota = int(float64(info.PriceData.Quota) * ra)
  162. }
  163. }
  164. }
  165. // 7. 预扣费(仅首次 — 重试时 info.Billing 已存在,跳过)
  166. if info.Billing == nil && !info.PriceData.FreeModel {
  167. info.ForcePreConsume = true
  168. if apiErr := service.PreConsumeBilling(c, info.PriceData.Quota, info); apiErr != nil {
  169. return nil, service.TaskErrorFromAPIError(apiErr)
  170. }
  171. }
  172. // 8. 构建请求体
  173. requestBody, err := adaptor.BuildRequestBody(c, info)
  174. if err != nil {
  175. return nil, service.TaskErrorWrapper(err, "build_request_failed", http.StatusInternalServerError)
  176. }
  177. // 9. 发送请求
  178. resp, err := adaptor.DoRequest(c, info, requestBody)
  179. if err != nil {
  180. return nil, service.TaskErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
  181. }
  182. if resp != nil && resp.StatusCode != http.StatusOK {
  183. responseBody, _ := io.ReadAll(resp.Body)
  184. return nil, service.TaskErrorWrapper(fmt.Errorf("%s", string(responseBody)), "fail_to_fetch_task", resp.StatusCode)
  185. }
  186. // 10. 返回 OtherRatios 给下游(header 必须在 DoResponse 写 body 之前设置)
  187. otherRatios := info.PriceData.OtherRatios
  188. if otherRatios == nil {
  189. otherRatios = map[string]float64{}
  190. }
  191. ratiosJSON, _ := common.Marshal(otherRatios)
  192. c.Header("X-New-Api-Other-Ratios", string(ratiosJSON))
  193. // 11. 解析响应
  194. upstreamTaskID, taskData, taskErr := adaptor.DoResponse(c, resp, info)
  195. if taskErr != nil {
  196. return nil, taskErr
  197. }
  198. // 11. 提交后计费调整:让适配器根据上游实际返回调整 OtherRatios
  199. finalQuota := info.PriceData.Quota
  200. if adjustedRatios := adaptor.AdjustBillingOnSubmit(info, taskData); len(adjustedRatios) > 0 {
  201. // 基于调整后的 ratios 重新计算 quota
  202. finalQuota = recalcQuotaFromRatios(info, adjustedRatios)
  203. info.PriceData.OtherRatios = adjustedRatios
  204. info.PriceData.Quota = finalQuota
  205. }
  206. return &TaskSubmitResult{
  207. UpstreamTaskID: upstreamTaskID,
  208. TaskData: taskData,
  209. Platform: platform,
  210. ModelName: modelName,
  211. Quota: finalQuota,
  212. }, nil
  213. }
  214. // recalcQuotaFromRatios 根据 adjustedRatios 重新计算 quota。
  215. // 公式: baseQuota × ∏(ratio) — 其中 baseQuota 是不含 OtherRatios 的基础额度。
  216. func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float64) int {
  217. // 从 PriceData 获取不含 OtherRatios 的基础价格
  218. baseQuota := info.PriceData.Quota
  219. // 先除掉原有的 OtherRatios 恢复基础额度
  220. for _, ra := range info.PriceData.OtherRatios {
  221. if ra != 1.0 && ra > 0 {
  222. baseQuota = int(float64(baseQuota) / ra)
  223. }
  224. }
  225. // 应用新的 ratios
  226. result := float64(baseQuota)
  227. for _, ra := range ratios {
  228. if ra != 1.0 {
  229. result *= ra
  230. }
  231. }
  232. return int(result)
  233. }
  234. var fetchRespBuilders = map[int]func(c *gin.Context) (respBody []byte, taskResp *dto.TaskError){
  235. relayconstant.RelayModeSunoFetchByID: sunoFetchByIDRespBodyBuilder,
  236. relayconstant.RelayModeSunoFetch: sunoFetchRespBodyBuilder,
  237. relayconstant.RelayModeVideoFetchByID: videoFetchByIDRespBodyBuilder,
  238. }
  239. func RelayTaskFetch(c *gin.Context, relayMode int) (taskResp *dto.TaskError) {
  240. respBuilder, ok := fetchRespBuilders[relayMode]
  241. if !ok {
  242. taskResp = service.TaskErrorWrapperLocal(errors.New("invalid_relay_mode"), "invalid_relay_mode", http.StatusBadRequest)
  243. }
  244. respBody, taskErr := respBuilder(c)
  245. if taskErr != nil {
  246. return taskErr
  247. }
  248. if len(respBody) == 0 {
  249. respBody = []byte("{\"code\":\"success\",\"data\":null}")
  250. }
  251. c.Writer.Header().Set("Content-Type", "application/json")
  252. _, err := io.Copy(c.Writer, bytes.NewBuffer(respBody))
  253. if err != nil {
  254. taskResp = service.TaskErrorWrapper(err, "copy_response_body_failed", http.StatusInternalServerError)
  255. return
  256. }
  257. return
  258. }
  259. func sunoFetchRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  260. userId := c.GetInt("id")
  261. var condition = struct {
  262. IDs []any `json:"ids"`
  263. Action string `json:"action"`
  264. }{}
  265. err := c.BindJSON(&condition)
  266. if err != nil {
  267. taskResp = service.TaskErrorWrapper(err, "invalid_request", http.StatusBadRequest)
  268. return
  269. }
  270. var tasks []any
  271. if len(condition.IDs) > 0 {
  272. taskModels, err := model.GetByTaskIds(userId, condition.IDs)
  273. if err != nil {
  274. taskResp = service.TaskErrorWrapper(err, "get_tasks_failed", http.StatusInternalServerError)
  275. return
  276. }
  277. for _, task := range taskModels {
  278. tasks = append(tasks, TaskModel2Dto(task))
  279. }
  280. } else {
  281. tasks = make([]any, 0)
  282. }
  283. respBody, err = common.Marshal(dto.TaskResponse[[]any]{
  284. Code: "success",
  285. Data: tasks,
  286. })
  287. return
  288. }
  289. func sunoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  290. taskId := c.Param("id")
  291. userId := c.GetInt("id")
  292. originTask, exist, err := model.GetByTaskId(userId, taskId)
  293. if err != nil {
  294. taskResp = service.TaskErrorWrapper(err, "get_task_failed", http.StatusInternalServerError)
  295. return
  296. }
  297. if !exist {
  298. taskResp = service.TaskErrorWrapperLocal(errors.New("task_not_exist"), "task_not_exist", http.StatusBadRequest)
  299. return
  300. }
  301. respBody, err = common.Marshal(dto.TaskResponse[any]{
  302. Code: "success",
  303. Data: TaskModel2Dto(originTask),
  304. })
  305. return
  306. }
  307. func videoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  308. taskId := c.Param("task_id")
  309. if taskId == "" {
  310. taskId = c.GetString("task_id")
  311. }
  312. userId := c.GetInt("id")
  313. originTask, exist, err := model.GetByTaskId(userId, taskId)
  314. if err != nil {
  315. taskResp = service.TaskErrorWrapper(err, "get_task_failed", http.StatusInternalServerError)
  316. return
  317. }
  318. if !exist {
  319. taskResp = service.TaskErrorWrapperLocal(errors.New("task_not_exist"), "task_not_exist", http.StatusBadRequest)
  320. return
  321. }
  322. isOpenAIVideoAPI := strings.HasPrefix(c.Request.RequestURI, "/v1/videos/")
  323. // Gemini/Vertex 支持实时查询:用户 fetch 时直接从上游拉取最新状态
  324. if realtimeResp := tryRealtimeFetch(originTask, isOpenAIVideoAPI); len(realtimeResp) > 0 {
  325. respBody = realtimeResp
  326. return
  327. }
  328. // OpenAI Video API 格式: 走各 adaptor 的 ConvertToOpenAIVideo
  329. if isOpenAIVideoAPI {
  330. adaptor := GetTaskAdaptor(originTask.Platform)
  331. if adaptor == nil {
  332. taskResp = service.TaskErrorWrapperLocal(fmt.Errorf("invalid channel id: %d", originTask.ChannelId), "invalid_channel_id", http.StatusBadRequest)
  333. return
  334. }
  335. if converter, ok := adaptor.(channel.OpenAIVideoConverter); ok {
  336. openAIVideoData, err := converter.ConvertToOpenAIVideo(originTask)
  337. if err != nil {
  338. taskResp = service.TaskErrorWrapper(err, "convert_to_openai_video_failed", http.StatusInternalServerError)
  339. return
  340. }
  341. respBody = openAIVideoData
  342. return
  343. }
  344. taskResp = service.TaskErrorWrapperLocal(fmt.Errorf("not_implemented:%s", originTask.Platform), "not_implemented", http.StatusNotImplemented)
  345. return
  346. }
  347. // 通用 TaskDto 格式
  348. respBody, err = common.Marshal(dto.TaskResponse[any]{
  349. Code: "success",
  350. Data: TaskModel2Dto(originTask),
  351. })
  352. if err != nil {
  353. taskResp = service.TaskErrorWrapper(err, "marshal_response_failed", http.StatusInternalServerError)
  354. }
  355. return
  356. }
  357. // tryRealtimeFetch 尝试从上游实时拉取 Gemini/Vertex 任务状态。
  358. // 仅当渠道类型为 Gemini 或 Vertex 时触发;其他渠道或出错时返回 nil。
  359. // 当非 OpenAI Video API 时,还会构建自定义格式的响应体。
  360. func tryRealtimeFetch(task *model.Task, isOpenAIVideoAPI bool) []byte {
  361. channelModel, err := model.GetChannelById(task.ChannelId, true)
  362. if err != nil {
  363. return nil
  364. }
  365. if channelModel.Type != constant.ChannelTypeVertexAi && channelModel.Type != constant.ChannelTypeGemini {
  366. return nil
  367. }
  368. baseURL := constant.ChannelBaseURLs[channelModel.Type]
  369. if channelModel.GetBaseURL() != "" {
  370. baseURL = channelModel.GetBaseURL()
  371. }
  372. proxy := channelModel.GetSetting().Proxy
  373. adaptor := GetTaskAdaptor(constant.TaskPlatform(strconv.Itoa(channelModel.Type)))
  374. if adaptor == nil {
  375. return nil
  376. }
  377. resp, err := adaptor.FetchTask(baseURL, channelModel.Key, map[string]any{
  378. "task_id": task.GetUpstreamTaskID(),
  379. "action": task.Action,
  380. }, proxy)
  381. if err != nil || resp == nil {
  382. return nil
  383. }
  384. defer resp.Body.Close()
  385. body, err := io.ReadAll(resp.Body)
  386. if err != nil {
  387. return nil
  388. }
  389. ti, err := adaptor.ParseTaskResult(body)
  390. if err != nil || ti == nil {
  391. return nil
  392. }
  393. // 将上游最新状态更新到 task
  394. if ti.Status != "" {
  395. task.Status = model.TaskStatus(ti.Status)
  396. }
  397. if ti.Progress != "" {
  398. task.Progress = ti.Progress
  399. }
  400. if strings.HasPrefix(ti.Url, "data:") {
  401. // data: URI — kept in Data, not ResultURL
  402. } else if ti.Url != "" {
  403. task.PrivateData.ResultURL = ti.Url
  404. } else if task.Status == model.TaskStatusSuccess {
  405. // No URL from adaptor — construct proxy URL using public task ID
  406. task.PrivateData.ResultURL = taskcommon.BuildProxyURL(task.TaskID)
  407. }
  408. _ = task.Update()
  409. // OpenAI Video API 由调用者的 ConvertToOpenAIVideo 分支处理
  410. if isOpenAIVideoAPI {
  411. return nil
  412. }
  413. // 非 OpenAI Video API: 构建自定义格式响应
  414. format := detectVideoFormat(body)
  415. out := map[string]any{
  416. "error": nil,
  417. "format": format,
  418. "metadata": nil,
  419. "status": mapTaskStatusToSimple(task.Status),
  420. "task_id": task.TaskID,
  421. "url": task.GetResultURL(),
  422. }
  423. respBody, _ := common.Marshal(dto.TaskResponse[any]{
  424. Code: "success",
  425. Data: out,
  426. })
  427. return respBody
  428. }
  429. // detectVideoFormat 从 Gemini/Vertex 原始响应中探测视频格式
  430. func detectVideoFormat(rawBody []byte) string {
  431. var raw map[string]any
  432. if err := common.Unmarshal(rawBody, &raw); err != nil {
  433. return "mp4"
  434. }
  435. respObj, ok := raw["response"].(map[string]any)
  436. if !ok {
  437. return "mp4"
  438. }
  439. vids, ok := respObj["videos"].([]any)
  440. if !ok || len(vids) == 0 {
  441. return "mp4"
  442. }
  443. v0, ok := vids[0].(map[string]any)
  444. if !ok {
  445. return "mp4"
  446. }
  447. mt, ok := v0["mimeType"].(string)
  448. if !ok || mt == "" || strings.Contains(mt, "mp4") {
  449. return "mp4"
  450. }
  451. return mt
  452. }
  453. // mapTaskStatusToSimple 将内部 TaskStatus 映射为简化状态字符串
  454. func mapTaskStatusToSimple(status model.TaskStatus) string {
  455. switch status {
  456. case model.TaskStatusSuccess:
  457. return "succeeded"
  458. case model.TaskStatusFailure:
  459. return "failed"
  460. case model.TaskStatusQueued, model.TaskStatusSubmitted:
  461. return "queued"
  462. default:
  463. return "processing"
  464. }
  465. }
  466. func TaskModel2Dto(task *model.Task) *dto.TaskDto {
  467. return &dto.TaskDto{
  468. ID: task.ID,
  469. CreatedAt: task.CreatedAt,
  470. UpdatedAt: task.UpdatedAt,
  471. TaskID: task.TaskID,
  472. Platform: string(task.Platform),
  473. UserId: task.UserId,
  474. Group: task.Group,
  475. ChannelId: task.ChannelId,
  476. Quota: task.Quota,
  477. Action: task.Action,
  478. Status: string(task.Status),
  479. FailReason: task.FailReason,
  480. ResultURL: task.GetResultURL(),
  481. SubmitTime: task.SubmitTime,
  482. StartTime: task.StartTime,
  483. FinishTime: task.FinishTime,
  484. Progress: task.Progress,
  485. Properties: task.Properties,
  486. Username: task.Username,
  487. Data: task.Data,
  488. }
  489. }