adaptor.go 6.4 KB

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