adaptor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package vertex
  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/model"
  12. "github.com/gin-gonic/gin"
  13. "github.com/QuantumNous/new-api/constant"
  14. "github.com/QuantumNous/new-api/dto"
  15. "github.com/QuantumNous/new-api/relay/channel"
  16. geminitask "github.com/QuantumNous/new-api/relay/channel/task/gemini"
  17. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  18. vertexcore "github.com/QuantumNous/new-api/relay/channel/vertex"
  19. relaycommon "github.com/QuantumNous/new-api/relay/common"
  20. "github.com/QuantumNous/new-api/service"
  21. )
  22. // ============================
  23. // Request / Response structures
  24. // ============================
  25. type veoInstance struct {
  26. Prompt string `json:"prompt"`
  27. Image *geminitask.VeoImageInput `json:"image,omitempty"`
  28. // TODO: support referenceImages (style/asset references, up to 3 images)
  29. // TODO: support lastFrame (first+last frame interpolation, Veo 3.1)
  30. }
  31. type veoParameters struct {
  32. SampleCount int `json:"sampleCount"`
  33. DurationSeconds int `json:"durationSeconds,omitempty"`
  34. AspectRatio string `json:"aspectRatio,omitempty"`
  35. Resolution string `json:"resolution,omitempty"`
  36. NegativePrompt string `json:"negativePrompt,omitempty"`
  37. PersonGeneration string `json:"personGeneration,omitempty"`
  38. StorageUri string `json:"storageUri,omitempty"`
  39. CompressionQuality string `json:"compressionQuality,omitempty"`
  40. ResizeMode string `json:"resizeMode,omitempty"`
  41. Seed *int `json:"seed,omitempty"`
  42. GenerateAudio *bool `json:"generateAudio,omitempty"`
  43. }
  44. type requestPayload struct {
  45. Instances []veoInstance `json:"instances"`
  46. Parameters *veoParameters `json:"parameters,omitempty"`
  47. }
  48. type fetchOperationPayload struct {
  49. OperationName string `json:"operationName"`
  50. }
  51. type submitResponse struct {
  52. Name string `json:"name"`
  53. }
  54. type operationVideo struct {
  55. MimeType string `json:"mimeType"`
  56. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  57. Encoding string `json:"encoding"`
  58. }
  59. type operationResponse struct {
  60. Name string `json:"name"`
  61. Done bool `json:"done"`
  62. Response struct {
  63. Type string `json:"@type"`
  64. RaiMediaFilteredCount int `json:"raiMediaFilteredCount"`
  65. Videos []operationVideo `json:"videos"`
  66. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  67. Encoding string `json:"encoding"`
  68. Video string `json:"video"`
  69. } `json:"response"`
  70. Error struct {
  71. Message string `json:"message"`
  72. } `json:"error"`
  73. }
  74. // ============================
  75. // Adaptor implementation
  76. // ============================
  77. type TaskAdaptor struct {
  78. taskcommon.BaseBilling
  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. adc := &vertexcore.Credentials{}
  96. if err := common.Unmarshal([]byte(a.apiKey), adc); err != nil {
  97. return "", fmt.Errorf("failed to decode credentials: %w", err)
  98. }
  99. modelName := info.UpstreamModelName
  100. if modelName == "" {
  101. modelName = "veo-3.0-generate-001"
  102. }
  103. region := vertexcore.GetModelRegion(info.ApiVersion, modelName)
  104. if strings.TrimSpace(region) == "" {
  105. region = "global"
  106. }
  107. if region == "global" {
  108. return fmt.Sprintf(
  109. "https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/google/models/%s:predictLongRunning",
  110. adc.ProjectID,
  111. modelName,
  112. ), nil
  113. }
  114. return fmt.Sprintf(
  115. "https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:predictLongRunning",
  116. region,
  117. adc.ProjectID,
  118. region,
  119. modelName,
  120. ), nil
  121. }
  122. // BuildRequestHeader sets required headers.
  123. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  124. req.Header.Set("Content-Type", "application/json")
  125. req.Header.Set("Accept", "application/json")
  126. adc := &vertexcore.Credentials{}
  127. if err := common.Unmarshal([]byte(a.apiKey), adc); err != nil {
  128. return fmt.Errorf("failed to decode credentials: %w", err)
  129. }
  130. proxy := ""
  131. if info != nil {
  132. proxy = info.ChannelSetting.Proxy
  133. }
  134. token, err := vertexcore.AcquireAccessToken(*adc, proxy)
  135. if err != nil {
  136. return fmt.Errorf("failed to acquire access token: %w", err)
  137. }
  138. req.Header.Set("Authorization", "Bearer "+token)
  139. req.Header.Set("x-goog-user-project", adc.ProjectID)
  140. return nil
  141. }
  142. // EstimateBilling returns OtherRatios based on durationSeconds and resolution.
  143. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
  144. v, ok := c.Get("task_request")
  145. if !ok {
  146. return nil
  147. }
  148. req := v.(relaycommon.TaskSubmitReq)
  149. seconds := geminitask.ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
  150. resolution := geminitask.ResolveVeoResolution(req.Metadata, req.Size)
  151. resRatio := geminitask.VeoResolutionRatio(info.UpstreamModelName, resolution)
  152. return map[string]float64{
  153. "seconds": float64(seconds),
  154. "resolution": resRatio,
  155. }
  156. }
  157. // BuildRequestBody converts request into Vertex specific format.
  158. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  159. v, ok := c.Get("task_request")
  160. if !ok {
  161. return nil, fmt.Errorf("request not found in context")
  162. }
  163. req := v.(relaycommon.TaskSubmitReq)
  164. instance := veoInstance{Prompt: req.Prompt}
  165. if img := geminitask.ExtractMultipartImage(c, info); img != nil {
  166. instance.Image = img
  167. } else if len(req.Images) > 0 {
  168. if parsed := geminitask.ParseImageInput(req.Images[0]); parsed != nil {
  169. instance.Image = parsed
  170. info.Action = constant.TaskActionGenerate
  171. }
  172. }
  173. params := &veoParameters{}
  174. if err := taskcommon.UnmarshalMetadata(req.Metadata, params); err != nil {
  175. return nil, fmt.Errorf("unmarshal metadata failed: %w", err)
  176. }
  177. if params.DurationSeconds == 0 && req.Duration > 0 {
  178. params.DurationSeconds = req.Duration
  179. }
  180. if params.Resolution == "" && req.Size != "" {
  181. params.Resolution = geminitask.SizeToVeoResolution(req.Size)
  182. }
  183. if params.AspectRatio == "" && req.Size != "" {
  184. params.AspectRatio = geminitask.SizeToVeoAspectRatio(req.Size)
  185. }
  186. params.Resolution = strings.ToLower(params.Resolution)
  187. params.SampleCount = 1
  188. body := requestPayload{
  189. Instances: []veoInstance{instance},
  190. Parameters: params,
  191. }
  192. data, err := common.Marshal(body)
  193. if err != nil {
  194. return nil, err
  195. }
  196. return bytes.NewReader(data), nil
  197. }
  198. // DoRequest delegates to common helper.
  199. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  200. return channel.DoTaskApiRequest(a, c, info, requestBody)
  201. }
  202. // DoResponse handles upstream response, returns taskID etc.
  203. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  204. responseBody, err := io.ReadAll(resp.Body)
  205. if err != nil {
  206. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  207. }
  208. _ = resp.Body.Close()
  209. var s submitResponse
  210. if err := common.Unmarshal(responseBody, &s); err != nil {
  211. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  212. }
  213. if strings.TrimSpace(s.Name) == "" {
  214. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  215. }
  216. localID := taskcommon.EncodeLocalTaskID(s.Name)
  217. ov := dto.NewOpenAIVideo()
  218. ov.ID = info.PublicTaskID
  219. ov.TaskID = info.PublicTaskID
  220. ov.CreatedAt = time.Now().Unix()
  221. ov.Model = info.OriginModelName
  222. c.JSON(http.StatusOK, ov)
  223. return localID, responseBody, nil
  224. }
  225. func (a *TaskAdaptor) GetModelList() []string {
  226. return []string{
  227. "veo-3.0-generate-001",
  228. "veo-3.0-fast-generate-001",
  229. "veo-3.1-generate-preview",
  230. "veo-3.1-fast-generate-preview",
  231. }
  232. }
  233. func (a *TaskAdaptor) GetChannelName() string { return "vertex" }
  234. // FetchTask fetch task status
  235. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  236. taskID, ok := body["task_id"].(string)
  237. if !ok {
  238. return nil, fmt.Errorf("invalid task_id")
  239. }
  240. upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
  241. if err != nil {
  242. return nil, fmt.Errorf("decode task_id failed: %w", err)
  243. }
  244. region := extractRegionFromOperationName(upstreamName)
  245. if region == "" {
  246. region = "us-central1"
  247. }
  248. project := extractProjectFromOperationName(upstreamName)
  249. modelName := extractModelFromOperationName(upstreamName)
  250. if project == "" || modelName == "" {
  251. return nil, fmt.Errorf("cannot extract project/model from operation name")
  252. }
  253. var url string
  254. if region == "global" {
  255. url = fmt.Sprintf("https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/google/models/%s:fetchPredictOperation", project, modelName)
  256. } else {
  257. url = fmt.Sprintf("https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:fetchPredictOperation", region, project, region, modelName)
  258. }
  259. payload := fetchOperationPayload{OperationName: upstreamName}
  260. data, err := common.Marshal(payload)
  261. if err != nil {
  262. return nil, err
  263. }
  264. adc := &vertexcore.Credentials{}
  265. if err := common.Unmarshal([]byte(key), adc); err != nil {
  266. return nil, fmt.Errorf("failed to decode credentials: %w", err)
  267. }
  268. token, err := vertexcore.AcquireAccessToken(*adc, proxy)
  269. if err != nil {
  270. return nil, fmt.Errorf("failed to acquire access token: %w", err)
  271. }
  272. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
  273. if err != nil {
  274. return nil, err
  275. }
  276. req.Header.Set("Content-Type", "application/json")
  277. req.Header.Set("Accept", "application/json")
  278. req.Header.Set("Authorization", "Bearer "+token)
  279. req.Header.Set("x-goog-user-project", adc.ProjectID)
  280. client, err := service.GetHttpClientWithProxy(proxy)
  281. if err != nil {
  282. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  283. }
  284. return client.Do(req)
  285. }
  286. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  287. var op operationResponse
  288. if err := common.Unmarshal(respBody, &op); err != nil {
  289. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  290. }
  291. ti := &relaycommon.TaskInfo{}
  292. if op.Error.Message != "" {
  293. ti.Status = model.TaskStatusFailure
  294. ti.Reason = op.Error.Message
  295. ti.Progress = "100%"
  296. return ti, nil
  297. }
  298. if !op.Done {
  299. ti.Status = model.TaskStatusInProgress
  300. ti.Progress = "50%"
  301. return ti, nil
  302. }
  303. ti.Status = model.TaskStatusSuccess
  304. ti.Progress = "100%"
  305. if len(op.Response.Videos) > 0 {
  306. v0 := op.Response.Videos[0]
  307. if v0.BytesBase64Encoded != "" {
  308. mime := strings.TrimSpace(v0.MimeType)
  309. if mime == "" {
  310. enc := strings.TrimSpace(v0.Encoding)
  311. if enc == "" {
  312. enc = "mp4"
  313. }
  314. if strings.Contains(enc, "/") {
  315. mime = enc
  316. } else {
  317. mime = "video/" + enc
  318. }
  319. }
  320. ti.Url = "data:" + mime + ";base64," + v0.BytesBase64Encoded
  321. return ti, nil
  322. }
  323. }
  324. if op.Response.BytesBase64Encoded != "" {
  325. enc := strings.TrimSpace(op.Response.Encoding)
  326. if enc == "" {
  327. enc = "mp4"
  328. }
  329. mime := enc
  330. if !strings.Contains(enc, "/") {
  331. mime = "video/" + enc
  332. }
  333. ti.Url = "data:" + mime + ";base64," + op.Response.BytesBase64Encoded
  334. return ti, nil
  335. }
  336. if op.Response.Video != "" { // some variants use `video` as base64
  337. enc := strings.TrimSpace(op.Response.Encoding)
  338. if enc == "" {
  339. enc = "mp4"
  340. }
  341. mime := enc
  342. if !strings.Contains(enc, "/") {
  343. mime = "video/" + enc
  344. }
  345. ti.Url = "data:" + mime + ";base64," + op.Response.Video
  346. return ti, nil
  347. }
  348. return ti, nil
  349. }
  350. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  351. // Use GetUpstreamTaskID() to get the real upstream operation name for model extraction.
  352. // task.TaskID is now a public task_xxxx ID, no longer a base64-encoded upstream name.
  353. upstreamTaskID := task.GetUpstreamTaskID()
  354. upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
  355. if err != nil {
  356. upstreamName = ""
  357. }
  358. modelName := extractModelFromOperationName(upstreamName)
  359. if strings.TrimSpace(modelName) == "" {
  360. modelName = "veo-3.0-generate-001"
  361. }
  362. v := dto.NewOpenAIVideo()
  363. v.ID = task.TaskID
  364. v.Model = modelName
  365. v.Status = task.Status.ToVideoStatus()
  366. v.SetProgressStr(task.Progress)
  367. v.CreatedAt = task.CreatedAt
  368. v.CompletedAt = task.UpdatedAt
  369. if resultURL := task.GetResultURL(); strings.HasPrefix(resultURL, "data:") && len(resultURL) > 0 {
  370. v.SetMetadata("url", resultURL)
  371. }
  372. return common.Marshal(v)
  373. }
  374. // ============================
  375. // helpers
  376. // ============================
  377. var regionRe = regexp.MustCompile(`locations/([a-z0-9-]+)/`)
  378. func extractRegionFromOperationName(name string) string {
  379. m := regionRe.FindStringSubmatch(name)
  380. if len(m) == 2 {
  381. return m[1]
  382. }
  383. return ""
  384. }
  385. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  386. func extractModelFromOperationName(name string) string {
  387. m := modelRe.FindStringSubmatch(name)
  388. if len(m) == 2 {
  389. return m[1]
  390. }
  391. idx := strings.Index(name, "models/")
  392. if idx >= 0 {
  393. s := name[idx+len("models/"):]
  394. if p := strings.Index(s, "/operations/"); p > 0 {
  395. return s[:p]
  396. }
  397. }
  398. return ""
  399. }
  400. var projectRe = regexp.MustCompile(`projects/([^/]+)/locations/`)
  401. func extractProjectFromOperationName(name string) string {
  402. m := projectRe.FindStringSubmatch(name)
  403. if len(m) == 2 {
  404. return m[1]
  405. }
  406. return ""
  407. }