relay-gemini.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. package gemini
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. "github.com/QuantumNous/new-api/common"
  14. "github.com/QuantumNous/new-api/constant"
  15. "github.com/QuantumNous/new-api/dto"
  16. "github.com/QuantumNous/new-api/logger"
  17. "github.com/QuantumNous/new-api/relay/channel/openai"
  18. relaycommon "github.com/QuantumNous/new-api/relay/common"
  19. "github.com/QuantumNous/new-api/relay/helper"
  20. "github.com/QuantumNous/new-api/service"
  21. "github.com/QuantumNous/new-api/setting/model_setting"
  22. "github.com/QuantumNous/new-api/setting/reasoning"
  23. "github.com/QuantumNous/new-api/types"
  24. "github.com/gin-gonic/gin"
  25. )
  26. // https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference?hl=zh-cn#blob
  27. var geminiSupportedMimeTypes = map[string]bool{
  28. "application/pdf": true,
  29. "audio/mpeg": true,
  30. "audio/mp3": true,
  31. "audio/wav": true,
  32. "image/png": true,
  33. "image/jpeg": true,
  34. "image/jpg": true, // support old image/jpeg
  35. "image/webp": true,
  36. "text/plain": true,
  37. "video/mov": true,
  38. "video/mpeg": true,
  39. "video/mp4": true,
  40. "video/mpg": true,
  41. "video/avi": true,
  42. "video/wmv": true,
  43. "video/mpegps": true,
  44. "video/flv": true,
  45. }
  46. const thoughtSignatureBypassValue = "context_engineering_is_the_way_to_go"
  47. // Gemini 允许的思考预算范围
  48. const (
  49. pro25MinBudget = 128
  50. pro25MaxBudget = 32768
  51. flash25MaxBudget = 24576
  52. flash25LiteMinBudget = 512
  53. flash25LiteMaxBudget = 24576
  54. )
  55. func isNew25ProModel(modelName string) bool {
  56. return strings.HasPrefix(modelName, "gemini-2.5-pro") &&
  57. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-05-06") &&
  58. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-03-25")
  59. }
  60. func is25FlashLiteModel(modelName string) bool {
  61. return strings.HasPrefix(modelName, "gemini-2.5-flash-lite")
  62. }
  63. // clampThinkingBudget 根据模型名称将预算限制在允许的范围内
  64. func clampThinkingBudget(modelName string, budget int) int {
  65. isNew25Pro := isNew25ProModel(modelName)
  66. is25FlashLite := is25FlashLiteModel(modelName)
  67. if is25FlashLite {
  68. if budget < flash25LiteMinBudget {
  69. return flash25LiteMinBudget
  70. }
  71. if budget > flash25LiteMaxBudget {
  72. return flash25LiteMaxBudget
  73. }
  74. } else if isNew25Pro {
  75. if budget < pro25MinBudget {
  76. return pro25MinBudget
  77. }
  78. if budget > pro25MaxBudget {
  79. return pro25MaxBudget
  80. }
  81. } else { // 其他模型
  82. if budget < 0 {
  83. return 0
  84. }
  85. if budget > flash25MaxBudget {
  86. return flash25MaxBudget
  87. }
  88. }
  89. return budget
  90. }
  91. // "effort": "high" - Allocates a large portion of tokens for reasoning (approximately 80% of max_tokens)
  92. // "effort": "medium" - Allocates a moderate portion of tokens (approximately 50% of max_tokens)
  93. // "effort": "low" - Allocates a smaller portion of tokens (approximately 20% of max_tokens)
  94. // "effort": "minimal" - Allocates a minimal portion of tokens (approximately 5% of max_tokens)
  95. func clampThinkingBudgetByEffort(modelName string, effort string) int {
  96. isNew25Pro := isNew25ProModel(modelName)
  97. is25FlashLite := is25FlashLiteModel(modelName)
  98. maxBudget := 0
  99. if is25FlashLite {
  100. maxBudget = flash25LiteMaxBudget
  101. }
  102. if isNew25Pro {
  103. maxBudget = pro25MaxBudget
  104. } else {
  105. maxBudget = flash25MaxBudget
  106. }
  107. switch effort {
  108. case "high":
  109. maxBudget = maxBudget * 80 / 100
  110. case "medium":
  111. maxBudget = maxBudget * 50 / 100
  112. case "low":
  113. maxBudget = maxBudget * 20 / 100
  114. case "minimal":
  115. maxBudget = maxBudget * 5 / 100
  116. }
  117. return clampThinkingBudget(modelName, maxBudget)
  118. }
  119. func ThinkingAdaptor(geminiRequest *dto.GeminiChatRequest, info *relaycommon.RelayInfo, oaiRequest ...dto.GeneralOpenAIRequest) {
  120. if model_setting.GetGeminiSettings().ThinkingAdapterEnabled {
  121. modelName := info.UpstreamModelName
  122. isNew25Pro := strings.HasPrefix(modelName, "gemini-2.5-pro") &&
  123. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-05-06") &&
  124. !strings.HasPrefix(modelName, "gemini-2.5-pro-preview-03-25")
  125. if strings.Contains(modelName, "-thinking-") {
  126. parts := strings.SplitN(modelName, "-thinking-", 2)
  127. if len(parts) == 2 && parts[1] != "" {
  128. if budgetTokens, err := strconv.Atoi(parts[1]); err == nil {
  129. clampedBudget := clampThinkingBudget(modelName, budgetTokens)
  130. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  131. ThinkingBudget: common.GetPointer(clampedBudget),
  132. IncludeThoughts: true,
  133. }
  134. }
  135. }
  136. } else if strings.HasSuffix(modelName, "-thinking") {
  137. unsupportedModels := []string{
  138. "gemini-2.5-pro-preview-05-06",
  139. "gemini-2.5-pro-preview-03-25",
  140. }
  141. isUnsupported := false
  142. for _, unsupportedModel := range unsupportedModels {
  143. if strings.HasPrefix(modelName, unsupportedModel) {
  144. isUnsupported = true
  145. break
  146. }
  147. }
  148. if isUnsupported {
  149. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  150. IncludeThoughts: true,
  151. }
  152. } else {
  153. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  154. IncludeThoughts: true,
  155. }
  156. if geminiRequest.GenerationConfig.MaxOutputTokens > 0 {
  157. budgetTokens := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage * float64(geminiRequest.GenerationConfig.MaxOutputTokens)
  158. clampedBudget := clampThinkingBudget(modelName, int(budgetTokens))
  159. geminiRequest.GenerationConfig.ThinkingConfig.ThinkingBudget = common.GetPointer(clampedBudget)
  160. } else {
  161. if len(oaiRequest) > 0 {
  162. // 如果有reasoningEffort参数,则根据其值设置思考预算
  163. geminiRequest.GenerationConfig.ThinkingConfig.ThinkingBudget = common.GetPointer(clampThinkingBudgetByEffort(modelName, oaiRequest[0].ReasoningEffort))
  164. }
  165. }
  166. }
  167. } else if strings.HasSuffix(modelName, "-nothinking") {
  168. if !isNew25Pro {
  169. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  170. ThinkingBudget: common.GetPointer(0),
  171. }
  172. }
  173. } else if _, level, ok := reasoning.TrimEffortSuffix(info.UpstreamModelName); ok && level != "" {
  174. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  175. IncludeThoughts: true,
  176. ThinkingLevel: level,
  177. }
  178. info.ReasoningEffort = level
  179. }
  180. }
  181. }
  182. // Setting safety to the lowest possible values since Gemini is already powerless enough
  183. func CovertOpenAI2Gemini(c *gin.Context, textRequest dto.GeneralOpenAIRequest, info *relaycommon.RelayInfo) (*dto.GeminiChatRequest, error) {
  184. geminiRequest := dto.GeminiChatRequest{
  185. Contents: make([]dto.GeminiChatContent, 0, len(textRequest.Messages)),
  186. GenerationConfig: dto.GeminiChatGenerationConfig{
  187. Temperature: textRequest.Temperature,
  188. TopP: textRequest.TopP,
  189. MaxOutputTokens: textRequest.GetMaxTokens(),
  190. Seed: int64(textRequest.Seed),
  191. },
  192. }
  193. attachThoughtSignature := (info.ChannelType == constant.ChannelTypeGemini ||
  194. info.ChannelType == constant.ChannelTypeVertexAi) &&
  195. model_setting.GetGeminiSettings().FunctionCallThoughtSignatureEnabled
  196. if model_setting.IsGeminiModelSupportImagine(info.UpstreamModelName) {
  197. geminiRequest.GenerationConfig.ResponseModalities = []string{
  198. "TEXT",
  199. "IMAGE",
  200. }
  201. }
  202. adaptorWithExtraBody := false
  203. // patch extra_body
  204. if len(textRequest.ExtraBody) > 0 {
  205. if !strings.HasSuffix(info.UpstreamModelName, "-nothinking") {
  206. var extraBody map[string]interface{}
  207. if err := common.Unmarshal(textRequest.ExtraBody, &extraBody); err != nil {
  208. return nil, fmt.Errorf("invalid extra body: %w", err)
  209. }
  210. // eg. {"google":{"thinking_config":{"thinking_budget":5324,"include_thoughts":true}}}
  211. if googleBody, ok := extraBody["google"].(map[string]interface{}); ok {
  212. adaptorWithExtraBody = true
  213. // check error param name like thinkingConfig, should be thinking_config
  214. if _, hasErrorParam := googleBody["thinkingConfig"]; hasErrorParam {
  215. return nil, errors.New("extra_body.google.thinkingConfig is not supported, use extra_body.google.thinking_config instead")
  216. }
  217. if thinkingConfig, ok := googleBody["thinking_config"].(map[string]interface{}); ok {
  218. // check error param name like thinkingBudget, should be thinking_budget
  219. if _, hasErrorParam := thinkingConfig["thinkingBudget"]; hasErrorParam {
  220. return nil, errors.New("extra_body.google.thinking_config.thinkingBudget is not supported, use extra_body.google.thinking_config.thinking_budget instead")
  221. }
  222. if budget, ok := thinkingConfig["thinking_budget"].(float64); ok {
  223. budgetInt := int(budget)
  224. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  225. ThinkingBudget: common.GetPointer(budgetInt),
  226. IncludeThoughts: true,
  227. }
  228. } else {
  229. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  230. IncludeThoughts: true,
  231. }
  232. }
  233. }
  234. // check error param name like imageConfig, should be image_config
  235. if _, hasErrorParam := googleBody["imageConfig"]; hasErrorParam {
  236. return nil, errors.New("extra_body.google.imageConfig is not supported, use extra_body.google.image_config instead")
  237. }
  238. if imageConfig, ok := googleBody["image_config"].(map[string]interface{}); ok {
  239. // check error param name like aspectRatio, should be aspect_ratio
  240. if _, hasErrorParam := imageConfig["aspectRatio"]; hasErrorParam {
  241. return nil, errors.New("extra_body.google.image_config.aspectRatio is not supported, use extra_body.google.image_config.aspect_ratio instead")
  242. }
  243. // check error param name like imageSize, should be image_size
  244. if _, hasErrorParam := imageConfig["imageSize"]; hasErrorParam {
  245. return nil, errors.New("extra_body.google.image_config.imageSize is not supported, use extra_body.google.image_config.image_size instead")
  246. }
  247. // convert snake_case to camelCase for Gemini API
  248. geminiImageConfig := make(map[string]interface{})
  249. if aspectRatio, ok := imageConfig["aspect_ratio"]; ok {
  250. geminiImageConfig["aspectRatio"] = aspectRatio
  251. }
  252. if imageSize, ok := imageConfig["image_size"]; ok {
  253. geminiImageConfig["imageSize"] = imageSize
  254. }
  255. if len(geminiImageConfig) > 0 {
  256. imageConfigBytes, err := common.Marshal(geminiImageConfig)
  257. if err != nil {
  258. return nil, fmt.Errorf("failed to marshal image_config: %w", err)
  259. }
  260. geminiRequest.GenerationConfig.ImageConfig = imageConfigBytes
  261. }
  262. }
  263. }
  264. }
  265. }
  266. if !adaptorWithExtraBody {
  267. ThinkingAdaptor(&geminiRequest, info, textRequest)
  268. }
  269. safetySettings := make([]dto.GeminiChatSafetySettings, 0, len(SafetySettingList))
  270. for _, category := range SafetySettingList {
  271. safetySettings = append(safetySettings, dto.GeminiChatSafetySettings{
  272. Category: category,
  273. Threshold: model_setting.GetGeminiSafetySetting(category),
  274. })
  275. }
  276. geminiRequest.SafetySettings = safetySettings
  277. // openaiContent.FuncToToolCalls()
  278. if textRequest.Tools != nil {
  279. functions := make([]dto.FunctionRequest, 0, len(textRequest.Tools))
  280. googleSearch := false
  281. codeExecution := false
  282. urlContext := false
  283. for _, tool := range textRequest.Tools {
  284. if tool.Function.Name == "googleSearch" {
  285. googleSearch = true
  286. continue
  287. }
  288. if tool.Function.Name == "codeExecution" {
  289. codeExecution = true
  290. continue
  291. }
  292. if tool.Function.Name == "urlContext" {
  293. urlContext = true
  294. continue
  295. }
  296. if tool.Function.Parameters != nil {
  297. params, ok := tool.Function.Parameters.(map[string]interface{})
  298. if ok {
  299. if props, hasProps := params["properties"].(map[string]interface{}); hasProps {
  300. if len(props) == 0 {
  301. tool.Function.Parameters = nil
  302. }
  303. }
  304. }
  305. }
  306. // Clean the parameters before appending
  307. cleanedParams := cleanFunctionParameters(tool.Function.Parameters)
  308. tool.Function.Parameters = cleanedParams
  309. functions = append(functions, tool.Function)
  310. }
  311. geminiTools := geminiRequest.GetTools()
  312. if codeExecution {
  313. geminiTools = append(geminiTools, dto.GeminiChatTool{
  314. CodeExecution: make(map[string]string),
  315. })
  316. }
  317. if googleSearch {
  318. geminiTools = append(geminiTools, dto.GeminiChatTool{
  319. GoogleSearch: make(map[string]string),
  320. })
  321. }
  322. if urlContext {
  323. geminiTools = append(geminiTools, dto.GeminiChatTool{
  324. URLContext: make(map[string]string),
  325. })
  326. }
  327. if len(functions) > 0 {
  328. geminiTools = append(geminiTools, dto.GeminiChatTool{
  329. FunctionDeclarations: functions,
  330. })
  331. }
  332. geminiRequest.SetTools(geminiTools)
  333. }
  334. if textRequest.ResponseFormat != nil && (textRequest.ResponseFormat.Type == "json_schema" || textRequest.ResponseFormat.Type == "json_object") {
  335. geminiRequest.GenerationConfig.ResponseMimeType = "application/json"
  336. if len(textRequest.ResponseFormat.JsonSchema) > 0 {
  337. // 先将json.RawMessage解析
  338. var jsonSchema dto.FormatJsonSchema
  339. if err := common.Unmarshal(textRequest.ResponseFormat.JsonSchema, &jsonSchema); err == nil {
  340. cleanedSchema := removeAdditionalPropertiesWithDepth(jsonSchema.Schema, 0)
  341. geminiRequest.GenerationConfig.ResponseSchema = cleanedSchema
  342. }
  343. }
  344. }
  345. tool_call_ids := make(map[string]string)
  346. var system_content []string
  347. //shouldAddDummyModelMessage := false
  348. for _, message := range textRequest.Messages {
  349. if message.Role == "system" || message.Role == "developer" {
  350. system_content = append(system_content, message.StringContent())
  351. continue
  352. } else if message.Role == "tool" || message.Role == "function" {
  353. if len(geminiRequest.Contents) == 0 || geminiRequest.Contents[len(geminiRequest.Contents)-1].Role == "model" {
  354. geminiRequest.Contents = append(geminiRequest.Contents, dto.GeminiChatContent{
  355. Role: "user",
  356. })
  357. }
  358. var parts = &geminiRequest.Contents[len(geminiRequest.Contents)-1].Parts
  359. name := ""
  360. if message.Name != nil {
  361. name = *message.Name
  362. } else if val, exists := tool_call_ids[message.ToolCallId]; exists {
  363. name = val
  364. }
  365. var contentMap map[string]interface{}
  366. contentStr := message.StringContent()
  367. // 1. 尝试解析为 JSON 对象
  368. if err := json.Unmarshal([]byte(contentStr), &contentMap); err != nil {
  369. // 2. 如果失败,尝试解析为 JSON 数组
  370. var contentSlice []interface{}
  371. if err := json.Unmarshal([]byte(contentStr), &contentSlice); err == nil {
  372. // 如果是数组,包装成对象
  373. contentMap = map[string]interface{}{"result": contentSlice}
  374. } else {
  375. // 3. 如果再次失败,作为纯文本处理
  376. contentMap = map[string]interface{}{"content": contentStr}
  377. }
  378. }
  379. functionResp := &dto.GeminiFunctionResponse{
  380. Name: name,
  381. Response: contentMap,
  382. }
  383. *parts = append(*parts, dto.GeminiPart{
  384. FunctionResponse: functionResp,
  385. })
  386. continue
  387. }
  388. var parts []dto.GeminiPart
  389. content := dto.GeminiChatContent{
  390. Role: message.Role,
  391. }
  392. shouldAttachThoughtSignature := attachThoughtSignature && (message.Role == "assistant" || message.Role == "model")
  393. signatureAttached := false
  394. // isToolCall := false
  395. if message.ToolCalls != nil {
  396. // message.Role = "model"
  397. // isToolCall = true
  398. for _, call := range message.ParseToolCalls() {
  399. args := map[string]interface{}{}
  400. if call.Function.Arguments != "" {
  401. if json.Unmarshal([]byte(call.Function.Arguments), &args) != nil {
  402. return nil, fmt.Errorf("invalid arguments for function %s, args: %s", call.Function.Name, call.Function.Arguments)
  403. }
  404. }
  405. toolCall := dto.GeminiPart{
  406. FunctionCall: &dto.FunctionCall{
  407. FunctionName: call.Function.Name,
  408. Arguments: args,
  409. },
  410. }
  411. if shouldAttachThoughtSignature && !signatureAttached && hasFunctionCallContent(toolCall.FunctionCall) && len(toolCall.ThoughtSignature) == 0 {
  412. toolCall.ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  413. signatureAttached = true
  414. }
  415. parts = append(parts, toolCall)
  416. tool_call_ids[call.ID] = call.Function.Name
  417. }
  418. }
  419. openaiContent := message.ParseContent()
  420. imageNum := 0
  421. for _, part := range openaiContent {
  422. if part.Type == dto.ContentTypeText {
  423. if part.Text == "" {
  424. continue
  425. }
  426. // check markdown image ![image](data:image/jpeg;base64,xxxxxxxxxxxx)
  427. // 使用字符串查找而非正则,避免大文本性能问题
  428. text := part.Text
  429. hasMarkdownImage := false
  430. for {
  431. // 快速检查是否包含 markdown 图片标记
  432. startIdx := strings.Index(text, "![")
  433. if startIdx == -1 {
  434. break
  435. }
  436. // 找到 ](
  437. bracketIdx := strings.Index(text[startIdx:], "](data:")
  438. if bracketIdx == -1 {
  439. break
  440. }
  441. bracketIdx += startIdx
  442. // 找到闭合的 )
  443. closeIdx := strings.Index(text[bracketIdx+2:], ")")
  444. if closeIdx == -1 {
  445. break
  446. }
  447. closeIdx += bracketIdx + 2
  448. hasMarkdownImage = true
  449. // 添加图片前的文本
  450. if startIdx > 0 {
  451. textBefore := text[:startIdx]
  452. if textBefore != "" {
  453. parts = append(parts, dto.GeminiPart{
  454. Text: textBefore,
  455. })
  456. }
  457. }
  458. // 提取 data URL (从 "](" 后面开始,到 ")" 之前)
  459. dataUrl := text[bracketIdx+2 : closeIdx]
  460. imageNum += 1
  461. if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
  462. return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
  463. }
  464. format, base64String, err := service.DecodeBase64FileData(dataUrl)
  465. if err != nil {
  466. return nil, fmt.Errorf("decode markdown base64 image data failed: %s", err.Error())
  467. }
  468. imgPart := dto.GeminiPart{
  469. InlineData: &dto.GeminiInlineData{
  470. MimeType: format,
  471. Data: base64String,
  472. },
  473. }
  474. if shouldAttachThoughtSignature {
  475. imgPart.ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  476. }
  477. parts = append(parts, imgPart)
  478. // 继续处理剩余文本
  479. text = text[closeIdx+1:]
  480. }
  481. // 添加剩余文本或原始文本(如果没有找到 markdown 图片)
  482. if !hasMarkdownImage {
  483. parts = append(parts, dto.GeminiPart{
  484. Text: part.Text,
  485. })
  486. }
  487. } else if part.Type == dto.ContentTypeImageURL {
  488. imageNum += 1
  489. if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
  490. return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
  491. }
  492. // 判断是否是url
  493. if strings.HasPrefix(part.GetImageMedia().Url, "http") {
  494. // 是url,获取文件的类型和base64编码的数据
  495. fileData, err := service.GetFileBase64FromUrl(c, part.GetImageMedia().Url, "formatting image for Gemini")
  496. if err != nil {
  497. return nil, fmt.Errorf("get file base64 from url '%s' failed: %w", part.GetImageMedia().Url, err)
  498. }
  499. // 校验 MimeType 是否在 Gemini 支持的白名单中
  500. if _, ok := geminiSupportedMimeTypes[strings.ToLower(fileData.MimeType)]; !ok {
  501. url := part.GetImageMedia().Url
  502. return nil, fmt.Errorf("mime type is not supported by Gemini: '%s', url: '%s', supported types are: %v", fileData.MimeType, url, getSupportedMimeTypesList())
  503. }
  504. parts = append(parts, dto.GeminiPart{
  505. InlineData: &dto.GeminiInlineData{
  506. MimeType: fileData.MimeType, // 使用原始的 MimeType,因为大小写可能对API有意义
  507. Data: fileData.Base64Data,
  508. },
  509. })
  510. } else {
  511. format, base64String, err := service.DecodeBase64FileData(part.GetImageMedia().Url)
  512. if err != nil {
  513. return nil, fmt.Errorf("decode base64 image data failed: %s", err.Error())
  514. }
  515. parts = append(parts, dto.GeminiPart{
  516. InlineData: &dto.GeminiInlineData{
  517. MimeType: format,
  518. Data: base64String,
  519. },
  520. })
  521. }
  522. } else if part.Type == dto.ContentTypeFile {
  523. if part.GetFile().FileId != "" {
  524. return nil, fmt.Errorf("only base64 file is supported in gemini")
  525. }
  526. format, base64String, err := service.DecodeBase64FileData(part.GetFile().FileData)
  527. if err != nil {
  528. return nil, fmt.Errorf("decode base64 file data failed: %s", err.Error())
  529. }
  530. parts = append(parts, dto.GeminiPart{
  531. InlineData: &dto.GeminiInlineData{
  532. MimeType: format,
  533. Data: base64String,
  534. },
  535. })
  536. } else if part.Type == dto.ContentTypeInputAudio {
  537. if part.GetInputAudio().Data == "" {
  538. return nil, fmt.Errorf("only base64 audio is supported in gemini")
  539. }
  540. base64String, err := service.DecodeBase64AudioData(part.GetInputAudio().Data)
  541. if err != nil {
  542. return nil, fmt.Errorf("decode base64 audio data failed: %s", err.Error())
  543. }
  544. parts = append(parts, dto.GeminiPart{
  545. InlineData: &dto.GeminiInlineData{
  546. MimeType: "audio/" + part.GetInputAudio().Format,
  547. Data: base64String,
  548. },
  549. })
  550. }
  551. }
  552. // 如果需要附加签名但还没有附加(没有 tool_calls 或 tool_calls 为空),
  553. // 则在第一个文本 part 上附加 thoughtSignature
  554. if shouldAttachThoughtSignature && !signatureAttached && len(parts) > 0 {
  555. for i := range parts {
  556. if parts[i].Text != "" {
  557. parts[i].ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  558. break
  559. }
  560. }
  561. }
  562. content.Parts = parts
  563. // there's no assistant role in gemini and API shall vomit if Role is not user or model
  564. if content.Role == "assistant" {
  565. content.Role = "model"
  566. }
  567. if len(content.Parts) > 0 {
  568. geminiRequest.Contents = append(geminiRequest.Contents, content)
  569. }
  570. }
  571. if len(system_content) > 0 {
  572. geminiRequest.SystemInstructions = &dto.GeminiChatContent{
  573. Parts: []dto.GeminiPart{
  574. {
  575. Text: strings.Join(system_content, "\n"),
  576. },
  577. },
  578. }
  579. }
  580. return &geminiRequest, nil
  581. }
  582. func hasFunctionCallContent(call *dto.FunctionCall) bool {
  583. if call == nil {
  584. return false
  585. }
  586. if strings.TrimSpace(call.FunctionName) != "" {
  587. return true
  588. }
  589. switch v := call.Arguments.(type) {
  590. case nil:
  591. return false
  592. case string:
  593. return strings.TrimSpace(v) != ""
  594. case map[string]interface{}:
  595. return len(v) > 0
  596. case []interface{}:
  597. return len(v) > 0
  598. default:
  599. return true
  600. }
  601. }
  602. // Helper function to get a list of supported MIME types for error messages
  603. func getSupportedMimeTypesList() []string {
  604. keys := make([]string, 0, len(geminiSupportedMimeTypes))
  605. for k := range geminiSupportedMimeTypes {
  606. keys = append(keys, k)
  607. }
  608. return keys
  609. }
  610. var geminiOpenAPISchemaAllowedFields = map[string]struct{}{
  611. "anyOf": {},
  612. "default": {},
  613. "description": {},
  614. "enum": {},
  615. "example": {},
  616. "format": {},
  617. "items": {},
  618. "maxItems": {},
  619. "maxLength": {},
  620. "maxProperties": {},
  621. "maximum": {},
  622. "minItems": {},
  623. "minLength": {},
  624. "minProperties": {},
  625. "minimum": {},
  626. "nullable": {},
  627. "pattern": {},
  628. "properties": {},
  629. "propertyOrdering": {},
  630. "required": {},
  631. "title": {},
  632. "type": {},
  633. }
  634. const geminiFunctionSchemaMaxDepth = 64
  635. // cleanFunctionParameters recursively removes unsupported fields from Gemini function parameters.
  636. func cleanFunctionParameters(params interface{}) interface{} {
  637. return cleanFunctionParametersWithDepth(params, 0)
  638. }
  639. func cleanFunctionParametersWithDepth(params interface{}, depth int) interface{} {
  640. if params == nil {
  641. return nil
  642. }
  643. if depth >= geminiFunctionSchemaMaxDepth {
  644. return cleanFunctionParametersShallow(params)
  645. }
  646. switch v := params.(type) {
  647. case map[string]interface{}:
  648. // Keep only Gemini-supported OpenAPI schema subset fields (per official SDK Schema).
  649. cleanedMap := make(map[string]interface{}, len(v))
  650. for k, val := range v {
  651. if _, ok := geminiOpenAPISchemaAllowedFields[k]; ok {
  652. cleanedMap[k] = val
  653. }
  654. }
  655. normalizeGeminiSchemaTypeAndNullable(cleanedMap)
  656. // Clean properties
  657. if props, ok := cleanedMap["properties"].(map[string]interface{}); ok && props != nil {
  658. cleanedProps := make(map[string]interface{})
  659. for propName, propValue := range props {
  660. cleanedProps[propName] = cleanFunctionParametersWithDepth(propValue, depth+1)
  661. }
  662. cleanedMap["properties"] = cleanedProps
  663. }
  664. // Recursively clean items in arrays
  665. if items, ok := cleanedMap["items"].(map[string]interface{}); ok && items != nil {
  666. cleanedMap["items"] = cleanFunctionParametersWithDepth(items, depth+1)
  667. }
  668. // OpenAPI tuple-style items is not supported by Gemini SDK Schema; keep first to avoid API rejection.
  669. if itemsArray, ok := cleanedMap["items"].([]interface{}); ok && len(itemsArray) > 0 {
  670. cleanedMap["items"] = cleanFunctionParametersWithDepth(itemsArray[0], depth+1)
  671. }
  672. // Recursively clean anyOf
  673. if nested, ok := cleanedMap["anyOf"].([]interface{}); ok && nested != nil {
  674. cleanedNested := make([]interface{}, len(nested))
  675. for i, item := range nested {
  676. cleanedNested[i] = cleanFunctionParametersWithDepth(item, depth+1)
  677. }
  678. cleanedMap["anyOf"] = cleanedNested
  679. }
  680. return cleanedMap
  681. case []interface{}:
  682. // Handle arrays of schemas
  683. cleanedArray := make([]interface{}, len(v))
  684. for i, item := range v {
  685. cleanedArray[i] = cleanFunctionParametersWithDepth(item, depth+1)
  686. }
  687. return cleanedArray
  688. default:
  689. // Not a map or array, return as is (e.g., could be a primitive)
  690. return params
  691. }
  692. }
  693. func cleanFunctionParametersShallow(params interface{}) interface{} {
  694. switch v := params.(type) {
  695. case map[string]interface{}:
  696. cleanedMap := make(map[string]interface{}, len(v))
  697. for k, val := range v {
  698. if _, ok := geminiOpenAPISchemaAllowedFields[k]; ok {
  699. cleanedMap[k] = val
  700. }
  701. }
  702. normalizeGeminiSchemaTypeAndNullable(cleanedMap)
  703. // Stop recursion and avoid retaining huge nested structures.
  704. delete(cleanedMap, "properties")
  705. delete(cleanedMap, "items")
  706. delete(cleanedMap, "anyOf")
  707. return cleanedMap
  708. case []interface{}:
  709. // Prefer an empty list over deep recursion on attacker-controlled inputs.
  710. return []interface{}{}
  711. default:
  712. return params
  713. }
  714. }
  715. func normalizeGeminiSchemaTypeAndNullable(schema map[string]interface{}) {
  716. rawType, ok := schema["type"]
  717. if !ok || rawType == nil {
  718. return
  719. }
  720. normalize := func(t string) (string, bool) {
  721. switch strings.ToLower(strings.TrimSpace(t)) {
  722. case "object":
  723. return "OBJECT", false
  724. case "array":
  725. return "ARRAY", false
  726. case "string":
  727. return "STRING", false
  728. case "integer":
  729. return "INTEGER", false
  730. case "number":
  731. return "NUMBER", false
  732. case "boolean":
  733. return "BOOLEAN", false
  734. case "null":
  735. return "", true
  736. default:
  737. return t, false
  738. }
  739. }
  740. switch t := rawType.(type) {
  741. case string:
  742. normalized, isNull := normalize(t)
  743. if isNull {
  744. schema["nullable"] = true
  745. delete(schema, "type")
  746. return
  747. }
  748. schema["type"] = normalized
  749. case []interface{}:
  750. nullable := false
  751. var chosen string
  752. for _, item := range t {
  753. if s, ok := item.(string); ok {
  754. normalized, isNull := normalize(s)
  755. if isNull {
  756. nullable = true
  757. continue
  758. }
  759. if chosen == "" {
  760. chosen = normalized
  761. }
  762. }
  763. }
  764. if nullable {
  765. schema["nullable"] = true
  766. }
  767. if chosen != "" {
  768. schema["type"] = chosen
  769. } else {
  770. delete(schema, "type")
  771. }
  772. }
  773. }
  774. func removeAdditionalPropertiesWithDepth(schema interface{}, depth int) interface{} {
  775. if depth >= 5 {
  776. return schema
  777. }
  778. v, ok := schema.(map[string]interface{})
  779. if !ok || len(v) == 0 {
  780. return schema
  781. }
  782. // 删除所有的title字段
  783. delete(v, "title")
  784. delete(v, "$schema")
  785. // 如果type不为object和array,则直接返回
  786. if typeVal, exists := v["type"]; !exists || (typeVal != "object" && typeVal != "array") {
  787. return schema
  788. }
  789. switch v["type"] {
  790. case "object":
  791. delete(v, "additionalProperties")
  792. // 处理 properties
  793. if properties, ok := v["properties"].(map[string]interface{}); ok {
  794. for key, value := range properties {
  795. properties[key] = removeAdditionalPropertiesWithDepth(value, depth+1)
  796. }
  797. }
  798. for _, field := range []string{"allOf", "anyOf", "oneOf"} {
  799. if nested, ok := v[field].([]interface{}); ok {
  800. for i, item := range nested {
  801. nested[i] = removeAdditionalPropertiesWithDepth(item, depth+1)
  802. }
  803. }
  804. }
  805. case "array":
  806. if items, ok := v["items"].(map[string]interface{}); ok {
  807. v["items"] = removeAdditionalPropertiesWithDepth(items, depth+1)
  808. }
  809. }
  810. return v
  811. }
  812. func unescapeString(s string) (string, error) {
  813. var result []rune
  814. escaped := false
  815. i := 0
  816. for i < len(s) {
  817. r, size := utf8.DecodeRuneInString(s[i:]) // 正确解码UTF-8字符
  818. if r == utf8.RuneError {
  819. return "", fmt.Errorf("invalid UTF-8 encoding")
  820. }
  821. if escaped {
  822. // 如果是转义符后的字符,检查其类型
  823. switch r {
  824. case '"':
  825. result = append(result, '"')
  826. case '\\':
  827. result = append(result, '\\')
  828. case '/':
  829. result = append(result, '/')
  830. case 'b':
  831. result = append(result, '\b')
  832. case 'f':
  833. result = append(result, '\f')
  834. case 'n':
  835. result = append(result, '\n')
  836. case 'r':
  837. result = append(result, '\r')
  838. case 't':
  839. result = append(result, '\t')
  840. case '\'':
  841. result = append(result, '\'')
  842. default:
  843. // 如果遇到一个非法的转义字符,直接按原样输出
  844. result = append(result, '\\', r)
  845. }
  846. escaped = false
  847. } else {
  848. if r == '\\' {
  849. escaped = true // 记录反斜杠作为转义符
  850. } else {
  851. result = append(result, r)
  852. }
  853. }
  854. i += size // 移动到下一个字符
  855. }
  856. return string(result), nil
  857. }
  858. func unescapeMapOrSlice(data interface{}) interface{} {
  859. switch v := data.(type) {
  860. case map[string]interface{}:
  861. for k, val := range v {
  862. v[k] = unescapeMapOrSlice(val)
  863. }
  864. case []interface{}:
  865. for i, val := range v {
  866. v[i] = unescapeMapOrSlice(val)
  867. }
  868. case string:
  869. if unescaped, err := unescapeString(v); err != nil {
  870. return v
  871. } else {
  872. return unescaped
  873. }
  874. }
  875. return data
  876. }
  877. func getResponseToolCall(item *dto.GeminiPart) *dto.ToolCallResponse {
  878. var argsBytes []byte
  879. var err error
  880. if result, ok := item.FunctionCall.Arguments.(map[string]interface{}); ok {
  881. argsBytes, err = json.Marshal(unescapeMapOrSlice(result))
  882. } else {
  883. argsBytes, err = json.Marshal(item.FunctionCall.Arguments)
  884. }
  885. if err != nil {
  886. return nil
  887. }
  888. return &dto.ToolCallResponse{
  889. ID: fmt.Sprintf("call_%s", common.GetUUID()),
  890. Type: "function",
  891. Function: dto.FunctionResponse{
  892. Arguments: string(argsBytes),
  893. Name: item.FunctionCall.FunctionName,
  894. },
  895. }
  896. }
  897. func responseGeminiChat2OpenAI(c *gin.Context, response *dto.GeminiChatResponse) *dto.OpenAITextResponse {
  898. fullTextResponse := dto.OpenAITextResponse{
  899. Id: helper.GetResponseID(c),
  900. Object: "chat.completion",
  901. Created: common.GetTimestamp(),
  902. Choices: make([]dto.OpenAITextResponseChoice, 0, len(response.Candidates)),
  903. }
  904. isToolCall := false
  905. for _, candidate := range response.Candidates {
  906. choice := dto.OpenAITextResponseChoice{
  907. Index: int(candidate.Index),
  908. Message: dto.Message{
  909. Role: "assistant",
  910. Content: "",
  911. },
  912. FinishReason: constant.FinishReasonStop,
  913. }
  914. if len(candidate.Content.Parts) > 0 {
  915. var texts []string
  916. var toolCalls []dto.ToolCallResponse
  917. for _, part := range candidate.Content.Parts {
  918. if part.InlineData != nil {
  919. // 媒体内容
  920. if strings.HasPrefix(part.InlineData.MimeType, "image") {
  921. imgText := "![image](data:" + part.InlineData.MimeType + ";base64," + part.InlineData.Data + ")"
  922. texts = append(texts, imgText)
  923. } else {
  924. // 其他媒体类型,直接显示链接
  925. texts = append(texts, fmt.Sprintf("[media](data:%s;base64,%s)", part.InlineData.MimeType, part.InlineData.Data))
  926. }
  927. } else if part.FunctionCall != nil {
  928. choice.FinishReason = constant.FinishReasonToolCalls
  929. if call := getResponseToolCall(&part); call != nil {
  930. toolCalls = append(toolCalls, *call)
  931. }
  932. } else if part.Thought {
  933. choice.Message.ReasoningContent = part.Text
  934. } else {
  935. if part.ExecutableCode != nil {
  936. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```")
  937. } else if part.CodeExecutionResult != nil {
  938. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```")
  939. } else {
  940. // 过滤掉空行
  941. if part.Text != "\n" {
  942. texts = append(texts, part.Text)
  943. }
  944. }
  945. }
  946. }
  947. if len(toolCalls) > 0 {
  948. choice.Message.SetToolCalls(toolCalls)
  949. isToolCall = true
  950. }
  951. choice.Message.SetStringContent(strings.Join(texts, "\n"))
  952. }
  953. if candidate.FinishReason != nil {
  954. switch *candidate.FinishReason {
  955. case "STOP":
  956. choice.FinishReason = constant.FinishReasonStop
  957. case "MAX_TOKENS":
  958. choice.FinishReason = constant.FinishReasonLength
  959. default:
  960. choice.FinishReason = constant.FinishReasonContentFilter
  961. }
  962. }
  963. if isToolCall {
  964. choice.FinishReason = constant.FinishReasonToolCalls
  965. }
  966. fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
  967. }
  968. return &fullTextResponse
  969. }
  970. func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*dto.ChatCompletionsStreamResponse, bool) {
  971. choices := make([]dto.ChatCompletionsStreamResponseChoice, 0, len(geminiResponse.Candidates))
  972. isStop := false
  973. for _, candidate := range geminiResponse.Candidates {
  974. if candidate.FinishReason != nil && *candidate.FinishReason == "STOP" {
  975. isStop = true
  976. candidate.FinishReason = nil
  977. }
  978. choice := dto.ChatCompletionsStreamResponseChoice{
  979. Index: int(candidate.Index),
  980. Delta: dto.ChatCompletionsStreamResponseChoiceDelta{
  981. //Role: "assistant",
  982. },
  983. }
  984. var texts []string
  985. isTools := false
  986. isThought := false
  987. if candidate.FinishReason != nil {
  988. // p := GeminiConvertFinishReason(*candidate.FinishReason)
  989. switch *candidate.FinishReason {
  990. case "STOP":
  991. choice.FinishReason = &constant.FinishReasonStop
  992. case "MAX_TOKENS":
  993. choice.FinishReason = &constant.FinishReasonLength
  994. default:
  995. choice.FinishReason = &constant.FinishReasonContentFilter
  996. }
  997. }
  998. for _, part := range candidate.Content.Parts {
  999. if part.InlineData != nil {
  1000. if strings.HasPrefix(part.InlineData.MimeType, "image") {
  1001. imgText := "![image](data:" + part.InlineData.MimeType + ";base64," + part.InlineData.Data + ")"
  1002. texts = append(texts, imgText)
  1003. }
  1004. } else if part.FunctionCall != nil {
  1005. isTools = true
  1006. if call := getResponseToolCall(&part); call != nil {
  1007. call.SetIndex(len(choice.Delta.ToolCalls))
  1008. choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
  1009. }
  1010. } else if part.Thought {
  1011. isThought = true
  1012. texts = append(texts, part.Text)
  1013. } else {
  1014. if part.ExecutableCode != nil {
  1015. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```\n")
  1016. } else if part.CodeExecutionResult != nil {
  1017. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```\n")
  1018. } else {
  1019. if part.Text != "\n" {
  1020. texts = append(texts, part.Text)
  1021. }
  1022. }
  1023. }
  1024. }
  1025. if isThought {
  1026. choice.Delta.SetReasoningContent(strings.Join(texts, "\n"))
  1027. } else {
  1028. choice.Delta.SetContentString(strings.Join(texts, "\n"))
  1029. }
  1030. if isTools {
  1031. choice.FinishReason = &constant.FinishReasonToolCalls
  1032. }
  1033. choices = append(choices, choice)
  1034. }
  1035. var response dto.ChatCompletionsStreamResponse
  1036. response.Object = "chat.completion.chunk"
  1037. response.Choices = choices
  1038. return &response, isStop
  1039. }
  1040. func handleStream(c *gin.Context, info *relaycommon.RelayInfo, resp *dto.ChatCompletionsStreamResponse) error {
  1041. streamData, err := common.Marshal(resp)
  1042. if err != nil {
  1043. return fmt.Errorf("failed to marshal stream response: %w", err)
  1044. }
  1045. err = openai.HandleStreamFormat(c, info, string(streamData), info.ChannelSetting.ForceFormat, info.ChannelSetting.ThinkingToContent)
  1046. if err != nil {
  1047. return fmt.Errorf("failed to handle stream format: %w", err)
  1048. }
  1049. return nil
  1050. }
  1051. func handleFinalStream(c *gin.Context, info *relaycommon.RelayInfo, resp *dto.ChatCompletionsStreamResponse) error {
  1052. streamData, err := common.Marshal(resp)
  1053. if err != nil {
  1054. return fmt.Errorf("failed to marshal stream response: %w", err)
  1055. }
  1056. openai.HandleFinalResponse(c, info, string(streamData), resp.Id, resp.Created, resp.Model, resp.GetSystemFingerprint(), resp.Usage, false)
  1057. return nil
  1058. }
  1059. func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response, callback func(data string, geminiResponse *dto.GeminiChatResponse) bool) (*dto.Usage, *types.NewAPIError) {
  1060. var usage = &dto.Usage{}
  1061. var imageCount int
  1062. responseText := strings.Builder{}
  1063. helper.StreamScannerHandler(c, resp, info, func(data string) bool {
  1064. var geminiResponse dto.GeminiChatResponse
  1065. err := common.UnmarshalJsonStr(data, &geminiResponse)
  1066. if err != nil {
  1067. logger.LogError(c, "error unmarshalling stream response: "+err.Error())
  1068. return false
  1069. }
  1070. // 统计图片数量
  1071. for _, candidate := range geminiResponse.Candidates {
  1072. for _, part := range candidate.Content.Parts {
  1073. if part.InlineData != nil && part.InlineData.MimeType != "" {
  1074. imageCount++
  1075. }
  1076. if part.Text != "" {
  1077. responseText.WriteString(part.Text)
  1078. }
  1079. }
  1080. }
  1081. // 更新使用量统计
  1082. if geminiResponse.UsageMetadata.TotalTokenCount != 0 {
  1083. usage.PromptTokens = geminiResponse.UsageMetadata.PromptTokenCount
  1084. usage.CompletionTokens = geminiResponse.UsageMetadata.CandidatesTokenCount + geminiResponse.UsageMetadata.ThoughtsTokenCount
  1085. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  1086. usage.TotalTokens = geminiResponse.UsageMetadata.TotalTokenCount
  1087. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  1088. if detail.Modality == "AUDIO" {
  1089. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  1090. } else if detail.Modality == "TEXT" {
  1091. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  1092. }
  1093. }
  1094. }
  1095. return callback(data, &geminiResponse)
  1096. })
  1097. if imageCount != 0 {
  1098. if usage.CompletionTokens == 0 {
  1099. usage.CompletionTokens = imageCount * 1400
  1100. }
  1101. }
  1102. usage.PromptTokensDetails.TextTokens = usage.PromptTokens
  1103. if usage.TotalTokens > 0 {
  1104. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  1105. }
  1106. if usage.CompletionTokens <= 0 {
  1107. str := responseText.String()
  1108. if len(str) > 0 {
  1109. usage = service.ResponseText2Usage(c, responseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
  1110. } else {
  1111. usage = &dto.Usage{}
  1112. }
  1113. }
  1114. return usage, nil
  1115. }
  1116. func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1117. id := helper.GetResponseID(c)
  1118. createAt := common.GetTimestamp()
  1119. finishReason := constant.FinishReasonStop
  1120. toolCallIndexByChoice := make(map[int]map[string]int)
  1121. nextToolCallIndexByChoice := make(map[int]int)
  1122. usage, err := geminiStreamHandler(c, info, resp, func(data string, geminiResponse *dto.GeminiChatResponse) bool {
  1123. response, isStop := streamResponseGeminiChat2OpenAI(geminiResponse)
  1124. response.Id = id
  1125. response.Created = createAt
  1126. response.Model = info.UpstreamModelName
  1127. for choiceIdx := range response.Choices {
  1128. choiceKey := response.Choices[choiceIdx].Index
  1129. for toolIdx := range response.Choices[choiceIdx].Delta.ToolCalls {
  1130. tool := &response.Choices[choiceIdx].Delta.ToolCalls[toolIdx]
  1131. if tool.ID == "" {
  1132. continue
  1133. }
  1134. m := toolCallIndexByChoice[choiceKey]
  1135. if m == nil {
  1136. m = make(map[string]int)
  1137. toolCallIndexByChoice[choiceKey] = m
  1138. }
  1139. if idx, ok := m[tool.ID]; ok {
  1140. tool.SetIndex(idx)
  1141. continue
  1142. }
  1143. idx := nextToolCallIndexByChoice[choiceKey]
  1144. nextToolCallIndexByChoice[choiceKey] = idx + 1
  1145. m[tool.ID] = idx
  1146. tool.SetIndex(idx)
  1147. }
  1148. }
  1149. logger.LogDebug(c, fmt.Sprintf("info.SendResponseCount = %d", info.SendResponseCount))
  1150. if info.SendResponseCount == 0 {
  1151. // send first response
  1152. emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil)
  1153. if response.IsToolCall() {
  1154. if len(emptyResponse.Choices) > 0 && len(response.Choices) > 0 {
  1155. toolCalls := response.Choices[0].Delta.ToolCalls
  1156. copiedToolCalls := make([]dto.ToolCallResponse, len(toolCalls))
  1157. for idx := range toolCalls {
  1158. copiedToolCalls[idx] = toolCalls[idx]
  1159. copiedToolCalls[idx].Function.Arguments = ""
  1160. }
  1161. emptyResponse.Choices[0].Delta.ToolCalls = copiedToolCalls
  1162. }
  1163. finishReason = constant.FinishReasonToolCalls
  1164. err := handleStream(c, info, emptyResponse)
  1165. if err != nil {
  1166. logger.LogError(c, err.Error())
  1167. }
  1168. response.ClearToolCalls()
  1169. if response.IsFinished() {
  1170. response.Choices[0].FinishReason = nil
  1171. }
  1172. } else {
  1173. err := handleStream(c, info, emptyResponse)
  1174. if err != nil {
  1175. logger.LogError(c, err.Error())
  1176. }
  1177. }
  1178. }
  1179. err := handleStream(c, info, response)
  1180. if err != nil {
  1181. logger.LogError(c, err.Error())
  1182. }
  1183. if isStop {
  1184. _ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
  1185. }
  1186. return true
  1187. })
  1188. if err != nil {
  1189. return usage, err
  1190. }
  1191. response := helper.GenerateFinalUsageResponse(id, createAt, info.UpstreamModelName, *usage)
  1192. handleErr := handleFinalStream(c, info, response)
  1193. if handleErr != nil {
  1194. common.SysLog("send final response failed: " + handleErr.Error())
  1195. }
  1196. return usage, nil
  1197. }
  1198. func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1199. responseBody, err := io.ReadAll(resp.Body)
  1200. if err != nil {
  1201. return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1202. }
  1203. service.CloseResponseBodyGracefully(resp)
  1204. if common.DebugEnabled {
  1205. println(string(responseBody))
  1206. }
  1207. var geminiResponse dto.GeminiChatResponse
  1208. err = common.Unmarshal(responseBody, &geminiResponse)
  1209. if err != nil {
  1210. return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1211. }
  1212. if len(geminiResponse.Candidates) == 0 {
  1213. //return nil, types.NewOpenAIError(errors.New("no candidates returned"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1214. //if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
  1215. // return nil, types.NewOpenAIError(errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason), types.ErrorCodePromptBlocked, http.StatusBadRequest)
  1216. //} else {
  1217. // return nil, types.NewOpenAIError(errors.New("empty response from Gemini API"), types.ErrorCodeEmptyResponse, http.StatusInternalServerError)
  1218. //}
  1219. }
  1220. fullTextResponse := responseGeminiChat2OpenAI(c, &geminiResponse)
  1221. fullTextResponse.Model = info.UpstreamModelName
  1222. usage := dto.Usage{
  1223. PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
  1224. CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount,
  1225. TotalTokens: geminiResponse.UsageMetadata.TotalTokenCount,
  1226. }
  1227. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  1228. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  1229. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  1230. if detail.Modality == "AUDIO" {
  1231. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  1232. } else if detail.Modality == "TEXT" {
  1233. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  1234. }
  1235. }
  1236. fullTextResponse.Usage = usage
  1237. switch info.RelayFormat {
  1238. case types.RelayFormatOpenAI:
  1239. responseBody, err = common.Marshal(fullTextResponse)
  1240. if err != nil {
  1241. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  1242. }
  1243. case types.RelayFormatClaude:
  1244. claudeResp := service.ResponseOpenAI2Claude(fullTextResponse, info)
  1245. claudeRespStr, err := common.Marshal(claudeResp)
  1246. if err != nil {
  1247. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  1248. }
  1249. responseBody = claudeRespStr
  1250. case types.RelayFormatGemini:
  1251. break
  1252. }
  1253. service.IOCopyBytesGracefully(c, resp, responseBody)
  1254. return &usage, nil
  1255. }
  1256. func GeminiEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1257. defer service.CloseResponseBodyGracefully(resp)
  1258. responseBody, readErr := io.ReadAll(resp.Body)
  1259. if readErr != nil {
  1260. return nil, types.NewOpenAIError(readErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1261. }
  1262. var geminiResponse dto.GeminiBatchEmbeddingResponse
  1263. if jsonErr := common.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  1264. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1265. }
  1266. // convert to openai format response
  1267. openAIResponse := dto.OpenAIEmbeddingResponse{
  1268. Object: "list",
  1269. Data: make([]dto.OpenAIEmbeddingResponseItem, 0, len(geminiResponse.Embeddings)),
  1270. Model: info.UpstreamModelName,
  1271. }
  1272. for i, embedding := range geminiResponse.Embeddings {
  1273. openAIResponse.Data = append(openAIResponse.Data, dto.OpenAIEmbeddingResponseItem{
  1274. Object: "embedding",
  1275. Embedding: embedding.Values,
  1276. Index: i,
  1277. })
  1278. }
  1279. // calculate usage
  1280. // https://ai.google.dev/gemini-api/docs/pricing?hl=zh-cn#text-embedding-004
  1281. // Google has not yet clarified how embedding models will be billed
  1282. // refer to openai billing method to use input tokens billing
  1283. // https://platform.openai.com/docs/guides/embeddings#what-are-embeddings
  1284. usage := service.ResponseText2Usage(c, "", info.UpstreamModelName, info.GetEstimatePromptTokens())
  1285. openAIResponse.Usage = *usage
  1286. jsonResponse, jsonErr := common.Marshal(openAIResponse)
  1287. if jsonErr != nil {
  1288. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1289. }
  1290. service.IOCopyBytesGracefully(c, resp, jsonResponse)
  1291. return usage, nil
  1292. }
  1293. func GeminiImageHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1294. responseBody, readErr := io.ReadAll(resp.Body)
  1295. if readErr != nil {
  1296. return nil, types.NewOpenAIError(readErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1297. }
  1298. _ = resp.Body.Close()
  1299. var geminiResponse dto.GeminiImageResponse
  1300. if jsonErr := common.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  1301. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1302. }
  1303. if len(geminiResponse.Predictions) == 0 {
  1304. return nil, types.NewOpenAIError(errors.New("no images generated"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1305. }
  1306. // convert to openai format response
  1307. openAIResponse := dto.ImageResponse{
  1308. Created: common.GetTimestamp(),
  1309. Data: make([]dto.ImageData, 0, len(geminiResponse.Predictions)),
  1310. }
  1311. for _, prediction := range geminiResponse.Predictions {
  1312. if prediction.RaiFilteredReason != "" {
  1313. continue // skip filtered image
  1314. }
  1315. openAIResponse.Data = append(openAIResponse.Data, dto.ImageData{
  1316. B64Json: prediction.BytesBase64Encoded,
  1317. })
  1318. }
  1319. jsonResponse, jsonErr := json.Marshal(openAIResponse)
  1320. if jsonErr != nil {
  1321. return nil, types.NewError(jsonErr, types.ErrorCodeBadResponseBody)
  1322. }
  1323. c.Writer.Header().Set("Content-Type", "application/json")
  1324. c.Writer.WriteHeader(resp.StatusCode)
  1325. _, _ = c.Writer.Write(jsonResponse)
  1326. // https://github.com/google-gemini/cookbook/blob/719a27d752aac33f39de18a8d3cb42a70874917e/quickstarts/Counting_Tokens.ipynb
  1327. // each image has fixed 258 tokens
  1328. const imageTokens = 258
  1329. generatedImages := len(openAIResponse.Data)
  1330. usage := &dto.Usage{
  1331. PromptTokens: imageTokens * generatedImages, // each generated image has fixed 258 tokens
  1332. CompletionTokens: 0, // image generation does not calculate completion tokens
  1333. TotalTokens: imageTokens * generatedImages,
  1334. }
  1335. return usage, nil
  1336. }
  1337. type GeminiModelsResponse struct {
  1338. Models []dto.GeminiModel `json:"models"`
  1339. NextPageToken string `json:"nextPageToken"`
  1340. }
  1341. func FetchGeminiModels(baseURL, apiKey, proxyURL string) ([]string, error) {
  1342. client, err := service.GetHttpClientWithProxy(proxyURL)
  1343. if err != nil {
  1344. return nil, fmt.Errorf("创建HTTP客户端失败: %v", err)
  1345. }
  1346. allModels := make([]string, 0)
  1347. nextPageToken := ""
  1348. maxPages := 100 // Safety limit to prevent infinite loops
  1349. for page := 0; page < maxPages; page++ {
  1350. url := fmt.Sprintf("%s/v1beta/models", baseURL)
  1351. if nextPageToken != "" {
  1352. url = fmt.Sprintf("%s?pageToken=%s", url, nextPageToken)
  1353. }
  1354. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  1355. request, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  1356. if err != nil {
  1357. cancel()
  1358. return nil, fmt.Errorf("创建请求失败: %v", err)
  1359. }
  1360. request.Header.Set("x-goog-api-key", apiKey)
  1361. response, err := client.Do(request)
  1362. if err != nil {
  1363. cancel()
  1364. return nil, fmt.Errorf("请求失败: %v", err)
  1365. }
  1366. if response.StatusCode != http.StatusOK {
  1367. body, _ := io.ReadAll(response.Body)
  1368. response.Body.Close()
  1369. cancel()
  1370. return nil, fmt.Errorf("服务器返回错误 %d: %s", response.StatusCode, string(body))
  1371. }
  1372. body, err := io.ReadAll(response.Body)
  1373. response.Body.Close()
  1374. cancel()
  1375. if err != nil {
  1376. return nil, fmt.Errorf("读取响应失败: %v", err)
  1377. }
  1378. var modelsResponse GeminiModelsResponse
  1379. if err = common.Unmarshal(body, &modelsResponse); err != nil {
  1380. return nil, fmt.Errorf("解析响应失败: %v", err)
  1381. }
  1382. for _, model := range modelsResponse.Models {
  1383. modelNameValue, ok := model.Name.(string)
  1384. if !ok {
  1385. continue
  1386. }
  1387. modelName := strings.TrimPrefix(modelNameValue, "models/")
  1388. allModels = append(allModels, modelName)
  1389. }
  1390. nextPageToken = modelsResponse.NextPageToken
  1391. if nextPageToken == "" {
  1392. break
  1393. }
  1394. }
  1395. return allModels, nil
  1396. }