adaptor.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package gemini
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/constant"
  10. "one-api/dto"
  11. "one-api/relay/channel"
  12. relaycommon "one-api/relay/common"
  13. "one-api/service"
  14. "strings"
  15. "github.com/gin-gonic/gin"
  16. )
  17. type Adaptor struct {
  18. }
  19. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  20. //TODO implement me
  21. return nil, errors.New("not implemented")
  22. }
  23. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  24. if !strings.HasPrefix(info.UpstreamModelName, "imagen") {
  25. return nil, errors.New("not supported model for image generation")
  26. }
  27. // convert size to aspect ratio
  28. aspectRatio := "1:1" // default aspect ratio
  29. switch request.Size {
  30. case "1024x1024":
  31. aspectRatio = "1:1"
  32. case "1024x1792":
  33. aspectRatio = "9:16"
  34. case "1792x1024":
  35. aspectRatio = "16:9"
  36. }
  37. // build gemini imagen request
  38. geminiRequest := GeminiImageRequest{
  39. Instances: []GeminiImageInstance{
  40. {
  41. Prompt: request.Prompt,
  42. },
  43. },
  44. Parameters: GeminiImageParameters{
  45. SampleCount: request.N,
  46. AspectRatio: aspectRatio,
  47. PersonGeneration: "allow_adult", // default allow adult
  48. },
  49. }
  50. return geminiRequest, nil
  51. }
  52. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  53. }
  54. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  55. // 从映射中获取模型名称对应的版本,如果找不到就使用 info.ApiVersion 或默认的版本 "v1beta"
  56. version, beta := constant.GeminiModelMap[info.UpstreamModelName]
  57. if !beta {
  58. if info.ApiVersion != "" {
  59. version = info.ApiVersion
  60. } else {
  61. version = "v1beta"
  62. }
  63. }
  64. if strings.HasPrefix(info.UpstreamModelName, "imagen") {
  65. return fmt.Sprintf("%s/%s/models/%s:predict", info.BaseUrl, version, info.UpstreamModelName), nil
  66. }
  67. action := "generateContent"
  68. if info.IsStream {
  69. action = "streamGenerateContent?alt=sse"
  70. }
  71. return fmt.Sprintf("%s/%s/models/%s:%s", info.BaseUrl, version, info.UpstreamModelName, action), nil
  72. }
  73. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  74. channel.SetupApiRequestHeader(info, c, req)
  75. req.Set("x-goog-api-key", info.ApiKey)
  76. return nil
  77. }
  78. func (a *Adaptor) ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  79. if request == nil {
  80. return nil, errors.New("request is nil")
  81. }
  82. ai, err := CovertGemini2OpenAI(*request)
  83. if err != nil {
  84. return nil, err
  85. }
  86. return ai, nil
  87. }
  88. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  89. return nil, nil
  90. }
  91. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  92. //TODO implement me
  93. return nil, errors.New("not implemented")
  94. }
  95. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  96. return channel.DoApiRequest(a, c, info, requestBody)
  97. }
  98. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  99. if strings.HasPrefix(info.UpstreamModelName, "imagen") {
  100. return GeminiImageHandler(c, resp, info)
  101. }
  102. if info.IsStream {
  103. err, usage = GeminiChatStreamHandler(c, resp, info)
  104. } else {
  105. err, usage = GeminiChatHandler(c, resp, info)
  106. }
  107. return
  108. }
  109. func GeminiImageHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  110. responseBody, readErr := io.ReadAll(resp.Body)
  111. if readErr != nil {
  112. return nil, service.OpenAIErrorWrapper(readErr, "read_response_body_failed", http.StatusInternalServerError)
  113. }
  114. _ = resp.Body.Close()
  115. var geminiResponse GeminiImageResponse
  116. if jsonErr := json.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  117. return nil, service.OpenAIErrorWrapper(jsonErr, "unmarshal_response_body_failed", http.StatusInternalServerError)
  118. }
  119. if len(geminiResponse.Predictions) == 0 {
  120. return nil, service.OpenAIErrorWrapper(errors.New("no images generated"), "no_images", http.StatusBadRequest)
  121. }
  122. // convert to openai format response
  123. openAIResponse := dto.ImageResponse{
  124. Created: common.GetTimestamp(),
  125. Data: make([]dto.ImageData, 0, len(geminiResponse.Predictions)),
  126. }
  127. for _, prediction := range geminiResponse.Predictions {
  128. if prediction.RaiFilteredReason != "" {
  129. continue // skip filtered image
  130. }
  131. openAIResponse.Data = append(openAIResponse.Data, dto.ImageData{
  132. B64Json: prediction.BytesBase64Encoded,
  133. })
  134. }
  135. jsonResponse, jsonErr := json.Marshal(openAIResponse)
  136. if jsonErr != nil {
  137. return nil, service.OpenAIErrorWrapper(jsonErr, "marshal_response_failed", http.StatusInternalServerError)
  138. }
  139. c.Writer.Header().Set("Content-Type", "application/json")
  140. c.Writer.WriteHeader(resp.StatusCode)
  141. _, _ = c.Writer.Write(jsonResponse)
  142. // https://github.com/google-gemini/cookbook/blob/719a27d752aac33f39de18a8d3cb42a70874917e/quickstarts/Counting_Tokens.ipynb
  143. // each image has fixed 258 tokens
  144. const imageTokens = 258
  145. generatedImages := len(openAIResponse.Data)
  146. usage = &dto.Usage{
  147. PromptTokens: imageTokens * generatedImages, // each generated image has fixed 258 tokens
  148. CompletionTokens: 0, // image generation does not calculate completion tokens
  149. TotalTokens: imageTokens * generatedImages,
  150. }
  151. return usage, nil
  152. }
  153. func (a *Adaptor) GetModelList() []string {
  154. return ModelList
  155. }
  156. func (a *Adaptor) GetChannelName() string {
  157. return ChannelName
  158. }