fix(gemini): normalize ai studio google search tools

This commit is contained in:
YanzheL
2026-04-01 00:45:56 +08:00
parent 0ebe0ce585
commit dd5978f222
2 changed files with 91 additions and 2 deletions
@@ -612,7 +612,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
fullURL += "?alt=sse"
}
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(geminiReq))
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(restGeminiReq))
if err != nil {
return nil, "", err
}
@@ -685,7 +686,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
fullURL += "?alt=sse"
}
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(geminiReq))
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(restGeminiReq))
if err != nil {
return nil, "", err
}
@@ -3240,6 +3242,46 @@ func convertClaudeToolsToGeminiTools(tools any) []any {
return out
}
func normalizeGeminiRequestForAIStudio(body []byte) []byte {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body
}
tools, ok := payload["tools"].([]any)
if !ok || len(tools) == 0 {
return body
}
modified := false
for _, rawTool := range tools {
tool, ok := rawTool.(map[string]any)
if !ok {
continue
}
googleSearch, ok := tool["googleSearch"]
if !ok {
continue
}
if _, exists := tool["google_search"]; exists {
continue
}
tool["google_search"] = googleSearch
delete(tool, "googleSearch")
modified = true
}
if !modified {
return body
}
normalized, err := json.Marshal(payload)
if err != nil {
return body
}
return normalized
}
func isClaudeWebSearchToolMap(tool map[string]any) bool {
toolType, _ := tool["type"].(string)
if strings.HasPrefix(toolType, "web_search") || toolType == "google_search" {