adaptor.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package gemini
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/relay/channel"
  15. relaycommon "github.com/QuantumNous/new-api/relay/common"
  16. "github.com/QuantumNous/new-api/service"
  17. "github.com/QuantumNous/new-api/setting/model_setting"
  18. "github.com/gin-gonic/gin"
  19. )
  20. // ============================
  21. // Request / Response structures
  22. // ============================
  23. type requestPayload struct {
  24. Instances []map[string]any `json:"instances"`
  25. Parameters map[string]any `json:"parameters,omitempty"`
  26. }
  27. type submitResponse struct {
  28. Name string `json:"name"`
  29. }
  30. type operationVideo struct {
  31. MimeType string `json:"mimeType"`
  32. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  33. Encoding string `json:"encoding"`
  34. }
  35. type operationResponse struct {
  36. Name string `json:"name"`
  37. Done bool `json:"done"`
  38. Response struct {
  39. Type string `json:"@type"`
  40. RaiMediaFilteredCount int `json:"raiMediaFilteredCount"`
  41. Videos []operationVideo `json:"videos"`
  42. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  43. Encoding string `json:"encoding"`
  44. Video string `json:"video"`
  45. GenerateVideoResponse struct {
  46. GeneratedSamples []struct {
  47. Video struct {
  48. URI string `json:"uri"`
  49. } `json:"video"`
  50. } `json:"generatedSamples"`
  51. } `json:"generateVideoResponse"`
  52. } `json:"response"`
  53. Error struct {
  54. Message string `json:"message"`
  55. } `json:"error"`
  56. }
  57. // ============================
  58. // Adaptor implementation
  59. // ============================
  60. type TaskAdaptor struct {
  61. ChannelType int
  62. apiKey string
  63. baseURL string
  64. }
  65. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  66. a.ChannelType = info.ChannelType
  67. a.baseURL = info.ChannelBaseUrl
  68. a.apiKey = info.ApiKey
  69. }
  70. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  71. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  72. // Use the standard validation method for TaskSubmitReq
  73. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionTextGenerate)
  74. }
  75. // BuildRequestURL constructs the upstream URL.
  76. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  77. modelName := info.OriginModelName
  78. if modelName == "" {
  79. modelName = "veo-3.0-generate-001"
  80. }
  81. version := model_setting.GetGeminiVersionSetting(modelName)
  82. return fmt.Sprintf(
  83. "%s/%s/models/%s:predictLongRunning",
  84. a.baseURL,
  85. version,
  86. modelName,
  87. ), nil
  88. }
  89. // BuildRequestHeader sets required headers.
  90. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  91. req.Header.Set("Content-Type", "application/json")
  92. req.Header.Set("Accept", "application/json")
  93. req.Header.Set("x-goog-api-key", a.apiKey)
  94. return nil
  95. }
  96. // BuildRequestBody converts request into Gemini specific format.
  97. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  98. v, ok := c.Get("task_request")
  99. if !ok {
  100. return nil, fmt.Errorf("request not found in context")
  101. }
  102. req := v.(relaycommon.TaskSubmitReq)
  103. body := requestPayload{
  104. Instances: []map[string]any{{"prompt": req.Prompt}},
  105. Parameters: map[string]any{},
  106. }
  107. // Add Veo-specific parameters from metadata
  108. if req.Metadata != nil {
  109. if v, ok := req.Metadata["aspectRatio"]; ok {
  110. body.Parameters["aspectRatio"] = v
  111. } else {
  112. body.Parameters["aspectRatio"] = "16:9" // default
  113. }
  114. if v, ok := req.Metadata["negativePrompt"]; ok {
  115. body.Parameters["negativePrompt"] = v
  116. }
  117. if v, ok := req.Metadata["durationSeconds"]; ok {
  118. body.Parameters["durationSeconds"] = v
  119. } else {
  120. body.Parameters["durationSeconds"] = "8" // default
  121. }
  122. if v, ok := req.Metadata["resolution"]; ok {
  123. body.Parameters["resolution"] = v
  124. }
  125. if v, ok := req.Metadata["personGeneration"]; ok {
  126. body.Parameters["personGeneration"] = v
  127. } else {
  128. body.Parameters["personGeneration"] = "allow_adult" // default
  129. }
  130. }
  131. data, err := json.Marshal(body)
  132. if err != nil {
  133. return nil, err
  134. }
  135. return bytes.NewReader(data), nil
  136. }
  137. // DoRequest delegates to common helper.
  138. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  139. return channel.DoTaskApiRequest(a, c, info, requestBody)
  140. }
  141. // DoResponse handles upstream response, returns taskID etc.
  142. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  143. responseBody, err := io.ReadAll(resp.Body)
  144. if err != nil {
  145. return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  146. }
  147. _ = resp.Body.Close()
  148. var s submitResponse
  149. if err := json.Unmarshal(responseBody, &s); err != nil {
  150. return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  151. }
  152. if strings.TrimSpace(s.Name) == "" {
  153. return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
  154. }
  155. localID := encodeLocalTaskID(s.Name)
  156. c.JSON(http.StatusOK, gin.H{"task_id": localID})
  157. return localID, responseBody, nil
  158. }
  159. func (a *TaskAdaptor) GetModelList() []string {
  160. return []string{"veo-3.0-generate-001"}
  161. }
  162. func (a *TaskAdaptor) GetChannelName() string {
  163. return "gemini"
  164. }
  165. // FetchTask fetch task status
  166. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) {
  167. taskID, ok := body["task_id"].(string)
  168. if !ok {
  169. return nil, fmt.Errorf("invalid task_id")
  170. }
  171. upstreamName, err := decodeLocalTaskID(taskID)
  172. if err != nil {
  173. return nil, fmt.Errorf("decode task_id failed: %w", err)
  174. }
  175. // For Gemini API, we use GET request to the operations endpoint
  176. version := model_setting.GetGeminiVersionSetting("veo-3.0-generate-001")
  177. url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
  178. req, err := http.NewRequest(http.MethodGet, url, nil)
  179. if err != nil {
  180. return nil, err
  181. }
  182. req.Header.Set("Accept", "application/json")
  183. req.Header.Set("x-goog-api-key", key)
  184. return service.GetHttpClient().Do(req)
  185. }
  186. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  187. var op operationResponse
  188. if err := json.Unmarshal(respBody, &op); err != nil {
  189. return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
  190. }
  191. ti := &relaycommon.TaskInfo{}
  192. if op.Error.Message != "" {
  193. ti.Status = model.TaskStatusFailure
  194. ti.Reason = op.Error.Message
  195. ti.Progress = "100%"
  196. return ti, nil
  197. }
  198. if !op.Done {
  199. ti.Status = model.TaskStatusInProgress
  200. ti.Progress = "50%"
  201. return ti, nil
  202. }
  203. ti.Status = model.TaskStatusSuccess
  204. ti.Progress = "100%"
  205. // Extract URL from generateVideoResponse if available
  206. if len(op.Response.GenerateVideoResponse.GeneratedSamples) > 0 {
  207. if uri := op.Response.GenerateVideoResponse.GeneratedSamples[0].Video.URI; uri != "" {
  208. ti.Url = uri
  209. }
  210. }
  211. return ti, nil
  212. }
  213. // ============================
  214. // helpers
  215. // ============================
  216. func encodeLocalTaskID(name string) string {
  217. // Add timestamp to ensure uniqueness
  218. timestamp := time.Now().Unix()
  219. data := fmt.Sprintf("%s:%d", name, timestamp)
  220. return base64.RawURLEncoding.EncodeToString([]byte(data))
  221. }
  222. func decodeLocalTaskID(local string) (string, error) {
  223. b, err := base64.RawURLEncoding.DecodeString(local)
  224. if err != nil {
  225. return "", err
  226. }
  227. // Extract the operation name from encoded data (remove timestamp if present)
  228. parts := strings.Split(string(b), ":")
  229. if len(parts) > 0 {
  230. return parts[0], nil
  231. }
  232. return string(b), nil
  233. }