adaptor.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package doubao
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/constant"
  11. "github.com/QuantumNous/new-api/dto"
  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/gin-gonic/gin"
  17. "github.com/pkg/errors"
  18. )
  19. // ============================
  20. // Request / Response structures
  21. // ============================
  22. type ContentItem struct {
  23. Type string `json:"type"` // "text", "image_url" or "video"
  24. Text string `json:"text,omitempty"` // for text type
  25. ImageURL *ImageURL `json:"image_url,omitempty"` // for image_url type
  26. Video *VideoReference `json:"video,omitempty"` // for video (sample) type
  27. }
  28. type ImageURL struct {
  29. URL string `json:"url"`
  30. }
  31. type VideoReference struct {
  32. URL string `json:"url"` // Draft video URL
  33. }
  34. type requestPayload struct {
  35. Model string `json:"model"`
  36. Content []ContentItem `json:"content"`
  37. CallbackURL string `json:"callback_url,omitempty"`
  38. ReturnLastFrame *dto.BoolValue `json:"return_last_frame,omitempty"`
  39. ServiceTier string `json:"service_tier,omitempty"`
  40. ExecutionExpiresAfter dto.IntValue `json:"execution_expires_after,omitempty"`
  41. GenerateAudio *dto.BoolValue `json:"generate_audio,omitempty"`
  42. Draft *dto.BoolValue `json:"draft,omitempty"`
  43. Resolution string `json:"resolution,omitempty"`
  44. Ratio string `json:"ratio,omitempty"`
  45. Duration dto.IntValue `json:"duration,omitempty"`
  46. Frames dto.IntValue `json:"frames,omitempty"`
  47. Seed dto.IntValue `json:"seed,omitempty"`
  48. CameraFixed *dto.BoolValue `json:"camera_fixed,omitempty"`
  49. Watermark *dto.BoolValue `json:"watermark,omitempty"`
  50. }
  51. type responsePayload struct {
  52. ID string `json:"id"` // task_id
  53. }
  54. type responseTask struct {
  55. ID string `json:"id"`
  56. Model string `json:"model"`
  57. Status string `json:"status"`
  58. Content struct {
  59. VideoURL string `json:"video_url"`
  60. } `json:"content"`
  61. Seed int `json:"seed"`
  62. Resolution string `json:"resolution"`
  63. Duration int `json:"duration"`
  64. Ratio string `json:"ratio"`
  65. FramesPerSecond int `json:"framespersecond"`
  66. ServiceTier string `json:"service_tier"`
  67. Usage struct {
  68. CompletionTokens int `json:"completion_tokens"`
  69. TotalTokens int `json:"total_tokens"`
  70. } `json:"usage"`
  71. CreatedAt int64 `json:"created_at"`
  72. UpdatedAt int64 `json:"updated_at"`
  73. }
  74. // ============================
  75. // Adaptor implementation
  76. // ============================
  77. type TaskAdaptor struct {
  78. ChannelType int
  79. apiKey string
  80. baseURL string
  81. }
  82. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  83. a.ChannelType = info.ChannelType
  84. a.baseURL = info.ChannelBaseUrl
  85. a.apiKey = info.ApiKey
  86. }
  87. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  88. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  89. // Accept only POST /v1/video/generations as "generate" action.
  90. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate)
  91. }
  92. // BuildRequestURL constructs the upstream URL.
  93. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  94. return fmt.Sprintf("%s/api/v3/contents/generations/tasks", a.baseURL), nil
  95. }
  96. // BuildRequestHeader sets required headers.
  97. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  98. req.Header.Set("Content-Type", "application/json")
  99. req.Header.Set("Accept", "application/json")
  100. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  101. return nil
  102. }
  103. // BuildRequestBody converts request into Doubao specific format.
  104. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  105. req, err := relaycommon.GetTaskRequest(c)
  106. if err != nil {
  107. return nil, err
  108. }
  109. body, err := a.convertToRequestPayload(&req)
  110. if err != nil {
  111. return nil, errors.Wrap(err, "convert request payload failed")
  112. }
  113. info.UpstreamModelName = body.Model
  114. data, err := json.Marshal(body)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return bytes.NewReader(data), nil
  119. }
  120. // DoRequest delegates to common helper.
  121. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  122. return channel.DoTaskApiRequest(a, c, info, requestBody)
  123. }
  124. // DoResponse handles upstream response, returns taskID etc.
  125. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  126. responseBody, err := io.ReadAll(resp.Body)
  127. if err != nil {
  128. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  129. return
  130. }
  131. _ = resp.Body.Close()
  132. // Parse Doubao response
  133. var dResp responsePayload
  134. if err := json.Unmarshal(responseBody, &dResp); err != nil {
  135. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  136. return
  137. }
  138. if dResp.ID == "" {
  139. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  140. return
  141. }
  142. ov := dto.NewOpenAIVideo()
  143. ov.ID = dResp.ID
  144. ov.TaskID = dResp.ID
  145. ov.CreatedAt = time.Now().Unix()
  146. ov.Model = info.OriginModelName
  147. c.JSON(http.StatusOK, ov)
  148. return dResp.ID, responseBody, nil
  149. }
  150. // FetchTask fetch task status
  151. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  152. taskID, ok := body["task_id"].(string)
  153. if !ok {
  154. return nil, fmt.Errorf("invalid task_id")
  155. }
  156. uri := fmt.Sprintf("%s/api/v3/contents/generations/tasks/%s", baseUrl, taskID)
  157. req, err := http.NewRequest(http.MethodGet, uri, nil)
  158. if err != nil {
  159. return nil, err
  160. }
  161. req.Header.Set("Accept", "application/json")
  162. req.Header.Set("Content-Type", "application/json")
  163. req.Header.Set("Authorization", "Bearer "+key)
  164. client, err := service.GetHttpClientWithProxy(proxy)
  165. if err != nil {
  166. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  167. }
  168. return client.Do(req)
  169. }
  170. func (a *TaskAdaptor) GetModelList() []string {
  171. return ModelList
  172. }
  173. func (a *TaskAdaptor) GetChannelName() string {
  174. return ChannelName
  175. }
  176. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) {
  177. r := requestPayload{
  178. Model: req.Model,
  179. Content: []ContentItem{},
  180. }
  181. // Add text prompt
  182. if req.Prompt != "" {
  183. r.Content = append(r.Content, ContentItem{
  184. Type: "text",
  185. Text: req.Prompt,
  186. })
  187. }
  188. // Add images if present
  189. if req.HasImage() {
  190. for _, imgURL := range req.Images {
  191. r.Content = append(r.Content, ContentItem{
  192. Type: "image_url",
  193. ImageURL: &ImageURL{
  194. URL: imgURL,
  195. },
  196. })
  197. }
  198. }
  199. metadata := req.Metadata
  200. medaBytes, err := json.Marshal(metadata)
  201. if err != nil {
  202. return nil, errors.Wrap(err, "metadata marshal metadata failed")
  203. }
  204. err = json.Unmarshal(medaBytes, &r)
  205. if err != nil {
  206. return nil, errors.Wrap(err, "unmarshal metadata failed")
  207. }
  208. return &r, nil
  209. }
  210. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  211. resTask := responseTask{}
  212. if err := json.Unmarshal(respBody, &resTask); err != nil {
  213. return nil, errors.Wrap(err, "unmarshal task result failed")
  214. }
  215. taskResult := relaycommon.TaskInfo{
  216. Code: 0,
  217. }
  218. // Map Doubao status to internal status
  219. switch resTask.Status {
  220. case "pending", "queued":
  221. taskResult.Status = model.TaskStatusQueued
  222. taskResult.Progress = "10%"
  223. case "processing", "running":
  224. taskResult.Status = model.TaskStatusInProgress
  225. taskResult.Progress = "50%"
  226. case "succeeded":
  227. taskResult.Status = model.TaskStatusSuccess
  228. taskResult.Progress = "100%"
  229. taskResult.Url = resTask.Content.VideoURL
  230. // 解析 usage 信息用于按倍率计费
  231. taskResult.CompletionTokens = resTask.Usage.CompletionTokens
  232. taskResult.TotalTokens = resTask.Usage.TotalTokens
  233. case "failed":
  234. taskResult.Status = model.TaskStatusFailure
  235. taskResult.Progress = "100%"
  236. taskResult.Reason = "task failed"
  237. default:
  238. // Unknown status, treat as processing
  239. taskResult.Status = model.TaskStatusInProgress
  240. taskResult.Progress = "30%"
  241. }
  242. return &taskResult, nil
  243. }
  244. func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
  245. var dResp responseTask
  246. if err := json.Unmarshal(originTask.Data, &dResp); err != nil {
  247. return nil, errors.Wrap(err, "unmarshal doubao task data failed")
  248. }
  249. openAIVideo := dto.NewOpenAIVideo()
  250. openAIVideo.ID = originTask.TaskID
  251. openAIVideo.TaskID = originTask.TaskID
  252. openAIVideo.Status = originTask.Status.ToVideoStatus()
  253. openAIVideo.SetProgressStr(originTask.Progress)
  254. openAIVideo.SetMetadata("url", dResp.Content.VideoURL)
  255. openAIVideo.CreatedAt = originTask.CreatedAt
  256. openAIVideo.CompletedAt = originTask.UpdatedAt
  257. openAIVideo.Model = originTask.Properties.OriginModelName
  258. if dResp.Status == "failed" {
  259. openAIVideo.Error = &dto.OpenAIVideoError{
  260. Message: "task failed",
  261. Code: "failed",
  262. }
  263. }
  264. jsonData, _ := common.Marshal(openAIVideo)
  265. return jsonData, nil
  266. }