adaptor.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // Request / Response structures
  24. // ============================
  25. // GeminiVideoGenerationConfig represents the video generation configuration
  26. // Based on: https://ai.google.dev/gemini-api/docs/video
  27. type GeminiVideoGenerationConfig struct {
  28. AspectRatio string `json:"aspectRatio,omitempty"` // "16:9" or "9:16"
  29. DurationSeconds float64 `json:"durationSeconds,omitempty"` // 4, 6, or 8 (as number)
  30. NegativePrompt string `json:"negativePrompt,omitempty"` // unwanted elements
  31. PersonGeneration string `json:"personGeneration,omitempty"` // "allow_all" for text-to-video, "allow_adult" for image-to-video
  32. Resolution string `json:"resolution,omitempty"` // video resolution
  33. }
  34. // GeminiVideoRequest represents a single video generation instance
  35. type GeminiVideoRequest struct {
  36. Prompt string `json:"prompt"`
  37. }
  38. // GeminiVideoPayload represents the complete video generation request payload
  39. type GeminiVideoPayload struct {
  40. Instances []GeminiVideoRequest `json:"instances"`
  41. Parameters GeminiVideoGenerationConfig `json:"parameters,omitempty"`
  42. }
  43. type submitResponse struct {
  44. Name string `json:"name"`
  45. }
  46. type operationVideo struct {
  47. MimeType string `json:"mimeType"`
  48. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  49. Encoding string `json:"encoding"`
  50. }
  51. type operationResponse struct {
  52. Name string `json:"name"`
  53. Done bool `json:"done"`
  54. Response struct {
  55. Type string `json:"@type"`
  56. RaiMediaFilteredCount int `json:"raiMediaFilteredCount"`
  57. Videos []operationVideo `json:"videos"`
  58. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  59. Encoding string `json:"encoding"`
  60. Video string `json:"video"`
  61. GenerateVideoResponse struct {
  62. GeneratedSamples []struct {
  63. Video struct {
  64. URI string `json:"uri"`
  65. } `json:"video"`
  66. } `json:"generatedSamples"`
  67. } `json:"generateVideoResponse"`
  68. } `json:"response"`
  69. Error struct {
  70. Message string `json:"message"`
  71. } `json:"error"`
  72. }
  73. // ============================
  74. // Adaptor implementation
  75. // ============================
  76. type TaskAdaptor struct {
  77. ChannelType int
  78. apiKey string
  79. baseURL string
  80. }
  81. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  82. a.ChannelType = info.ChannelType
  83. a.baseURL = info.ChannelBaseUrl
  84. a.apiKey = info.ApiKey
  85. }
  86. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  87. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  88. // Use the standard validation method for TaskSubmitReq
  89. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionTextGenerate)
  90. }
  91. // BuildRequestURL constructs the upstream URL.
  92. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  93. modelName := info.OriginModelName
  94. version := model_setting.GetGeminiVersionSetting(modelName)
  95. return fmt.Sprintf(
  96. "%s/%s/models/%s:predictLongRunning",
  97. a.baseURL,
  98. version,
  99. modelName,
  100. ), nil
  101. }
  102. // BuildRequestHeader sets required headers.
  103. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  104. req.Header.Set("Content-Type", "application/json")
  105. req.Header.Set("Accept", "application/json")
  106. req.Header.Set("x-goog-api-key", a.apiKey)
  107. return nil
  108. }
  109. // BuildRequestBody converts request into Gemini specific format.
  110. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  111. v, ok := c.Get("task_request")
  112. if !ok {
  113. return nil, fmt.Errorf("request not found in context")
  114. }
  115. req, ok := v.(relaycommon.TaskSubmitReq)
  116. if !ok {
  117. return nil, fmt.Errorf("unexpected task_request type")
  118. }
  119. // Create structured video generation request
  120. body := GeminiVideoPayload{
  121. Instances: []GeminiVideoRequest{
  122. {Prompt: req.Prompt},
  123. },
  124. Parameters: GeminiVideoGenerationConfig{},
  125. }
  126. metadata := req.Metadata
  127. if err := taskcommon.UnmarshalMetadata(metadata, &body.Parameters); err != nil {
  128. return nil, errors.Wrap(err, "unmarshal metadata failed")
  129. }
  130. data, err := common.Marshal(body)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return bytes.NewReader(data), nil
  135. }
  136. // DoRequest delegates to common helper.
  137. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  138. return channel.DoTaskApiRequest(a, c, info, requestBody)
  139. }
  140. // DoResponse handles upstream response, returns taskID etc.
  141. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  142. responseBody, err := io.ReadAll(resp.Body)
  143. if err != nil {
  144. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  145. }
  146. _ = resp.Body.Close()
  147. var s submitResponse
  148. if err := common.Unmarshal(responseBody, &s); err != nil {
  149. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  150. }
  151. if strings.TrimSpace(s.Name) == "" {
  152. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  153. }
  154. taskID = taskcommon.EncodeLocalTaskID(s.Name)
  155. ov := dto.NewOpenAIVideo()
  156. ov.ID = info.PublicTaskID
  157. ov.TaskID = info.PublicTaskID
  158. ov.CreatedAt = time.Now().Unix()
  159. ov.Model = info.OriginModelName
  160. c.JSON(http.StatusOK, ov)
  161. return taskID, responseBody, nil
  162. }
  163. func (a *TaskAdaptor) GetModelList() []string {
  164. return []string{"veo-3.0-generate-001", "veo-3.1-generate-preview", "veo-3.1-fast-generate-preview"}
  165. }
  166. func (a *TaskAdaptor) GetChannelName() string {
  167. return "gemini"
  168. }
  169. // FetchTask fetch task status
  170. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  171. taskID, ok := body["task_id"].(string)
  172. if !ok {
  173. return nil, fmt.Errorf("invalid task_id")
  174. }
  175. upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
  176. if err != nil {
  177. return nil, fmt.Errorf("decode task_id failed: %w", err)
  178. }
  179. // For Gemini API, we use GET request to the operations endpoint
  180. version := model_setting.GetGeminiVersionSetting("default")
  181. url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
  182. req, err := http.NewRequest(http.MethodGet, url, nil)
  183. if err != nil {
  184. return nil, err
  185. }
  186. req.Header.Set("Accept", "application/json")
  187. req.Header.Set("x-goog-api-key", key)
  188. client, err := service.GetHttpClientWithProxy(proxy)
  189. if err != nil {
  190. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  191. }
  192. return client.Do(req)
  193. }
  194. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  195. var op operationResponse
  196. if err := common.Unmarshal(respBody, &op); err != nil {
  197. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  198. }
  199. ti := &relaycommon.TaskInfo{}
  200. if op.Error.Message != "" {
  201. ti.Status = model.TaskStatusFailure
  202. ti.Reason = op.Error.Message
  203. ti.Progress = "100%"
  204. return ti, nil
  205. }
  206. if !op.Done {
  207. ti.Status = model.TaskStatusInProgress
  208. ti.Progress = "50%"
  209. return ti, nil
  210. }
  211. ti.Status = model.TaskStatusSuccess
  212. ti.Progress = "100%"
  213. ti.TaskID = taskcommon.EncodeLocalTaskID(op.Name)
  214. // Url intentionally left empty — the caller constructs the proxy URL using the public task ID
  215. // Extract URL from generateVideoResponse if available
  216. if len(op.Response.GenerateVideoResponse.GeneratedSamples) > 0 {
  217. if uri := op.Response.GenerateVideoResponse.GeneratedSamples[0].Video.URI; uri != "" {
  218. ti.RemoteUrl = uri
  219. }
  220. }
  221. return ti, nil
  222. }
  223. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  224. // Use GetUpstreamTaskID() to get the real upstream operation name for model extraction.
  225. // task.TaskID is now a public task_xxxx ID, no longer a base64-encoded upstream name.
  226. upstreamTaskID := task.GetUpstreamTaskID()
  227. upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
  228. if err != nil {
  229. upstreamName = ""
  230. }
  231. modelName := extractModelFromOperationName(upstreamName)
  232. if strings.TrimSpace(modelName) == "" {
  233. modelName = "veo-3.0-generate-001"
  234. }
  235. video := dto.NewOpenAIVideo()
  236. video.ID = task.TaskID
  237. video.Model = modelName
  238. video.Status = task.Status.ToVideoStatus()
  239. video.SetProgressStr(task.Progress)
  240. video.CreatedAt = task.CreatedAt
  241. if task.FinishTime > 0 {
  242. video.CompletedAt = task.FinishTime
  243. } else if task.UpdatedAt > 0 {
  244. video.CompletedAt = task.UpdatedAt
  245. }
  246. return common.Marshal(video)
  247. }
  248. // ============================
  249. // helpers
  250. // ============================
  251. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  252. func extractModelFromOperationName(name string) string {
  253. if name == "" {
  254. return ""
  255. }
  256. if m := modelRe.FindStringSubmatch(name); len(m) == 2 {
  257. return m[1]
  258. }
  259. if idx := strings.Index(name, "models/"); idx >= 0 {
  260. s := name[idx+len("models/"):]
  261. if p := strings.Index(s, "/operations/"); p > 0 {
  262. return s[:p]
  263. }
  264. }
  265. return ""
  266. }