relay_task.go 13 KB

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