adaptor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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.5") {
  269. aliReq.Parameters.Resolution = "1080P"
  270. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-flash") {
  271. aliReq.Parameters.Resolution = "720P"
  272. } else if strings.HasPrefix(req.Model, "wan2.2-i2v-plus") {
  273. aliReq.Parameters.Resolution = "1080P"
  274. } else {
  275. aliReq.Parameters.Resolution = "720P"
  276. }
  277. }
  278. }
  279. // 处理时长
  280. if req.Duration > 0 {
  281. aliReq.Parameters.Duration = req.Duration
  282. } else if req.Seconds != "" {
  283. seconds, err := strconv.Atoi(req.Seconds)
  284. if err != nil {
  285. return nil, errors.Wrap(err, "convert seconds to int failed")
  286. } else {
  287. aliReq.Parameters.Duration = seconds
  288. }
  289. } else {
  290. aliReq.Parameters.Duration = 5 // 默认5秒
  291. }
  292. // 从 metadata 中提取额外参数
  293. if req.Metadata != nil {
  294. if metadataBytes, err := common.Marshal(req.Metadata); err == nil {
  295. err = common.Unmarshal(metadataBytes, aliReq)
  296. if err != nil {
  297. return nil, errors.Wrap(err, "unmarshal metadata failed")
  298. }
  299. } else {
  300. return nil, errors.Wrap(err, "marshal metadata failed")
  301. }
  302. }
  303. if aliReq.Model != req.Model {
  304. return nil, errors.New("can't change model with metadata")
  305. }
  306. info.PriceData.OtherRatios = map[string]float64{
  307. "seconds": float64(aliReq.Parameters.Duration),
  308. }
  309. ratios, err := ProcessAliOtherRatios(aliReq)
  310. if err != nil {
  311. return nil, err
  312. }
  313. for s, f := range ratios {
  314. info.PriceData.OtherRatios[s] = f
  315. }
  316. return aliReq, nil
  317. }
  318. // DoRequest delegates to common helper
  319. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  320. return channel.DoTaskApiRequest(a, c, info, requestBody)
  321. }
  322. // DoResponse handles upstream response
  323. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  324. responseBody, err := io.ReadAll(resp.Body)
  325. if err != nil {
  326. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  327. return
  328. }
  329. _ = resp.Body.Close()
  330. // 解析阿里响应
  331. var aliResp AliVideoResponse
  332. if err := common.Unmarshal(responseBody, &aliResp); err != nil {
  333. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  334. return
  335. }
  336. // 检查错误
  337. if aliResp.Code != "" {
  338. taskErr = service.TaskErrorWrapper(fmt.Errorf("%s: %s", aliResp.Code, aliResp.Message), "ali_api_error", resp.StatusCode)
  339. return
  340. }
  341. if aliResp.Output.TaskID == "" {
  342. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  343. return
  344. }
  345. // 转换为 OpenAI 格式响应
  346. openAIResp := dto.NewOpenAIVideo()
  347. openAIResp.ID = aliResp.Output.TaskID
  348. openAIResp.Model = c.GetString("model")
  349. if openAIResp.Model == "" && info != nil {
  350. openAIResp.Model = info.OriginModelName
  351. }
  352. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  353. openAIResp.CreatedAt = common.GetTimestamp()
  354. // 返回 OpenAI 格式
  355. c.JSON(http.StatusOK, openAIResp)
  356. return aliResp.Output.TaskID, responseBody, nil
  357. }
  358. // FetchTask 查询任务状态
  359. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  360. taskID, ok := body["task_id"].(string)
  361. if !ok {
  362. return nil, fmt.Errorf("invalid task_id")
  363. }
  364. uri := fmt.Sprintf("%s/api/v1/tasks/%s", baseUrl, taskID)
  365. req, err := http.NewRequest(http.MethodGet, uri, nil)
  366. if err != nil {
  367. return nil, err
  368. }
  369. req.Header.Set("Authorization", "Bearer "+key)
  370. client, err := service.GetHttpClientWithProxy(proxy)
  371. if err != nil {
  372. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  373. }
  374. return client.Do(req)
  375. }
  376. func (a *TaskAdaptor) GetModelList() []string {
  377. return ModelList
  378. }
  379. func (a *TaskAdaptor) GetChannelName() string {
  380. return ChannelName
  381. }
  382. // ParseTaskResult 解析任务结果
  383. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  384. var aliResp AliVideoResponse
  385. if err := common.Unmarshal(respBody, &aliResp); err != nil {
  386. return nil, errors.Wrap(err, "unmarshal task result failed")
  387. }
  388. taskResult := relaycommon.TaskInfo{
  389. Code: 0,
  390. }
  391. // 状态映射
  392. switch aliResp.Output.TaskStatus {
  393. case "PENDING":
  394. taskResult.Status = model.TaskStatusQueued
  395. case "RUNNING":
  396. taskResult.Status = model.TaskStatusInProgress
  397. case "SUCCEEDED":
  398. taskResult.Status = model.TaskStatusSuccess
  399. // 阿里直接返回视频URL,不需要额外的代理端点
  400. taskResult.Url = aliResp.Output.VideoURL
  401. case "FAILED", "CANCELED", "UNKNOWN":
  402. taskResult.Status = model.TaskStatusFailure
  403. if aliResp.Message != "" {
  404. taskResult.Reason = aliResp.Message
  405. } else if aliResp.Output.Message != "" {
  406. taskResult.Reason = fmt.Sprintf("task failed, code: %s , message: %s", aliResp.Output.Code, aliResp.Output.Message)
  407. } else {
  408. taskResult.Reason = "task failed"
  409. }
  410. default:
  411. taskResult.Status = model.TaskStatusQueued
  412. }
  413. return &taskResult, nil
  414. }
  415. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  416. var aliResp AliVideoResponse
  417. if err := common.Unmarshal(task.Data, &aliResp); err != nil {
  418. return nil, errors.Wrap(err, "unmarshal ali response failed")
  419. }
  420. openAIResp := dto.NewOpenAIVideo()
  421. openAIResp.ID = task.TaskID
  422. openAIResp.Status = convertAliStatus(aliResp.Output.TaskStatus)
  423. openAIResp.Model = task.Properties.OriginModelName
  424. openAIResp.SetProgressStr(task.Progress)
  425. openAIResp.CreatedAt = task.CreatedAt
  426. openAIResp.CompletedAt = task.UpdatedAt
  427. // 设置视频URL(核心字段)
  428. openAIResp.SetMetadata("url", aliResp.Output.VideoURL)
  429. // 错误处理
  430. if aliResp.Code != "" {
  431. openAIResp.Error = &dto.OpenAIVideoError{
  432. Code: aliResp.Code,
  433. Message: aliResp.Message,
  434. }
  435. } else if aliResp.Output.Code != "" {
  436. openAIResp.Error = &dto.OpenAIVideoError{
  437. Code: aliResp.Output.Code,
  438. Message: aliResp.Output.Message,
  439. }
  440. }
  441. return common.Marshal(openAIResp)
  442. }
  443. func convertAliStatus(aliStatus string) string {
  444. switch aliStatus {
  445. case "PENDING":
  446. return dto.VideoStatusQueued
  447. case "RUNNING":
  448. return dto.VideoStatusInProgress
  449. case "SUCCEEDED":
  450. return dto.VideoStatusCompleted
  451. case "FAILED", "CANCELED", "UNKNOWN":
  452. return dto.VideoStatusFailed
  453. default:
  454. return dto.VideoStatusUnknown
  455. }
  456. }