adaptor.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package sora
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "strings"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/QuantumNous/new-api/constant"
  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. type ContentItem struct {
  21. Type string `json:"type"` // "text" or "image_url"
  22. Text string `json:"text,omitempty"` // for text type
  23. ImageURL *ImageURL `json:"image_url,omitempty"` // for image_url type
  24. }
  25. type ImageURL struct {
  26. URL string `json:"url"`
  27. }
  28. type responseTask struct {
  29. ID string `json:"id"`
  30. TaskID string `json:"task_id,omitempty"` //兼容旧接口
  31. Object string `json:"object"`
  32. Model string `json:"model"`
  33. Status string `json:"status"`
  34. Progress int `json:"progress"`
  35. CreatedAt int64 `json:"created_at"`
  36. CompletedAt int64 `json:"completed_at,omitempty"`
  37. ExpiresAt int64 `json:"expires_at,omitempty"`
  38. Seconds string `json:"seconds,omitempty"`
  39. Size string `json:"size,omitempty"`
  40. RemixedFromVideoID string `json:"remixed_from_video_id,omitempty"`
  41. Error *struct {
  42. Message string `json:"message"`
  43. Code string `json:"code"`
  44. } `json:"error,omitempty"`
  45. }
  46. // ============================
  47. // Adaptor implementation
  48. // ============================
  49. type TaskAdaptor struct {
  50. ChannelType int
  51. apiKey string
  52. baseURL string
  53. }
  54. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  55. a.ChannelType = info.ChannelType
  56. a.baseURL = info.ChannelBaseUrl
  57. a.apiKey = info.ApiKey
  58. }
  59. func validateRemixRequest(c *gin.Context) *dto.TaskError {
  60. var req struct {
  61. Prompt string `json:"prompt"`
  62. }
  63. if err := common.UnmarshalBodyReusable(c, &req); err != nil {
  64. return service.TaskErrorWrapperLocal(err, "invalid_request", http.StatusBadRequest)
  65. }
  66. if strings.TrimSpace(req.Prompt) == "" {
  67. return service.TaskErrorWrapperLocal(fmt.Errorf("field prompt is required"), "invalid_request", http.StatusBadRequest)
  68. }
  69. return nil
  70. }
  71. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  72. if info.Action == constant.TaskActionRemix {
  73. return validateRemixRequest(c)
  74. }
  75. return relaycommon.ValidateMultipartDirect(c, info)
  76. }
  77. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  78. if info.Action == constant.TaskActionRemix {
  79. return fmt.Sprintf("%s/v1/videos/%s/remix", a.baseURL, info.OriginTaskID), nil
  80. }
  81. return fmt.Sprintf("%s/v1/videos", a.baseURL), nil
  82. }
  83. // BuildRequestHeader sets required headers.
  84. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  85. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  86. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  87. return nil
  88. }
  89. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  90. storage, err := common.GetBodyStorage(c)
  91. if err != nil {
  92. return nil, errors.Wrap(err, "get_request_body_failed")
  93. }
  94. return common.ReaderOnly(storage), nil
  95. }
  96. // DoRequest delegates to common helper.
  97. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  98. return channel.DoTaskApiRequest(a, c, info, requestBody)
  99. }
  100. // DoResponse handles upstream response, returns taskID etc.
  101. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  102. responseBody, err := io.ReadAll(resp.Body)
  103. if err != nil {
  104. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  105. return
  106. }
  107. _ = resp.Body.Close()
  108. // Parse Sora response
  109. var dResp responseTask
  110. if err := common.Unmarshal(responseBody, &dResp); err != nil {
  111. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  112. return
  113. }
  114. upstreamID := dResp.ID
  115. if upstreamID == "" {
  116. upstreamID = dResp.TaskID
  117. }
  118. if upstreamID == "" {
  119. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  120. return
  121. }
  122. // 使用公开 task_xxxx ID 返回给客户端
  123. dResp.ID = info.PublicTaskID
  124. dResp.TaskID = info.PublicTaskID
  125. c.JSON(http.StatusOK, dResp)
  126. return upstreamID, responseBody, nil
  127. }
  128. // FetchTask fetch task status
  129. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  130. taskID, ok := body["task_id"].(string)
  131. if !ok {
  132. return nil, fmt.Errorf("invalid task_id")
  133. }
  134. uri := fmt.Sprintf("%s/v1/videos/%s", baseUrl, taskID)
  135. req, err := http.NewRequest(http.MethodGet, uri, nil)
  136. if err != nil {
  137. return nil, err
  138. }
  139. req.Header.Set("Authorization", "Bearer "+key)
  140. client, err := service.GetHttpClientWithProxy(proxy)
  141. if err != nil {
  142. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  143. }
  144. return client.Do(req)
  145. }
  146. func (a *TaskAdaptor) GetModelList() []string {
  147. return ModelList
  148. }
  149. func (a *TaskAdaptor) GetChannelName() string {
  150. return ChannelName
  151. }
  152. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  153. resTask := responseTask{}
  154. if err := common.Unmarshal(respBody, &resTask); err != nil {
  155. return nil, errors.Wrap(err, "unmarshal task result failed")
  156. }
  157. taskResult := relaycommon.TaskInfo{
  158. Code: 0,
  159. }
  160. switch resTask.Status {
  161. case "queued", "pending":
  162. taskResult.Status = model.TaskStatusQueued
  163. case "processing", "in_progress":
  164. taskResult.Status = model.TaskStatusInProgress
  165. case "completed":
  166. taskResult.Status = model.TaskStatusSuccess
  167. // Url intentionally left empty — the caller constructs the proxy URL using the public task ID
  168. case "failed", "cancelled":
  169. taskResult.Status = model.TaskStatusFailure
  170. if resTask.Error != nil {
  171. taskResult.Reason = resTask.Error.Message
  172. } else {
  173. taskResult.Reason = "task failed"
  174. }
  175. default:
  176. }
  177. if resTask.Progress > 0 && resTask.Progress < 100 {
  178. taskResult.Progress = fmt.Sprintf("%d%%", resTask.Progress)
  179. }
  180. return &taskResult, nil
  181. }
  182. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  183. return task.Data, nil
  184. }