adaptor.go 7.8 KB

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