adaptor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package ali
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/logger"
  12. "github.com/QuantumNous/new-api/model"
  13. "github.com/QuantumNous/new-api/relay/channel"
  14. relaycommon "github.com/QuantumNous/new-api/relay/common"
  15. "github.com/QuantumNous/new-api/service"
  16. "github.com/samber/lo"
  17. "github.com/gin-gonic/gin"
  18. "github.com/pkg/errors"
  19. )
  20. // ============================
  21. // Request / Response structures
  22. // ============================
  23. // AliVideoRequest 阿里通义万相视频生成请求
  24. type AliVideoRequest struct {
  25. Model string `json:"model"`
  26. Input AliVideoInput `json:"input"`
  27. Parameters *AliVideoParameters `json:"parameters,omitempty"`
  28. }
  29. // AliVideoInput 视频输入参数
  30. type AliVideoInput struct {
  31. Prompt string `json:"prompt,omitempty"` // 文本提示词
  32. ImgURL string `json:"img_url,omitempty"` // 首帧图像URL或Base64(图生视频)
  33. FirstFrameURL string `json:"first_frame_url,omitempty"` // 首帧图片URL(首尾帧生视频)
  34. LastFrameURL string `json:"last_frame_url,omitempty"` // 尾帧图片URL(首尾帧生视频)
  35. AudioURL string `json:"audio_url,omitempty"` // 音频URL(wan2.5支持)
  36. NegativePrompt string `json:"negative_prompt,omitempty"` // 反向提示词
  37. Template string `json:"template,omitempty"` // 视频特效模板
  38. }
  39. // AliVideoParameters 视频参数
  40. type AliVideoParameters struct {
  41. Resolution string `json:"resolution,omitempty"` // 分辨率: 480P/720P/1080P(图生视频、首尾帧生视频)
  42. Size string `json:"size,omitempty"` // 尺寸: 如 "832*480"(文生视频)
  43. Duration int `json:"duration,omitempty"` // 时长: 3-10秒
  44. PromptExtend bool `json:"prompt_extend,omitempty"` // 是否开启prompt智能改写
  45. Watermark bool `json:"watermark,omitempty"` // 是否添加水印
  46. Audio *bool `json:"audio,omitempty"` // 是否添加音频(wan2.5)
  47. Seed int `json:"seed,omitempty"` // 随机数种子
  48. }
  49. // AliVideoResponse 阿里通义万相响应
  50. type AliVideoResponse struct {
  51. Output AliVideoOutput `json:"output"`
  52. RequestID string `json:"request_id"`
  53. Code string `json:"code,omitempty"`
  54. Message string `json:"message,omitempty"`
  55. Usage *AliUsage `json:"usage,omitempty"`
  56. }
  57. // AliVideoOutput 输出信息
  58. type AliVideoOutput struct {
  59. TaskID string `json:"task_id"`
  60. TaskStatus string `json:"task_status"`
  61. SubmitTime string `json:"submit_time,omitempty"`
  62. ScheduledTime string `json:"scheduled_time,omitempty"`
  63. EndTime string `json:"end_time,omitempty"`
  64. OrigPrompt string `json:"orig_prompt,omitempty"`
  65. ActualPrompt string `json:"actual_prompt,omitempty"`
  66. VideoURL string `json:"video_url,omitempty"`
  67. Code string `json:"code,omitempty"`
  68. Message string `json:"message,omitempty"`
  69. }
  70. // AliUsage 使用统计
  71. type AliUsage struct {
  72. Duration int `json:"duration,omitempty"`
  73. VideoCount int `json:"video_count,omitempty"`
  74. SR int `json:"SR,omitempty"`
  75. }
  76. type AliMetadata struct {
  77. // Input 相关
  78. AudioURL string `json:"audio_url,omitempty"` // 音频URL
  79. ImgURL string `json:"img_url,omitempty"` // 图片URL(图生视频)
  80. FirstFrameURL string `json:"first_frame_url,omitempty"` // 首帧图片URL(首尾帧生视频)
  81. LastFrameURL string `json:"last_frame_url,omitempty"` // 尾帧图片URL(首尾帧生视频)
  82. NegativePrompt string `json:"negative_prompt,omitempty"` // 反向提示词
  83. Template string `json:"template,omitempty"` // 视频特效模板
  84. // Parameters 相关
  85. Resolution *string `json:"resolution,omitempty"` // 分辨率: 480P/720P/1080P
  86. Size *string `json:"size,omitempty"` // 尺寸: 如 "832*480"
  87. Duration *int `json:"duration,omitempty"` // 时长
  88. PromptExtend *bool `json:"prompt_extend,omitempty"` // 是否开启prompt智能改写
  89. Watermark *bool `json:"watermark,omitempty"` // 是否添加水印
  90. Audio *bool `json:"audio,omitempty"` // 是否添加音频
  91. Seed *int `json:"seed,omitempty"` // 随机数种子
  92. }
  93. // ============================
  94. // Adaptor implementation
  95. // ============================
  96. type TaskAdaptor struct {
  97. ChannelType int
  98. apiKey string
  99. baseURL string
  100. aliReq *AliVideoRequest
  101. }
  102. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  103. a.ChannelType = info.ChannelType
  104. a.baseURL = info.ChannelBaseUrl
  105. a.apiKey = info.ApiKey
  106. }
  107. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  108. // 阿里通义万相支持 JSON 格式,不使用 multipart
  109. var taskReq relaycommon.TaskSubmitReq
  110. if err := common.UnmarshalBodyReusable(c, &taskReq); err != nil {
  111. return service.TaskErrorWrapper(err, "unmarshal_task_request_failed", http.StatusBadRequest)
  112. }
  113. aliReq, err := a.convertToAliRequest(info, taskReq)
  114. if err != nil {
  115. return service.TaskErrorWrapper(err, "convert_to_ali_request_failed", http.StatusInternalServerError)
  116. }
  117. a.aliReq = aliReq
  118. logger.LogJson(c, "ali video request body", aliReq)
  119. return relaycommon.ValidateMultipartDirect(c, info)
  120. }
  121. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  122. return fmt.Sprintf("%s/api/v1/services/aigc/video-generation/video-synthesis", a.baseURL), nil
  123. }
  124. // BuildRequestHeader sets required headers for Ali API
  125. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  126. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  127. req.Header.Set("Content-Type", "application/json")
  128. req.Header.Set("X-DashScope-Async", "enable") // 阿里异步任务必须设置
  129. return nil
  130. }
  131. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  132. bodyBytes, err := common.Marshal(a.aliReq)
  133. if err != nil {
  134. return nil, errors.Wrap(err, "marshal_ali_request_failed")
  135. }
  136. return bytes.NewReader(bodyBytes), nil
  137. }
  138. var (
  139. size480p = []string{
  140. "832*480",
  141. "480*832",
  142. "624*624",
  143. }
  144. size720p = []string{
  145. "1280*720",
  146. "720*1280",
  147. "960*960",
  148. "1088*832",
  149. "832*1088",
  150. }
  151. size1080p = []string{
  152. "1920*1080",
  153. "1080*1920",
  154. "1440*1440",
  155. "1632*1248",
  156. "1248*1632",
  157. }
  158. )
  159. func sizeToResolution(size string) (string, error) {
  160. if lo.Contains(size480p, size) {
  161. return "480P", nil
  162. } else if lo.Contains(size720p, size) {
  163. return "720P", nil
  164. } else if lo.Contains(size1080p, size) {
  165. return "1080P", nil
  166. }
  167. return "", fmt.Errorf("invalid size: %s", size)
  168. }
  169. func ProcessAliOtherRatios(aliReq *AliVideoRequest) (map[string]float64, error) {
  170. otherRatios := make(map[string]float64)
  171. aliRatios := map[string]map[string]float64{
  172. "wan2.6-i2v": {
  173. "720P": 1,
  174. "1080P": 1 / 0.6,
  175. },
  176. "wan2.5-t2v-preview": {
  177. "480P": 1,
  178. "720P": 2,
  179. "1080P": 1 / 0.3,
  180. },
  181. "wan2.2-t2v-plus": {
  182. "480P": 1,
  183. "1080P": 0.7 / 0.14,
  184. },
  185. "wan2.5-i2v-preview": {
  186. "480P": 1,
  187. "720P": 2,
  188. "1080P": 1 / 0.3,
  189. },
  190. "wan2.2-i2v-plus": {
  191. "480P": 1,
  192. "1080P": 0.7 / 0.14,
  193. },
  194. "wan2.2-kf2v-flash": {
  195. "480P": 1,
  196. "720P": 2,
  197. "1080P": 4.8,
  198. },
  199. "wan2.2-i2v-flash": {
  200. "480P": 1,
  201. "720P": 2,
  202. },
  203. "wan2.2-s2v": {
  204. "480P": 1,
  205. "720P": 0.9 / 0.5,
  206. },
  207. }
  208. var resolution string
  209. // size match
  210. if aliReq.Parameters.Size != "" {
  211. toResolution, err := sizeToResolution(aliReq.Parameters.Size)
  212. if err != nil {
  213. return nil, err
  214. }
  215. resolution = toResolution
  216. } else {
  217. resolution = strings.ToUpper(aliReq.Parameters.Resolution)
  218. if !strings.HasSuffix(resolution, "P") {
  219. resolution = resolution + "P"
  220. }
  221. }
  222. if otherRatio, ok := aliRatios[aliReq.Model]; ok {
  223. if ratio, ok := otherRatio[resolution]; ok {
  224. otherRatios[fmt.Sprintf("resolution-%s", resolution)] = ratio
  225. }
  226. }
  227. return otherRatios, nil
  228. }
  229. func (a *TaskAdaptor) convertToAliRequest(info *relaycommon.RelayInfo, req relaycommon.TaskSubmitReq) (*AliVideoRequest, error) {
  230. aliReq := &AliVideoRequest{
  231. Model: req.Model,
  232. Input: AliVideoInput{
  233. Prompt: req.Prompt,
  234. ImgURL: req.InputReference,
  235. },
  236. Parameters: &AliVideoParameters{
  237. PromptExtend: true, // 默认开启智能改写
  238. Watermark: false,
  239. },
  240. }
  241. // 处理分辨率映射
  242. if req.Size != "" {
  243. // text to video size must be contained *
  244. if strings.Contains(req.Model, "t2v") && !strings.Contains(req.Size, "*") {
  245. return nil, fmt.Errorf("invalid size: %s, example: %s", req.Size, "1920*1080")
  246. }
  247. if strings.Contains(req.Size, "*") {
  248. aliReq.Parameters.Size = req.Size
  249. } else {
  250. resolution := strings.ToUpper(req.Size)
  251. // 支持 480p, 720p, 1080p 或 480P, 720P, 1080P
  252. if !strings.HasSuffix(resolution, "P") {
  253. resolution = resolution + "P"
  254. }
  255. aliReq.Parameters.Resolution = resolution
  256. }
  257. } else {
  258. // 根据模型设置默认分辨率
  259. if strings.Contains(req.Model, "t2v") { // image to video
  260. if strings.HasPrefix(req.Model, "wan2.5") {
  261. aliReq.Parameters.Size = "1920*1080"
  262. } else if strings.HasPrefix(req.Model, "wan2.2") {
  263. aliReq.Parameters.Size = "1920*1080"
  264. } else {
  265. aliReq.Parameters.Size = "1280*720"
  266. }
  267. } else {
  268. if strings.HasPrefix(req.Model, "wan2.6") {
  269. aliReq.Parameters.Resolution = "1080P"
  270. } else if strings.HasPrefix(req.Model, "wan2.5") {
  271. aliReq.Parameters.Resolution = "1080P"
  272. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-flash") {
  273. aliReq.Parameters.Resolution = "720P"
  274. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-plus") {
  275. aliReq.Parameters.Resolution = "1080P"
  276. } else {
  277. aliReq.Parameters.Resolution = "720P"
  278. }
  279. }
  280. }
  281. // 处理时长
  282. if req.Duration > 0 {
  283. aliReq.Parameters.Duration = req.Duration
  284. } else if req.Seconds != "" {
  285. seconds, err := strconv.Atoi(req.Seconds)
  286. if err != nil {
  287. return nil, errors.Wrap(err, "convert seconds to int failed")
  288. } else {
  289. aliReq.Parameters.Duration = seconds
  290. }
  291. } else {
  292. aliReq.Parameters.Duration = 5 // 默认5秒
  293. }
  294. // 从 metadata 中提取额外参数
  295. if req.Metadata != nil {
  296. if metadataBytes, err := common.Marshal(req.Metadata); err == nil {
  297. err = common.Unmarshal(metadataBytes, aliReq)
  298. if err != nil {
  299. return nil, errors.Wrap(err, "unmarshal metadata failed")
  300. }
  301. } else {
  302. return nil, errors.Wrap(err, "marshal metadata failed")
  303. }
  304. }
  305. if aliReq.Model != req.Model {
  306. return nil, errors.New("can't change model with metadata")
  307. }
  308. info.PriceData.OtherRatios = map[string]float64{
  309. "seconds": float64(aliReq.Parameters.Duration),
  310. }
  311. ratios, err := ProcessAliOtherRatios(aliReq)
  312. if err != nil {
  313. return nil, err
  314. }
  315. for s, f := range ratios {
  316. info.PriceData.OtherRatios[s] = f
  317. }
  318. return aliReq, nil
  319. }
  320. // DoRequest delegates to common helper
  321. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  322. return channel.DoTaskApiRequest(a, c, info, requestBody)
  323. }
  324. // DoResponse handles upstream response
  325. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  326. responseBody, err := io.ReadAll(resp.Body)
  327. if err != nil {
  328. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  329. return
  330. }
  331. _ = resp.Body.Close()
  332. // 解析阿里响应
  333. var aliResp AliVideoResponse
  334. if err := common.Unmarshal(responseBody, &aliResp); err != nil {
  335. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  336. return
  337. }
  338. // 检查错误
  339. if aliResp.Code != "" {
  340. taskErr = service.TaskErrorWrapper(fmt.Errorf("%s: %s", aliResp.Code, aliResp.Message), "ali_api_error", resp.StatusCode)
  341. return
  342. }
  343. if aliResp.Output.TaskID == "" {
  344. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  345. return
  346. }
  347. // 转换为 OpenAI 格式响应
  348. openAIResp := dto.NewOpenAIVideo()
  349. openAIResp.ID = info.PublicTaskID
  350. openAIResp.TaskID = info.PublicTaskID
  351. openAIResp.Model = c.GetString("model")
  352. if openAIResp.Model == "" && info != nil {
  353. openAIResp.Model = info.OriginModelName
  354. }
  355. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  356. openAIResp.CreatedAt = common.GetTimestamp()
  357. // 返回 OpenAI 格式
  358. c.JSON(http.StatusOK, openAIResp)
  359. return aliResp.Output.TaskID, responseBody, nil
  360. }
  361. // FetchTask 查询任务状态
  362. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  363. taskID, ok := body["task_id"].(string)
  364. if !ok {
  365. return nil, fmt.Errorf("invalid task_id")
  366. }
  367. uri := fmt.Sprintf("%s/api/v1/tasks/%s", baseUrl, taskID)
  368. req, err := http.NewRequest(http.MethodGet, uri, nil)
  369. if err != nil {
  370. return nil, err
  371. }
  372. req.Header.Set("Authorization", "Bearer "+key)
  373. client, err := service.GetHttpClientWithProxy(proxy)
  374. if err != nil {
  375. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  376. }
  377. return client.Do(req)
  378. }
  379. func (a *TaskAdaptor) GetModelList() []string {
  380. return ModelList
  381. }
  382. func (a *TaskAdaptor) GetChannelName() string {
  383. return ChannelName
  384. }
  385. // ParseTaskResult 解析任务结果
  386. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  387. var aliResp AliVideoResponse
  388. if err := common.Unmarshal(respBody, &aliResp); err != nil {
  389. return nil, errors.Wrap(err, "unmarshal task result failed")
  390. }
  391. taskResult := relaycommon.TaskInfo{
  392. Code: 0,
  393. }
  394. // 状态映射
  395. switch aliResp.Output.TaskStatus {
  396. case "PENDING":
  397. taskResult.Status = model.TaskStatusQueued
  398. case "RUNNING":
  399. taskResult.Status = model.TaskStatusInProgress
  400. case "SUCCEEDED":
  401. taskResult.Status = model.TaskStatusSuccess
  402. // 阿里直接返回视频URL,不需要额外的代理端点
  403. taskResult.Url = aliResp.Output.VideoURL
  404. case "FAILED", "CANCELED", "UNKNOWN":
  405. taskResult.Status = model.TaskStatusFailure
  406. if aliResp.Message != "" {
  407. taskResult.Reason = aliResp.Message
  408. } else if aliResp.Output.Message != "" {
  409. taskResult.Reason = fmt.Sprintf("task failed, code: %s , message: %s", aliResp.Output.Code, aliResp.Output.Message)
  410. } else {
  411. taskResult.Reason = "task failed"
  412. }
  413. default:
  414. taskResult.Status = model.TaskStatusQueued
  415. }
  416. return &taskResult, nil
  417. }
  418. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  419. var aliResp AliVideoResponse
  420. if err := common.Unmarshal(task.Data, &aliResp); err != nil {
  421. return nil, errors.Wrap(err, "unmarshal ali response failed")
  422. }
  423. openAIResp := dto.NewOpenAIVideo()
  424. openAIResp.ID = task.TaskID
  425. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  426. openAIResp.Model = task.Properties.OriginModelName
  427. openAIResp.SetProgressStr(task.Progress)
  428. openAIResp.CreatedAt = task.CreatedAt
  429. openAIResp.CompletedAt = task.UpdatedAt
  430. // 设置视频URL(核心字段)
  431. openAIResp.SetMetadata("url", aliResp.Output.VideoURL)
  432. // 错误处理
  433. if aliResp.Code != "" {
  434. openAIResp.Error = &dto.OpenAIVideoError{
  435. Code: aliResp.Code,
  436. Message: aliResp.Message,
  437. }
  438. } else if aliResp.Output.Code != "" {
  439. openAIResp.Error = &dto.OpenAIVideoError{
  440. Code: aliResp.Output.Code,
  441. Message: aliResp.Output.Message,
  442. }
  443. }
  444. return common.Marshal(openAIResp)
  445. }
  446. func convertAliStatus(aliStatus string) string {
  447. switch aliStatus {
  448. case "PENDING":
  449. return dto.VideoStatusQueued
  450. case "RUNNING":
  451. return dto.VideoStatusInProgress
  452. case "SUCCEEDED":
  453. return dto.VideoStatusCompleted
  454. case "FAILED", "CANCELED", "UNKNOWN":
  455. return dto.VideoStatusFailed
  456. default:
  457. return dto.VideoStatusUnknown
  458. }
  459. }