adaptor.go 13 KB

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