adaptor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package vertex
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "regexp"
  10. "strings"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/model"
  13. "github.com/gin-gonic/gin"
  14. "github.com/QuantumNous/new-api/constant"
  15. "github.com/QuantumNous/new-api/dto"
  16. "github.com/QuantumNous/new-api/relay/channel"
  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 := json.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 := json.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 := json.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 := json.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 := encodeLocalTaskID(s.Name)
  188. c.JSON(http.StatusOK, gin.H{"task_id": localID})
  189. return localID, responseBody, nil
  190. }
  191. func (a *TaskAdaptor) GetModelList() []string { return []string{"veo-3.0-generate-001"} }
  192. func (a *TaskAdaptor) GetChannelName() string { return "vertex" }
  193. // FetchTask fetch task status
  194. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  195. taskID, ok := body["task_id"].(string)
  196. if !ok {
  197. return nil, fmt.Errorf("invalid task_id")
  198. }
  199. upstreamName, err := decodeLocalTaskID(taskID)
  200. if err != nil {
  201. return nil, fmt.Errorf("decode task_id failed: %w", err)
  202. }
  203. region := extractRegionFromOperationName(upstreamName)
  204. if region == "" {
  205. region = "us-central1"
  206. }
  207. project := extractProjectFromOperationName(upstreamName)
  208. modelName := extractModelFromOperationName(upstreamName)
  209. if project == "" || modelName == "" {
  210. return nil, fmt.Errorf("cannot extract project/model from operation name")
  211. }
  212. var url string
  213. if region == "global" {
  214. url = fmt.Sprintf("https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/google/models/%s:fetchPredictOperation", project, modelName)
  215. } else {
  216. url = fmt.Sprintf("https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:fetchPredictOperation", region, project, region, modelName)
  217. }
  218. payload := map[string]string{"operationName": upstreamName}
  219. data, err := json.Marshal(payload)
  220. if err != nil {
  221. return nil, err
  222. }
  223. adc := &vertexcore.Credentials{}
  224. if err := json.Unmarshal([]byte(key), adc); err != nil {
  225. return nil, fmt.Errorf("failed to decode credentials: %w", err)
  226. }
  227. token, err := vertexcore.AcquireAccessToken(*adc, proxy)
  228. if err != nil {
  229. return nil, fmt.Errorf("failed to acquire access token: %w", err)
  230. }
  231. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
  232. if err != nil {
  233. return nil, err
  234. }
  235. req.Header.Set("Content-Type", "application/json")
  236. req.Header.Set("Accept", "application/json")
  237. req.Header.Set("Authorization", "Bearer "+token)
  238. req.Header.Set("x-goog-user-project", adc.ProjectID)
  239. client, err := service.GetHttpClientWithProxy(proxy)
  240. if err != nil {
  241. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  242. }
  243. return client.Do(req)
  244. }
  245. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  246. var op operationResponse
  247. if err := json.Unmarshal(respBody, &op); err != nil {
  248. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  249. }
  250. ti := &relaycommon.TaskInfo{}
  251. if op.Error.Message != "" {
  252. ti.Status = model.TaskStatusFailure
  253. ti.Reason = op.Error.Message
  254. ti.Progress = "100%"
  255. return ti, nil
  256. }
  257. if !op.Done {
  258. ti.Status = model.TaskStatusInProgress
  259. ti.Progress = "50%"
  260. return ti, nil
  261. }
  262. ti.Status = model.TaskStatusSuccess
  263. ti.Progress = "100%"
  264. if len(op.Response.Videos) > 0 {
  265. v0 := op.Response.Videos[0]
  266. if v0.BytesBase64Encoded != "" {
  267. mime := strings.TrimSpace(v0.MimeType)
  268. if mime == "" {
  269. enc := strings.TrimSpace(v0.Encoding)
  270. if enc == "" {
  271. enc = "mp4"
  272. }
  273. if strings.Contains(enc, "/") {
  274. mime = enc
  275. } else {
  276. mime = "video/" + enc
  277. }
  278. }
  279. ti.Url = "data:" + mime + ";base64," + v0.BytesBase64Encoded
  280. return ti, nil
  281. }
  282. }
  283. if op.Response.BytesBase64Encoded != "" {
  284. enc := strings.TrimSpace(op.Response.Encoding)
  285. if enc == "" {
  286. enc = "mp4"
  287. }
  288. mime := enc
  289. if !strings.Contains(enc, "/") {
  290. mime = "video/" + enc
  291. }
  292. ti.Url = "data:" + mime + ";base64," + op.Response.BytesBase64Encoded
  293. return ti, nil
  294. }
  295. if op.Response.Video != "" { // some variants use `video` as base64
  296. enc := strings.TrimSpace(op.Response.Encoding)
  297. if enc == "" {
  298. enc = "mp4"
  299. }
  300. mime := enc
  301. if !strings.Contains(enc, "/") {
  302. mime = "video/" + enc
  303. }
  304. ti.Url = "data:" + mime + ";base64," + op.Response.Video
  305. return ti, nil
  306. }
  307. return ti, nil
  308. }
  309. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  310. upstreamName, err := decodeLocalTaskID(task.TaskID)
  311. if err != nil {
  312. upstreamName = ""
  313. }
  314. modelName := extractModelFromOperationName(upstreamName)
  315. if strings.TrimSpace(modelName) == "" {
  316. modelName = "veo-3.0-generate-001"
  317. }
  318. v := dto.NewOpenAIVideo()
  319. v.ID = task.TaskID
  320. v.Model = modelName
  321. v.Status = task.Status.ToVideoStatus()
  322. v.SetProgressStr(task.Progress)
  323. v.CreatedAt = task.CreatedAt
  324. v.CompletedAt = task.UpdatedAt
  325. if strings.HasPrefix(task.FailReason, "data:") && len(task.FailReason) > 0 {
  326. v.SetMetadata("url", task.FailReason)
  327. }
  328. return common.Marshal(v)
  329. }
  330. // ============================
  331. // helpers
  332. // ============================
  333. func encodeLocalTaskID(name string) string {
  334. return base64.RawURLEncoding.EncodeToString([]byte(name))
  335. }
  336. func decodeLocalTaskID(local string) (string, error) {
  337. b, err := base64.RawURLEncoding.DecodeString(local)
  338. if err != nil {
  339. return "", err
  340. }
  341. return string(b), nil
  342. }
  343. var regionRe = regexp.MustCompile(`locations/([a-z0-9-]+)/`)
  344. func extractRegionFromOperationName(name string) string {
  345. m := regionRe.FindStringSubmatch(name)
  346. if len(m) == 2 {
  347. return m[1]
  348. }
  349. return ""
  350. }
  351. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  352. func extractModelFromOperationName(name string) string {
  353. m := modelRe.FindStringSubmatch(name)
  354. if len(m) == 2 {
  355. return m[1]
  356. }
  357. idx := strings.Index(name, "models/")
  358. if idx >= 0 {
  359. s := name[idx+len("models/"):]
  360. if p := strings.Index(s, "/operations/"); p > 0 {
  361. return s[:p]
  362. }
  363. }
  364. return ""
  365. }
  366. var projectRe = regexp.MustCompile(`projects/([^/]+)/locations/`)
  367. func extractProjectFromOperationName(name string) string {
  368. m := projectRe.FindStringSubmatch(name)
  369. if len(m) == 2 {
  370. return m[1]
  371. }
  372. return ""
  373. }