relay-gemini.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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. if stopSequences := parseStopSequences(textRequest.Stop); len(stopSequences) > 0 {
  203. // Gemini supports up to 5 stop sequences
  204. if len(stopSequences) > 5 {
  205. stopSequences = stopSequences[:5]
  206. }
  207. geminiRequest.GenerationConfig.StopSequences = stopSequences
  208. }
  209. adaptorWithExtraBody := false
  210. // patch extra_body
  211. if len(textRequest.ExtraBody) > 0 {
  212. if !strings.HasSuffix(info.UpstreamModelName, "-nothinking") {
  213. var extraBody map[string]interface{}
  214. if err := common.Unmarshal(textRequest.ExtraBody, &extraBody); err != nil {
  215. return nil, fmt.Errorf("invalid extra body: %w", err)
  216. }
  217. // eg. {"google":{"thinking_config":{"thinking_budget":5324,"include_thoughts":true}}}
  218. if googleBody, ok := extraBody["google"].(map[string]interface{}); ok {
  219. adaptorWithExtraBody = true
  220. // check error param name like thinkingConfig, should be thinking_config
  221. if _, hasErrorParam := googleBody["thinkingConfig"]; hasErrorParam {
  222. return nil, errors.New("extra_body.google.thinkingConfig is not supported, use extra_body.google.thinking_config instead")
  223. }
  224. if thinkingConfig, ok := googleBody["thinking_config"].(map[string]interface{}); ok {
  225. // check error param name like thinkingBudget, should be thinking_budget
  226. if _, hasErrorParam := thinkingConfig["thinkingBudget"]; hasErrorParam {
  227. return nil, errors.New("extra_body.google.thinking_config.thinkingBudget is not supported, use extra_body.google.thinking_config.thinking_budget instead")
  228. }
  229. if budget, ok := thinkingConfig["thinking_budget"].(float64); ok {
  230. budgetInt := int(budget)
  231. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  232. ThinkingBudget: common.GetPointer(budgetInt),
  233. IncludeThoughts: true,
  234. }
  235. } else {
  236. geminiRequest.GenerationConfig.ThinkingConfig = &dto.GeminiThinkingConfig{
  237. IncludeThoughts: true,
  238. }
  239. }
  240. }
  241. // check error param name like imageConfig, should be image_config
  242. if _, hasErrorParam := googleBody["imageConfig"]; hasErrorParam {
  243. return nil, errors.New("extra_body.google.imageConfig is not supported, use extra_body.google.image_config instead")
  244. }
  245. if imageConfig, ok := googleBody["image_config"].(map[string]interface{}); ok {
  246. // check error param name like aspectRatio, should be aspect_ratio
  247. if _, hasErrorParam := imageConfig["aspectRatio"]; hasErrorParam {
  248. return nil, errors.New("extra_body.google.image_config.aspectRatio is not supported, use extra_body.google.image_config.aspect_ratio instead")
  249. }
  250. // check error param name like imageSize, should be image_size
  251. if _, hasErrorParam := imageConfig["imageSize"]; hasErrorParam {
  252. return nil, errors.New("extra_body.google.image_config.imageSize is not supported, use extra_body.google.image_config.image_size instead")
  253. }
  254. // convert snake_case to camelCase for Gemini API
  255. geminiImageConfig := make(map[string]interface{})
  256. if aspectRatio, ok := imageConfig["aspect_ratio"]; ok {
  257. geminiImageConfig["aspectRatio"] = aspectRatio
  258. }
  259. if imageSize, ok := imageConfig["image_size"]; ok {
  260. geminiImageConfig["imageSize"] = imageSize
  261. }
  262. if len(geminiImageConfig) > 0 {
  263. imageConfigBytes, err := common.Marshal(geminiImageConfig)
  264. if err != nil {
  265. return nil, fmt.Errorf("failed to marshal image_config: %w", err)
  266. }
  267. geminiRequest.GenerationConfig.ImageConfig = imageConfigBytes
  268. }
  269. }
  270. }
  271. }
  272. }
  273. if !adaptorWithExtraBody {
  274. ThinkingAdaptor(&geminiRequest, info, textRequest)
  275. }
  276. safetySettings := make([]dto.GeminiChatSafetySettings, 0, len(SafetySettingList))
  277. for _, category := range SafetySettingList {
  278. safetySettings = append(safetySettings, dto.GeminiChatSafetySettings{
  279. Category: category,
  280. Threshold: model_setting.GetGeminiSafetySetting(category),
  281. })
  282. }
  283. geminiRequest.SafetySettings = safetySettings
  284. // openaiContent.FuncToToolCalls()
  285. if textRequest.Tools != nil {
  286. functions := make([]dto.FunctionRequest, 0, len(textRequest.Tools))
  287. googleSearch := false
  288. codeExecution := false
  289. urlContext := false
  290. for _, tool := range textRequest.Tools {
  291. if tool.Function.Name == "googleSearch" {
  292. googleSearch = true
  293. continue
  294. }
  295. if tool.Function.Name == "codeExecution" {
  296. codeExecution = true
  297. continue
  298. }
  299. if tool.Function.Name == "urlContext" {
  300. urlContext = true
  301. continue
  302. }
  303. if tool.Function.Parameters != nil {
  304. params, ok := tool.Function.Parameters.(map[string]interface{})
  305. if ok {
  306. if props, hasProps := params["properties"].(map[string]interface{}); hasProps {
  307. if len(props) == 0 {
  308. tool.Function.Parameters = nil
  309. }
  310. }
  311. }
  312. }
  313. // Clean the parameters before appending
  314. cleanedParams := cleanFunctionParameters(tool.Function.Parameters)
  315. tool.Function.Parameters = cleanedParams
  316. functions = append(functions, tool.Function)
  317. }
  318. geminiTools := geminiRequest.GetTools()
  319. if codeExecution {
  320. geminiTools = append(geminiTools, dto.GeminiChatTool{
  321. CodeExecution: make(map[string]string),
  322. })
  323. }
  324. if googleSearch {
  325. geminiTools = append(geminiTools, dto.GeminiChatTool{
  326. GoogleSearch: make(map[string]string),
  327. })
  328. }
  329. if urlContext {
  330. geminiTools = append(geminiTools, dto.GeminiChatTool{
  331. URLContext: make(map[string]string),
  332. })
  333. }
  334. if len(functions) > 0 {
  335. geminiTools = append(geminiTools, dto.GeminiChatTool{
  336. FunctionDeclarations: functions,
  337. })
  338. }
  339. geminiRequest.SetTools(geminiTools)
  340. // [NEW] Convert OpenAI tool_choice to Gemini toolConfig.functionCallingConfig
  341. // Mapping: "auto" -> "AUTO", "none" -> "NONE", "required" -> "ANY"
  342. // Object format: {"type": "function", "function": {"name": "xxx"}} -> "ANY" + allowedFunctionNames
  343. if textRequest.ToolChoice != nil {
  344. geminiRequest.ToolConfig = convertToolChoiceToGeminiConfig(textRequest.ToolChoice)
  345. }
  346. }
  347. if textRequest.ResponseFormat != nil && (textRequest.ResponseFormat.Type == "json_schema" || textRequest.ResponseFormat.Type == "json_object") {
  348. geminiRequest.GenerationConfig.ResponseMimeType = "application/json"
  349. if len(textRequest.ResponseFormat.JsonSchema) > 0 {
  350. // 先将json.RawMessage解析
  351. var jsonSchema dto.FormatJsonSchema
  352. if err := common.Unmarshal(textRequest.ResponseFormat.JsonSchema, &jsonSchema); err == nil {
  353. cleanedSchema := removeAdditionalPropertiesWithDepth(jsonSchema.Schema, 0)
  354. geminiRequest.GenerationConfig.ResponseSchema = cleanedSchema
  355. }
  356. }
  357. }
  358. tool_call_ids := make(map[string]string)
  359. var system_content []string
  360. //shouldAddDummyModelMessage := false
  361. for _, message := range textRequest.Messages {
  362. if message.Role == "system" || message.Role == "developer" {
  363. system_content = append(system_content, message.StringContent())
  364. continue
  365. } else if message.Role == "tool" || message.Role == "function" {
  366. if len(geminiRequest.Contents) == 0 || geminiRequest.Contents[len(geminiRequest.Contents)-1].Role == "model" {
  367. geminiRequest.Contents = append(geminiRequest.Contents, dto.GeminiChatContent{
  368. Role: "user",
  369. })
  370. }
  371. var parts = &geminiRequest.Contents[len(geminiRequest.Contents)-1].Parts
  372. name := ""
  373. if message.Name != nil {
  374. name = *message.Name
  375. } else if val, exists := tool_call_ids[message.ToolCallId]; exists {
  376. name = val
  377. }
  378. var contentMap map[string]interface{}
  379. contentStr := message.StringContent()
  380. // 1. 尝试解析为 JSON 对象
  381. if err := json.Unmarshal([]byte(contentStr), &contentMap); err != nil {
  382. // 2. 如果失败,尝试解析为 JSON 数组
  383. var contentSlice []interface{}
  384. if err := json.Unmarshal([]byte(contentStr), &contentSlice); err == nil {
  385. // 如果是数组,包装成对象
  386. contentMap = map[string]interface{}{"result": contentSlice}
  387. } else {
  388. // 3. 如果再次失败,作为纯文本处理
  389. contentMap = map[string]interface{}{"content": contentStr}
  390. }
  391. }
  392. functionResp := &dto.GeminiFunctionResponse{
  393. Name: name,
  394. Response: contentMap,
  395. }
  396. *parts = append(*parts, dto.GeminiPart{
  397. FunctionResponse: functionResp,
  398. })
  399. continue
  400. }
  401. var parts []dto.GeminiPart
  402. content := dto.GeminiChatContent{
  403. Role: message.Role,
  404. }
  405. shouldAttachThoughtSignature := attachThoughtSignature && (message.Role == "assistant" || message.Role == "model")
  406. signatureAttached := false
  407. // isToolCall := false
  408. if message.ToolCalls != nil {
  409. // message.Role = "model"
  410. // isToolCall = true
  411. for _, call := range message.ParseToolCalls() {
  412. args := map[string]interface{}{}
  413. if call.Function.Arguments != "" {
  414. if json.Unmarshal([]byte(call.Function.Arguments), &args) != nil {
  415. return nil, fmt.Errorf("invalid arguments for function %s, args: %s", call.Function.Name, call.Function.Arguments)
  416. }
  417. }
  418. toolCall := dto.GeminiPart{
  419. FunctionCall: &dto.FunctionCall{
  420. FunctionName: call.Function.Name,
  421. Arguments: args,
  422. },
  423. }
  424. if shouldAttachThoughtSignature && !signatureAttached && hasFunctionCallContent(toolCall.FunctionCall) && len(toolCall.ThoughtSignature) == 0 {
  425. toolCall.ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  426. signatureAttached = true
  427. }
  428. parts = append(parts, toolCall)
  429. tool_call_ids[call.ID] = call.Function.Name
  430. }
  431. }
  432. openaiContent := message.ParseContent()
  433. imageNum := 0
  434. for _, part := range openaiContent {
  435. if part.Type == dto.ContentTypeText {
  436. if part.Text == "" {
  437. continue
  438. }
  439. // check markdown image ![image](data:image/jpeg;base64,xxxxxxxxxxxx)
  440. // 使用字符串查找而非正则,避免大文本性能问题
  441. text := part.Text
  442. hasMarkdownImage := false
  443. for {
  444. // 快速检查是否包含 markdown 图片标记
  445. startIdx := strings.Index(text, "![")
  446. if startIdx == -1 {
  447. break
  448. }
  449. // 找到 ](
  450. bracketIdx := strings.Index(text[startIdx:], "](data:")
  451. if bracketIdx == -1 {
  452. break
  453. }
  454. bracketIdx += startIdx
  455. // 找到闭合的 )
  456. closeIdx := strings.Index(text[bracketIdx+2:], ")")
  457. if closeIdx == -1 {
  458. break
  459. }
  460. closeIdx += bracketIdx + 2
  461. hasMarkdownImage = true
  462. // 添加图片前的文本
  463. if startIdx > 0 {
  464. textBefore := text[:startIdx]
  465. if textBefore != "" {
  466. parts = append(parts, dto.GeminiPart{
  467. Text: textBefore,
  468. })
  469. }
  470. }
  471. // 提取 data URL (从 "](" 后面开始,到 ")" 之前)
  472. dataUrl := text[bracketIdx+2 : closeIdx]
  473. imageNum += 1
  474. if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
  475. return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
  476. }
  477. format, base64String, err := service.DecodeBase64FileData(dataUrl)
  478. if err != nil {
  479. return nil, fmt.Errorf("decode markdown base64 image data failed: %s", err.Error())
  480. }
  481. imgPart := dto.GeminiPart{
  482. InlineData: &dto.GeminiInlineData{
  483. MimeType: format,
  484. Data: base64String,
  485. },
  486. }
  487. if shouldAttachThoughtSignature {
  488. imgPart.ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  489. }
  490. parts = append(parts, imgPart)
  491. // 继续处理剩余文本
  492. text = text[closeIdx+1:]
  493. }
  494. // 添加剩余文本或原始文本(如果没有找到 markdown 图片)
  495. if !hasMarkdownImage {
  496. parts = append(parts, dto.GeminiPart{
  497. Text: part.Text,
  498. })
  499. }
  500. } else if part.Type == dto.ContentTypeImageURL {
  501. imageNum += 1
  502. if constant.GeminiVisionMaxImageNum != -1 && imageNum > constant.GeminiVisionMaxImageNum {
  503. return nil, fmt.Errorf("too many images in the message, max allowed is %d", constant.GeminiVisionMaxImageNum)
  504. }
  505. // 判断是否是url
  506. if strings.HasPrefix(part.GetImageMedia().Url, "http") {
  507. // 是url,获取文件的类型和base64编码的数据
  508. fileData, err := service.GetFileBase64FromUrl(c, part.GetImageMedia().Url, "formatting image for Gemini")
  509. if err != nil {
  510. return nil, fmt.Errorf("get file base64 from url '%s' failed: %w", part.GetImageMedia().Url, err)
  511. }
  512. // 校验 MimeType 是否在 Gemini 支持的白名单中
  513. if _, ok := geminiSupportedMimeTypes[strings.ToLower(fileData.MimeType)]; !ok {
  514. url := part.GetImageMedia().Url
  515. return nil, fmt.Errorf("mime type is not supported by Gemini: '%s', url: '%s', supported types are: %v", fileData.MimeType, url, getSupportedMimeTypesList())
  516. }
  517. parts = append(parts, dto.GeminiPart{
  518. InlineData: &dto.GeminiInlineData{
  519. MimeType: fileData.MimeType, // 使用原始的 MimeType,因为大小写可能对API有意义
  520. Data: fileData.Base64Data,
  521. },
  522. })
  523. } else {
  524. format, base64String, err := service.DecodeBase64FileData(part.GetImageMedia().Url)
  525. if err != nil {
  526. return nil, fmt.Errorf("decode base64 image data failed: %s", err.Error())
  527. }
  528. parts = append(parts, dto.GeminiPart{
  529. InlineData: &dto.GeminiInlineData{
  530. MimeType: format,
  531. Data: base64String,
  532. },
  533. })
  534. }
  535. } else if part.Type == dto.ContentTypeFile {
  536. if part.GetFile().FileId != "" {
  537. return nil, fmt.Errorf("only base64 file is supported in gemini")
  538. }
  539. format, base64String, err := service.DecodeBase64FileData(part.GetFile().FileData)
  540. if err != nil {
  541. return nil, fmt.Errorf("decode base64 file data failed: %s", err.Error())
  542. }
  543. parts = append(parts, dto.GeminiPart{
  544. InlineData: &dto.GeminiInlineData{
  545. MimeType: format,
  546. Data: base64String,
  547. },
  548. })
  549. } else if part.Type == dto.ContentTypeInputAudio {
  550. if part.GetInputAudio().Data == "" {
  551. return nil, fmt.Errorf("only base64 audio is supported in gemini")
  552. }
  553. base64String, err := service.DecodeBase64AudioData(part.GetInputAudio().Data)
  554. if err != nil {
  555. return nil, fmt.Errorf("decode base64 audio data failed: %s", err.Error())
  556. }
  557. parts = append(parts, dto.GeminiPart{
  558. InlineData: &dto.GeminiInlineData{
  559. MimeType: "audio/" + part.GetInputAudio().Format,
  560. Data: base64String,
  561. },
  562. })
  563. }
  564. }
  565. // 如果需要附加签名但还没有附加(没有 tool_calls 或 tool_calls 为空),
  566. // 则在第一个文本 part 上附加 thoughtSignature
  567. if shouldAttachThoughtSignature && !signatureAttached && len(parts) > 0 {
  568. for i := range parts {
  569. if parts[i].Text != "" {
  570. parts[i].ThoughtSignature = json.RawMessage(strconv.Quote(thoughtSignatureBypassValue))
  571. break
  572. }
  573. }
  574. }
  575. content.Parts = parts
  576. // there's no assistant role in gemini and API shall vomit if Role is not user or model
  577. if content.Role == "assistant" {
  578. content.Role = "model"
  579. }
  580. if len(content.Parts) > 0 {
  581. geminiRequest.Contents = append(geminiRequest.Contents, content)
  582. }
  583. }
  584. if len(system_content) > 0 {
  585. geminiRequest.SystemInstructions = &dto.GeminiChatContent{
  586. Parts: []dto.GeminiPart{
  587. {
  588. Text: strings.Join(system_content, "\n"),
  589. },
  590. },
  591. }
  592. }
  593. return &geminiRequest, nil
  594. }
  595. // parseStopSequences 解析停止序列,支持字符串或字符串数组
  596. func parseStopSequences(stop any) []string {
  597. if stop == nil {
  598. return nil
  599. }
  600. switch v := stop.(type) {
  601. case string:
  602. if v != "" {
  603. return []string{v}
  604. }
  605. case []string:
  606. return v
  607. case []interface{}:
  608. sequences := make([]string, 0, len(v))
  609. for _, item := range v {
  610. if str, ok := item.(string); ok && str != "" {
  611. sequences = append(sequences, str)
  612. }
  613. }
  614. return sequences
  615. }
  616. return nil
  617. }
  618. func hasFunctionCallContent(call *dto.FunctionCall) bool {
  619. if call == nil {
  620. return false
  621. }
  622. if strings.TrimSpace(call.FunctionName) != "" {
  623. return true
  624. }
  625. switch v := call.Arguments.(type) {
  626. case nil:
  627. return false
  628. case string:
  629. return strings.TrimSpace(v) != ""
  630. case map[string]interface{}:
  631. return len(v) > 0
  632. case []interface{}:
  633. return len(v) > 0
  634. default:
  635. return true
  636. }
  637. }
  638. // Helper function to get a list of supported MIME types for error messages
  639. func getSupportedMimeTypesList() []string {
  640. keys := make([]string, 0, len(geminiSupportedMimeTypes))
  641. for k := range geminiSupportedMimeTypes {
  642. keys = append(keys, k)
  643. }
  644. return keys
  645. }
  646. var geminiOpenAPISchemaAllowedFields = map[string]struct{}{
  647. "anyOf": {},
  648. "default": {},
  649. "description": {},
  650. "enum": {},
  651. "example": {},
  652. "format": {},
  653. "items": {},
  654. "maxItems": {},
  655. "maxLength": {},
  656. "maxProperties": {},
  657. "maximum": {},
  658. "minItems": {},
  659. "minLength": {},
  660. "minProperties": {},
  661. "minimum": {},
  662. "nullable": {},
  663. "pattern": {},
  664. "properties": {},
  665. "propertyOrdering": {},
  666. "required": {},
  667. "title": {},
  668. "type": {},
  669. }
  670. const geminiFunctionSchemaMaxDepth = 64
  671. // cleanFunctionParameters recursively removes unsupported fields from Gemini function parameters.
  672. func cleanFunctionParameters(params interface{}) interface{} {
  673. return cleanFunctionParametersWithDepth(params, 0)
  674. }
  675. func cleanFunctionParametersWithDepth(params interface{}, depth int) interface{} {
  676. if params == nil {
  677. return nil
  678. }
  679. if depth >= geminiFunctionSchemaMaxDepth {
  680. return cleanFunctionParametersShallow(params)
  681. }
  682. switch v := params.(type) {
  683. case map[string]interface{}:
  684. // Keep only Gemini-supported OpenAPI schema subset fields (per official SDK Schema).
  685. cleanedMap := make(map[string]interface{}, len(v))
  686. for k, val := range v {
  687. if _, ok := geminiOpenAPISchemaAllowedFields[k]; ok {
  688. cleanedMap[k] = val
  689. }
  690. }
  691. normalizeGeminiSchemaTypeAndNullable(cleanedMap)
  692. // Clean properties
  693. if props, ok := cleanedMap["properties"].(map[string]interface{}); ok && props != nil {
  694. cleanedProps := make(map[string]interface{})
  695. for propName, propValue := range props {
  696. cleanedProps[propName] = cleanFunctionParametersWithDepth(propValue, depth+1)
  697. }
  698. cleanedMap["properties"] = cleanedProps
  699. }
  700. // Recursively clean items in arrays
  701. if items, ok := cleanedMap["items"].(map[string]interface{}); ok && items != nil {
  702. cleanedMap["items"] = cleanFunctionParametersWithDepth(items, depth+1)
  703. }
  704. // OpenAPI tuple-style items is not supported by Gemini SDK Schema; keep first to avoid API rejection.
  705. if itemsArray, ok := cleanedMap["items"].([]interface{}); ok && len(itemsArray) > 0 {
  706. cleanedMap["items"] = cleanFunctionParametersWithDepth(itemsArray[0], depth+1)
  707. }
  708. // Recursively clean anyOf
  709. if nested, ok := cleanedMap["anyOf"].([]interface{}); ok && nested != nil {
  710. cleanedNested := make([]interface{}, len(nested))
  711. for i, item := range nested {
  712. cleanedNested[i] = cleanFunctionParametersWithDepth(item, depth+1)
  713. }
  714. cleanedMap["anyOf"] = cleanedNested
  715. }
  716. return cleanedMap
  717. case []interface{}:
  718. // Handle arrays of schemas
  719. cleanedArray := make([]interface{}, len(v))
  720. for i, item := range v {
  721. cleanedArray[i] = cleanFunctionParametersWithDepth(item, depth+1)
  722. }
  723. return cleanedArray
  724. default:
  725. // Not a map or array, return as is (e.g., could be a primitive)
  726. return params
  727. }
  728. }
  729. func cleanFunctionParametersShallow(params interface{}) interface{} {
  730. switch v := params.(type) {
  731. case map[string]interface{}:
  732. cleanedMap := make(map[string]interface{}, len(v))
  733. for k, val := range v {
  734. if _, ok := geminiOpenAPISchemaAllowedFields[k]; ok {
  735. cleanedMap[k] = val
  736. }
  737. }
  738. normalizeGeminiSchemaTypeAndNullable(cleanedMap)
  739. // Stop recursion and avoid retaining huge nested structures.
  740. delete(cleanedMap, "properties")
  741. delete(cleanedMap, "items")
  742. delete(cleanedMap, "anyOf")
  743. return cleanedMap
  744. case []interface{}:
  745. // Prefer an empty list over deep recursion on attacker-controlled inputs.
  746. return []interface{}{}
  747. default:
  748. return params
  749. }
  750. }
  751. func normalizeGeminiSchemaTypeAndNullable(schema map[string]interface{}) {
  752. rawType, ok := schema["type"]
  753. if !ok || rawType == nil {
  754. return
  755. }
  756. normalize := func(t string) (string, bool) {
  757. switch strings.ToLower(strings.TrimSpace(t)) {
  758. case "object":
  759. return "OBJECT", false
  760. case "array":
  761. return "ARRAY", false
  762. case "string":
  763. return "STRING", false
  764. case "integer":
  765. return "INTEGER", false
  766. case "number":
  767. return "NUMBER", false
  768. case "boolean":
  769. return "BOOLEAN", false
  770. case "null":
  771. return "", true
  772. default:
  773. return t, false
  774. }
  775. }
  776. switch t := rawType.(type) {
  777. case string:
  778. normalized, isNull := normalize(t)
  779. if isNull {
  780. schema["nullable"] = true
  781. delete(schema, "type")
  782. return
  783. }
  784. schema["type"] = normalized
  785. case []interface{}:
  786. nullable := false
  787. var chosen string
  788. for _, item := range t {
  789. if s, ok := item.(string); ok {
  790. normalized, isNull := normalize(s)
  791. if isNull {
  792. nullable = true
  793. continue
  794. }
  795. if chosen == "" {
  796. chosen = normalized
  797. }
  798. }
  799. }
  800. if nullable {
  801. schema["nullable"] = true
  802. }
  803. if chosen != "" {
  804. schema["type"] = chosen
  805. } else {
  806. delete(schema, "type")
  807. }
  808. }
  809. }
  810. func removeAdditionalPropertiesWithDepth(schema interface{}, depth int) interface{} {
  811. if depth >= 5 {
  812. return schema
  813. }
  814. v, ok := schema.(map[string]interface{})
  815. if !ok || len(v) == 0 {
  816. return schema
  817. }
  818. // 删除所有的title字段
  819. delete(v, "title")
  820. delete(v, "$schema")
  821. // 如果type不为object和array,则直接返回
  822. if typeVal, exists := v["type"]; !exists || (typeVal != "object" && typeVal != "array") {
  823. return schema
  824. }
  825. switch v["type"] {
  826. case "object":
  827. delete(v, "additionalProperties")
  828. // 处理 properties
  829. if properties, ok := v["properties"].(map[string]interface{}); ok {
  830. for key, value := range properties {
  831. properties[key] = removeAdditionalPropertiesWithDepth(value, depth+1)
  832. }
  833. }
  834. for _, field := range []string{"allOf", "anyOf", "oneOf"} {
  835. if nested, ok := v[field].([]interface{}); ok {
  836. for i, item := range nested {
  837. nested[i] = removeAdditionalPropertiesWithDepth(item, depth+1)
  838. }
  839. }
  840. }
  841. case "array":
  842. if items, ok := v["items"].(map[string]interface{}); ok {
  843. v["items"] = removeAdditionalPropertiesWithDepth(items, depth+1)
  844. }
  845. }
  846. return v
  847. }
  848. func unescapeString(s string) (string, error) {
  849. var result []rune
  850. escaped := false
  851. i := 0
  852. for i < len(s) {
  853. r, size := utf8.DecodeRuneInString(s[i:]) // 正确解码UTF-8字符
  854. if r == utf8.RuneError {
  855. return "", fmt.Errorf("invalid UTF-8 encoding")
  856. }
  857. if escaped {
  858. // 如果是转义符后的字符,检查其类型
  859. switch r {
  860. case '"':
  861. result = append(result, '"')
  862. case '\\':
  863. result = append(result, '\\')
  864. case '/':
  865. result = append(result, '/')
  866. case 'b':
  867. result = append(result, '\b')
  868. case 'f':
  869. result = append(result, '\f')
  870. case 'n':
  871. result = append(result, '\n')
  872. case 'r':
  873. result = append(result, '\r')
  874. case 't':
  875. result = append(result, '\t')
  876. case '\'':
  877. result = append(result, '\'')
  878. default:
  879. // 如果遇到一个非法的转义字符,直接按原样输出
  880. result = append(result, '\\', r)
  881. }
  882. escaped = false
  883. } else {
  884. if r == '\\' {
  885. escaped = true // 记录反斜杠作为转义符
  886. } else {
  887. result = append(result, r)
  888. }
  889. }
  890. i += size // 移动到下一个字符
  891. }
  892. return string(result), nil
  893. }
  894. func unescapeMapOrSlice(data interface{}) interface{} {
  895. switch v := data.(type) {
  896. case map[string]interface{}:
  897. for k, val := range v {
  898. v[k] = unescapeMapOrSlice(val)
  899. }
  900. case []interface{}:
  901. for i, val := range v {
  902. v[i] = unescapeMapOrSlice(val)
  903. }
  904. case string:
  905. if unescaped, err := unescapeString(v); err != nil {
  906. return v
  907. } else {
  908. return unescaped
  909. }
  910. }
  911. return data
  912. }
  913. func getResponseToolCall(item *dto.GeminiPart) *dto.ToolCallResponse {
  914. var argsBytes []byte
  915. var err error
  916. // 移除 unescapeMapOrSlice 调用,直接使用 json.Marshal
  917. // JSON 序列化/反序列化已经正确处理了转义字符
  918. argsBytes, err = json.Marshal(item.FunctionCall.Arguments)
  919. if err != nil {
  920. return nil
  921. }
  922. return &dto.ToolCallResponse{
  923. ID: fmt.Sprintf("call_%s", common.GetUUID()),
  924. Type: "function",
  925. Function: dto.FunctionResponse{
  926. Arguments: string(argsBytes),
  927. Name: item.FunctionCall.FunctionName,
  928. },
  929. }
  930. }
  931. func responseGeminiChat2OpenAI(c *gin.Context, response *dto.GeminiChatResponse) *dto.OpenAITextResponse {
  932. fullTextResponse := dto.OpenAITextResponse{
  933. Id: helper.GetResponseID(c),
  934. Object: "chat.completion",
  935. Created: common.GetTimestamp(),
  936. Choices: make([]dto.OpenAITextResponseChoice, 0, len(response.Candidates)),
  937. }
  938. isToolCall := false
  939. for _, candidate := range response.Candidates {
  940. choice := dto.OpenAITextResponseChoice{
  941. Index: int(candidate.Index),
  942. Message: dto.Message{
  943. Role: "assistant",
  944. Content: "",
  945. },
  946. FinishReason: constant.FinishReasonStop,
  947. }
  948. if len(candidate.Content.Parts) > 0 {
  949. var texts []string
  950. var toolCalls []dto.ToolCallResponse
  951. for _, part := range candidate.Content.Parts {
  952. if part.InlineData != nil {
  953. // 媒体内容
  954. if strings.HasPrefix(part.InlineData.MimeType, "image") {
  955. imgText := "![image](data:" + part.InlineData.MimeType + ";base64," + part.InlineData.Data + ")"
  956. texts = append(texts, imgText)
  957. } else {
  958. // 其他媒体类型,直接显示链接
  959. texts = append(texts, fmt.Sprintf("[media](data:%s;base64,%s)", part.InlineData.MimeType, part.InlineData.Data))
  960. }
  961. } else if part.FunctionCall != nil {
  962. choice.FinishReason = constant.FinishReasonToolCalls
  963. if call := getResponseToolCall(&part); call != nil {
  964. toolCalls = append(toolCalls, *call)
  965. }
  966. } else if part.Thought {
  967. choice.Message.ReasoningContent = part.Text
  968. } else {
  969. if part.ExecutableCode != nil {
  970. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```")
  971. } else if part.CodeExecutionResult != nil {
  972. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```")
  973. } else {
  974. // 过滤掉空行
  975. if part.Text != "\n" {
  976. texts = append(texts, part.Text)
  977. }
  978. }
  979. }
  980. }
  981. if len(toolCalls) > 0 {
  982. choice.Message.SetToolCalls(toolCalls)
  983. isToolCall = true
  984. }
  985. choice.Message.SetStringContent(strings.Join(texts, "\n"))
  986. }
  987. if candidate.FinishReason != nil {
  988. switch *candidate.FinishReason {
  989. case "STOP":
  990. choice.FinishReason = constant.FinishReasonStop
  991. case "MAX_TOKENS":
  992. choice.FinishReason = constant.FinishReasonLength
  993. case "SAFETY":
  994. // Safety filter triggered
  995. choice.FinishReason = constant.FinishReasonContentFilter
  996. case "RECITATION":
  997. // Recitation (citation) detected
  998. choice.FinishReason = constant.FinishReasonContentFilter
  999. case "BLOCKLIST":
  1000. // Blocklist triggered
  1001. choice.FinishReason = constant.FinishReasonContentFilter
  1002. case "PROHIBITED_CONTENT":
  1003. // Prohibited content detected
  1004. choice.FinishReason = constant.FinishReasonContentFilter
  1005. case "SPII":
  1006. // Sensitive personally identifiable information
  1007. choice.FinishReason = constant.FinishReasonContentFilter
  1008. case "OTHER":
  1009. // Other reasons
  1010. choice.FinishReason = constant.FinishReasonContentFilter
  1011. default:
  1012. choice.FinishReason = constant.FinishReasonContentFilter
  1013. }
  1014. }
  1015. if isToolCall {
  1016. choice.FinishReason = constant.FinishReasonToolCalls
  1017. }
  1018. fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
  1019. }
  1020. return &fullTextResponse
  1021. }
  1022. func streamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*dto.ChatCompletionsStreamResponse, bool) {
  1023. choices := make([]dto.ChatCompletionsStreamResponseChoice, 0, len(geminiResponse.Candidates))
  1024. isStop := false
  1025. for _, candidate := range geminiResponse.Candidates {
  1026. if candidate.FinishReason != nil && *candidate.FinishReason == "STOP" {
  1027. isStop = true
  1028. candidate.FinishReason = nil
  1029. }
  1030. choice := dto.ChatCompletionsStreamResponseChoice{
  1031. Index: int(candidate.Index),
  1032. Delta: dto.ChatCompletionsStreamResponseChoiceDelta{
  1033. //Role: "assistant",
  1034. },
  1035. }
  1036. var texts []string
  1037. isTools := false
  1038. isThought := false
  1039. if candidate.FinishReason != nil {
  1040. // Map Gemini FinishReason to OpenAI finish_reason
  1041. switch *candidate.FinishReason {
  1042. case "STOP":
  1043. // Normal completion
  1044. choice.FinishReason = &constant.FinishReasonStop
  1045. case "MAX_TOKENS":
  1046. // Reached maximum token limit
  1047. choice.FinishReason = &constant.FinishReasonLength
  1048. case "SAFETY":
  1049. // Safety filter triggered
  1050. choice.FinishReason = &constant.FinishReasonContentFilter
  1051. case "RECITATION":
  1052. // Recitation (citation) detected
  1053. choice.FinishReason = &constant.FinishReasonContentFilter
  1054. case "BLOCKLIST":
  1055. // Blocklist triggered
  1056. choice.FinishReason = &constant.FinishReasonContentFilter
  1057. case "PROHIBITED_CONTENT":
  1058. // Prohibited content detected
  1059. choice.FinishReason = &constant.FinishReasonContentFilter
  1060. case "SPII":
  1061. // Sensitive personally identifiable information
  1062. choice.FinishReason = &constant.FinishReasonContentFilter
  1063. case "OTHER":
  1064. // Other reasons
  1065. choice.FinishReason = &constant.FinishReasonContentFilter
  1066. default:
  1067. // Unknown reason, treat as content filter
  1068. choice.FinishReason = &constant.FinishReasonContentFilter
  1069. }
  1070. }
  1071. for _, part := range candidate.Content.Parts {
  1072. if part.InlineData != nil {
  1073. if strings.HasPrefix(part.InlineData.MimeType, "image") {
  1074. imgText := "![image](data:" + part.InlineData.MimeType + ";base64," + part.InlineData.Data + ")"
  1075. texts = append(texts, imgText)
  1076. }
  1077. } else if part.FunctionCall != nil {
  1078. isTools = true
  1079. if call := getResponseToolCall(&part); call != nil {
  1080. call.SetIndex(len(choice.Delta.ToolCalls))
  1081. choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
  1082. }
  1083. } else if part.Thought {
  1084. isThought = true
  1085. texts = append(texts, part.Text)
  1086. } else {
  1087. if part.ExecutableCode != nil {
  1088. texts = append(texts, "```"+part.ExecutableCode.Language+"\n"+part.ExecutableCode.Code+"\n```\n")
  1089. } else if part.CodeExecutionResult != nil {
  1090. texts = append(texts, "```output\n"+part.CodeExecutionResult.Output+"\n```\n")
  1091. } else {
  1092. if part.Text != "\n" {
  1093. texts = append(texts, part.Text)
  1094. }
  1095. }
  1096. }
  1097. }
  1098. if isThought {
  1099. choice.Delta.SetReasoningContent(strings.Join(texts, "\n"))
  1100. } else {
  1101. choice.Delta.SetContentString(strings.Join(texts, "\n"))
  1102. }
  1103. if isTools {
  1104. choice.FinishReason = &constant.FinishReasonToolCalls
  1105. }
  1106. choices = append(choices, choice)
  1107. }
  1108. var response dto.ChatCompletionsStreamResponse
  1109. response.Object = "chat.completion.chunk"
  1110. response.Choices = choices
  1111. return &response, isStop
  1112. }
  1113. func handleStream(c *gin.Context, info *relaycommon.RelayInfo, resp *dto.ChatCompletionsStreamResponse) error {
  1114. streamData, err := common.Marshal(resp)
  1115. if err != nil {
  1116. return fmt.Errorf("failed to marshal stream response: %w", err)
  1117. }
  1118. err = openai.HandleStreamFormat(c, info, string(streamData), info.ChannelSetting.ForceFormat, info.ChannelSetting.ThinkingToContent)
  1119. if err != nil {
  1120. return fmt.Errorf("failed to handle stream format: %w", err)
  1121. }
  1122. return nil
  1123. }
  1124. func handleFinalStream(c *gin.Context, info *relaycommon.RelayInfo, resp *dto.ChatCompletionsStreamResponse) error {
  1125. streamData, err := common.Marshal(resp)
  1126. if err != nil {
  1127. return fmt.Errorf("failed to marshal stream response: %w", err)
  1128. }
  1129. openai.HandleFinalResponse(c, info, string(streamData), resp.Id, resp.Created, resp.Model, resp.GetSystemFingerprint(), resp.Usage, false)
  1130. return nil
  1131. }
  1132. func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response, callback func(data string, geminiResponse *dto.GeminiChatResponse) bool) (*dto.Usage, *types.NewAPIError) {
  1133. var usage = &dto.Usage{}
  1134. var imageCount int
  1135. responseText := strings.Builder{}
  1136. helper.StreamScannerHandler(c, resp, info, func(data string) bool {
  1137. var geminiResponse dto.GeminiChatResponse
  1138. err := common.UnmarshalJsonStr(data, &geminiResponse)
  1139. if err != nil {
  1140. logger.LogError(c, "error unmarshalling stream response: "+err.Error())
  1141. return false
  1142. }
  1143. if len(geminiResponse.Candidates) == 0 && geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
  1144. common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
  1145. }
  1146. // 统计图片数量
  1147. for _, candidate := range geminiResponse.Candidates {
  1148. for _, part := range candidate.Content.Parts {
  1149. if part.InlineData != nil && part.InlineData.MimeType != "" {
  1150. imageCount++
  1151. }
  1152. if part.Text != "" {
  1153. responseText.WriteString(part.Text)
  1154. }
  1155. }
  1156. }
  1157. // 更新使用量统计
  1158. if geminiResponse.UsageMetadata.TotalTokenCount != 0 {
  1159. usage.PromptTokens = geminiResponse.UsageMetadata.PromptTokenCount
  1160. usage.CompletionTokens = geminiResponse.UsageMetadata.CandidatesTokenCount + geminiResponse.UsageMetadata.ThoughtsTokenCount
  1161. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  1162. usage.TotalTokens = geminiResponse.UsageMetadata.TotalTokenCount
  1163. usage.PromptTokensDetails.CachedTokens = geminiResponse.UsageMetadata.CachedContentTokenCount
  1164. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  1165. if detail.Modality == "AUDIO" {
  1166. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  1167. } else if detail.Modality == "TEXT" {
  1168. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  1169. }
  1170. }
  1171. }
  1172. return callback(data, &geminiResponse)
  1173. })
  1174. if imageCount != 0 {
  1175. if usage.CompletionTokens == 0 {
  1176. usage.CompletionTokens = imageCount * 1400
  1177. }
  1178. }
  1179. usage.PromptTokensDetails.TextTokens = usage.PromptTokens
  1180. if usage.TotalTokens > 0 {
  1181. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  1182. }
  1183. if usage.CompletionTokens <= 0 {
  1184. str := responseText.String()
  1185. if len(str) > 0 {
  1186. usage = service.ResponseText2Usage(c, responseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
  1187. } else {
  1188. usage = &dto.Usage{}
  1189. }
  1190. }
  1191. return usage, nil
  1192. }
  1193. func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1194. id := helper.GetResponseID(c)
  1195. createAt := common.GetTimestamp()
  1196. finishReason := constant.FinishReasonStop
  1197. toolCallIndexByChoice := make(map[int]map[string]int)
  1198. nextToolCallIndexByChoice := make(map[int]int)
  1199. usage, err := geminiStreamHandler(c, info, resp, func(data string, geminiResponse *dto.GeminiChatResponse) bool {
  1200. response, isStop := streamResponseGeminiChat2OpenAI(geminiResponse)
  1201. response.Id = id
  1202. response.Created = createAt
  1203. response.Model = info.UpstreamModelName
  1204. for choiceIdx := range response.Choices {
  1205. choiceKey := response.Choices[choiceIdx].Index
  1206. for toolIdx := range response.Choices[choiceIdx].Delta.ToolCalls {
  1207. tool := &response.Choices[choiceIdx].Delta.ToolCalls[toolIdx]
  1208. if tool.ID == "" {
  1209. continue
  1210. }
  1211. m := toolCallIndexByChoice[choiceKey]
  1212. if m == nil {
  1213. m = make(map[string]int)
  1214. toolCallIndexByChoice[choiceKey] = m
  1215. }
  1216. if idx, ok := m[tool.ID]; ok {
  1217. tool.SetIndex(idx)
  1218. continue
  1219. }
  1220. idx := nextToolCallIndexByChoice[choiceKey]
  1221. nextToolCallIndexByChoice[choiceKey] = idx + 1
  1222. m[tool.ID] = idx
  1223. tool.SetIndex(idx)
  1224. }
  1225. }
  1226. logger.LogDebug(c, fmt.Sprintf("info.SendResponseCount = %d", info.SendResponseCount))
  1227. if info.SendResponseCount == 0 {
  1228. // send first response
  1229. emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil)
  1230. if response.IsToolCall() {
  1231. if len(emptyResponse.Choices) > 0 && len(response.Choices) > 0 {
  1232. toolCalls := response.Choices[0].Delta.ToolCalls
  1233. copiedToolCalls := make([]dto.ToolCallResponse, len(toolCalls))
  1234. for idx := range toolCalls {
  1235. copiedToolCalls[idx] = toolCalls[idx]
  1236. copiedToolCalls[idx].Function.Arguments = ""
  1237. }
  1238. emptyResponse.Choices[0].Delta.ToolCalls = copiedToolCalls
  1239. }
  1240. finishReason = constant.FinishReasonToolCalls
  1241. err := handleStream(c, info, emptyResponse)
  1242. if err != nil {
  1243. logger.LogError(c, err.Error())
  1244. }
  1245. response.ClearToolCalls()
  1246. if response.IsFinished() {
  1247. response.Choices[0].FinishReason = nil
  1248. }
  1249. } else {
  1250. err := handleStream(c, info, emptyResponse)
  1251. if err != nil {
  1252. logger.LogError(c, err.Error())
  1253. }
  1254. }
  1255. }
  1256. err := handleStream(c, info, response)
  1257. if err != nil {
  1258. logger.LogError(c, err.Error())
  1259. }
  1260. if isStop {
  1261. _ = handleStream(c, info, helper.GenerateStopResponse(id, createAt, info.UpstreamModelName, finishReason))
  1262. }
  1263. return true
  1264. })
  1265. if err != nil {
  1266. return usage, err
  1267. }
  1268. response := helper.GenerateFinalUsageResponse(id, createAt, info.UpstreamModelName, *usage)
  1269. handleErr := handleFinalStream(c, info, response)
  1270. if handleErr != nil {
  1271. common.SysLog("send final response failed: " + handleErr.Error())
  1272. }
  1273. return usage, nil
  1274. }
  1275. func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1276. responseBody, err := io.ReadAll(resp.Body)
  1277. if err != nil {
  1278. return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1279. }
  1280. service.CloseResponseBodyGracefully(resp)
  1281. if common.DebugEnabled {
  1282. println(string(responseBody))
  1283. }
  1284. var geminiResponse dto.GeminiChatResponse
  1285. err = common.Unmarshal(responseBody, &geminiResponse)
  1286. if err != nil {
  1287. return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1288. }
  1289. if len(geminiResponse.Candidates) == 0 {
  1290. usage := dto.Usage{
  1291. PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
  1292. }
  1293. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  1294. usage.PromptTokensDetails.CachedTokens = geminiResponse.UsageMetadata.CachedContentTokenCount
  1295. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  1296. if detail.Modality == "AUDIO" {
  1297. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  1298. } else if detail.Modality == "TEXT" {
  1299. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  1300. }
  1301. }
  1302. if usage.PromptTokens <= 0 {
  1303. usage.PromptTokens = info.GetEstimatePromptTokens()
  1304. }
  1305. var newAPIError *types.NewAPIError
  1306. if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
  1307. common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
  1308. newAPIError = types.NewOpenAIError(
  1309. errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason),
  1310. types.ErrorCodePromptBlocked,
  1311. http.StatusBadRequest,
  1312. )
  1313. } else {
  1314. common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "gemini_empty_candidates")
  1315. newAPIError = types.NewOpenAIError(
  1316. errors.New("empty response from Gemini API"),
  1317. types.ErrorCodeEmptyResponse,
  1318. http.StatusInternalServerError,
  1319. )
  1320. }
  1321. service.ResetStatusCode(newAPIError, c.GetString("status_code_mapping"))
  1322. switch info.RelayFormat {
  1323. case types.RelayFormatClaude:
  1324. c.JSON(newAPIError.StatusCode, gin.H{
  1325. "type": "error",
  1326. "error": newAPIError.ToClaudeError(),
  1327. })
  1328. default:
  1329. c.JSON(newAPIError.StatusCode, gin.H{
  1330. "error": newAPIError.ToOpenAIError(),
  1331. })
  1332. }
  1333. return &usage, nil
  1334. }
  1335. fullTextResponse := responseGeminiChat2OpenAI(c, &geminiResponse)
  1336. fullTextResponse.Model = info.UpstreamModelName
  1337. usage := dto.Usage{
  1338. PromptTokens: geminiResponse.UsageMetadata.PromptTokenCount,
  1339. CompletionTokens: geminiResponse.UsageMetadata.CandidatesTokenCount,
  1340. TotalTokens: geminiResponse.UsageMetadata.TotalTokenCount,
  1341. }
  1342. usage.CompletionTokenDetails.ReasoningTokens = geminiResponse.UsageMetadata.ThoughtsTokenCount
  1343. usage.PromptTokensDetails.CachedTokens = geminiResponse.UsageMetadata.CachedContentTokenCount
  1344. usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
  1345. for _, detail := range geminiResponse.UsageMetadata.PromptTokensDetails {
  1346. if detail.Modality == "AUDIO" {
  1347. usage.PromptTokensDetails.AudioTokens = detail.TokenCount
  1348. } else if detail.Modality == "TEXT" {
  1349. usage.PromptTokensDetails.TextTokens = detail.TokenCount
  1350. }
  1351. }
  1352. fullTextResponse.Usage = usage
  1353. switch info.RelayFormat {
  1354. case types.RelayFormatOpenAI:
  1355. responseBody, err = common.Marshal(fullTextResponse)
  1356. if err != nil {
  1357. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  1358. }
  1359. case types.RelayFormatClaude:
  1360. claudeResp := service.ResponseOpenAI2Claude(fullTextResponse, info)
  1361. claudeRespStr, err := common.Marshal(claudeResp)
  1362. if err != nil {
  1363. return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
  1364. }
  1365. responseBody = claudeRespStr
  1366. case types.RelayFormatGemini:
  1367. break
  1368. }
  1369. service.IOCopyBytesGracefully(c, resp, responseBody)
  1370. return &usage, nil
  1371. }
  1372. func GeminiEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1373. defer service.CloseResponseBodyGracefully(resp)
  1374. responseBody, readErr := io.ReadAll(resp.Body)
  1375. if readErr != nil {
  1376. return nil, types.NewOpenAIError(readErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1377. }
  1378. var geminiResponse dto.GeminiBatchEmbeddingResponse
  1379. if jsonErr := common.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  1380. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1381. }
  1382. // convert to openai format response
  1383. openAIResponse := dto.OpenAIEmbeddingResponse{
  1384. Object: "list",
  1385. Data: make([]dto.OpenAIEmbeddingResponseItem, 0, len(geminiResponse.Embeddings)),
  1386. Model: info.UpstreamModelName,
  1387. }
  1388. for i, embedding := range geminiResponse.Embeddings {
  1389. openAIResponse.Data = append(openAIResponse.Data, dto.OpenAIEmbeddingResponseItem{
  1390. Object: "embedding",
  1391. Embedding: embedding.Values,
  1392. Index: i,
  1393. })
  1394. }
  1395. // calculate usage
  1396. // https://ai.google.dev/gemini-api/docs/pricing?hl=zh-cn#text-embedding-004
  1397. // Google has not yet clarified how embedding models will be billed
  1398. // refer to openai billing method to use input tokens billing
  1399. // https://platform.openai.com/docs/guides/embeddings#what-are-embeddings
  1400. usage := service.ResponseText2Usage(c, "", info.UpstreamModelName, info.GetEstimatePromptTokens())
  1401. openAIResponse.Usage = *usage
  1402. jsonResponse, jsonErr := common.Marshal(openAIResponse)
  1403. if jsonErr != nil {
  1404. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1405. }
  1406. service.IOCopyBytesGracefully(c, resp, jsonResponse)
  1407. return usage, nil
  1408. }
  1409. func GeminiImageHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
  1410. responseBody, readErr := io.ReadAll(resp.Body)
  1411. if readErr != nil {
  1412. return nil, types.NewOpenAIError(readErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1413. }
  1414. _ = resp.Body.Close()
  1415. var geminiResponse dto.GeminiImageResponse
  1416. if jsonErr := common.Unmarshal(responseBody, &geminiResponse); jsonErr != nil {
  1417. return nil, types.NewOpenAIError(jsonErr, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1418. }
  1419. if len(geminiResponse.Predictions) == 0 {
  1420. return nil, types.NewOpenAIError(errors.New("no images generated"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
  1421. }
  1422. // convert to openai format response
  1423. openAIResponse := dto.ImageResponse{
  1424. Created: common.GetTimestamp(),
  1425. Data: make([]dto.ImageData, 0, len(geminiResponse.Predictions)),
  1426. }
  1427. for _, prediction := range geminiResponse.Predictions {
  1428. if prediction.RaiFilteredReason != "" {
  1429. continue // skip filtered image
  1430. }
  1431. openAIResponse.Data = append(openAIResponse.Data, dto.ImageData{
  1432. B64Json: prediction.BytesBase64Encoded,
  1433. })
  1434. }
  1435. jsonResponse, jsonErr := json.Marshal(openAIResponse)
  1436. if jsonErr != nil {
  1437. return nil, types.NewError(jsonErr, types.ErrorCodeBadResponseBody)
  1438. }
  1439. c.Writer.Header().Set("Content-Type", "application/json")
  1440. c.Writer.WriteHeader(resp.StatusCode)
  1441. _, _ = c.Writer.Write(jsonResponse)
  1442. // https://github.com/google-gemini/cookbook/blob/719a27d752aac33f39de18a8d3cb42a70874917e/quickstarts/Counting_Tokens.ipynb
  1443. // each image has fixed 258 tokens
  1444. const imageTokens = 258
  1445. generatedImages := len(openAIResponse.Data)
  1446. usage := &dto.Usage{
  1447. PromptTokens: imageTokens * generatedImages, // each generated image has fixed 258 tokens
  1448. CompletionTokens: 0, // image generation does not calculate completion tokens
  1449. TotalTokens: imageTokens * generatedImages,
  1450. }
  1451. return usage, nil
  1452. }
  1453. type GeminiModelsResponse struct {
  1454. Models []dto.GeminiModel `json:"models"`
  1455. NextPageToken string `json:"nextPageToken"`
  1456. }
  1457. func FetchGeminiModels(baseURL, apiKey, proxyURL string) ([]string, error) {
  1458. client, err := service.GetHttpClientWithProxy(proxyURL)
  1459. if err != nil {
  1460. return nil, fmt.Errorf("创建HTTP客户端失败: %v", err)
  1461. }
  1462. allModels := make([]string, 0)
  1463. nextPageToken := ""
  1464. maxPages := 100 // Safety limit to prevent infinite loops
  1465. for page := 0; page < maxPages; page++ {
  1466. url := fmt.Sprintf("%s/v1beta/models", baseURL)
  1467. if nextPageToken != "" {
  1468. url = fmt.Sprintf("%s?pageToken=%s", url, nextPageToken)
  1469. }
  1470. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  1471. request, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  1472. if err != nil {
  1473. cancel()
  1474. return nil, fmt.Errorf("创建请求失败: %v", err)
  1475. }
  1476. request.Header.Set("x-goog-api-key", apiKey)
  1477. response, err := client.Do(request)
  1478. if err != nil {
  1479. cancel()
  1480. return nil, fmt.Errorf("请求失败: %v", err)
  1481. }
  1482. if response.StatusCode != http.StatusOK {
  1483. body, _ := io.ReadAll(response.Body)
  1484. response.Body.Close()
  1485. cancel()
  1486. return nil, fmt.Errorf("服务器返回错误 %d: %s", response.StatusCode, string(body))
  1487. }
  1488. body, err := io.ReadAll(response.Body)
  1489. response.Body.Close()
  1490. cancel()
  1491. if err != nil {
  1492. return nil, fmt.Errorf("读取响应失败: %v", err)
  1493. }
  1494. var modelsResponse GeminiModelsResponse
  1495. if err = common.Unmarshal(body, &modelsResponse); err != nil {
  1496. return nil, fmt.Errorf("解析响应失败: %v", err)
  1497. }
  1498. for _, model := range modelsResponse.Models {
  1499. modelNameValue, ok := model.Name.(string)
  1500. if !ok {
  1501. continue
  1502. }
  1503. modelName := strings.TrimPrefix(modelNameValue, "models/")
  1504. allModels = append(allModels, modelName)
  1505. }
  1506. nextPageToken = modelsResponse.NextPageToken
  1507. if nextPageToken == "" {
  1508. break
  1509. }
  1510. }
  1511. return allModels, nil
  1512. }
  1513. // convertToolChoiceToGeminiConfig converts OpenAI tool_choice to Gemini toolConfig
  1514. // OpenAI tool_choice values:
  1515. // - "auto": Let the model decide (default)
  1516. // - "none": Don't call any tools
  1517. // - "required": Must call at least one tool
  1518. // - {"type": "function", "function": {"name": "xxx"}}: Call specific function
  1519. //
  1520. // Gemini functionCallingConfig.mode values:
  1521. // - "AUTO": Model decides whether to call functions
  1522. // - "NONE": Model won't call functions
  1523. // - "ANY": Model must call at least one function
  1524. func convertToolChoiceToGeminiConfig(toolChoice any) *dto.ToolConfig {
  1525. if toolChoice == nil {
  1526. return nil
  1527. }
  1528. // Handle string values: "auto", "none", "required"
  1529. if toolChoiceStr, ok := toolChoice.(string); ok {
  1530. config := &dto.ToolConfig{
  1531. FunctionCallingConfig: &dto.FunctionCallingConfig{},
  1532. }
  1533. switch toolChoiceStr {
  1534. case "auto":
  1535. config.FunctionCallingConfig.Mode = "AUTO"
  1536. case "none":
  1537. config.FunctionCallingConfig.Mode = "NONE"
  1538. case "required":
  1539. config.FunctionCallingConfig.Mode = "ANY"
  1540. default:
  1541. // Unknown string value, default to AUTO
  1542. config.FunctionCallingConfig.Mode = "AUTO"
  1543. }
  1544. return config
  1545. }
  1546. // Handle object value: {"type": "function", "function": {"name": "xxx"}}
  1547. if toolChoiceMap, ok := toolChoice.(map[string]interface{}); ok {
  1548. if toolChoiceMap["type"] == "function" {
  1549. config := &dto.ToolConfig{
  1550. FunctionCallingConfig: &dto.FunctionCallingConfig{
  1551. Mode: "ANY",
  1552. },
  1553. }
  1554. // Extract function name if specified
  1555. if function, ok := toolChoiceMap["function"].(map[string]interface{}); ok {
  1556. if name, ok := function["name"].(string); ok && name != "" {
  1557. config.FunctionCallingConfig.AllowedFunctionNames = []string{name}
  1558. }
  1559. }
  1560. return config
  1561. }
  1562. // Unsupported map structure (type is not "function"), return nil
  1563. return nil
  1564. }
  1565. // Unsupported type, return nil
  1566. return nil
  1567. }