diff --git a/internal/gateway/gemini_aistudio_search_test.go b/internal/gateway/gemini_aistudio_search_test.go new file mode 100644 index 000000000..e72ca10d0 --- /dev/null +++ b/internal/gateway/gemini_aistudio_search_test.go @@ -0,0 +1,214 @@ +package gateway + +import ( + "bytes" + "io" + "net/http" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// aiStudioGrounded is a Gemini API stream that searched with googleSearch: +// Google's grounding example's shape (ai.google.dev/gemini-api/docs/ +// google-search), webSearchQueries, groundingChunks and groundingSupports +// with the answer. +var aiStudioGrounded = sse( + `data: {"candidates":[{"content":{"parts":[{"text":"Spain won Euro 2024, defeating England 2-1 in the final."}],"role":"model"},"index":0}],"modelVersion":"gemini-2.5-flash"}`, + `data: {"candidates":[{"content":{"parts":[{"text":" This victory marks Spain's record fourth European Championship title."}],"role":"model"},"finishReason":"STOP","index":0,"groundingMetadata":{"webSearchQueries":["UEFA Euro 2024 winner","who won euro 2024"],"searchEntryPoint":{"renderedContent":""},"groundingChunks":[{"web":{"uri":"https://vertexaisearch.cloud.google.com/grounding-api-redirect/aljazeera","title":"aljazeera.com"}},{"web":{"uri":"https://vertexaisearch.cloud.google.com/grounding-api-redirect/uefa","title":"uefa.com"}}],"groundingSupports":[{"segment":{"startIndex":0,"endIndex":56,"text":"Spain won Euro 2024, defeating England 2-1 in the final."},"groundingChunkIndices":[0]}]}}],"usageMetadata":{"promptTokenCount":12,"candidatesTokenCount":30,"totalTokenCount":42},"modelVersion":"gemini-2.5-flash"}`, +) + +type aiStudioCall struct { + url, key, auth string + body []byte +} + +// aiStudio saves the Google Gemini preset with an AI Studio key and gives +// a server whose client answers for generativelanguage.googleapis.com: +// the Gemini API with aiStudioGrounded, OpenAI-compatible Chat with chat's +// stream (by the request's body and how many Chat requests came before), and +// anything else with a 404 the test fails on. +func aiStudio(t *testing.T, chat func(n int, body []byte) string) (*Server, func() []aiStudioCall) { + t.Helper() + fresh(t) + if err := provider.Save(provider.Provider{ID: "google", Name: "Google Gemini", Preset: "google", + Chat: provider.AIStudioChat, Key: "AIza-k", Models: []string{"gemini-2.5-flash"}}); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var calls []aiStudioCall + chats := 0 + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + mu.Lock() + calls = append(calls, aiStudioCall{r.URL.String(), r.Header.Get("x-goog-api-key"), r.Header.Get("Authorization"), b}) + n := chats + mu.Unlock() + reply := func(ct, body string) (*http.Response, error) { + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {ct}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil + } + switch { + case r.URL.Host != "generativelanguage.googleapis.com": + case strings.HasPrefix(r.URL.Path, "/v1beta/models/") && strings.HasSuffix(r.URL.Path, ":streamGenerateContent"): + return reply("text/event-stream", aiStudioGrounded) + case r.URL.Path == "/v1beta/openai/chat/completions" && chat != nil: + mu.Lock() + chats++ + mu.Unlock() + return reply("text/event-stream", chat(n, b)) + } + t.Errorf("asked %s %s", r.Method, r.URL) + return &http.Response{StatusCode: 404, Header: http.Header{}, Body: io.NopCloser(bytes.NewReader(nil)), Request: r}, nil + })} + return s, func() []aiStudioCall { + mu.Lock() + defer mu.Unlock() + return append([]aiStudioCall(nil), calls...) + } +} + +func geminiCalls(calls []aiStudioCall) []aiStudioCall { + var out []aiStudioCall + for _, c := range calls { + if strings.Contains(c.url, "/v1beta/models/") { + out = append(out, c) + } + } + return out +} + +func checkGoogleSearch(t *testing.T, what string, c aiStudioCall) { + t.Helper() + if c.url != "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse" { + t.Errorf("%s: asked %s", what, c.url) + } + if c.key != "AIza-k" || c.auth != "" { + t.Errorf("%s: signed key=%q auth=%q", what, c.key, c.auth) + } + if tools := gjson.GetBytes(c.body, "tools").Raw; tools != `[{"googleSearch":{}}]` { + t.Errorf("%s: tools %s", what, tools) + } +} + +// A web search on an AI Studio key, with no tools of the client's own +// (Claude Code's WebSearch), is Gemini's googleSearch on the user's own key +// and credit, at AI Studio's Gemini API, and what it found comes back as +// the client's search result (cocoasoda on Discord). +func TestAIStudioKeySearchesByGoogleSearch(t *testing.T) { + s, calls := aiStudio(t, nil) + code, _, raw, _ := request(t, s, "POST", "/v1/messages", "application/json", + `{"model":"google/gemini-2.5-flash","max_tokens":1024,"messages":[{"role":"user","content":"Perform a web search for the query: who won euro 2024"}],"tools":[{"type":"web_search_20250305","name":"web_search","max_uses":8}]}`) + body := string(raw) + if code != 200 || !strings.Contains(body, "Spain won Euro 2024") { + t.Fatalf("messages: %d %s", code, body) + } + if !strings.Contains(body, `"web_search_tool_result"`) || !strings.Contains(body, "aljazeera.com") || !strings.Contains(body, "grounding-api-redirect/uefa") { + t.Errorf("the search isn't in the reply: %s", body) + } + gem := geminiCalls(calls()) + if len(gem) != 1 || len(calls()) != 1 { + t.Fatalf("calls %d, Gemini %d", len(calls()), len(gem)) + } + checkGoogleSearch(t, "search", gem[0]) + if !strings.Contains(gjson.GetBytes(gem[0].body, "contents").Raw, "who won euro 2024") { + t.Errorf("contents %s", gem[0].body) + } +} + +// A turn with the client's own tools (Codex, Claude Code) stays on Chat, +// where Gemini can't have googleSearch beside function tools; its model is +// given a search tool, which the same key answers by a googleSearch +// request of its own, never another provider and never a silent drop of +// the search. +func TestAIStudioKeySearchesBesideTools(t *testing.T) { + var asked []string + s, calls := aiStudio(t, func(n int, body []byte) string { + var names []string + for _, tl := range gjson.GetBytes(body, "tools").Array() { + names = append(names, tl.Get("function.name").String()) + } + asked = append(asked, strings.Join(names, ",")) + if n == 0 { + return sse( + `data: {"id":"c1","object":"chat.completion.chunk","model":"gemini-2.5-flash","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"web_search","arguments":"{\"query\":\"who won euro 2024\"}"}}]},"finish_reason":null}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","model":"gemini-2.5-flash","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":8,"total_tokens":28}}`, + `data: [DONE]`) + } + if !strings.Contains(string(body), "Spain won Euro 2024") { + t.Errorf("the search's result isn't in the next round: %s", body) + } + return sse( + `data: {"id":"c2","object":"chat.completion.chunk","model":"gemini-2.5-flash","choices":[{"index":0,"delta":{"role":"assistant","content":"Spain won."},"finish_reason":null}]}`, + `data: {"id":"c2","object":"chat.completion.chunk","model":"gemini-2.5-flash","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":60,"completion_tokens":3,"total_tokens":63}}`, + `data: [DONE]`) + }) + code, _, raw, _ := request(t, s, "POST", "/v1/messages", "application/json", + `{"model":"google/gemini-2.5-flash","max_tokens":1024,"messages":[{"role":"user","content":"Who won Euro 2024? Search the web."}],"tools":[{"name":"Bash","description":"Run a command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"type":"web_search_20250305","name":"web_search","max_uses":8}]}`) + if code != 200 || !strings.Contains(string(raw), "Spain won.") { + t.Fatalf("messages: %d %s", code, raw) + } + if len(asked) < 2 || !strings.Contains(asked[0], "Bash") || !strings.Contains(asked[0], "web_search") { + t.Errorf("Chat was asked with tools %q", asked) + } + gem := geminiCalls(calls()) + if len(gem) != 1 { + t.Fatalf("Gemini asked %d times: %+v", len(gem), calls()) + } + checkGoogleSearch(t, "own search", gem[0]) + if strings.Contains(string(gem[0].body), "functionDeclarations") || !strings.Contains(string(gem[0].body), "who won euro 2024") { + t.Errorf("own search body %s", gem[0].body) + } +} + +// A Gemini client's own request (Gemini CLI) with googleSearch goes to AI +// Studio's Gemini API as it is, tools and all. +func TestAIStudioKeyRelaysGeminiClient(t *testing.T) { + s, calls := aiStudio(t, nil) + code, _, raw, _ := request(t, s, "POST", "/v1beta/models/google/gemini-2.5-flash:streamGenerateContent?alt=sse", "application/json", + `{"contents":[{"role":"user","parts":[{"text":"Who won the euro 2024?"}]}],"tools":[{"googleSearch":{}}]}`) + if code != 200 || !strings.Contains(string(raw), "Spain won Euro 2024") || !strings.Contains(string(raw), "groundingMetadata") { + t.Fatalf("gemini stream: %d %s", code, raw) + } + gem := geminiCalls(calls()) + if len(gem) != 1 || len(calls()) != 1 { + t.Fatalf("calls %+v", calls()) + } + checkGoogleSearch(t, "relay", gem[0]) +} + +// Only an AI Studio key's own Gemini API searches this way: a Google +// sign-in, Vertex, a relay's Gemini URL and an image model keep what they +// did. +func TestGeminiKeySearchesScope(t *testing.T) { + plain := &Request{WebSearch: true, Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "news?"}}}}} + tools := &Request{WebSearch: true, Messages: plain.Messages, Tools: []Tool{{Name: "bash"}}} + none := &Request{WebSearch: true, Messages: plain.Messages, Tools: tools.Tools, ToolChoice: "none"} + studio := provider.Provider{ID: "google", Chat: provider.AIStudioChat, Gemini: provider.AIStudioGemini, Key: "k"} + if !geminiKeySearches(studio) { + t.Fatal("an AI Studio key doesn't search by its Gemini API") + } + if !searchesFor(studio, provider.Gemini, "gemini-2.5-flash", plain) || !searchesFor(studio, provider.Gemini, "gemini-2.5-flash", none) { + t.Error("an AI Studio key without tools doesn't search by googleSearch") + } + if searchesFor(studio, provider.Gemini, "gemini-2.5-flash", tools) { + t.Error("an AI Studio key with function tools is said to search by googleSearch, which would be dropped") + } + if searchesFor(studio, provider.Gemini, "gemini-2.5-flash-image", plain) || searchesFor(studio, provider.Chat, "gemini-2.5-flash", plain) { + t.Error("an image model, or AI Studio's Chat, is said to search by itself") + } + relay := provider.Provider{ID: "relay", Gemini: "https://relay.example/v1beta", Key: "k"} + if geminiKeySearches(relay) { + t.Error("a relay's Gemini URL searches by googleSearch") + } + signin := provider.Provider{ID: "antigravity", Account: &provider.Account{Agent: "antigravity", User: "u"}, Gemini: provider.AIStudioGemini} + if geminiKeySearches(signin) { + t.Error("a Google sign-in is taken for an AI Studio key") + } +} diff --git a/internal/gateway/search.go b/internal/gateway/search.go index c75f0ae50..95d7ae8f4 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -147,6 +147,17 @@ func codeAssistSearches(p provider.Provider, proto provider.Protocol, model stri return proto == provider.CodeAssist && googleAccount(p) && searchModel(model) } +// geminiKeySearches is a provider asked with a key at Google AI Studio's +// Gemini API, the Google Gemini preset's beside its OpenAI-compatible one +// (provider.AIStudioGemini; cocoasoda on Discord): Gemini runs googleSearch +// there for a request that declares no function, as on Code Assist. One +// that does — Codex's every turn, Claude Code's — is given magpie's search, +// which the provider answers itself (searchesOwn), so the searches spend +// the user's own Gemini API credit. No other vendor's API is read as one. +func geminiKeySearches(p provider.Provider) bool { + return p.Account == nil && !p.IsPlugin() && !p.IsVertex() && searchesItself(p, provider.Gemini) +} + // searchModel is a model Code Assist runs googleSearch for: Gemini's, not // Claude's or GPT-OSS's on Antigravity, nor an image model. func searchModel(model string) bool { @@ -157,6 +168,9 @@ func searchModel(model string) bool { // searchesFor is searchesItself for one request: a Google sign-in's Gemini // searches by itself only for a request without function tools. func searchesFor(p provider.Provider, proto provider.Protocol, model string, req *Request) bool { + if proto == provider.Gemini && geminiKeySearches(p) { + return searchModel(model) && (len(req.Tools) == 0 || req.ToolChoice == "none") + } if searchesModel(p, proto, model) { return true } @@ -675,7 +689,7 @@ func searcherReady(p provider.Provider) (string, bool) { // what searchableModel says of a model is the model's and the // provider's list's, which keptSmallCands is kept by var keep func(catalog.Model) bool - if googleAccount(p) || p.IsRemoteMagpie() || partSearcher(p) { + if googleAccount(p) || geminiKeySearches(p) || p.IsRemoteMagpie() || partSearcher(p) { keep = func(m catalog.Model) bool { return searchableModel(p, m.ID) } } c, ready := smallReadyOf(p, keptSmallCands(p, "search", keep), provider.Anthropic) diff --git a/internal/gateway/search_kimi.go b/internal/gateway/search_kimi.go index 689b29cad..b97cb7b06 100644 --- a/internal/gateway/search_kimi.go +++ b/internal/gateway/search_kimi.go @@ -53,13 +53,13 @@ func canSearchFor(p provider.Provider) bool { // searchesOwn is whether p searches for its own models: by its Kimi Code // plan's or WorkBuddy plan's search service (#1798), or a Google sign-in's -// own Gemini. Never with provider search Off in Settings (#1483), which +// or an AI Studio key's own Gemini (geminiKeySearches). Never with provider search Off in Settings (#1483), which // leaves the search APIs alone, nor with plugins/search off. func searchesOwn(p provider.Provider) bool { if !searchServed() || settings.Load().Searcher == "off" { return false } - return provider.KimiCodeSearch(p) != "" || wbSearches(p) || googleAccount(p) && searcherModel(p) != "" + return provider.KimiCodeSearch(p) != "" || wbSearches(p) || (googleAccount(p) || geminiKeySearches(p)) && searcherModel(p) != "" } // searchingOn is ctx for the searches made for a model of p. diff --git a/internal/gateway/search_remote.go b/internal/gateway/search_remote.go index 9f24e19eb..19a455ae1 100644 --- a/internal/gateway/search_remote.go +++ b/internal/gateway/search_remote.go @@ -57,7 +57,7 @@ func remoteSearchesAny(p provider.Provider) bool { // provider's. func searchableModel(p provider.Provider, model string) bool { switch { - case googleAccount(p): + case googleAccount(p), geminiKeySearches(p): return searchModel(model) case p.IsRemoteMagpie(): return remoteSearch(p, model) == searchNative diff --git a/internal/provider/gemini_api.go b/internal/provider/gemini_api.go index 4cab12c27..a02feea0f 100644 --- a/internal/provider/gemini_api.go +++ b/internal/provider/gemini_api.go @@ -42,3 +42,30 @@ func GeminiPath(model string, stream bool) string { } return "/models/" + m + ":generateContent" } + +// AIStudioChat is Google AI Studio's OpenAI-compatible base, the Google +// Gemini preset's Chat URL. +const AIStudioChat = "https://generativelanguage.googleapis.com/v1beta/openai" + +// AIStudioGemini is Google AI Studio's own Gemini API (generateContent), +// beside its OpenAI-compatible one. +const AIStudioGemini = "https://generativelanguage.googleapis.com/v1beta" + +// aiStudioNative gives a provider at AI Studio's OpenAI-compatible base, +// the Google Gemini preset's or one typed in, the Gemini API at the same +// place with the same key (cocoasoda on Discord): Gemini's own clients are +// relayed there as they ask, and googleSearch, which the OpenAI-compatible +// API has no tool for, is run there. Its other requests stay on chat +// completions, which Speaks names first. A Gemini URL of the provider's +// own is kept. +func (p *Provider) aiStudioNative() { + if p.Gemini == "" && p.Account == nil && strings.EqualFold(p.Chat, AIStudioChat) { + p.Gemini = AIStudioGemini + } +} + +// AIStudioPair is a provider at both of AI Studio's APIs: its models are +// the OpenAI-compatible list's, which is the Gemini API's list again. +func (p Provider) AIStudioPair() bool { + return strings.EqualFold(p.Chat, AIStudioChat) && strings.EqualFold(p.Gemini, AIStudioGemini) +} diff --git a/internal/provider/gemini_api_test.go b/internal/provider/gemini_api_test.go index b4c845a22..b8249cc4e 100644 --- a/internal/provider/gemini_api_test.go +++ b/internal/provider/gemini_api_test.go @@ -110,3 +110,38 @@ func TestFactoryGeminiUnchanged(t *testing.T) { t.Errorf("factory auth %v", h) } } + +// An AI Studio key (the Google Gemini preset, or a provider at AI Studio's +// OpenAI-compatible URL) speaks AI Studio's Gemini API too, with the same +// key, so a Gemini client and Google Search reach it (cocoasoda on +// Discord); one's own Gemini URL is kept, and nothing else gets one. +func TestAIStudioSpeaksGemini(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + for _, p := range []Provider{ + {ID: "google", Name: "Google Gemini", Preset: "google", Chat: AIStudioChat, Key: "AIza-k"}, + {ID: "studio", Name: "Studio", Chat: AIStudioChat + "/", Key: "AIza-k"}, + {ID: "relay", Name: "Relay", Chat: AIStudioChat, Gemini: "https://relay.example/v1beta", Key: "AIza-k"}, + {ID: "other", Name: "Other", Chat: "https://relay.example/v1beta/openai", Key: "k"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + want := map[string]string{"google": AIStudioGemini, "studio": AIStudioGemini, "relay": "https://relay.example/v1beta", "other": ""} + for id, base := range want { + p, err := Find(id) + if err != nil { + t.Fatal(err) + } + if p.Gemini != base { + t.Errorf("%s: Gemini = %q, want %q", id, p.Gemini, base) + } + if speaks := p.Speaks(); slices.Contains(speaks, Gemini) != (base != "") || !slices.Contains(speaks, Chat) { + t.Errorf("%s speaks %v", id, speaks) + } + if p.AIStudioPair() != (id == "google" || id == "studio") { + t.Errorf("%s: AIStudioPair = %v", id, p.AIStudioPair()) + } + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 3760d4661..e29d7b382 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -774,6 +774,11 @@ func (p Provider) fetchOne(ctx context.Context) (fetched, error) { if p.Gemini == "" { continue // Factory's, whose list is its sign-in's } + if p.AIStudioPair() { + // AI Studio's OpenAI-compatible list is its Gemini API's + // list, asked once + continue + } if p.IsOpenCode() { // OpenCode's Gemini models are in the list its other // APIs share, asked at its chat URL; it has no Gemini diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 49d7e8ccc..d1463b212 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -1545,6 +1545,7 @@ func normalize(p Provider) Provider { } } p.Gemini = GeminiBase(p.Gemini) + p.aiStudioNative() // a pick whose URL is gone (cleared from the CLI) is no pick if p.BaseAPI != "" && p.baseOf(p.BaseAPI) == "" { p.BaseAPI = ""