adaptor.go 9.5 KB

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