adaptor.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package sora
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/dto"
  10. "one-api/model"
  11. "one-api/relay/channel"
  12. relaycommon "one-api/relay/common"
  13. "one-api/service"
  14. "one-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 (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  61. return relaycommon.ValidateMultipartDirect(c, info)
  62. }
  63. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  64. return fmt.Sprintf("%s/v1/videos", a.baseURL), nil
  65. }
  66. // BuildRequestHeader sets required headers.
  67. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  68. req.Header.Set("Authorization", "Bearer "+a.apiKey)
  69. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  70. return nil
  71. }
  72. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  73. cachedBody, err := common.GetRequestBody(c)
  74. if err != nil {
  75. return nil, errors.Wrap(err, "get_request_body_failed")
  76. }
  77. return bytes.NewReader(cachedBody), nil
  78. }
  79. // DoRequest delegates to common helper.
  80. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  81. return channel.DoTaskApiRequest(a, c, info, requestBody)
  82. }
  83. // DoResponse handles upstream response, returns taskID etc.
  84. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, _ *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  85. responseBody, err := io.ReadAll(resp.Body)
  86. if err != nil {
  87. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  88. return
  89. }
  90. _ = resp.Body.Close()
  91. // Parse Sora response
  92. var dResp responseTask
  93. if err := json.Unmarshal(responseBody, &dResp); err != nil {
  94. taskErr = service.TaskErrorWrapper(errors.Wrapf(err, "body: %s", responseBody), "unmarshal_response_body_failed", http.StatusInternalServerError)
  95. return
  96. }
  97. if dResp.ID == "" {
  98. if dResp.TaskID == "" {
  99. taskErr = service.TaskErrorWrapper(fmt.Errorf("task_id is empty"), "invalid_response", http.StatusInternalServerError)
  100. return
  101. }
  102. dResp.ID = dResp.TaskID
  103. dResp.TaskID = ""
  104. }
  105. c.JSON(http.StatusOK, dResp)
  106. return dResp.ID, responseBody, nil
  107. }
  108. // FetchTask fetch task status
  109. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  110. taskID, ok := body["task_id"].(string)
  111. if !ok {
  112. return nil, fmt.Errorf("invalid task_id")
  113. }
  114. uri := fmt.Sprintf("%s/v1/videos/%s", baseUrl, taskID)
  115. req, err := http.NewRequest(http.MethodGet, uri, nil)
  116. if err != nil {
  117. return nil, err
  118. }
  119. req.Header.Set("Authorization", "Bearer "+key)
  120. return service.GetHttpClient().Do(req)
  121. }
  122. func (a *TaskAdaptor) GetModelList() []string {
  123. return ModelList
  124. }
  125. func (a *TaskAdaptor) GetChannelName() string {
  126. return ChannelName
  127. }
  128. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  129. resTask := responseTask{}
  130. if err := json.Unmarshal(respBody, &resTask); err != nil {
  131. return nil, errors.Wrap(err, "unmarshal task result failed")
  132. }
  133. taskResult := relaycommon.TaskInfo{
  134. Code: 0,
  135. }
  136. switch resTask.Status {
  137. case "queued", "pending":
  138. taskResult.Status = model.TaskStatusQueued
  139. case "processing", "in_progress":
  140. taskResult.Status = model.TaskStatusInProgress
  141. case "completed":
  142. taskResult.Status = model.TaskStatusSuccess
  143. taskResult.Url = fmt.Sprintf("%s/v1/videos/%s/content", system_setting.ServerAddress, resTask.ID)
  144. case "failed", "cancelled":
  145. taskResult.Status = model.TaskStatusFailure
  146. if resTask.Error != nil {
  147. taskResult.Reason = resTask.Error.Message
  148. } else {
  149. taskResult.Reason = "task failed"
  150. }
  151. default:
  152. }
  153. if resTask.Progress > 0 && resTask.Progress < 100 {
  154. taskResult.Progress = fmt.Sprintf("%d%%", resTask.Progress)
  155. }
  156. return &taskResult, nil
  157. }
  158. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) (*relaycommon.OpenAIVideo, error) {
  159. openAIVideo := &relaycommon.OpenAIVideo{}
  160. err := json.Unmarshal(task.Data, openAIVideo)
  161. if err != nil {
  162. return nil, errors.Wrap(err, "unmarshal to OpenAIVideo failed")
  163. }
  164. return openAIVideo, nil
  165. }