adaptor.go 6.4 KB

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