adaptor.go 9.5 KB

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