adaptor.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package gemini
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "regexp"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/relay/channel"
  15. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  16. relaycommon "github.com/QuantumNous/new-api/relay/common"
  17. "github.com/QuantumNous/new-api/service"
  18. "github.com/QuantumNous/new-api/setting/model_setting"
  19. "github.com/gin-gonic/gin"
  20. "github.com/pkg/errors"
  21. )
  22. // ============================
  23. // Adaptor implementation
  24. // ============================
  25. type TaskAdaptor struct {
  26. taskcommon.BaseBilling
  27. ChannelType int
  28. apiKey string
  29. baseURL string
  30. }
  31. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  32. a.ChannelType = info.ChannelType
  33. a.baseURL = info.ChannelBaseUrl
  34. a.apiKey = info.ApiKey
  35. }
  36. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  37. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  38. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionTextGenerate)
  39. }
  40. // BuildRequestURL constructs the Gemini API generateVideos endpoint.
  41. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  42. modelName := info.UpstreamModelName
  43. version := model_setting.GetGeminiVersionSetting(modelName)
  44. return fmt.Sprintf(
  45. "%s/%s/models/%s:generateVideos",
  46. a.baseURL,
  47. version,
  48. modelName,
  49. ), nil
  50. }
  51. // BuildRequestHeader sets required headers.
  52. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  53. req.Header.Set("Content-Type", "application/json")
  54. req.Header.Set("Accept", "application/json")
  55. req.Header.Set("x-goog-api-key", a.apiKey)
  56. return nil
  57. }
  58. // BuildRequestBody converts request into the Gemini API generateVideos format.
  59. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  60. v, ok := c.Get("task_request")
  61. if !ok {
  62. return nil, fmt.Errorf("request not found in context")
  63. }
  64. req, ok := v.(relaycommon.TaskSubmitReq)
  65. if !ok {
  66. return nil, fmt.Errorf("unexpected task_request type")
  67. }
  68. body := GeminiVideoPayload{
  69. Prompt: req.Prompt,
  70. Config: &GeminiVideoGenerationConfig{},
  71. }
  72. if img := ExtractMultipartImage(c, info); img != nil {
  73. body.Image = img
  74. } else if len(req.Images) > 0 {
  75. if parsed := ParseImageInput(req.Images[0]); parsed != nil {
  76. body.Image = parsed
  77. info.Action = constant.TaskActionGenerate
  78. }
  79. }
  80. if err := taskcommon.UnmarshalMetadata(req.Metadata, body.Config); err != nil {
  81. return nil, errors.Wrap(err, "unmarshal metadata failed")
  82. }
  83. if body.Config.DurationSeconds == 0 && req.Duration > 0 {
  84. body.Config.DurationSeconds = req.Duration
  85. }
  86. if body.Config.Resolution == "" && req.Size != "" {
  87. body.Config.Resolution = SizeToVeoResolution(req.Size)
  88. }
  89. if body.Config.AspectRatio == "" && req.Size != "" {
  90. body.Config.AspectRatio = SizeToVeoAspectRatio(req.Size)
  91. }
  92. body.Config.Resolution = strings.ToLower(body.Config.Resolution)
  93. body.Config.NumberOfVideos = 1
  94. data, err := common.Marshal(body)
  95. if err != nil {
  96. return nil, err
  97. }
  98. return bytes.NewReader(data), nil
  99. }
  100. // DoRequest delegates to common helper.
  101. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  102. return channel.DoTaskApiRequest(a, c, info, requestBody)
  103. }
  104. // DoResponse handles upstream response, returns taskID etc.
  105. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  106. responseBody, err := io.ReadAll(resp.Body)
  107. if err != nil {
  108. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  109. }
  110. _ = resp.Body.Close()
  111. var s submitResponse
  112. if err := common.Unmarshal(responseBody, &s); err != nil {
  113. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  114. }
  115. if strings.TrimSpace(s.Name) == "" {
  116. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  117. }
  118. taskID = taskcommon.EncodeLocalTaskID(s.Name)
  119. ov := dto.NewOpenAIVideo()
  120. ov.ID = info.PublicTaskID
  121. ov.TaskID = info.PublicTaskID
  122. ov.CreatedAt = time.Now().Unix()
  123. ov.Model = info.OriginModelName
  124. c.JSON(http.StatusOK, ov)
  125. return taskID, responseBody, nil
  126. }
  127. func (a *TaskAdaptor) GetModelList() []string {
  128. return []string{
  129. "veo-3.0-generate-001",
  130. "veo-3.0-fast-generate-001",
  131. "veo-3.1-generate-preview",
  132. "veo-3.1-fast-generate-preview",
  133. }
  134. }
  135. func (a *TaskAdaptor) GetChannelName() string {
  136. return "gemini"
  137. }
  138. // EstimateBilling returns OtherRatios based on durationSeconds and resolution.
  139. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
  140. v, ok := c.Get("task_request")
  141. if !ok {
  142. return nil
  143. }
  144. req, ok := v.(relaycommon.TaskSubmitReq)
  145. if !ok {
  146. return nil
  147. }
  148. seconds := ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
  149. resolution := ResolveVeoResolution(req.Metadata, req.Size)
  150. resRatio := VeoResolutionRatio(info.UpstreamModelName, resolution)
  151. return map[string]float64{
  152. "seconds": float64(seconds),
  153. "resolution": resRatio,
  154. }
  155. }
  156. // FetchTask polls task status via the Gemini operations GET endpoint.
  157. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  158. taskID, ok := body["task_id"].(string)
  159. if !ok {
  160. return nil, fmt.Errorf("invalid task_id")
  161. }
  162. upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
  163. if err != nil {
  164. return nil, fmt.Errorf("decode task_id failed: %w", err)
  165. }
  166. version := model_setting.GetGeminiVersionSetting("default")
  167. url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
  168. req, err := http.NewRequest(http.MethodGet, url, nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. req.Header.Set("Accept", "application/json")
  173. req.Header.Set("x-goog-api-key", key)
  174. client, err := service.GetHttpClientWithProxy(proxy)
  175. if err != nil {
  176. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  177. }
  178. return client.Do(req)
  179. }
  180. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  181. var op operationResponse
  182. if err := common.Unmarshal(respBody, &op); err != nil {
  183. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  184. }
  185. ti := &relaycommon.TaskInfo{}
  186. if op.Error.Message != "" {
  187. ti.Status = model.TaskStatusFailure
  188. ti.Reason = op.Error.Message
  189. ti.Progress = "100%"
  190. return ti, nil
  191. }
  192. if !op.Done {
  193. ti.Status = model.TaskStatusInProgress
  194. ti.Progress = "50%"
  195. return ti, nil
  196. }
  197. ti.Status = model.TaskStatusSuccess
  198. ti.Progress = "100%"
  199. ti.TaskID = taskcommon.EncodeLocalTaskID(op.Name)
  200. if len(op.Response.GenerateVideoResponse.GeneratedVideos) > 0 {
  201. if uri := op.Response.GenerateVideoResponse.GeneratedVideos[0].Video.URI; uri != "" {
  202. ti.RemoteUrl = uri
  203. }
  204. }
  205. return ti, nil
  206. }
  207. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  208. upstreamTaskID := task.GetUpstreamTaskID()
  209. upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
  210. if err != nil {
  211. upstreamName = ""
  212. }
  213. modelName := extractModelFromOperationName(upstreamName)
  214. if strings.TrimSpace(modelName) == "" {
  215. modelName = "veo-3.0-generate-001"
  216. }
  217. video := dto.NewOpenAIVideo()
  218. video.ID = task.TaskID
  219. video.Model = modelName
  220. video.Status = task.Status.ToVideoStatus()
  221. video.SetProgressStr(task.Progress)
  222. video.CreatedAt = task.CreatedAt
  223. if task.FinishTime > 0 {
  224. video.CompletedAt = task.FinishTime
  225. } else if task.UpdatedAt > 0 {
  226. video.CompletedAt = task.UpdatedAt
  227. }
  228. return common.Marshal(video)
  229. }
  230. // ============================
  231. // helpers
  232. // ============================
  233. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  234. func extractModelFromOperationName(name string) string {
  235. if name == "" {
  236. return ""
  237. }
  238. if m := modelRe.FindStringSubmatch(name); len(m) == 2 {
  239. return m[1]
  240. }
  241. if idx := strings.Index(name, "models/"); idx >= 0 {
  242. s := name[idx+len("models/"):]
  243. if p := strings.Index(s, "/operations/"); p > 0 {
  244. return s[:p]
  245. }
  246. }
  247. return ""
  248. }