adaptor.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 predictLongRunning endpoint for Veo.
  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:predictLongRunning",
  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 Veo predictLongRunning 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. instance := VeoInstance{Prompt: req.Prompt}
  69. if img := ExtractMultipartImage(c, info); img != nil {
  70. instance.Image = img
  71. } else if len(req.Images) > 0 {
  72. if parsed := ParseImageInput(req.Images[0]); parsed != nil {
  73. instance.Image = parsed
  74. info.Action = constant.TaskActionGenerate
  75. }
  76. }
  77. params := &VeoParameters{}
  78. if err := taskcommon.UnmarshalMetadata(req.Metadata, params); err != nil {
  79. return nil, errors.Wrap(err, "unmarshal metadata failed")
  80. }
  81. if params.DurationSeconds == 0 && req.Duration > 0 {
  82. params.DurationSeconds = req.Duration
  83. }
  84. if params.Resolution == "" && req.Size != "" {
  85. params.Resolution = SizeToVeoResolution(req.Size)
  86. }
  87. if params.AspectRatio == "" && req.Size != "" {
  88. params.AspectRatio = SizeToVeoAspectRatio(req.Size)
  89. }
  90. params.Resolution = strings.ToLower(params.Resolution)
  91. params.SampleCount = 1
  92. body := VeoRequestPayload{
  93. Instances: []VeoInstance{instance},
  94. Parameters: params,
  95. }
  96. data, err := common.Marshal(body)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return bytes.NewReader(data), nil
  101. }
  102. // DoRequest delegates to common helper.
  103. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  104. return channel.DoTaskApiRequest(a, c, info, requestBody)
  105. }
  106. // DoResponse handles upstream response, returns taskID etc.
  107. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  108. responseBody, err := io.ReadAll(resp.Body)
  109. if err != nil {
  110. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  111. }
  112. _ = resp.Body.Close()
  113. var s submitResponse
  114. if err := common.Unmarshal(responseBody, &s); err != nil {
  115. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  116. }
  117. if strings.TrimSpace(s.Name) == "" {
  118. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  119. }
  120. taskID = taskcommon.EncodeLocalTaskID(s.Name)
  121. ov := dto.NewOpenAIVideo()
  122. ov.ID = info.PublicTaskID
  123. ov.TaskID = info.PublicTaskID
  124. ov.CreatedAt = time.Now().Unix()
  125. ov.Model = info.OriginModelName
  126. c.JSON(http.StatusOK, ov)
  127. return taskID, responseBody, nil
  128. }
  129. func (a *TaskAdaptor) GetModelList() []string {
  130. return []string{
  131. "veo-3.0-generate-001",
  132. "veo-3.0-fast-generate-001",
  133. "veo-3.1-generate-preview",
  134. "veo-3.1-fast-generate-preview",
  135. }
  136. }
  137. func (a *TaskAdaptor) GetChannelName() string {
  138. return "gemini"
  139. }
  140. // EstimateBilling returns OtherRatios based on durationSeconds and resolution.
  141. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
  142. v, ok := c.Get("task_request")
  143. if !ok {
  144. return nil
  145. }
  146. req, ok := v.(relaycommon.TaskSubmitReq)
  147. if !ok {
  148. return nil
  149. }
  150. seconds := ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
  151. resolution := ResolveVeoResolution(req.Metadata, req.Size)
  152. resRatio := VeoResolutionRatio(info.UpstreamModelName, resolution)
  153. return map[string]float64{
  154. "seconds": float64(seconds),
  155. "resolution": resRatio,
  156. }
  157. }
  158. // FetchTask polls task status via the Gemini operations GET endpoint.
  159. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  160. taskID, ok := body["task_id"].(string)
  161. if !ok {
  162. return nil, fmt.Errorf("invalid task_id")
  163. }
  164. upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
  165. if err != nil {
  166. return nil, fmt.Errorf("decode task_id failed: %w", err)
  167. }
  168. version := model_setting.GetGeminiVersionSetting("default")
  169. url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
  170. req, err := http.NewRequest(http.MethodGet, url, nil)
  171. if err != nil {
  172. return nil, err
  173. }
  174. req.Header.Set("Accept", "application/json")
  175. req.Header.Set("x-goog-api-key", key)
  176. client, err := service.GetHttpClientWithProxy(proxy)
  177. if err != nil {
  178. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  179. }
  180. return client.Do(req)
  181. }
  182. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  183. var op operationResponse
  184. if err := common.Unmarshal(respBody, &op); err != nil {
  185. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  186. }
  187. ti := &relaycommon.TaskInfo{}
  188. if op.Error.Message != "" {
  189. ti.Status = model.TaskStatusFailure
  190. ti.Reason = op.Error.Message
  191. ti.Progress = "100%"
  192. return ti, nil
  193. }
  194. if !op.Done {
  195. ti.Status = model.TaskStatusInProgress
  196. ti.Progress = "50%"
  197. return ti, nil
  198. }
  199. ti.Status = model.TaskStatusSuccess
  200. ti.Progress = "100%"
  201. ti.TaskID = taskcommon.EncodeLocalTaskID(op.Name)
  202. if len(op.Response.GenerateVideoResponse.GeneratedVideos) > 0 {
  203. if uri := op.Response.GenerateVideoResponse.GeneratedVideos[0].Video.URI; uri != "" {
  204. ti.RemoteUrl = uri
  205. }
  206. }
  207. return ti, nil
  208. }
  209. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  210. upstreamTaskID := task.GetUpstreamTaskID()
  211. upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
  212. if err != nil {
  213. upstreamName = ""
  214. }
  215. modelName := extractModelFromOperationName(upstreamName)
  216. if strings.TrimSpace(modelName) == "" {
  217. modelName = "veo-3.0-generate-001"
  218. }
  219. video := dto.NewOpenAIVideo()
  220. video.ID = task.TaskID
  221. video.Model = modelName
  222. video.Status = task.Status.ToVideoStatus()
  223. video.SetProgressStr(task.Progress)
  224. video.CreatedAt = task.CreatedAt
  225. if task.FinishTime > 0 {
  226. video.CompletedAt = task.FinishTime
  227. } else if task.UpdatedAt > 0 {
  228. video.CompletedAt = task.UpdatedAt
  229. }
  230. return common.Marshal(video)
  231. }
  232. // ============================
  233. // helpers
  234. // ============================
  235. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  236. func extractModelFromOperationName(name string) string {
  237. if name == "" {
  238. return ""
  239. }
  240. if m := modelRe.FindStringSubmatch(name); len(m) == 2 {
  241. return m[1]
  242. }
  243. if idx := strings.Index(name, "models/"); idx >= 0 {
  244. s := name[idx+len("models/"):]
  245. if p := strings.Index(s, "/operations/"); p > 0 {
  246. return s[:p]
  247. }
  248. }
  249. return ""
  250. }