adaptor.go 13 KB

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