adaptor.go 13 KB

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