relay_task.go 15 KB

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