relay_task.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. package relay
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. "strings"
  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/model"
  15. "github.com/QuantumNous/new-api/relay/channel"
  16. relaycommon "github.com/QuantumNous/new-api/relay/common"
  17. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  18. "github.com/QuantumNous/new-api/service"
  19. "github.com/QuantumNous/new-api/setting/ratio_setting"
  20. "github.com/gin-gonic/gin"
  21. )
  22. /*
  23. Task 任务通过平台、Action 区分任务
  24. */
  25. func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  26. info.InitChannelMeta(c)
  27. // ensure TaskRelayInfo is initialized to avoid nil dereference when accessing embedded fields
  28. if info.TaskRelayInfo == nil {
  29. info.TaskRelayInfo = &relaycommon.TaskRelayInfo{}
  30. }
  31. path := c.Request.URL.Path
  32. if strings.Contains(path, "/v1/videos/") && strings.HasSuffix(path, "/remix") {
  33. info.Action = constant.TaskActionRemix
  34. }
  35. // 提取 remix 任务的 video_id
  36. if info.Action == constant.TaskActionRemix {
  37. videoID := c.Param("video_id")
  38. if strings.TrimSpace(videoID) == "" {
  39. return service.TaskErrorWrapperLocal(fmt.Errorf("video_id is required"), "invalid_request", http.StatusBadRequest)
  40. }
  41. info.OriginTaskID = videoID
  42. }
  43. platform := constant.TaskPlatform(c.GetString("platform"))
  44. // 获取原始任务信息
  45. if info.OriginTaskID != "" {
  46. originTask, exist, err := model.GetByTaskId(info.UserId, info.OriginTaskID)
  47. if err != nil {
  48. taskErr = service.TaskErrorWrapper(err, "get_origin_task_failed", http.StatusInternalServerError)
  49. return
  50. }
  51. if !exist {
  52. taskErr = service.TaskErrorWrapperLocal(errors.New("task_origin_not_exist"), "task_not_exist", http.StatusBadRequest)
  53. return
  54. }
  55. if info.OriginModelName == "" {
  56. if originTask.Properties.OriginModelName != "" {
  57. info.OriginModelName = originTask.Properties.OriginModelName
  58. } else if originTask.Properties.UpstreamModelName != "" {
  59. info.OriginModelName = originTask.Properties.UpstreamModelName
  60. } else {
  61. var taskData map[string]interface{}
  62. _ = json.Unmarshal(originTask.Data, &taskData)
  63. if m, ok := taskData["model"].(string); ok && m != "" {
  64. info.OriginModelName = m
  65. platform = originTask.Platform
  66. }
  67. }
  68. }
  69. if originTask.ChannelId != info.ChannelId {
  70. channel, err := model.GetChannelById(originTask.ChannelId, true)
  71. if err != nil {
  72. taskErr = service.TaskErrorWrapperLocal(err, "channel_not_found", http.StatusBadRequest)
  73. return
  74. }
  75. if channel.Status != common.ChannelStatusEnabled {
  76. taskErr = service.TaskErrorWrapperLocal(errors.New("the channel of the origin task is disabled"), "task_channel_disable", http.StatusBadRequest)
  77. return
  78. }
  79. c.Set("base_url", channel.GetBaseURL())
  80. c.Set("channel_id", originTask.ChannelId)
  81. c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
  82. info.ChannelBaseUrl = channel.GetBaseURL()
  83. info.ChannelId = originTask.ChannelId
  84. platform = originTask.Platform
  85. }
  86. // 使用原始任务的参数
  87. if info.Action == constant.TaskActionRemix {
  88. var taskData map[string]interface{}
  89. _ = json.Unmarshal(originTask.Data, &taskData)
  90. secondsStr, _ := taskData["seconds"].(string)
  91. seconds, _ := strconv.Atoi(secondsStr)
  92. if seconds <= 0 {
  93. seconds = 4
  94. }
  95. sizeStr, _ := taskData["size"].(string)
  96. if info.PriceData.OtherRatios == nil {
  97. info.PriceData.OtherRatios = map[string]float64{}
  98. }
  99. info.PriceData.OtherRatios["seconds"] = float64(seconds)
  100. info.PriceData.OtherRatios["size"] = 1
  101. if sizeStr == "1792x1024" || sizeStr == "1024x1792" {
  102. info.PriceData.OtherRatios["size"] = 1.666667
  103. }
  104. }
  105. }
  106. if platform == "" {
  107. platform = GetTaskPlatform(c)
  108. }
  109. info.InitChannelMeta(c)
  110. adaptor := GetTaskAdaptor(platform)
  111. if adaptor == nil {
  112. return service.TaskErrorWrapperLocal(fmt.Errorf("invalid api platform: %s", platform), "invalid_api_platform", http.StatusBadRequest)
  113. }
  114. adaptor.Init(info)
  115. // get & validate taskRequest 获取并验证文本请求
  116. taskErr = adaptor.ValidateRequestAndSetAction(c, info)
  117. if taskErr != nil {
  118. return
  119. }
  120. modelName := info.OriginModelName
  121. if modelName == "" {
  122. modelName = service.CoverTaskActionToModelName(platform, info.Action)
  123. }
  124. modelPrice, success := ratio_setting.GetModelPrice(modelName, true)
  125. if !success {
  126. defaultPrice, ok := ratio_setting.GetDefaultModelPriceMap()[modelName]
  127. if !ok {
  128. modelPrice = 0.1
  129. } else {
  130. modelPrice = defaultPrice
  131. }
  132. }
  133. // 预扣
  134. groupRatio := ratio_setting.GetGroupRatio(info.UsingGroup)
  135. var ratio float64
  136. userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(info.UserGroup, info.UsingGroup)
  137. if hasUserGroupRatio {
  138. ratio = modelPrice * userGroupRatio
  139. } else {
  140. ratio = modelPrice * groupRatio
  141. }
  142. // FIXME: 临时修补,支持任务仅按次计费
  143. if !common.StringsContains(constant.TaskPricePatches, modelName) {
  144. if len(info.PriceData.OtherRatios) > 0 {
  145. for _, ra := range info.PriceData.OtherRatios {
  146. if 1.0 != ra {
  147. ratio *= ra
  148. }
  149. }
  150. }
  151. }
  152. println(fmt.Sprintf("model: %s, model_price: %.4f, group: %s, group_ratio: %.4f, final_ratio: %.4f", modelName, modelPrice, info.UsingGroup, groupRatio, ratio))
  153. userQuota, err := model.GetUserQuota(info.UserId, false)
  154. if err != nil {
  155. taskErr = service.TaskErrorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
  156. return
  157. }
  158. quota := int(ratio * common.QuotaPerUnit)
  159. if userQuota-quota < 0 {
  160. taskErr = service.TaskErrorWrapperLocal(errors.New("user quota is not enough"), "quota_not_enough", http.StatusForbidden)
  161. return
  162. }
  163. // build body
  164. requestBody, err := adaptor.BuildRequestBody(c, info)
  165. if err != nil {
  166. taskErr = service.TaskErrorWrapper(err, "build_request_failed", http.StatusInternalServerError)
  167. return
  168. }
  169. // do request
  170. resp, err := adaptor.DoRequest(c, info, requestBody)
  171. if err != nil {
  172. taskErr = service.TaskErrorWrapper(err, "do_request_failed", http.StatusInternalServerError)
  173. return
  174. }
  175. // handle response
  176. if resp != nil && resp.StatusCode != http.StatusOK {
  177. responseBody, _ := io.ReadAll(resp.Body)
  178. taskErr = service.TaskErrorWrapper(fmt.Errorf(string(responseBody)), "fail_to_fetch_task", resp.StatusCode)
  179. return
  180. }
  181. defer func() {
  182. // release quota
  183. if info.ConsumeQuota && taskErr == nil {
  184. err := service.PostConsumeQuota(info, quota, 0, true)
  185. if err != nil {
  186. common.SysLog("error consuming token remain quota: " + err.Error())
  187. }
  188. if quota != 0 {
  189. tokenName := c.GetString("token_name")
  190. //gRatio := groupRatio
  191. //if hasUserGroupRatio {
  192. // gRatio = userGroupRatio
  193. //}
  194. logContent := fmt.Sprintf("操作 %s", info.Action)
  195. // FIXME: 临时修补,支持任务仅按次计费
  196. if common.StringsContains(constant.TaskPricePatches, modelName) {
  197. logContent = fmt.Sprintf("%s,按次计费", logContent)
  198. } else {
  199. if len(info.PriceData.OtherRatios) > 0 {
  200. var contents []string
  201. for key, ra := range info.PriceData.OtherRatios {
  202. if 1.0 != ra {
  203. contents = append(contents, fmt.Sprintf("%s: %.2f", key, ra))
  204. }
  205. }
  206. if len(contents) > 0 {
  207. logContent = fmt.Sprintf("%s, 计算参数:%s", logContent, strings.Join(contents, ", "))
  208. }
  209. }
  210. }
  211. other := make(map[string]interface{})
  212. if c != nil && c.Request != nil && c.Request.URL != nil {
  213. other["request_path"] = c.Request.URL.Path
  214. }
  215. other["model_price"] = modelPrice
  216. other["group_ratio"] = groupRatio
  217. if hasUserGroupRatio {
  218. other["user_group_ratio"] = userGroupRatio
  219. }
  220. model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{
  221. ChannelId: info.ChannelId,
  222. ModelName: modelName,
  223. TokenName: tokenName,
  224. Quota: quota,
  225. Content: logContent,
  226. TokenId: info.TokenId,
  227. Group: info.UsingGroup,
  228. Other: other,
  229. })
  230. model.UpdateUserUsedQuotaAndRequestCount(info.UserId, quota)
  231. model.UpdateChannelUsedQuota(info.ChannelId, quota)
  232. }
  233. }
  234. }()
  235. taskID, taskData, taskErr := adaptor.DoResponse(c, resp, info)
  236. if taskErr != nil {
  237. return
  238. }
  239. info.ConsumeQuota = true
  240. // insert task
  241. task := model.InitTask(platform, info)
  242. task.TaskID = taskID
  243. task.Quota = quota
  244. task.Data = taskData
  245. task.Action = info.Action
  246. err = task.Insert()
  247. if err != nil {
  248. taskErr = service.TaskErrorWrapper(err, "insert_task_failed", http.StatusInternalServerError)
  249. return
  250. }
  251. return nil
  252. }
  253. var fetchRespBuilders = map[int]func(c *gin.Context) (respBody []byte, taskResp *dto.TaskError){
  254. relayconstant.RelayModeSunoFetchByID: sunoFetchByIDRespBodyBuilder,
  255. relayconstant.RelayModeSunoFetch: sunoFetchRespBodyBuilder,
  256. relayconstant.RelayModeVideoFetchByID: videoFetchByIDRespBodyBuilder,
  257. }
  258. func RelayTaskFetch(c *gin.Context, relayMode int) (taskResp *dto.TaskError) {
  259. respBuilder, ok := fetchRespBuilders[relayMode]
  260. if !ok {
  261. taskResp = service.TaskErrorWrapperLocal(errors.New("invalid_relay_mode"), "invalid_relay_mode", http.StatusBadRequest)
  262. }
  263. respBody, taskErr := respBuilder(c)
  264. if taskErr != nil {
  265. return taskErr
  266. }
  267. if len(respBody) == 0 {
  268. respBody = []byte("{\"code\":\"success\",\"data\":null}")
  269. }
  270. c.Writer.Header().Set("Content-Type", "application/json")
  271. _, err := io.Copy(c.Writer, bytes.NewBuffer(respBody))
  272. if err != nil {
  273. taskResp = service.TaskErrorWrapper(err, "copy_response_body_failed", http.StatusInternalServerError)
  274. return
  275. }
  276. return
  277. }
  278. func sunoFetchRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  279. userId := c.GetInt("id")
  280. var condition = struct {
  281. IDs []any `json:"ids"`
  282. Action string `json:"action"`
  283. }{}
  284. err := c.BindJSON(&condition)
  285. if err != nil {
  286. taskResp = service.TaskErrorWrapper(err, "invalid_request", http.StatusBadRequest)
  287. return
  288. }
  289. var tasks []any
  290. if len(condition.IDs) > 0 {
  291. taskModels, err := model.GetByTaskIds(userId, condition.IDs)
  292. if err != nil {
  293. taskResp = service.TaskErrorWrapper(err, "get_tasks_failed", http.StatusInternalServerError)
  294. return
  295. }
  296. for _, task := range taskModels {
  297. tasks = append(tasks, TaskModel2Dto(task))
  298. }
  299. } else {
  300. tasks = make([]any, 0)
  301. }
  302. respBody, err = json.Marshal(dto.TaskResponse[[]any]{
  303. Code: "success",
  304. Data: tasks,
  305. })
  306. return
  307. }
  308. func sunoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  309. taskId := c.Param("id")
  310. userId := c.GetInt("id")
  311. originTask, exist, err := model.GetByTaskId(userId, taskId)
  312. if err != nil {
  313. taskResp = service.TaskErrorWrapper(err, "get_task_failed", http.StatusInternalServerError)
  314. return
  315. }
  316. if !exist {
  317. taskResp = service.TaskErrorWrapperLocal(errors.New("task_not_exist"), "task_not_exist", http.StatusBadRequest)
  318. return
  319. }
  320. respBody, err = json.Marshal(dto.TaskResponse[any]{
  321. Code: "success",
  322. Data: TaskModel2Dto(originTask),
  323. })
  324. return
  325. }
  326. func videoFetchByIDRespBodyBuilder(c *gin.Context) (respBody []byte, taskResp *dto.TaskError) {
  327. taskId := c.Param("task_id")
  328. if taskId == "" {
  329. taskId = c.GetString("task_id")
  330. }
  331. userId := c.GetInt("id")
  332. originTask, exist, err := model.GetByTaskId(userId, taskId)
  333. if err != nil {
  334. taskResp = service.TaskErrorWrapper(err, "get_task_failed", http.StatusInternalServerError)
  335. return
  336. }
  337. if !exist {
  338. taskResp = service.TaskErrorWrapperLocal(errors.New("task_not_exist"), "task_not_exist", http.StatusBadRequest)
  339. return
  340. }
  341. func() {
  342. channelModel, err2 := model.GetChannelById(originTask.ChannelId, true)
  343. if err2 != nil {
  344. return
  345. }
  346. if channelModel.Type != constant.ChannelTypeVertexAi && channelModel.Type != constant.ChannelTypeGemini {
  347. return
  348. }
  349. baseURL := constant.ChannelBaseURLs[channelModel.Type]
  350. if channelModel.GetBaseURL() != "" {
  351. baseURL = channelModel.GetBaseURL()
  352. }
  353. adaptor := GetTaskAdaptor(constant.TaskPlatform(strconv.Itoa(channelModel.Type)))
  354. if adaptor == nil {
  355. return
  356. }
  357. resp, err2 := adaptor.FetchTask(baseURL, channelModel.Key, map[string]any{
  358. "task_id": originTask.TaskID,
  359. "action": originTask.Action,
  360. })
  361. if err2 != nil || resp == nil {
  362. return
  363. }
  364. defer resp.Body.Close()
  365. body, err2 := io.ReadAll(resp.Body)
  366. if err2 != nil {
  367. return
  368. }
  369. ti, err2 := adaptor.ParseTaskResult(body)
  370. if err2 == nil && ti != nil {
  371. if ti.Status != "" {
  372. originTask.Status = model.TaskStatus(ti.Status)
  373. }
  374. if ti.Progress != "" {
  375. originTask.Progress = ti.Progress
  376. }
  377. if ti.Url != "" {
  378. if strings.HasPrefix(ti.Url, "data:") {
  379. } else {
  380. originTask.FailReason = ti.Url
  381. }
  382. }
  383. _ = originTask.Update()
  384. var raw map[string]any
  385. _ = json.Unmarshal(body, &raw)
  386. format := "mp4"
  387. if respObj, ok := raw["response"].(map[string]any); ok {
  388. if vids, ok := respObj["videos"].([]any); ok && len(vids) > 0 {
  389. if v0, ok := vids[0].(map[string]any); ok {
  390. if mt, ok := v0["mimeType"].(string); ok && mt != "" {
  391. if strings.Contains(mt, "mp4") {
  392. format = "mp4"
  393. } else {
  394. format = mt
  395. }
  396. }
  397. }
  398. }
  399. }
  400. status := "processing"
  401. switch originTask.Status {
  402. case model.TaskStatusSuccess:
  403. status = "succeeded"
  404. case model.TaskStatusFailure:
  405. status = "failed"
  406. case model.TaskStatusQueued, model.TaskStatusSubmitted:
  407. status = "queued"
  408. }
  409. if !strings.HasPrefix(c.Request.RequestURI, "/v1/videos/") {
  410. out := map[string]any{
  411. "error": nil,
  412. "format": format,
  413. "metadata": nil,
  414. "status": status,
  415. "task_id": originTask.TaskID,
  416. "url": originTask.FailReason,
  417. }
  418. respBody, _ = json.Marshal(dto.TaskResponse[any]{
  419. Code: "success",
  420. Data: out,
  421. })
  422. }
  423. }
  424. }()
  425. if len(respBody) != 0 {
  426. return
  427. }
  428. if strings.HasPrefix(c.Request.RequestURI, "/v1/videos/") {
  429. adaptor := GetTaskAdaptor(originTask.Platform)
  430. if adaptor == nil {
  431. taskResp = service.TaskErrorWrapperLocal(fmt.Errorf("invalid channel id: %d", originTask.ChannelId), "invalid_channel_id", http.StatusBadRequest)
  432. return
  433. }
  434. if converter, ok := adaptor.(channel.OpenAIVideoConverter); ok {
  435. openAIVideoData, err := converter.ConvertToOpenAIVideo(originTask)
  436. if err != nil {
  437. taskResp = service.TaskErrorWrapper(err, "convert_to_openai_video_failed", http.StatusInternalServerError)
  438. return
  439. }
  440. respBody = openAIVideoData
  441. return
  442. }
  443. taskResp = service.TaskErrorWrapperLocal(errors.New(fmt.Sprintf("not_implemented:%s", originTask.Platform)), "not_implemented", http.StatusNotImplemented)
  444. return
  445. }
  446. respBody, err = json.Marshal(dto.TaskResponse[any]{
  447. Code: "success",
  448. Data: TaskModel2Dto(originTask),
  449. })
  450. if err != nil {
  451. taskResp = service.TaskErrorWrapper(err, "marshal_response_failed", http.StatusInternalServerError)
  452. }
  453. return
  454. }
  455. func TaskModel2Dto(task *model.Task) *dto.TaskDto {
  456. return &dto.TaskDto{
  457. TaskID: task.TaskID,
  458. Action: task.Action,
  459. Status: string(task.Status),
  460. FailReason: task.FailReason,
  461. SubmitTime: task.SubmitTime,
  462. StartTime: task.StartTime,
  463. FinishTime: task.FinishTime,
  464. Progress: task.Progress,
  465. Data: task.Data,
  466. }
  467. }