adaptor.go 12 KB

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