gateway: Gemini's own tools (Google Search, URL context, code execution) reach Gemini (daoche_wuzui on X)
daoche_wuzui (X, v0.1.4095): magpie's Gemini route ignored Gemini's built-in
tools. A generateContent body's googleSearch/urlContext/codeExecution were
dropped in parseGemini, so the model never searched and no
groundingMetadata came back.
- ir.Request carries GoogleTools. parseGemini keeps googleSearch (and
google_search_retrieval), urlContext and codeExecution; chat's tools
read them in both shapes ({"googleSearch":{}} and {"type":"url_context"}).
- buildCodeAssistSent, shared by Code Assist, AI Studio, Vertex and plugins
spoken to on Code Assist, sends them when no function is declared
(Google refuses built-ins beside functionDeclarations), Gemini models only.
- A plugin whose API is googleapis.com (Antigravity) now searches itself
for Anthropic web_search, like the built-in Gemini accounts.
- The Gemini reply carries groundingMetadata (chunks + webSearchQueries),
streamed and not; executableCode/codeExecutionResult parts are read
as text instead of being lost.
Run:
- mote-run at 3dc1f13ed (before rebasing onto 27 newer commits):
go test -tags nogui ./internal/gateway ./internal/provider ok (916s, 139s);
go vet both; GOOS=windows go vet ./... ok; GOOS=linux go vet -tags nogui
./... ok; gofmt -l clean.
- At 80f1e05a3 (the rebase after it only took agent, claude and davsync commits): go vet and GOOS=windows go vet of gateway and provider ok; go test -run "Gemini|CodeAssist|Search|Google|Antigravity|AIStudio|Vertex|Chat|Plugin" ./internal/gateway ok (83s); go test ./internal/provider ok (136s).
- Broken by hand, each red: googleToolsFor, googlePlugin, the reply's
grounding, the ranCode decode, chatGoogleTool.
- Real account, sandbox HOME (Antigravity plugin, gemini-3.8-flash-low),
the plugin patched in the sandbox to log what magpie sent it:
- generateContent with googleSearch+urlContext+codeExecution: the three
tools reached the plugin, the reply had groundingMetadata (3 chunks,
webSearchQueries).
- streamGenerateContent: groundingMetadata in the stream.
- /v1/chat/completions with {"googleSearch":{}},{"type":"url_context"}:
both reached the plugin, a grounded answer came back.
- /v1/messages web_search_20250305: googleSearch sent, the reply had
server_tool_use + web_search_tool_result.
Not tried: an AI Studio key or Vertex account (unit tests only); the
Gemini CLI account (Google refuses individual Code Assist now); real
code-execution parts (Antigravity's model wrote code as text); whether
Antigravity honours urlContext (a fetch gave the same stale page with and
without it). Anthropic web_fetch is not mapped to urlContext. The full
./... suite is queued behind six runs on mote's suite.lock and had not
run when this was pushed.
This commit is contained in:
@@ -1857,6 +1857,18 @@ sign-in (5), by googleSearch, and like one is `Own`: its own models search
|
||||
first whoever is named. Before, it searched for its own models only and
|
||||
the picker never listed it (cocoasoda on Discord,
|
||||
`TestAIStudioKeySearchesForOthers`).
|
||||
Gemini's other tools of its own a client offers (`urlContext`,
|
||||
`codeExecution`, `googleMaps` and the rest, `Request.GoogleTools`, from a
|
||||
Gemini client's `tools` or the same objects among a Chat request's,
|
||||
`chatGoogleTool`) go on as sent to a Gemini model on Code Assist, the
|
||||
Gemini API and Vertex (`buildCodeAssistSent`), beside googleSearch and,
|
||||
like it, only when no function is declared; Claude on Antigravity gets
|
||||
none. A plugin whose provider is at `*.googleapis.com` on Code Assist
|
||||
(Antigravity's, `googlePlugin`) searches by googleSearch as a Google
|
||||
sign-in does. Code Gemini ran comes back as text in fences (`ranCode`),
|
||||
and a search reaches a Gemini client as `groundingMetadata` (`grounding`).
|
||||
Before, all three were dropped on every translated route (daoche_wuzui on
|
||||
X, `TestGeminiClientKeepsGoogleTools`).
|
||||
A ChatGPT account (Codex's sign-in, `codexSearches`) searches for another
|
||||
model by the ChatGPT backend's own search, `POST <CodexBase>/alpha/search`,
|
||||
the request Codex's web.run sends by itself with no model turn
|
||||
|
||||
@@ -12,9 +12,11 @@ import (
|
||||
"path"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/lazyre"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
@@ -182,10 +184,23 @@ func readChat(body []byte, facts bool) (*Request, error) {
|
||||
}
|
||||
r.System = strings.Join(sys, "\n\n")
|
||||
r.WebSearch = len(c.WebSearchOptions) > 0 && string(c.WebSearchOptions) != "null"
|
||||
for _, t := range c.Tools {
|
||||
for i, t := range c.Tools {
|
||||
if strings.HasPrefix(t.Type, "web_search") {
|
||||
r.WebSearch = true
|
||||
}
|
||||
if t.Function.Name == "" {
|
||||
// Google's own tools as Gemini spells them, which LiteLLM's
|
||||
// and Gemini's other OpenAI-shaped clients send among the
|
||||
// tools — {"googleSearch":{}}, {"url_context":{}} — or by
|
||||
// type, {"type":"url_context"}: googleSearch is the web
|
||||
// search, the rest go on to a Gemini upstream (GoogleTools).
|
||||
// Read as functions, they went out as tools with no name.
|
||||
if search, kept, ok := chatGoogleTool(gjson.GetBytes(body, "tools."+strconv.Itoa(i))); ok {
|
||||
r.WebSearch = r.WebSearch || search
|
||||
r.GoogleTools = append(r.GoogleTools, kept...)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if t.Type != "" && t.Type != "function" {
|
||||
continue
|
||||
}
|
||||
@@ -1787,3 +1802,28 @@ func renderChat(res Result, model string) []byte {
|
||||
"usage": res.Usage.chat()})
|
||||
return b
|
||||
}
|
||||
|
||||
// chatGoogleTool reads a Chat request's tool that is one of Google's own,
|
||||
// keyed by its name ({"googleSearch":{}}) or typed with it
|
||||
// ({"type":"url_context"}, its settings under the same name if any): ok
|
||||
// when it is one.
|
||||
func chatGoogleTool(t gjson.Result) (search bool, kept []json.RawMessage, ok bool) {
|
||||
var m map[string]json.RawMessage
|
||||
if !t.IsObject() || json.Unmarshal([]byte(t.Raw), &m) != nil {
|
||||
return false, nil, false
|
||||
}
|
||||
if typ := snakeToCamel(t.Get("type").String()); typ != "" {
|
||||
if !googleSearchTools[typ] && !googleToolNames[typ] {
|
||||
return false, nil, false
|
||||
}
|
||||
v := m[t.Get("type").String()]
|
||||
if len(v) == 0 {
|
||||
v = m[typ]
|
||||
}
|
||||
search, kept = googleTools(map[string]json.RawMessage{typ: v}, true)
|
||||
return search, kept, true
|
||||
}
|
||||
delete(m, "type")
|
||||
search, kept = googleTools(m, true)
|
||||
return search, kept, search || len(kept) > 0
|
||||
}
|
||||
|
||||
@@ -658,10 +658,18 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
}
|
||||
fc["mode"] = mode
|
||||
req["toolConfig"] = map[string]any{"functionCallingConfig": fc}
|
||||
} else if r.WebSearch {
|
||||
} else if google := googleToolsFor(r, sent); r.WebSearch || len(google) > 0 {
|
||||
// Google's own search, which Code Assist runs on Gemini as long as
|
||||
// no function is declared beside it (codeAssistSearches)
|
||||
req["tools"] = []map[string]any{{"googleSearch": map[string]any{}}}
|
||||
// no function is declared beside it (codeAssistSearches), and the
|
||||
// client's other Google tools (URL context, code execution)
|
||||
var tools []any
|
||||
if r.WebSearch {
|
||||
tools = append(tools, map[string]any{"googleSearch": map[string]any{}})
|
||||
}
|
||||
for _, t := range google {
|
||||
tools = append(tools, t)
|
||||
}
|
||||
req["tools"] = tools
|
||||
}
|
||||
|
||||
gen := map[string]any{}
|
||||
@@ -713,6 +721,16 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
return b
|
||||
}
|
||||
|
||||
// googleToolsFor are the client's Google tools (GoogleTools) the model
|
||||
// sent is given: Gemini's, not Claude's or GPT-OSS's on Antigravity nor an
|
||||
// image model's, which turn Google's tools away (searchModel).
|
||||
func googleToolsFor(r *Request, sent string) []json.RawMessage {
|
||||
if len(r.GoogleTools) == 0 || !searchModel(sent) {
|
||||
return nil
|
||||
}
|
||||
return r.GoogleTools
|
||||
}
|
||||
|
||||
// dropSecondAnswers leaves out a tool result whose call an earlier result
|
||||
// already answered, with the images it carried: the first answer stands, as
|
||||
// pairToolMessages and pairToolBlocks keep it for a Chat or Messages
|
||||
@@ -1563,6 +1581,11 @@ func (d *codeAssistDecoder) decode(data string, emit func(Event)) error {
|
||||
// reasoning above (#620)
|
||||
d.flush(emit)
|
||||
emit(Event{Kind: KImage, Name: p.InlineData.MimeType, Text: p.InlineData.Data})
|
||||
case p.ExecutableCode != nil || p.CodeExecutionResult != nil:
|
||||
// what Google's codeExecution ran and gave back, as text
|
||||
// in the answer: no other API has a part for code Google
|
||||
// ran, and left out the answer read as if it had none
|
||||
d.text(ranCode(p), emit)
|
||||
case p.Text != "" || p.Signature != "":
|
||||
d.text(p.Text, emit)
|
||||
if p.Signature != "" {
|
||||
@@ -1618,6 +1641,24 @@ func (d *codeAssistDecoder) decode(data string, emit func(Event)) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ranCode is a part of Google's codeExecution as text: the code in a
|
||||
// fence named for its language, what it printed in a plain one, and an
|
||||
// outcome other than OUTCOME_OK said beside it.
|
||||
func ranCode(p gPart) string {
|
||||
if c := p.ExecutableCode; c != nil {
|
||||
return "\n```" + strings.ToLower(c.Language) + "\n" + strings.TrimRight(c.Code, "\n") + "\n```\n"
|
||||
}
|
||||
r := p.CodeExecutionResult
|
||||
var b strings.Builder
|
||||
if r.Outcome != "" && r.Outcome != "OUTCOME_OK" {
|
||||
b.WriteString("\n" + r.Outcome + ":")
|
||||
}
|
||||
if out := strings.TrimRight(r.Output, "\n"); out != "" {
|
||||
b.WriteString("\n```\n" + out + "\n```\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Gemini's own tools live in a namespace, default_api, and a model now and
|
||||
// then names one of the client's with it: as a call's name
|
||||
// (default_api:bash), or, on Antigravity, as a whole call written out in
|
||||
|
||||
+121
-7
@@ -2,8 +2,10 @@ package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
@@ -30,6 +32,16 @@ type gPart struct {
|
||||
MimeType string `json:"mimeType"`
|
||||
FileURI string `json:"fileUri"`
|
||||
} `json:"fileData,omitempty"`
|
||||
// ExecutableCode and CodeExecutionResult are the code the model ran
|
||||
// with Google's codeExecution, and what it gave back
|
||||
ExecutableCode *struct {
|
||||
Language string `json:"language,omitempty"`
|
||||
Code string `json:"code"`
|
||||
} `json:"executableCode,omitempty"`
|
||||
CodeExecutionResult *struct {
|
||||
Outcome string `json:"outcome,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
} `json:"codeExecutionResult,omitempty"`
|
||||
FunctionCall *struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
@@ -62,8 +74,6 @@ type gRequest struct {
|
||||
Parameters json.RawMessage `json:"parameters,omitempty"`
|
||||
ParametersJSONSchema json.RawMessage `json:"parametersJsonSchema,omitempty"`
|
||||
} `json:"functionDeclarations,omitempty"`
|
||||
GoogleSearch json.RawMessage `json:"googleSearch,omitempty"`
|
||||
GoogleSnake json.RawMessage `json:"google_search,omitempty"`
|
||||
} `json:"tools,omitempty"`
|
||||
ToolConfig *struct {
|
||||
FunctionCallingConfig *struct {
|
||||
@@ -382,6 +392,12 @@ func parseGemini(body []byte) (*Request, error) {
|
||||
// Other protocols cannot carry Gemini file references as image URLs.
|
||||
msg.Parts = append(msg.Parts, Part{Kind: File, MediaType: p.FileData.MimeType, URL: p.FileData.FileURI})
|
||||
}
|
||||
case p.ExecutableCode != nil || p.CodeExecutionResult != nil:
|
||||
// code Google's codeExecution ran, an earlier turn's,
|
||||
// as the text a translated reply gave it (ranCode)
|
||||
if t := ranCode(p); t != "" {
|
||||
msg.Parts = append(msg.Parts, Part{Kind: Text, Text: t})
|
||||
}
|
||||
case p.Thought:
|
||||
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: p.Text, Signature: p.Signature})
|
||||
case p.Text != "" || p.Signature != "":
|
||||
@@ -404,10 +420,20 @@ func parseGemini(body []byte) (*Request, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, t := range g.Tools {
|
||||
if t.GoogleSearch != nil || t.GoogleSnake != nil {
|
||||
r.WebSearch = true
|
||||
// Google's own tools, beside the functions: googleSearch is
|
||||
// WebSearch, the rest go on as sent (GoogleTools). The body was
|
||||
// spelled in camelCase on its way in (geminiCamel).
|
||||
var rawTools struct {
|
||||
Tools []map[string]json.RawMessage `json:"tools"`
|
||||
}
|
||||
if json.Unmarshal(body, &rawTools) == nil {
|
||||
for _, t := range rawTools.Tools {
|
||||
search, kept := googleTools(t, false)
|
||||
r.WebSearch = r.WebSearch || search
|
||||
r.GoogleTools = append(r.GoogleTools, kept...)
|
||||
}
|
||||
}
|
||||
for _, t := range g.Tools {
|
||||
for _, f := range t.FunctionDeclarations {
|
||||
if allowed != nil && !allowed[f.Name] {
|
||||
continue
|
||||
@@ -440,6 +466,45 @@ func parseGemini(body []byte) (*Request, error) {
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// googleSearchTools are the names of Google's web search tool: today's
|
||||
// googleSearch, and Gemini 1.5's googleSearchRetrieval, which Gemini 2 and
|
||||
// later answer with googleSearch's 400 "use google_search instead".
|
||||
var googleSearchTools = map[string]bool{"googleSearch": true, "googleSearchRetrieval": true}
|
||||
|
||||
// googleToolNames are Google's own tools beside googleSearch that a Gemini
|
||||
// upstream runs itself, as the Gemini API spells them.
|
||||
var googleToolNames = map[string]bool{"urlContext": true, "codeExecution": true, "googleMaps": true,
|
||||
"fileSearch": true, "enterpriseWebSearch": true, "computerUse": true, "retrieval": true}
|
||||
|
||||
// googleTools reads one tool object of a request: whether it offers
|
||||
// googleSearch, and the other Google tools in it, each as a tool object of
|
||||
// its own. A Gemini request's (known false) holds only Google's tools beside
|
||||
// its functionDeclarations, so every other key is one, known or not; in a
|
||||
// Chat request's tools only the names Google gives them count, spelled
|
||||
// either way.
|
||||
func googleTools(t map[string]json.RawMessage, known bool) (search bool, kept []json.RawMessage) {
|
||||
// in the order of their names: a map's own order changes from one
|
||||
// read to the next, and the request's bytes would with it
|
||||
for _, name := range slices.Sorted(maps.Keys(t)) {
|
||||
k, v := snakeToCamel(name), t[name]
|
||||
switch {
|
||||
case k == "functionDeclarations":
|
||||
case googleSearchTools[k]:
|
||||
search = true
|
||||
case known && !googleToolNames[k]:
|
||||
default:
|
||||
if len(v) == 0 || string(v) == "null" {
|
||||
v = json.RawMessage("{}")
|
||||
}
|
||||
b, err := json.Marshal(map[string]json.RawMessage{k: v})
|
||||
if err == nil {
|
||||
kept = append(kept, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
return search, kept
|
||||
}
|
||||
|
||||
// geminiText joins the text parts of a Content, which may also arrive as a
|
||||
// bare string.
|
||||
func geminiText(raw json.RawMessage) string {
|
||||
@@ -753,6 +818,13 @@ func (e *geminiEncoder) event(ev Event) {
|
||||
if e.tool != nil {
|
||||
e.args.WriteString(ev.Text)
|
||||
}
|
||||
case KSearch:
|
||||
// what a search found, where Gemini's googleSearch tells it
|
||||
e.flushTool()
|
||||
if g := grounding([]Part{{Kind: Search, Text: ev.Text, Hits: ev.Hits}}); g != nil {
|
||||
e.w.event("", map[string]any{"candidates": []map[string]any{{"content": map[string]any{"role": "model", "parts": []map[string]any{}},
|
||||
"index": 0, "groundingMetadata": g}}, "modelVersion": e.model, "responseId": e.id})
|
||||
}
|
||||
case KError:
|
||||
e.w.event("", map[string]any{"error": map[string]any{"code": 502, "message": ev.Text, "status": "UNAVAILABLE"}})
|
||||
}
|
||||
@@ -777,14 +849,56 @@ func renderGemini(res Result, model string) []byte {
|
||||
if id == "" {
|
||||
id = newID()
|
||||
}
|
||||
cand := map[string]any{"content": map[string]any{"role": "model", "parts": geminiParts(res.Parts)},
|
||||
"finishReason": stopToGemini(res.Stop), "index": 0}
|
||||
if g := grounding(res.Parts); g != nil {
|
||||
cand["groundingMetadata"] = g
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"candidates": []map[string]any{{"content": map[string]any{"role": "model", "parts": geminiParts(res.Parts)},
|
||||
"finishReason": stopToGemini(res.Stop), "index": 0}},
|
||||
"candidates": []map[string]any{cand},
|
||||
"usageMetadata": res.Usage.gemini(), "modelVersion": model, "responseId": id,
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
// grounding is the searches among parts as a Gemini candidate's
|
||||
// groundingMetadata: the queries, and the pages found as its web chunks,
|
||||
// which a Gemini client lists as the answer's sources. A translated
|
||||
// reply's searches — Code Assist's googleSearch, magpie's own — reached a
|
||||
// Gemini client as nothing at all. nil with no search.
|
||||
func grounding(parts []Part) map[string]any {
|
||||
var queries []string
|
||||
chunks := []map[string]any{}
|
||||
seen := map[string]bool{}
|
||||
searched := false
|
||||
for _, p := range parts {
|
||||
if p.Kind != Search {
|
||||
continue
|
||||
}
|
||||
searched = true
|
||||
for _, q := range strings.Split(p.Text, "; ") {
|
||||
if q = strings.TrimSpace(q); q != "" && !slices.Contains(queries, q) {
|
||||
queries = append(queries, q)
|
||||
}
|
||||
}
|
||||
for _, h := range p.Hits {
|
||||
if h.URL == "" || seen[h.URL] {
|
||||
continue
|
||||
}
|
||||
seen[h.URL] = true
|
||||
chunks = append(chunks, map[string]any{"web": map[string]any{"uri": h.URL, "title": cmp.Or(h.Title, h.URL)}})
|
||||
}
|
||||
}
|
||||
if !searched {
|
||||
return nil
|
||||
}
|
||||
g := map[string]any{"groundingChunks": chunks}
|
||||
if len(queries) > 0 {
|
||||
g["webSearchQueries"] = queries
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// geminiModels is GET /v1beta/models: the catalog in Google's shape.
|
||||
func geminiModel(id, name string) map[string]any {
|
||||
return map[string]any{"name": "models/" + id, "displayName": name, "description": name + " via magpie",
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A Gemini client's own Google tools — googleSearch, urlContext,
|
||||
// codeExecution — reach Gemini as it sent them, and what googleSearch
|
||||
// found comes back to it as the candidate's groundingMetadata
|
||||
// (daoche_wuzui on X: magpie's Gemini dropped URL context and Google
|
||||
// Search).
|
||||
func TestGeminiClientKeepsGoogleTools(t *testing.T) {
|
||||
s, calls := aiStudio(t, nil)
|
||||
code, _, raw, _ := request(t, s, "POST", "/v1beta/models/google/gemini-2.5-flash:generateContent", "application/json",
|
||||
`{"contents":[{"role":"user","parts":[{"text":"who won euro 2024? see https://www.uefa.com/euro2024/"}]}],"tools":[{"googleSearch":{}},{"url_context":{}},{"codeExecution":{}}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("generateContent: %d %s", code, raw)
|
||||
}
|
||||
gem := geminiCalls(calls())
|
||||
if len(gem) != 1 {
|
||||
t.Fatalf("Gemini calls %d of %d", len(gem), len(calls()))
|
||||
}
|
||||
if tools := gjson.GetBytes(gem[0].body, "tools").Raw; tools != `[{"googleSearch":{}},{"urlContext":{}},{"codeExecution":{}}]` {
|
||||
t.Errorf("tools %s", tools)
|
||||
}
|
||||
g := gjson.GetBytes(raw, "candidates.0.groundingMetadata")
|
||||
if !strings.Contains(g.Get("webSearchQueries").Raw, "who won euro 2024") || g.Get("groundingChunks.#").Int() != 2 ||
|
||||
g.Get("groundingChunks.0.web.title").String() != "aljazeera.com" {
|
||||
t.Errorf("groundingMetadata %s in %s", g.Raw, raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), "Spain won Euro 2024") {
|
||||
t.Errorf("reply %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// The same tools in a Chat request, as Gemini's OpenAI-shaped clients send
|
||||
// them, by name or by type: googleSearch is the web search, the others are
|
||||
// kept for Gemini, and none goes on as a function with no name.
|
||||
func TestChatGoogleTools(t *testing.T) {
|
||||
r, err := readChat([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}],"tools":[
|
||||
{"googleSearch":{}},{"type":"url_context"},{"code_execution":{}},{"type":"function","function":{"name":"bash","parameters":{"type":"object"}}}]}`), false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !r.WebSearch {
|
||||
t.Error("googleSearch isn't a web search")
|
||||
}
|
||||
got, _ := json.Marshal(r.GoogleTools)
|
||||
if string(got) != `[{"urlContext":{}},{"codeExecution":{}}]` {
|
||||
t.Errorf("GoogleTools %s", got)
|
||||
}
|
||||
var names []string
|
||||
for _, tl := range r.Tools {
|
||||
names = append(names, tl.Name)
|
||||
}
|
||||
if strings.Join(names, ",") != "bash" {
|
||||
t.Errorf("tools %q", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Code Assist (Gemini CLI, Antigravity) sends a Gemini model the client's
|
||||
// Google tools with googleSearch, never a Claude model on the same
|
||||
// account, and never beside function declarations, which Google refuses.
|
||||
func TestCodeAssistSendsGoogleTools(t *testing.T) {
|
||||
r := &Request{WebSearch: true, GoogleTools: []json.RawMessage{json.RawMessage(`{"urlContext":{}}`), json.RawMessage(`{"codeExecution":{}}`)},
|
||||
Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}}
|
||||
tools := func(model string, r *Request) string {
|
||||
return gjson.GetBytes(buildCodeAssist(r, model, "antigravity"), "request.tools").Raw
|
||||
}
|
||||
if got := tools("gemini-3.8-flash", r); got != `[{"googleSearch":{}},{"urlContext":{}},{"codeExecution":{}}]` {
|
||||
t.Errorf("gemini: %s", got)
|
||||
}
|
||||
noSearch := *r
|
||||
noSearch.WebSearch = false
|
||||
if got := tools("gemini-3.8-flash", &noSearch); got != `[{"urlContext":{}},{"codeExecution":{}}]` {
|
||||
t.Errorf("gemini without search: %s", got)
|
||||
}
|
||||
if got := tools("claude-sonnet-4-6", &noSearch); got != "" {
|
||||
t.Errorf("claude: %s", got)
|
||||
}
|
||||
fns := *r
|
||||
fns.Tools = []Tool{{Name: "bash"}}
|
||||
if got := tools("gemini-3.8-flash", &fns); strings.Contains(got, "urlContext") || !strings.Contains(got, "functionDeclarations") {
|
||||
t.Errorf("beside functions: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A plugin speaking to Google's Code Assist (Antigravity's) searches with
|
||||
// googleSearch as a Google sign-in does; one at another host doesn't.
|
||||
func TestGooglePluginSearchesItself(t *testing.T) {
|
||||
plain := &Request{WebSearch: true, Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "news?"}}}}}
|
||||
ag := provider.PluginAtForTest("antigravity-plugin", "antigravity", "https://daily-cloudcode-pa.googleapis.com/v1beta")
|
||||
if !searchesFor(ag, provider.CodeAssist, "gemini-3.8-flash", plain) {
|
||||
t.Error("Antigravity's plugin doesn't search by googleSearch")
|
||||
}
|
||||
other := provider.PluginAtForTest("other", "other", "https://googleapis.com.evil.invalid/v1beta")
|
||||
if codeAssistSearches(other, provider.CodeAssist, "gemini-3.8-flash") {
|
||||
t.Error("a plugin at another host searches by googleSearch")
|
||||
}
|
||||
}
|
||||
|
||||
// Code Gemini ran and what it printed reach the client as text; they were
|
||||
// dropped.
|
||||
func TestCodeAssistDecodesRanCode(t *testing.T) {
|
||||
var text strings.Builder
|
||||
d := &codeAssistDecoder{}
|
||||
for _, line := range []string{
|
||||
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"executableCode":{"language":"PYTHON","code":"print(6*7)\n"}}]}}]}}`,
|
||||
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"codeExecutionResult":{"outcome":"OUTCOME_OK","output":"42\n"}}]}}]}}`,
|
||||
`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"It is 42."}]},"finishReason":"STOP"}]}}`,
|
||||
} {
|
||||
d.decode(line, func(ev Event) {
|
||||
if ev.Kind == KText {
|
||||
text.WriteString(ev.Text)
|
||||
}
|
||||
})
|
||||
}
|
||||
if got := text.String(); !strings.Contains(got, "```python\nprint(6*7)\n```") || !strings.Contains(got, "```\n42\n```") || !strings.HasSuffix(got, "It is 42.") {
|
||||
t.Errorf("text %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A search in a stream reaches a Gemini client as groundingMetadata.
|
||||
func TestGeminiStreamGrounding(t *testing.T) {
|
||||
g := grounding([]Part{{Kind: Text, Text: "x"}, {Kind: Search, Text: "a; b", Hits: []Hit{{URL: "https://a.example/", Title: "A"}, {URL: "https://a.example/"}, {URL: "https://b.example/"}}}})
|
||||
b, _ := json.Marshal(g)
|
||||
if string(b) != `{"groundingChunks":[{"web":{"title":"A","uri":"https://a.example/"}},{"web":{"title":"https://b.example/","uri":"https://b.example/"}}],"webSearchQueries":["a","b"]}` {
|
||||
t.Errorf("grounding %s", b)
|
||||
}
|
||||
if grounding([]Part{{Kind: Text, Text: "x"}}) != nil {
|
||||
t.Error("grounding without a search")
|
||||
}
|
||||
}
|
||||
@@ -301,6 +301,15 @@ type Request struct {
|
||||
ThinkOff bool
|
||||
Parallel *bool // parallel tool calls allowed
|
||||
WebSearch bool // the client offered its provider's own web search
|
||||
// GoogleTools are Gemini's own tools other than googleSearch (which
|
||||
// is WebSearch) that the client offered, each one tool object as
|
||||
// Google spells it — {"urlContext":{}}, {"codeExecution":{}},
|
||||
// {"googleMaps":{}} — for an upstream that speaks Gemini, inside
|
||||
// Code Assist's envelope too (buildCodeAssistSent). A Gemini client's
|
||||
// tools, or the same objects in a Chat request's tools. Left out, a
|
||||
// client's URL context and code execution were dropped on every
|
||||
// translated route (daoche_wuzui on X). No other API runs them.
|
||||
GoogleTools []json.RawMessage
|
||||
// Advisor is the model of Claude Code's advisor that magpie runs
|
||||
// itself (advisor_serve.go), "" when it doesn't: its calls and results
|
||||
// in the conversation are ToolCall and ToolResult parts then
|
||||
|
||||
@@ -143,7 +143,23 @@ func googleAccount(p provider.Provider) bool {
|
||||
// only a request that declares none (searchesFor). One that does is given
|
||||
// magpie's search, which the account answers itself (ownSearcher, #757).
|
||||
func codeAssistSearches(p provider.Provider, proto provider.Protocol, model string) bool {
|
||||
return proto == provider.CodeAssist && googleAccount(p) && searchModel(model)
|
||||
return proto == provider.CodeAssist && (googleAccount(p) || googlePlugin(p)) && searchModel(model)
|
||||
}
|
||||
|
||||
// googlePlugin is a plugin whose models are spoken to on Code Assist
|
||||
// (its npm @ai-sdk/google) at Google's own host: the Antigravity plugin's
|
||||
// account asks daily-cloudcode-pa.googleapis.com, which runs googleSearch
|
||||
// for Gemini as a built-in Google sign-in's Code Assist does. Left to
|
||||
// magpie's search, a Gemini client's googleSearch never reached it, and
|
||||
// the web_search function magpie offered in its place kept the client's
|
||||
// URL context out too (daoche_wuzui on X). A plugin at another host is
|
||||
// not known to.
|
||||
func googlePlugin(p provider.Provider) bool {
|
||||
if !p.IsPlugin() || p.Base(provider.CodeAssist) == "" {
|
||||
return false
|
||||
}
|
||||
h := strings.ToLower(provider.HostOf(p.PluginAPI()))
|
||||
return h == "googleapis.com" || strings.HasSuffix(h, ".googleapis.com")
|
||||
}
|
||||
|
||||
// geminiKeySearches is a provider asked with a key at Google AI Studio's
|
||||
|
||||
@@ -145,6 +145,15 @@ func PluginForTest(id, pluginID string) Provider {
|
||||
return Provider{ID: id, Account: &Account{Agent: "plugin", User: id, plugin: &pp}}
|
||||
}
|
||||
|
||||
// PluginAtForTest is PluginForTest for a plugin whose provider says its
|
||||
// requests go to api and whose models speak Code Assist.
|
||||
func PluginAtForTest(id, pluginID, api string) Provider {
|
||||
p := PluginForTest(id, pluginID)
|
||||
p.Account.plugin.API = api
|
||||
p.Account.codeAssist = pluginBase + pluginID
|
||||
return p
|
||||
}
|
||||
|
||||
// PluginProvider is the id OpenCode knows the plugin's provider p is by
|
||||
// (grok, kiro), whatever magpie names it; "" for one no plugin gives.
|
||||
func (p Provider) PluginProvider() string {
|
||||
|
||||
Reference in New Issue
Block a user