gateway: an AI Studio key speaks the Gemini API too, and searches by googleSearch

cocoasoda (Discord) asked for a native Gemini API mode on the Gemini API
provider, so it can search with Google Search on the API credit a Gemini
subscription comes with.

The Google Gemini preset (and any provider whose Chat URL is AI Studio's
OpenAI-compatible one) now gets AI Studio's Gemini API base,
https://generativelanguage.googleapis.com/v1beta, at the same key, filled
in by normalize, so existing providers get it on load. A Gemini URL of the
provider's own is kept; other hosts, Vertex and sign-ins get nothing.
Ordinary turns stay on Chat as before. What changes:

- A Gemini client (Gemini CLI) is relayed natively, its googleSearch tool
  included, instead of being translated onto Chat.
- A web search with no tools of the client's own (Claude Code's
  WebSearch) goes to the Gemini API with tools [{"googleSearch":{}}], and
  the grounding comes back as the client's search result.
- A turn with function tools stays on Chat: Gemini doesn't take
  googleSearch beside function declarations, so before this the switch to
  Gemini dropped the search silently. Its model is given magpie's search
  tool, and the same key answers it by a tool-less googleSearch request
  (searchesOwn / ownSearcher, as Google sign-ins do since #757), on the
  user's own credit, not another provider's.
- The model list isn't asked twice: AI Studio's OpenAI-compatible list is
  its Gemini API's list.

Run on mote at this change on 2c90922b0 (pushed on 898c314b7, which adds
GUI files and a WorkBuddy mover min only): gofmt -l clean;
GOOS=windows go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok;
go test ./internal/provider ok (194s). The whole ./internal/gateway run
was still going under other sessions' suites when this was pushed. The
new gateway tests (below), TestCodeAssistSearchesWithoutTools,
TestCustomGeminiUpstream and TestAIStudioThinking passed at the same
code before the rebase, which brought in only GUI and provider-pick
commits.

New tests: TestAIStudioSpeaksGemini, TestAIStudioKeySearchesByGoogleSearch,
TestAIStudioKeySearchesBesideTools, TestAIStudioKeyRelaysGeminiClient,
TestGeminiKeySearchesScope. The upstream is a fake transport for
generativelanguage.googleapis.com with Google's grounding example's shape
(webSearchQueries, groundingChunks, groundingSupports); no network.

Broken by hand, each red:
- normalize without aiStudioNative: TestAIStudioSpeaksGemini and all three
  gateway tests (Chat asked, 404 on the Gemini client).
- searchesFor without the AI Studio branch: BesideTools (the turn went
  to Gemini, where googleSearch would be dropped) and Scope.
- searchesOwn without geminiKeySearches: BesideTools (the search tool
  call went back to the client unanswered).

Not tried: a real AI Studio key (none here), so Google's live replies are
from its docs, not seen. Gemini 3's googleSearch beside function tools
(includeServerSideToolInvocations) is not used. The derived Gemini URL
can't be cleared by the user while the Chat URL is AI Studio's; normalize
fills it again.
This commit is contained in:
yetone
2026-11-03 02:21:35 +08:00
parent 898c314b79
commit 3e61d814e5
8 changed files with 300 additions and 4 deletions
@@ -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":"<!-- HTML and CSS for the search widget -->"},"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")
}
}
+15 -1
View File
@@ -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)
+2 -2
View File
@@ -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.
+1 -1
View File
@@ -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
+27
View File
@@ -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)
}
+35
View File
@@ -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())
}
}
}
+5
View File
@@ -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
+1
View File
@@ -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 = ""