adaptor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. token, err := vertexcore.AcquireAccessToken(*adc, "")
  107. if err != nil {
  108. return fmt.Errorf("failed to acquire access token: %w", err)
  109. }
  110. req.Header.Set("Authorization", "Bearer "+token)
  111. req.Header.Set("x-goog-user-project", adc.ProjectID)
  112. return nil
  113. }
  114. // BuildRequestBody converts request into Vertex specific format.
  115. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  116. v, ok := c.Get("task_request")
  117. if !ok {
  118. return nil, fmt.Errorf("request not found in context")
  119. }
  120. req := v.(relaycommon.TaskSubmitReq)
  121. body := requestPayload{
  122. Instances: []map[string]any{{"prompt": req.Prompt}},
  123. Parameters: map[string]any{},
  124. }
  125. if req.Metadata != nil {
  126. if v, ok := req.Metadata["storageUri"]; ok {
  127. body.Parameters["storageUri"] = v
  128. }
  129. if v, ok := req.Metadata["sampleCount"]; ok {
  130. body.Parameters["sampleCount"] = v
  131. }
  132. }
  133. if _, ok := body.Parameters["sampleCount"]; !ok {
  134. body.Parameters["sampleCount"] = 1
  135. }
  136. data, err := json.Marshal(body)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return bytes.NewReader(data), nil
  141. }
  142. // DoRequest delegates to common helper.
  143. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  144. return channel.DoTaskApiRequest(a, c, info, requestBody)
  145. }
  146. // DoResponse handles upstream response, returns taskID etc.
  147. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  148. responseBody, err := io.ReadAll(resp.Body)
  149. if err != nil {
  150. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  151. }
  152. _ = resp.Body.Close()
  153. var s submitResponse
  154. if err := json.Unmarshal(responseBody, &s); err != nil {
  155. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  156. }
  157. if strings.TrimSpace(s.Name) == "" {
  158. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  159. }
  160. localID := encodeLocalTaskID(s.Name)
  161. c.JSON(http.StatusOK, gin.H{"task_id": localID})
  162. return localID, responseBody, nil
  163. }
  164. func (a *TaskAdaptor) GetModelList() []string { return []string{"veo-3.0-generate-001"} }
  165. func (a *TaskAdaptor) GetChannelName() string { return "vertex" }
  166. // FetchTask fetch task status
  167. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  168. taskID, ok := body["task_id"].(string)
  169. if !ok {
  170. return nil, fmt.Errorf("invalid task_id")
  171. }
  172. upstreamName, err := decodeLocalTaskID(taskID)
  173. if err != nil {
  174. return nil, fmt.Errorf("decode task_id failed: %w", err)
  175. }
  176. region := extractRegionFromOperationName(upstreamName)
  177. if region == "" {
  178. region = "us-central1"
  179. }
  180. project := extractProjectFromOperationName(upstreamName)
  181. modelName := extractModelFromOperationName(upstreamName)
  182. if project == "" || modelName == "" {
  183. return nil, fmt.Errorf("cannot extract project/model from operation name")
  184. }
  185. var url string
  186. if region == "global" {
  187. url = fmt.Sprintf("https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/google/models/%s:fetchPredictOperation", project, modelName)
  188. } else {
  189. url = fmt.Sprintf("https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:fetchPredictOperation", region, project, region, modelName)
  190. }
  191. payload := map[string]string{"operationName": upstreamName}
  192. data, err := json.Marshal(payload)
  193. if err != nil {
  194. return nil, err
  195. }
  196. adc := &vertexcore.Credentials{}
  197. if err := json.Unmarshal([]byte(key), adc); err != nil {
  198. return nil, fmt.Errorf("failed to decode credentials: %w", err)
  199. }
  200. token, err := vertexcore.AcquireAccessToken(*adc, "")
  201. if err != nil {
  202. return nil, fmt.Errorf("failed to acquire access token: %w", err)
  203. }
  204. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
  205. if err != nil {
  206. return nil, err
  207. }
  208. req.Header.Set("Content-Type", "application/json")
  209. req.Header.Set("Accept", "application/json")
  210. req.Header.Set("Authorization", "Bearer "+token)
  211. req.Header.Set("x-goog-user-project", adc.ProjectID)
  212. return service.GetHttpClient().Do(req)
  213. }
  214. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  215. var op operationResponse
  216. if err := json.Unmarshal(respBody, &op); err != nil {
  217. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  218. }
  219. ti := &relaycommon.TaskInfo{}
  220. if op.Error.Message != "" {
  221. ti.Status = model.TaskStatusFailure
  222. ti.Reason = op.Error.Message
  223. ti.Progress = "100%"
  224. return ti, nil
  225. }
  226. if !op.Done {
  227. ti.Status = model.TaskStatusInProgress
  228. ti.Progress = "50%"
  229. return ti, nil
  230. }
  231. ti.Status = model.TaskStatusSuccess
  232. ti.Progress = "100%"
  233. if len(op.Response.Videos) > 0 {
  234. v0 := op.Response.Videos[0]
  235. if v0.BytesBase64Encoded != "" {
  236. mime := strings.TrimSpace(v0.MimeType)
  237. if mime == "" {
  238. enc := strings.TrimSpace(v0.Encoding)
  239. if enc == "" {
  240. enc = "mp4"
  241. }
  242. if strings.Contains(enc, "/") {
  243. mime = enc
  244. } else {
  245. mime = "video/" + enc
  246. }
  247. }
  248. ti.Url = "data:" + mime + ";base64," + v0.BytesBase64Encoded
  249. return ti, nil
  250. }
  251. }
  252. if op.Response.BytesBase64Encoded != "" {
  253. enc := strings.TrimSpace(op.Response.Encoding)
  254. if enc == "" {
  255. enc = "mp4"
  256. }
  257. mime := enc
  258. if !strings.Contains(enc, "/") {
  259. mime = "video/" + enc
  260. }
  261. ti.Url = "data:" + mime + ";base64," + op.Response.BytesBase64Encoded
  262. return ti, nil
  263. }
  264. if op.Response.Video != "" { // some variants use `video` as base64
  265. enc := strings.TrimSpace(op.Response.Encoding)
  266. if enc == "" {
  267. enc = "mp4"
  268. }
  269. mime := enc
  270. if !strings.Contains(enc, "/") {
  271. mime = "video/" + enc
  272. }
  273. ti.Url = "data:" + mime + ";base64," + op.Response.Video
  274. return ti, nil
  275. }
  276. return ti, nil
  277. }
  278. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  279. upstreamName, err := decodeLocalTaskID(task.TaskID)
  280. if err != nil {
  281. upstreamName = ""
  282. }
  283. modelName := extractModelFromOperationName(upstreamName)
  284. if strings.TrimSpace(modelName) == "" {
  285. modelName = "veo-3.0-generate-001"
  286. }
  287. v := dto.NewOpenAIVideo()
  288. v.ID = task.TaskID
  289. v.Model = modelName
  290. v.Status = task.Status.ToVideoStatus()
  291. v.SetProgressStr(task.Progress)
  292. v.CreatedAt = task.CreatedAt
  293. v.CompletedAt = task.UpdatedAt
  294. if strings.HasPrefix(task.FailReason, "data:") && len(task.FailReason) > 0 {
  295. v.SetMetadata("url", task.FailReason)
  296. }
  297. return common.Marshal(v)
  298. }
  299. // ============================
  300. // helpers
  301. // ============================
  302. func encodeLocalTaskID(name string) string {
  303. return base64.RawURLEncoding.EncodeToString([]byte(name))
  304. }
  305. func decodeLocalTaskID(local string) (string, error) {
  306. b, err := base64.RawURLEncoding.DecodeString(local)
  307. if err != nil {
  308. return "", err
  309. }
  310. return string(b), nil
  311. }
  312. var regionRe = regexp.MustCompile(`locations/([a-z0-9-]+)/`)
  313. func extractRegionFromOperationName(name string) string {
  314. m := regionRe.FindStringSubmatch(name)
  315. if len(m) == 2 {
  316. return m[1]
  317. }
  318. return ""
  319. }
  320. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  321. func extractModelFromOperationName(name string) string {
  322. m := modelRe.FindStringSubmatch(name)
  323. if len(m) == 2 {
  324. return m[1]
  325. }
  326. idx := strings.Index(name, "models/")
  327. if idx >= 0 {
  328. s := name[idx+len("models/"):]
  329. if p := strings.Index(s, "/operations/"); p > 0 {
  330. return s[:p]
  331. }
  332. }
  333. return ""
  334. }
  335. var projectRe = regexp.MustCompile(`projects/([^/]+)/locations/`)
  336. func extractProjectFromOperationName(name string) string {
  337. m := projectRe.FindStringSubmatch(name)
  338. if len(m) == 2 {
  339. return m[1]
  340. }
  341. return ""
  342. }