adaptor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. 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 根据用户请求中的 sampleCount 计算 OtherRatios。
  120. func (a *TaskAdaptor) EstimateBilling(c *gin.Context, _ *relaycommon.RelayInfo) map[string]float64 {
  121. sampleCount := 1
  122. v, ok := c.Get("task_request")
  123. if ok {
  124. req := v.(relaycommon.TaskSubmitReq)
  125. if req.Metadata != nil {
  126. if sc, exists := req.Metadata["sampleCount"]; exists {
  127. if i, ok := sc.(int); ok && i > 0 {
  128. sampleCount = i
  129. }
  130. if f, ok := sc.(float64); ok && int(f) > 0 {
  131. sampleCount = int(f)
  132. }
  133. }
  134. }
  135. }
  136. return map[string]float64{
  137. "sampleCount": float64(sampleCount),
  138. }
  139. }
  140. // BuildRequestBody converts request into Vertex specific format.
  141. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  142. v, ok := c.Get("task_request")
  143. if !ok {
  144. return nil, fmt.Errorf("request not found in context")
  145. }
  146. req := v.(relaycommon.TaskSubmitReq)
  147. body := requestPayload{
  148. Instances: []map[string]any{{"prompt": req.Prompt}},
  149. Parameters: map[string]any{},
  150. }
  151. if req.Metadata != nil {
  152. if v, ok := req.Metadata["storageUri"]; ok {
  153. body.Parameters["storageUri"] = v
  154. }
  155. if v, ok := req.Metadata["sampleCount"]; ok {
  156. if i, ok := v.(int); ok {
  157. body.Parameters["sampleCount"] = i
  158. }
  159. if f, ok := v.(float64); ok {
  160. body.Parameters["sampleCount"] = int(f)
  161. }
  162. }
  163. }
  164. if _, ok := body.Parameters["sampleCount"]; !ok {
  165. body.Parameters["sampleCount"] = 1
  166. }
  167. if body.Parameters["sampleCount"].(int) <= 0 {
  168. return nil, fmt.Errorf("sampleCount must be greater than 0")
  169. }
  170. data, err := common.Marshal(body)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return bytes.NewReader(data), nil
  175. }
  176. // DoRequest delegates to common helper.
  177. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  178. return channel.DoTaskApiRequest(a, c, info, requestBody)
  179. }
  180. // DoResponse handles upstream response, returns taskID etc.
  181. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  182. responseBody, err := io.ReadAll(resp.Body)
  183. if err != nil {
  184. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  185. }
  186. _ = resp.Body.Close()
  187. var s submitResponse
  188. if err := common.Unmarshal(responseBody, &s); err != nil {
  189. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  190. }
  191. if strings.TrimSpace(s.Name) == "" {
  192. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  193. }
  194. localID := taskcommon.EncodeLocalTaskID(s.Name)
  195. ov := dto.NewOpenAIVideo()
  196. ov.ID = info.PublicTaskID
  197. ov.TaskID = info.PublicTaskID
  198. ov.CreatedAt = time.Now().Unix()
  199. ov.Model = info.OriginModelName
  200. c.JSON(http.StatusOK, ov)
  201. return localID, responseBody, nil
  202. }
  203. func (a *TaskAdaptor) GetModelList() []string { return []string{"veo-3.0-generate-001"} }
  204. func (a *TaskAdaptor) GetChannelName() string { return "vertex" }
  205. // FetchTask fetch task status
  206. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  207. taskID, ok := body["task_id"].(string)
  208. if !ok {
  209. return nil, fmt.Errorf("invalid task_id")
  210. }
  211. upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
  212. if err != nil {
  213. return nil, fmt.Errorf("decode task_id failed: %w", err)
  214. }
  215. region := extractRegionFromOperationName(upstreamName)
  216. if region == "" {
  217. region = "us-central1"
  218. }
  219. project := extractProjectFromOperationName(upstreamName)
  220. modelName := extractModelFromOperationName(upstreamName)
  221. if project == "" || modelName == "" {
  222. return nil, fmt.Errorf("cannot extract project/model from operation name")
  223. }
  224. var url string
  225. if region == "global" {
  226. url = fmt.Sprintf("https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/google/models/%s:fetchPredictOperation", project, modelName)
  227. } else {
  228. url = fmt.Sprintf("https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:fetchPredictOperation", region, project, region, modelName)
  229. }
  230. payload := map[string]string{"operationName": upstreamName}
  231. data, err := common.Marshal(payload)
  232. if err != nil {
  233. return nil, err
  234. }
  235. adc := &vertexcore.Credentials{}
  236. if err := common.Unmarshal([]byte(key), adc); err != nil {
  237. return nil, fmt.Errorf("failed to decode credentials: %w", err)
  238. }
  239. token, err := vertexcore.AcquireAccessToken(*adc, proxy)
  240. if err != nil {
  241. return nil, fmt.Errorf("failed to acquire access token: %w", err)
  242. }
  243. req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
  244. if err != nil {
  245. return nil, err
  246. }
  247. req.Header.Set("Content-Type", "application/json")
  248. req.Header.Set("Accept", "application/json")
  249. req.Header.Set("Authorization", "Bearer "+token)
  250. req.Header.Set("x-goog-user-project", adc.ProjectID)
  251. client, err := service.GetHttpClientWithProxy(proxy)
  252. if err != nil {
  253. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  254. }
  255. return client.Do(req)
  256. }
  257. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  258. var op operationResponse
  259. if err := common.Unmarshal(respBody, &op); err != nil {
  260. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  261. }
  262. ti := &relaycommon.TaskInfo{}
  263. if op.Error.Message != "" {
  264. ti.Status = model.TaskStatusFailure
  265. ti.Reason = op.Error.Message
  266. ti.Progress = "100%"
  267. return ti, nil
  268. }
  269. if !op.Done {
  270. ti.Status = model.TaskStatusInProgress
  271. ti.Progress = "50%"
  272. return ti, nil
  273. }
  274. ti.Status = model.TaskStatusSuccess
  275. ti.Progress = "100%"
  276. if len(op.Response.Videos) > 0 {
  277. v0 := op.Response.Videos[0]
  278. if v0.BytesBase64Encoded != "" {
  279. mime := strings.TrimSpace(v0.MimeType)
  280. if mime == "" {
  281. enc := strings.TrimSpace(v0.Encoding)
  282. if enc == "" {
  283. enc = "mp4"
  284. }
  285. if strings.Contains(enc, "/") {
  286. mime = enc
  287. } else {
  288. mime = "video/" + enc
  289. }
  290. }
  291. ti.Url = "data:" + mime + ";base64," + v0.BytesBase64Encoded
  292. return ti, nil
  293. }
  294. }
  295. if op.Response.BytesBase64Encoded != "" {
  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.BytesBase64Encoded
  305. return ti, nil
  306. }
  307. if op.Response.Video != "" { // some variants use `video` as base64
  308. enc := strings.TrimSpace(op.Response.Encoding)
  309. if enc == "" {
  310. enc = "mp4"
  311. }
  312. mime := enc
  313. if !strings.Contains(enc, "/") {
  314. mime = "video/" + enc
  315. }
  316. ti.Url = "data:" + mime + ";base64," + op.Response.Video
  317. return ti, nil
  318. }
  319. return ti, nil
  320. }
  321. func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
  322. // Use GetUpstreamTaskID() to get the real upstream operation name for model extraction.
  323. // task.TaskID is now a public task_xxxx ID, no longer a base64-encoded upstream name.
  324. upstreamTaskID := task.GetUpstreamTaskID()
  325. upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
  326. if err != nil {
  327. upstreamName = ""
  328. }
  329. modelName := extractModelFromOperationName(upstreamName)
  330. if strings.TrimSpace(modelName) == "" {
  331. modelName = "veo-3.0-generate-001"
  332. }
  333. v := dto.NewOpenAIVideo()
  334. v.ID = task.TaskID
  335. v.Model = modelName
  336. v.Status = task.Status.ToVideoStatus()
  337. v.SetProgressStr(task.Progress)
  338. v.CreatedAt = task.CreatedAt
  339. v.CompletedAt = task.UpdatedAt
  340. if resultURL := task.GetResultURL(); strings.HasPrefix(resultURL, "data:") && len(resultURL) > 0 {
  341. v.SetMetadata("url", resultURL)
  342. }
  343. return common.Marshal(v)
  344. }
  345. // ============================
  346. // helpers
  347. // ============================
  348. var regionRe = regexp.MustCompile(`locations/([a-z0-9-]+)/`)
  349. func extractRegionFromOperationName(name string) string {
  350. m := regionRe.FindStringSubmatch(name)
  351. if len(m) == 2 {
  352. return m[1]
  353. }
  354. return ""
  355. }
  356. var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
  357. func extractModelFromOperationName(name string) string {
  358. m := modelRe.FindStringSubmatch(name)
  359. if len(m) == 2 {
  360. return m[1]
  361. }
  362. idx := strings.Index(name, "models/")
  363. if idx >= 0 {
  364. s := name[idx+len("models/"):]
  365. if p := strings.Index(s, "/operations/"); p > 0 {
  366. return s[:p]
  367. }
  368. }
  369. return ""
  370. }
  371. var projectRe = regexp.MustCompile(`projects/([^/]+)/locations/`)
  372. func extractProjectFromOperationName(name string) string {
  373. m := projectRe.FindStringSubmatch(name)
  374. if len(m) == 2 {
  375. return m[1]
  376. }
  377. return ""
  378. }