gemini.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. package dto
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "github.com/QuantumNous/new-api/common"
  6. "github.com/QuantumNous/new-api/logger"
  7. "github.com/QuantumNous/new-api/types"
  8. "github.com/gin-gonic/gin"
  9. )
  10. type GeminiChatRequest struct {
  11. Requests []GeminiChatRequest `json:"requests,omitempty"` // For batch requests
  12. Contents []GeminiChatContent `json:"contents"`
  13. SafetySettings []GeminiChatSafetySettings `json:"safetySettings,omitempty"`
  14. GenerationConfig GeminiChatGenerationConfig `json:"generationConfig,omitempty"`
  15. Tools json.RawMessage `json:"tools,omitempty"`
  16. ToolConfig *ToolConfig `json:"toolConfig,omitempty"`
  17. SystemInstructions *GeminiChatContent `json:"systemInstruction,omitempty"`
  18. CachedContent string `json:"cachedContent,omitempty"`
  19. }
  20. // UnmarshalJSON allows GeminiChatRequest to accept both snake_case and camelCase fields.
  21. func (r *GeminiChatRequest) UnmarshalJSON(data []byte) error {
  22. type Alias GeminiChatRequest
  23. var aux struct {
  24. Alias
  25. SystemInstructionSnake *GeminiChatContent `json:"system_instruction,omitempty"`
  26. }
  27. if err := common.Unmarshal(data, &aux); err != nil {
  28. return err
  29. }
  30. *r = GeminiChatRequest(aux.Alias)
  31. if aux.SystemInstructionSnake != nil {
  32. r.SystemInstructions = aux.SystemInstructionSnake
  33. }
  34. return nil
  35. }
  36. type ToolConfig struct {
  37. FunctionCallingConfig *FunctionCallingConfig `json:"functionCallingConfig,omitempty"`
  38. RetrievalConfig *RetrievalConfig `json:"retrievalConfig,omitempty"`
  39. }
  40. type FunctionCallingConfig struct {
  41. Mode FunctionCallingConfigMode `json:"mode,omitempty"`
  42. AllowedFunctionNames []string `json:"allowedFunctionNames,omitempty"`
  43. }
  44. type FunctionCallingConfigMode string
  45. type RetrievalConfig struct {
  46. LatLng *LatLng `json:"latLng,omitempty"`
  47. LanguageCode string `json:"languageCode,omitempty"`
  48. }
  49. type LatLng struct {
  50. Latitude *float64 `json:"latitude,omitempty"`
  51. Longitude *float64 `json:"longitude,omitempty"`
  52. }
  53. // createGeminiFileSource 根据数据内容创建正确类型的 FileSource
  54. func createGeminiFileSource(data string, mimeType string) *types.FileSource {
  55. if strings.HasPrefix(data, "http://") || strings.HasPrefix(data, "https://") {
  56. return types.NewURLFileSource(data)
  57. }
  58. return types.NewBase64FileSource(data, mimeType)
  59. }
  60. func (r *GeminiChatRequest) GetTokenCountMeta() *types.TokenCountMeta {
  61. var files []*types.FileMeta = make([]*types.FileMeta, 0)
  62. var maxTokens int
  63. if r.GenerationConfig.MaxOutputTokens > 0 {
  64. maxTokens = int(r.GenerationConfig.MaxOutputTokens)
  65. }
  66. var inputTexts []string
  67. for _, content := range r.Contents {
  68. for _, part := range content.Parts {
  69. if part.Text != "" {
  70. inputTexts = append(inputTexts, part.Text)
  71. }
  72. if part.InlineData != nil && part.InlineData.Data != "" {
  73. mimeType := part.InlineData.MimeType
  74. source := createGeminiFileSource(part.InlineData.Data, mimeType)
  75. var fileType types.FileType
  76. if strings.HasPrefix(mimeType, "image/") {
  77. fileType = types.FileTypeImage
  78. } else if strings.HasPrefix(mimeType, "audio/") {
  79. fileType = types.FileTypeAudio
  80. } else if strings.HasPrefix(mimeType, "video/") {
  81. fileType = types.FileTypeVideo
  82. } else {
  83. fileType = types.FileTypeFile
  84. }
  85. files = append(files, &types.FileMeta{
  86. FileType: fileType,
  87. Source: source,
  88. MimeType: mimeType,
  89. })
  90. }
  91. }
  92. }
  93. inputText := strings.Join(inputTexts, "\n")
  94. return &types.TokenCountMeta{
  95. CombineText: inputText,
  96. Files: files,
  97. MaxTokens: maxTokens,
  98. }
  99. }
  100. func (r *GeminiChatRequest) IsStream(c *gin.Context) bool {
  101. if c.Query("alt") == "sse" {
  102. return true
  103. }
  104. return false
  105. }
  106. func (r *GeminiChatRequest) SetModelName(modelName string) {
  107. // GeminiChatRequest does not have a model field, so this method does nothing.
  108. }
  109. func (r *GeminiChatRequest) GetTools() []GeminiChatTool {
  110. var tools []GeminiChatTool
  111. if strings.HasPrefix(string(r.Tools), "[") {
  112. // is array
  113. if err := common.Unmarshal(r.Tools, &tools); err != nil {
  114. logger.LogError(nil, "error_unmarshalling_tools: "+err.Error())
  115. return nil
  116. }
  117. } else if strings.HasPrefix(string(r.Tools), "{") {
  118. // is object
  119. singleTool := GeminiChatTool{}
  120. if err := common.Unmarshal(r.Tools, &singleTool); err != nil {
  121. logger.LogError(nil, "error_unmarshalling_single_tool: "+err.Error())
  122. return nil
  123. }
  124. tools = []GeminiChatTool{singleTool}
  125. }
  126. return tools
  127. }
  128. func (r *GeminiChatRequest) SetTools(tools []GeminiChatTool) {
  129. if len(tools) == 0 {
  130. r.Tools = json.RawMessage("[]")
  131. return
  132. }
  133. // Marshal the tools to JSON
  134. data, err := common.Marshal(tools)
  135. if err != nil {
  136. logger.LogError(nil, "error_marshalling_tools: "+err.Error())
  137. return
  138. }
  139. r.Tools = data
  140. }
  141. type GeminiThinkingConfig struct {
  142. IncludeThoughts bool `json:"includeThoughts,omitempty"`
  143. ThinkingBudget *int `json:"thinkingBudget,omitempty"`
  144. // TODO Conflict with thinkingbudget.
  145. ThinkingLevel string `json:"thinkingLevel,omitempty"`
  146. }
  147. // UnmarshalJSON allows GeminiThinkingConfig to accept both snake_case and camelCase fields.
  148. func (c *GeminiThinkingConfig) UnmarshalJSON(data []byte) error {
  149. type Alias GeminiThinkingConfig
  150. var aux struct {
  151. Alias
  152. IncludeThoughtsSnake *bool `json:"include_thoughts,omitempty"`
  153. ThinkingBudgetSnake *int `json:"thinking_budget,omitempty"`
  154. ThinkingLevelSnake string `json:"thinking_level,omitempty"`
  155. }
  156. if err := common.Unmarshal(data, &aux); err != nil {
  157. return err
  158. }
  159. *c = GeminiThinkingConfig(aux.Alias)
  160. if aux.IncludeThoughtsSnake != nil {
  161. c.IncludeThoughts = *aux.IncludeThoughtsSnake
  162. }
  163. if aux.ThinkingBudgetSnake != nil {
  164. c.ThinkingBudget = aux.ThinkingBudgetSnake
  165. }
  166. if aux.ThinkingLevelSnake != "" {
  167. c.ThinkingLevel = aux.ThinkingLevelSnake
  168. }
  169. return nil
  170. }
  171. func (c *GeminiThinkingConfig) SetThinkingBudget(budget int) {
  172. c.ThinkingBudget = &budget
  173. }
  174. type GeminiInlineData struct {
  175. MimeType string `json:"mimeType"`
  176. Data string `json:"data"`
  177. }
  178. // UnmarshalJSON custom unmarshaler for GeminiInlineData to support snake_case and camelCase for MimeType
  179. func (g *GeminiInlineData) UnmarshalJSON(data []byte) error {
  180. type Alias GeminiInlineData // Use type alias to avoid recursion
  181. var aux struct {
  182. Alias
  183. MimeTypeSnake string `json:"mime_type"`
  184. }
  185. if err := common.Unmarshal(data, &aux); err != nil {
  186. return err
  187. }
  188. *g = GeminiInlineData(aux.Alias) // Copy other fields if any in future
  189. // Prioritize snake_case if present
  190. if aux.MimeTypeSnake != "" {
  191. g.MimeType = aux.MimeTypeSnake
  192. } else if aux.MimeType != "" { // Fallback to camelCase from Alias
  193. g.MimeType = aux.MimeType
  194. }
  195. // g.Data would be populated by aux.Alias.Data
  196. return nil
  197. }
  198. type FunctionCall struct {
  199. FunctionName string `json:"name"`
  200. Arguments any `json:"args"`
  201. }
  202. type GeminiFunctionResponse struct {
  203. Name string `json:"name"`
  204. Response map[string]interface{} `json:"response"`
  205. WillContinue json.RawMessage `json:"willContinue,omitempty"`
  206. Scheduling json.RawMessage `json:"scheduling,omitempty"`
  207. Parts json.RawMessage `json:"parts,omitempty"`
  208. ID json.RawMessage `json:"id,omitempty"`
  209. }
  210. type GeminiPartExecutableCode struct {
  211. Language string `json:"language,omitempty"`
  212. Code string `json:"code,omitempty"`
  213. }
  214. type GeminiPartCodeExecutionResult struct {
  215. Outcome string `json:"outcome,omitempty"`
  216. Output string `json:"output,omitempty"`
  217. }
  218. type GeminiFileData struct {
  219. MimeType string `json:"mimeType,omitempty"`
  220. FileUri string `json:"fileUri,omitempty"`
  221. }
  222. type GeminiPart struct {
  223. Text string `json:"text,omitempty"`
  224. Thought bool `json:"thought,omitempty"`
  225. InlineData *GeminiInlineData `json:"inlineData,omitempty"`
  226. FunctionCall *FunctionCall `json:"functionCall,omitempty"`
  227. ThoughtSignature json.RawMessage `json:"thoughtSignature,omitempty"`
  228. FunctionResponse *GeminiFunctionResponse `json:"functionResponse,omitempty"`
  229. // Optional. Media resolution for the input media.
  230. MediaResolution json.RawMessage `json:"mediaResolution,omitempty"`
  231. VideoMetadata json.RawMessage `json:"videoMetadata,omitempty"`
  232. FileData *GeminiFileData `json:"fileData,omitempty"`
  233. ExecutableCode *GeminiPartExecutableCode `json:"executableCode,omitempty"`
  234. CodeExecutionResult *GeminiPartCodeExecutionResult `json:"codeExecutionResult,omitempty"`
  235. }
  236. // UnmarshalJSON custom unmarshaler for GeminiPart to support snake_case and camelCase for InlineData
  237. func (p *GeminiPart) UnmarshalJSON(data []byte) error {
  238. // Alias to avoid recursion during unmarshalling
  239. type Alias GeminiPart
  240. var aux struct {
  241. Alias
  242. InlineDataSnake *GeminiInlineData `json:"inline_data,omitempty"` // snake_case variant
  243. }
  244. if err := common.Unmarshal(data, &aux); err != nil {
  245. return err
  246. }
  247. // Assign fields from alias
  248. *p = GeminiPart(aux.Alias)
  249. // Prioritize snake_case for InlineData if present
  250. if aux.InlineDataSnake != nil {
  251. p.InlineData = aux.InlineDataSnake
  252. } else if aux.InlineData != nil { // Fallback to camelCase from Alias
  253. p.InlineData = aux.InlineData
  254. }
  255. // Other fields like Text, FunctionCall etc. are already populated via aux.Alias
  256. return nil
  257. }
  258. type GeminiChatContent struct {
  259. Role string `json:"role,omitempty"`
  260. Parts []GeminiPart `json:"parts"`
  261. }
  262. type GeminiChatSafetySettings struct {
  263. Category string `json:"category"`
  264. Threshold string `json:"threshold"`
  265. }
  266. type GeminiChatTool struct {
  267. GoogleSearch any `json:"googleSearch,omitempty"`
  268. GoogleSearchRetrieval any `json:"googleSearchRetrieval,omitempty"`
  269. CodeExecution any `json:"codeExecution,omitempty"`
  270. FunctionDeclarations any `json:"functionDeclarations,omitempty"`
  271. URLContext any `json:"urlContext,omitempty"`
  272. }
  273. type GeminiChatGenerationConfig struct {
  274. Temperature *float64 `json:"temperature,omitempty"`
  275. TopP float64 `json:"topP,omitempty"`
  276. TopK float64 `json:"topK,omitempty"`
  277. MaxOutputTokens uint `json:"maxOutputTokens,omitempty"`
  278. CandidateCount int `json:"candidateCount,omitempty"`
  279. StopSequences []string `json:"stopSequences,omitempty"`
  280. ResponseMimeType string `json:"responseMimeType,omitempty"`
  281. ResponseSchema any `json:"responseSchema,omitempty"`
  282. ResponseJsonSchema json.RawMessage `json:"responseJsonSchema,omitempty"`
  283. PresencePenalty *float32 `json:"presencePenalty,omitempty"`
  284. FrequencyPenalty *float32 `json:"frequencyPenalty,omitempty"`
  285. ResponseLogprobs bool `json:"responseLogprobs,omitempty"`
  286. Logprobs *int32 `json:"logprobs,omitempty"`
  287. MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
  288. Seed int64 `json:"seed,omitempty"`
  289. ResponseModalities []string `json:"responseModalities,omitempty"`
  290. ThinkingConfig *GeminiThinkingConfig `json:"thinkingConfig,omitempty"`
  291. SpeechConfig json.RawMessage `json:"speechConfig,omitempty"` // RawMessage to allow flexible speech config
  292. ImageConfig json.RawMessage `json:"imageConfig,omitempty"` // RawMessage to allow flexible image config
  293. }
  294. // UnmarshalJSON allows GeminiChatGenerationConfig to accept both snake_case and camelCase fields.
  295. func (c *GeminiChatGenerationConfig) UnmarshalJSON(data []byte) error {
  296. type Alias GeminiChatGenerationConfig
  297. var aux struct {
  298. Alias
  299. TopPSnake float64 `json:"top_p,omitempty"`
  300. TopKSnake float64 `json:"top_k,omitempty"`
  301. MaxOutputTokensSnake uint `json:"max_output_tokens,omitempty"`
  302. CandidateCountSnake int `json:"candidate_count,omitempty"`
  303. StopSequencesSnake []string `json:"stop_sequences,omitempty"`
  304. ResponseMimeTypeSnake string `json:"response_mime_type,omitempty"`
  305. ResponseSchemaSnake any `json:"response_schema,omitempty"`
  306. ResponseJsonSchemaSnake json.RawMessage `json:"response_json_schema,omitempty"`
  307. PresencePenaltySnake *float32 `json:"presence_penalty,omitempty"`
  308. FrequencyPenaltySnake *float32 `json:"frequency_penalty,omitempty"`
  309. ResponseLogprobsSnake bool `json:"response_logprobs,omitempty"`
  310. MediaResolutionSnake MediaResolution `json:"media_resolution,omitempty"`
  311. ResponseModalitiesSnake []string `json:"response_modalities,omitempty"`
  312. ThinkingConfigSnake *GeminiThinkingConfig `json:"thinking_config,omitempty"`
  313. SpeechConfigSnake json.RawMessage `json:"speech_config,omitempty"`
  314. ImageConfigSnake json.RawMessage `json:"image_config,omitempty"`
  315. }
  316. if err := common.Unmarshal(data, &aux); err != nil {
  317. return err
  318. }
  319. *c = GeminiChatGenerationConfig(aux.Alias)
  320. // Prioritize snake_case if present
  321. if aux.TopPSnake != 0 {
  322. c.TopP = aux.TopPSnake
  323. }
  324. if aux.TopKSnake != 0 {
  325. c.TopK = aux.TopKSnake
  326. }
  327. if aux.MaxOutputTokensSnake != 0 {
  328. c.MaxOutputTokens = aux.MaxOutputTokensSnake
  329. }
  330. if aux.CandidateCountSnake != 0 {
  331. c.CandidateCount = aux.CandidateCountSnake
  332. }
  333. if len(aux.StopSequencesSnake) > 0 {
  334. c.StopSequences = aux.StopSequencesSnake
  335. }
  336. if aux.ResponseMimeTypeSnake != "" {
  337. c.ResponseMimeType = aux.ResponseMimeTypeSnake
  338. }
  339. if aux.ResponseSchemaSnake != nil {
  340. c.ResponseSchema = aux.ResponseSchemaSnake
  341. }
  342. if len(aux.ResponseJsonSchemaSnake) > 0 {
  343. c.ResponseJsonSchema = aux.ResponseJsonSchemaSnake
  344. }
  345. if aux.PresencePenaltySnake != nil {
  346. c.PresencePenalty = aux.PresencePenaltySnake
  347. }
  348. if aux.FrequencyPenaltySnake != nil {
  349. c.FrequencyPenalty = aux.FrequencyPenaltySnake
  350. }
  351. if aux.ResponseLogprobsSnake {
  352. c.ResponseLogprobs = aux.ResponseLogprobsSnake
  353. }
  354. if aux.MediaResolutionSnake != "" {
  355. c.MediaResolution = aux.MediaResolutionSnake
  356. }
  357. if len(aux.ResponseModalitiesSnake) > 0 {
  358. c.ResponseModalities = aux.ResponseModalitiesSnake
  359. }
  360. if aux.ThinkingConfigSnake != nil {
  361. c.ThinkingConfig = aux.ThinkingConfigSnake
  362. }
  363. if len(aux.SpeechConfigSnake) > 0 {
  364. c.SpeechConfig = aux.SpeechConfigSnake
  365. }
  366. if len(aux.ImageConfigSnake) > 0 {
  367. c.ImageConfig = aux.ImageConfigSnake
  368. }
  369. return nil
  370. }
  371. type MediaResolution string
  372. type GeminiChatCandidate struct {
  373. Content GeminiChatContent `json:"content"`
  374. FinishReason *string `json:"finishReason"`
  375. Index int64 `json:"index"`
  376. SafetyRatings []GeminiChatSafetyRating `json:"safetyRatings"`
  377. }
  378. type GeminiChatSafetyRating struct {
  379. Category string `json:"category"`
  380. Probability string `json:"probability"`
  381. }
  382. type GeminiChatPromptFeedback struct {
  383. SafetyRatings []GeminiChatSafetyRating `json:"safetyRatings"`
  384. BlockReason *string `json:"blockReason,omitempty"`
  385. }
  386. type GeminiChatResponse struct {
  387. Candidates []GeminiChatCandidate `json:"candidates"`
  388. PromptFeedback *GeminiChatPromptFeedback `json:"promptFeedback,omitempty"`
  389. UsageMetadata GeminiUsageMetadata `json:"usageMetadata"`
  390. }
  391. type GeminiUsageMetadata struct {
  392. PromptTokenCount int `json:"promptTokenCount"`
  393. CandidatesTokenCount int `json:"candidatesTokenCount"`
  394. TotalTokenCount int `json:"totalTokenCount"`
  395. ThoughtsTokenCount int `json:"thoughtsTokenCount"`
  396. CachedContentTokenCount int `json:"cachedContentTokenCount"`
  397. PromptTokensDetails []GeminiPromptTokensDetails `json:"promptTokensDetails"`
  398. }
  399. type GeminiPromptTokensDetails struct {
  400. Modality string `json:"modality"`
  401. TokenCount int `json:"tokenCount"`
  402. }
  403. // Imagen related structs
  404. type GeminiImageRequest struct {
  405. Instances []GeminiImageInstance `json:"instances"`
  406. Parameters GeminiImageParameters `json:"parameters"`
  407. }
  408. type GeminiImageInstance struct {
  409. Prompt string `json:"prompt"`
  410. }
  411. type GeminiImageParameters struct {
  412. SampleCount int `json:"sampleCount,omitempty"`
  413. AspectRatio string `json:"aspectRatio,omitempty"`
  414. PersonGeneration string `json:"personGeneration,omitempty"`
  415. ImageSize string `json:"imageSize,omitempty"`
  416. }
  417. type GeminiImageResponse struct {
  418. Predictions []GeminiImagePrediction `json:"predictions"`
  419. }
  420. type GeminiImagePrediction struct {
  421. MimeType string `json:"mimeType"`
  422. BytesBase64Encoded string `json:"bytesBase64Encoded"`
  423. RaiFilteredReason string `json:"raiFilteredReason,omitempty"`
  424. SafetyAttributes any `json:"safetyAttributes,omitempty"`
  425. }
  426. // Embedding related structs
  427. type GeminiEmbeddingRequest struct {
  428. Model string `json:"model,omitempty"`
  429. Content GeminiChatContent `json:"content"`
  430. TaskType string `json:"taskType,omitempty"`
  431. Title string `json:"title,omitempty"`
  432. OutputDimensionality int `json:"outputDimensionality,omitempty"`
  433. }
  434. func (r *GeminiEmbeddingRequest) IsStream(c *gin.Context) bool {
  435. // Gemini embedding requests are not streamed
  436. return false
  437. }
  438. func (r *GeminiEmbeddingRequest) GetTokenCountMeta() *types.TokenCountMeta {
  439. var inputTexts []string
  440. for _, part := range r.Content.Parts {
  441. if part.Text != "" {
  442. inputTexts = append(inputTexts, part.Text)
  443. }
  444. }
  445. inputText := strings.Join(inputTexts, "\n")
  446. return &types.TokenCountMeta{
  447. CombineText: inputText,
  448. }
  449. }
  450. func (r *GeminiEmbeddingRequest) SetModelName(modelName string) {
  451. if modelName != "" {
  452. r.Model = modelName
  453. }
  454. }
  455. type GeminiBatchEmbeddingRequest struct {
  456. Requests []*GeminiEmbeddingRequest `json:"requests"`
  457. }
  458. func (r *GeminiBatchEmbeddingRequest) IsStream(c *gin.Context) bool {
  459. // Gemini batch embedding requests are not streamed
  460. return false
  461. }
  462. func (r *GeminiBatchEmbeddingRequest) GetTokenCountMeta() *types.TokenCountMeta {
  463. var inputTexts []string
  464. for _, request := range r.Requests {
  465. meta := request.GetTokenCountMeta()
  466. if meta != nil && meta.CombineText != "" {
  467. inputTexts = append(inputTexts, meta.CombineText)
  468. }
  469. }
  470. inputText := strings.Join(inputTexts, "\n")
  471. return &types.TokenCountMeta{
  472. CombineText: inputText,
  473. }
  474. }
  475. func (r *GeminiBatchEmbeddingRequest) SetModelName(modelName string) {
  476. if modelName != "" {
  477. for _, req := range r.Requests {
  478. req.SetModelName(modelName)
  479. }
  480. }
  481. }
  482. type GeminiEmbeddingResponse struct {
  483. Embedding ContentEmbedding `json:"embedding"`
  484. }
  485. type GeminiBatchEmbeddingResponse struct {
  486. Embeddings []*ContentEmbedding `json:"embeddings"`
  487. }
  488. type ContentEmbedding struct {
  489. Values []float64 `json:"values"`
  490. }