Files
magpie/internal/gateway/gemini.go
T
JoeyWu-tech ed9d849a21 gateway: a Gemini client's imageConfig reaches every Gemini upstream (#3820)
GuoJinguang (#3820): a Gemini client's generateContent asking a
gemini-*-image-preview model for generationConfig.imageConfig
{"imageSize":"4K"} drew 1024x1024 through magpie, where the same
request straight to their relay drew 4096x4096. The picture came, at
the model's default size, and nothing said the size had been dropped.

parseGemini didn't read imageConfig, so wherever magpie builds a Gemini
client's request again it was gone: a request asked for one body to a
Gemini API that isn't Vertex AI (always translated, since attempt asks
a Gemini API streamGenerateContent and reads the stream back into one
body), and every request to Code Assist or Antigravity, which go in
their envelope. A streamed request to a Gemini API, and a Gemini
client's request to Vertex AI, streamed or not, is relayed as it came
(passthrough) and kept it.

The reporter's request went to the relay's chat completions instead.
Their provider has a Chat URL beside its Gemini one, and attempt turns
relay off for a Gemini request asked for one body without ownAPI, so
it goes to the first API usable gives: Chat, as Speaks puts a custom
provider's Gemini last. That default is meant (uaSetup in
user_agent_test.go: "Gemini's own wire, which a provider on Chat too
isn't asked on"), and Chat has no field for imageConfig.

Now parseGemini keeps generationConfig.imageConfig as the client sent
it (Request.ImageConfig, raw as Metadata and ClientMetadata are, so
Vertex AI's own fields beside imageSize and aspectRatio go on too), and
buildCodeAssistSent, which every translation to a Gemini API goes
through, writes it into generationConfig: the Gemini API (buildGemini),
Vertex AI (buildVertex), and Code Assist and Antigravity in their
envelope. A request that asked for none is sent none. Chat, Responses
and Messages are left as they were: I found no vendor documenting a
field for it there, so none is made up. gateway-routing.md says where
imageConfig goes.

At a provider with both URLs, a request asked for one body reaches the
Gemini URL, and its imageConfig with it, when the user picks Gemini as
the API the model is asked on in the provider editor (SetModelAPI,
tested below). The next commit sends one that carries imageConfig
there by default.

Left as on main, each in its own issue:
- a Gemini client's image request to a provider with no Gemini URL
  (the Google Gemini preset's OpenAI-compatible endpoint, OpenRouter,
  another magpie, a relay saved with a Chat URL alone) carries no
  imageConfig, asks no modalities, and reads no image back from chat
  (#3935);
- /v1/images/generations and /v1/images/edits send a size to a Gemini
  image model as an aspect ratio only (drawGemini, drawChat), and to
  Code Assist only in words (drawCodeAssist), so nothing above 1K can
  be asked there; a Gemini client's request never takes that path
  (#3936);
- the rest of what a translated Gemini request drops: safetySettings,
  topK, seed, responseModalities, and the newer responseFormat
  (Google's next spelling of the same ask), among the fields
  parseGemini doesn't read (#3937).

This commit's tree (2b421ece, on origin/main 0c17aac2) wasn't run on
its own. It is 85b532c6 rebased, with the same internal/ patch-id and
the same gateway-routing.md line, which applied as is. Its two tests
ran at the next commit's tree, -count=5 and -race -count=5, and in the
full suite there. What was run for 85b532c6, at tree de27856c on
origin/main f8cd964a, the same code (not this tree), with go1.26.8,
linux/amd64, Linux 5.15, outside graftcp, umask 077:
- TestGeminiImageConfigReachesTheGeminiAPI, new: a fake relay records
  each request. Five generationConfigs (imageSize 4K, the reporter's;
  aspectRatio 16:9 and imageSize 2K beside a thinkingConfig; the
  snake_case image_config; none; temperature alone), at a provider
  with the Gemini URL alone (generateContent and streamed), with a Chat
  URL too (streamed), and with a Chat URL too and the model's API set
  to Gemini (generateContent): 4 of 4 subtests ok
- TestGeminiImageConfigReachesCodeAssist, new: the same five to an
  Antigravity sign-in's gemini-3.1-flash-image, generateContent and
  streamed, read in request.generationConfig: ok
- both on f8cd964a, the test file alone: red. The Gemini URL alone and
  the set-to-Gemini subtests, 3 asks each: "asked {...}:
  /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent was
  sent "": ...", no imageConfig; Code Assist, both methods, 3 asks
  each: "sent "": ..."; the two streamed subtests pass, the relay
  having kept it
- broken by hand in a scratch worktree at that tree, each alone:
  - parseGemini not reading it: the same 12 lines red
  - buildCodeAssistSent not writing it: the same 12 lines red
  - buildCodeAssistSent writing it when none was asked: 8 lines red,
    "asked for none: ... was sent null" and "sent null"
- both, -race -count=5: ok
- go test -tags nogui -count=1 -timeout 45m -v ./internal/gateway,
  Bun 1.4.2: 5402 passed with their subtests, 3 skipped, 1 red,
  TestPluginToldWhereTheAgentWorks (#3675)
- tools/vetset.sh: gofmt -l clean; vet for linux, windows and darwin
  with -tags nogui, windows vet, and the three builds exit 0; untagged
  linux vet and build exit 1 at pkg-config (no GTK headers here)
- the full suite ran once, at 44a63bd5's tree; de27856c is covered by
  the gateway package and the vet set above

Not tried: the reporter's relay, or any real Gemini API, Vertex AI or
Antigravity image model; the upstreams are fakes that record the body.
Whether a relay's Gemini API passes imageConfig on to Google is the
relay's.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

729 lines
22 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"fmt"
"slices"
"strings"
)
// ---- Google Gemini API (client side) ----------------------------------------
//
// Gemini CLI speaks only Google's own API, so the gateway serves it:
// POST /v1beta/models/{model}:generateContent
// POST /v1beta/models/{model}:streamGenerateContent?alt=sse
// POST /v1beta/models/{model}:countTokens
// GET /v1beta/models
// The model is in the path, so the route handler folds it (and whether the
// call streams) into the body before the shared request path sees it.
type gPart struct {
Text string `json:"text,omitempty"`
Thought bool `json:"thought,omitempty"`
Signature string `json:"thoughtSignature,omitempty"`
InlineData *struct {
MimeType string `json:"mimeType"`
Data string `json:"data"`
} `json:"inlineData,omitempty"`
FileData *struct {
MimeType string `json:"mimeType"`
FileURI string `json:"fileUri"`
} `json:"fileData,omitempty"`
FunctionCall *struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args json.RawMessage `json:"args,omitempty"`
} `json:"functionCall,omitempty"`
FunctionResponse *struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Response json.RawMessage `json:"response,omitempty"`
// Parts is what the function gave back beside its response: the
// image agy's view_file read, as inlineData (#1038)
Parts []gPart `json:"parts,omitempty"`
} `json:"functionResponse,omitempty"`
}
type gContent struct {
Role string `json:"role,omitempty"`
Parts []gPart `json:"parts"`
}
type gRequest struct {
Model string `json:"model"`
Stream bool `json:"stream"`
Contents []gContent `json:"contents"`
SystemInstruction json.RawMessage `json:"systemInstruction,omitempty"`
Tools []struct {
FunctionDeclarations []struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
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 {
Mode string `json:"mode"`
AllowedFunctionNames []string `json:"allowedFunctionNames,omitempty"`
} `json:"functionCallingConfig,omitempty"`
} `json:"toolConfig,omitempty"`
GenerationConfig *struct {
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"topP,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
ResponseMimeType string `json:"responseMimeType,omitempty"`
ResponseSchema json.RawMessage `json:"responseSchema,omitempty"`
ResponseJSONSchema json.RawMessage `json:"responseJsonSchema,omitempty"`
ThinkingConfig *gThinking `json:"thinkingConfig,omitempty"`
ImageConfig json.RawMessage `json:"imageConfig,omitempty"`
} `json:"generationConfig,omitempty"`
}
// gThinking is a Gemini request's generationConfig.thinkingConfig.
type gThinking struct {
ThinkingBudget *int `json:"thinkingBudget,omitempty"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
IncludeThoughts bool `json:"includeThoughts,omitempty"`
}
// effort is the reasoning the thinkingConfig asks for: its level, else its
// budget as the level it is nearest, -1 (the model decides) as medium. ""
// when it asks for none: a budget of 0, or includeThoughts alone.
func (tc *gThinking) effort() string {
switch {
case tc.ThinkingLevel != "":
return effortOf(tc.ThinkingLevel)
case tc.ThinkingBudget != nil && *tc.ThinkingBudget < 0:
return "medium" // -1: let the model decide
case tc.ThinkingBudget != nil:
return effortOfBudget(*tc.ThinkingBudget)
}
return ""
}
// buildGemini is a generateContent body for an upstream that speaks Gemini
// itself (Factory's /api/llm/g). The contents are the ones Code Assist
// sends inside its envelope. systemInstruction has no role: droid sends
// {parts:[{text}]}. droid sends no stream field; Factory answers SSE either
// way, and a client that asked for JSON is given it after the fact.
func buildGemini(r *Request, model string) ([]byte, error) {
req, err := geminiRequest(r, model, "gemini")
if err != nil {
return nil, err
}
req["model"] = model
return marshalBody(req, "")
}
// geminiRequest is the request inside the Code Assist envelope that
// buildCodeAssistSent builds for agent, unwrapped, with no stream field
// and a systemInstruction with no role.
func geminiRequest(r *Request, model, agent string) (map[string]any, error) {
var wrap struct {
Request map[string]any `json:"request"`
}
if err := json.Unmarshal(buildCodeAssistSent(r, model, agent), &wrap); err != nil {
return nil, err
}
if wrap.Request == nil {
return nil, fmt.Errorf("empty Gemini request")
}
if si, ok := wrap.Request["systemInstruction"].(map[string]any); ok {
delete(si, "role")
}
delete(wrap.Request, "stream")
return wrap.Request, nil
}
// geminiCamel spells a Gemini request's fields in camelCase. Google's API
// reads proto JSON, which takes a field by either name — inline_data,
// mime_type, function_call as well as inlineData — and clients (agy, the
// Python SDK's raw calls) send the snake_case ones; read only as camelCase
// an image or a PDF was left out, and the model made up what it held
// (#934). The values that are the caller's own — a call's args, a
// result's response, the schemas — keep their keys as they are.
func geminiCamel(body []byte) []byte {
if !bytes.Contains(body, []byte("_")) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var v any
if dec.Decode(&v) != nil {
return body
}
changed := false
v = camelKeys(v, &changed)
if !changed {
return body
}
out, err := json.Marshal(v)
if err != nil {
return body
}
return out
}
// geminiOwn are the fields whose values are the caller's, not Google's:
// their keys are kept as they are.
var geminiOwn = map[string]bool{"args": true, "response": true, "parameters": true, "parametersJsonSchema": true,
"responseSchema": true, "responseJsonSchema": true, "labels": true}
func camelKeys(v any, changed *bool) any {
switch t := v.(type) {
case []any:
for i := range t {
t[i] = camelKeys(t[i], changed)
}
case map[string]any:
for k, val := range t {
nk := k
if strings.Contains(k, "_") {
nk = snakeToCamel(k)
}
if !geminiOwn[nk] {
val = camelKeys(val, changed)
}
if nk == k {
t[k] = val
continue
}
*changed = true
delete(t, k)
if _, both := t[nk]; !both { // sent both ways, the camelCase one is kept
t[nk] = val
}
}
}
return v
}
func snakeToCamel(s string) string {
parts := strings.Split(s, "_")
for i := 1; i < len(parts); i++ {
if p := parts[i]; p != "" {
parts[i] = strings.ToUpper(p[:1]) + p[1:]
}
}
return strings.Join(parts, "")
}
func parseGemini(body []byte) (*Request, error) {
body = geminiCamel(body)
var g gRequest
if err := json.Unmarshal(body, &g); err != nil {
return nil, fmt.Errorf("invalid request: %v", err)
}
r := &Request{Model: g.Model, Stream: g.Stream}
r.System = geminiText(g.SystemInstruction)
if gc := g.GenerationConfig; gc != nil {
r.MaxTokens, r.Temp, r.TopP, r.Stop = gc.MaxOutputTokens, gc.Temperature, gc.TopP, gc.StopSequences
if tc := gc.ThinkingConfig; tc != nil {
r.Effort = tc.effort()
r.Thinking = r.Effort != ""
}
// the size and shape of the image asked for, which only an
// upstream that speaks Gemini takes (#3820)
if ic := gc.ImageConfig; len(ic) > 0 && string(ic) != "null" {
r.ImageConfig = ic
}
// structured output, asked for in the upstream's own field
// (Format) and in words as well: a Gemini client doesn't know
// OpenAI's rule that a json_object's prompt say "JSON"
if strings.HasPrefix(gc.ResponseMimeType, "application/json") {
ask := "Respond with a single JSON value and nothing else"
r.Format = &Format{Type: "json_object"}
if s := firstJSON(gc.ResponseJSONSchema, gc.ResponseSchema); s != "" {
ask += ", matching this JSON schema:\n" + s
r.Format = &Format{Type: "json_schema", Name: formatName, Schema: json.RawMessage(s)}
}
if r.System != "" {
r.System += "\n\n"
}
r.System += ask + "."
}
}
// function results carry the call's id when the client kept it; older
// clients send only the name, matched to the first call of that name
// still unanswered, as Gemini lists a turn's responses in its calls'
// order (two calls of one function each get their own answer), else to
// the latest call of that name
names := map[string]string{}
open := map[string][]string{} // calls of each name not yet answered
for _, c := range g.Contents {
role := "user"
if c.Role == "model" || c.Role == "assistant" {
role = "assistant"
}
msg := Message{Role: role}
// a function's result is the user's side of the turn whatever role
// it came under: Antigravity CLI sends its tools' results as
// "model" (#650), and kept there the request ends with the model's
// turn, which Antigravity turns away
turn := func(role string) {
if msg.Role != role {
if len(msg.Parts) > 0 {
r.Messages = append(r.Messages, msg)
}
msg = Message{Role: role}
}
}
for _, p := range c.Parts {
if p.FunctionResponse != nil {
turn("user")
} else {
turn(role)
}
switch {
case p.FunctionCall != nil:
fc := p.FunctionCall
id := fc.ID
if id == "" {
id = "call_" + newID()
}
names[fc.Name] = id
open[fc.Name] = append(open[fc.Name], id)
// its thought signature goes back to Gemini as it came (#1445)
msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: id, Name: fc.Name, Args: parseArgs(string(fc.Args)), Signature: p.Signature})
case p.FunctionResponse != nil:
fr := p.FunctionResponse
id := fr.ID
if id == "" {
id = names[fr.Name]
if q := open[fr.Name]; len(q) > 0 {
id = q[0]
}
}
open[fr.Name] = slices.DeleteFunc(open[fr.Name], func(c string) bool { return c == id })
text, isErr := functionResponseText(fr.Response)
images, files := functionResponseParts(fr.Parts, &text)
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: id, Name: fr.Name, Text: text, Images: images, IsError: isErr})
// a file no tool result can hold follows it in the same turn
msg.Parts = append(msg.Parts, files...)
case p.InlineData != nil:
if strings.HasPrefix(p.InlineData.MimeType, "image/") {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: p.InlineData.MimeType, Data: p.InlineData.Data})
} else {
msg.Parts = append(msg.Parts, Part{Kind: File, MediaType: p.InlineData.MimeType, Data: p.InlineData.Data})
}
case p.FileData != nil:
if strings.HasPrefix(p.FileData.MimeType, "image/") {
msg.Parts = append(msg.Parts, Part{Kind: Image, MediaType: p.FileData.MimeType, URL: p.FileData.FileURI})
} else {
// 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.Thought:
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: p.Text, Signature: p.Signature})
case p.Text != "" || p.Signature != "":
msg.Parts = append(msg.Parts, Part{Kind: Text, Text: p.Text, Signature: p.Signature})
}
}
if len(msg.Parts) > 0 {
r.Messages = append(r.Messages, msg)
}
}
// ANY and VALIDATED can limit declarations to named functions. Keep
// VALIDATED's auto choice, while ANY still requires a call.
var allowed map[string]bool
if g.ToolConfig != nil && g.ToolConfig.FunctionCallingConfig != nil {
fc := g.ToolConfig.FunctionCallingConfig
if (strings.EqualFold(fc.Mode, "ANY") || strings.EqualFold(fc.Mode, "VALIDATED")) && len(fc.AllowedFunctionNames) > 0 {
allowed = make(map[string]bool, len(fc.AllowedFunctionNames))
for _, name := range fc.AllowedFunctionNames {
allowed[name] = true
}
}
}
for _, t := range g.Tools {
if t.GoogleSearch != nil || t.GoogleSnake != nil {
r.WebSearch = true
}
for _, f := range t.FunctionDeclarations {
if allowed != nil && !allowed[f.Name] {
continue
}
schema := f.ParametersJSONSchema
if len(schema) == 0 {
schema = jsonSchema(f.Parameters)
}
r.Tools = append(r.Tools, Tool{Name: f.Name, Description: f.Description, Schema: schema})
}
}
if g.ToolConfig != nil && g.ToolConfig.FunctionCallingConfig != nil {
fc := g.ToolConfig.FunctionCallingConfig
switch strings.ToUpper(fc.Mode) {
case "NONE":
r.ToolChoice = "none"
case "ANY":
// A name is only forcible when its declaration survived filtering.
// Otherwise retain required so translated routes reject an empty
// callable set instead of silently returning plain text.
if len(fc.AllowedFunctionNames) == 1 && len(r.Tools) == 1 && r.Tools[0].Name == fc.AllowedFunctionNames[0] {
r.ToolChoice = "name:" + fc.AllowedFunctionNames[0]
} else {
r.ToolChoice = "required"
}
default:
r.ToolChoice = "auto"
}
}
return r, nil
}
// geminiText joins the text parts of a Content, which may also arrive as a
// bare string.
func geminiText(raw json.RawMessage) string {
if len(raw) == 0 {
return ""
}
var s string
if json.Unmarshal(raw, &s) == nil {
return s
}
var c gContent
if json.Unmarshal(raw, &c) != nil {
var parts []gPart
if json.Unmarshal(raw, &parts) != nil {
return ""
}
c.Parts = parts
}
var b strings.Builder
for _, p := range c.Parts {
if !p.Thought && p.Text != "" {
if b.Len() > 0 {
b.WriteString("\n\n")
}
b.WriteString(p.Text)
}
}
return b.String()
}
// functionResponseParts reads a functionResponse's own parts (Gemini 3's
// multimodal function responses): its images go with the result, as the
// other APIs' tool results carry them, and any other file (a PDF, audio)
// is given back as a part of the turn, since a tool result holds only
// text and images. Left unread, the model never saw what the tool read and
// made it up (#1038).
func functionResponseParts(parts []gPart, text *string) (images, files []Part) {
for _, p := range parts {
var part Part
switch {
case p.InlineData != nil:
part = Part{MediaType: p.InlineData.MimeType, Data: p.InlineData.Data}
case p.FileData != nil:
part = Part{MediaType: p.FileData.MimeType, URL: p.FileData.FileURI}
case p.Text != "" && !p.Thought:
if strings.TrimSpace(*text) != "" {
*text += "\n\n"
}
*text += p.Text
continue
default:
continue
}
if strings.HasPrefix(part.MediaType, "image/") {
part.Kind = Image
images = append(images, part)
} else {
part.Kind = File
files = append(files, part)
}
}
return images, files
}
// functionResponseText is what a tool said, as the other APIs carry it:
// Gemini CLI wraps output in {output} or {error}; anything else is the
// response object as JSON.
func functionResponseText(raw json.RawMessage) (string, bool) {
if len(raw) == 0 {
return "", false
}
var m map[string]json.RawMessage
if json.Unmarshal(raw, &m) == nil {
if e, ok := m["error"]; ok && len(m) == 1 {
var s string
if json.Unmarshal(e, &s) == nil {
return s, true
}
return string(e), true
}
if o, ok := m["output"]; ok && len(m) == 1 {
var s string
if json.Unmarshal(o, &s) == nil {
return s, false
}
return string(o), false
}
}
var s string
if json.Unmarshal(raw, &s) == nil {
return s, false
}
return string(raw), false
}
func firstJSON(xs ...json.RawMessage) string {
for _, x := range xs {
if len(x) > 0 {
return string(jsonSchema(x))
}
}
return ""
}
// jsonSchema turns Gemini's OpenAPI-flavoured schema into JSON Schema:
// type names come lowercased and its own extras drop out.
func jsonSchema(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 {
return nil
}
var v any
if json.Unmarshal(raw, &v) != nil {
return raw
}
var walk func(any) any
walk = func(v any) any {
switch x := v.(type) {
case map[string]any:
out := make(map[string]any, len(x))
for k, val := range x {
switch k {
case "type":
switch t := val.(type) {
case string:
out[k] = strings.ToLower(t)
case []any:
ts := make([]any, len(t))
for i, e := range t {
if s, ok := e.(string); ok {
ts[i] = strings.ToLower(s)
} else {
ts[i] = e
}
}
out[k] = ts
default:
out[k] = val
}
case "nullable":
if b, ok := val.(bool); ok && b {
out["x-nullable"] = true
}
case "propertyOrdering", "example":
default:
out[k] = walk(val)
}
}
return out
case []any:
out := make([]any, len(x))
for i, e := range x {
out[i] = walk(e)
}
return out
}
return v
}
b, err := json.Marshal(walk(v))
if err != nil {
return raw
}
return b
}
func stopToGemini(s string) string {
switch s {
case "length":
return "MAX_TOKENS"
case "filter":
return "SAFETY"
}
return "STOP"
}
// gemini is a Usage as usageMetadata: the prompt count includes cached
// tokens (see prompt), and thoughts are counted apart from the answer.
func (u Usage) gemini() map[string]any {
out := map[string]any{"promptTokenCount": u.prompt(), "candidatesTokenCount": max(u.Output-u.Reasoning, 0),
"totalTokenCount": u.prompt() + u.Output}
if u.CacheRead > 0 {
out["cachedContentTokenCount"] = u.CacheRead
}
if u.Reasoning > 0 {
out["thoughtsTokenCount"] = u.Reasoning
}
return out
}
// geminiParts renders reply parts. Function calls go out whole, so a
// streaming encoder holds one back until its arguments have all arrived.
func geminiParts(parts []Part) []map[string]any {
out := []map[string]any{}
for _, p := range parts {
switch p.Kind {
case Text:
if p.Text != "" || p.Signature != "" {
part := map[string]any{"text": p.Text}
if p.Signature != "" {
part["thoughtSignature"] = p.Signature
}
out = append(out, part)
}
case Thinking:
if p.Text != "" {
out = append(out, map[string]any{"text": p.Text, "thought": true})
}
case Image:
if p.Data != "" {
out = append(out, map[string]any{"inlineData": map[string]any{"mimeType": p.MediaType, "data": p.Data}})
}
case ToolCall:
// a signature that rode in the id goes where Gemini has it
id, sig := unsignedID(p.ID)
if id == "" {
id = "call_" + newID()
}
part := map[string]any{"functionCall": map[string]any{"id": id, "name": p.Name, "args": argsOf(p)}}
if sig != "" {
part["thoughtSignature"] = sig
}
out = append(out, part)
}
}
return out
}
// geminiEncoder writes events as a Gemini streamGenerateContent stream.
type geminiEncoder struct {
w *sseWriter
model string
id string
started bool
tool *Part // function call whose arguments are still arriving
args strings.Builder
col collector
}
func (e *geminiEncoder) chunk(parts []map[string]any, finish string, usage map[string]any) {
if len(parts) == 0 && finish == "" && usage == nil {
return
}
if parts == nil {
parts = []map[string]any{}
}
cand := map[string]any{"content": map[string]any{"role": "model", "parts": parts}, "index": 0}
if finish != "" {
cand["finishReason"] = finish
}
msg := map[string]any{"candidates": []map[string]any{cand}, "modelVersion": e.model, "responseId": e.id}
if usage != nil {
msg["usageMetadata"] = usage
}
e.w.event("", msg)
}
// keepalive sends nothing: Google's SDK takes a stream's "data: " lines
// one after another from the front and gets stuck on anything else, a
// comment too, and there is no event without content to send instead.
func (e *geminiEncoder) keepalive() {}
func (e *geminiEncoder) start(ev Event) {
if e.started {
return
}
e.started = true
e.id = ev.MsgID
if e.id == "" {
e.id = newID()
}
if ev.Model != "" {
e.model = ev.Model
}
e.w.begin()
}
// flushTool sends the function call that was being assembled.
func (e *geminiEncoder) flushTool() {
if e.tool == nil {
return
}
e.tool.Args = parseArgs(e.args.String())
e.chunk(geminiParts([]Part{*e.tool}), "", nil)
e.tool = nil
e.args.Reset()
}
func (e *geminiEncoder) event(ev Event) {
if ev.Kind != KStart && !e.started {
e.start(Event{})
}
switch ev.Kind {
case KStart:
e.start(ev)
case KText:
e.flushTool()
e.chunk(geminiParts([]Part{{Kind: Text, Text: ev.Text}}), "", nil)
case KThink:
e.flushTool()
e.chunk(geminiParts([]Part{{Kind: Thinking, Text: ev.Text}}), "", nil)
case KTextSig:
// Gemini's signature on its text, as Gemini streams it (#1445)
e.flushTool()
e.chunk([]map[string]any{{"text": "", "thoughtSignature": ev.Text}}, "", nil)
case KImage:
e.flushTool()
e.chunk(geminiParts([]Part{{Kind: Image, MediaType: ev.Name, Data: ev.Text}}), "", nil)
case KToolStart:
e.flushTool()
e.tool = &Part{Kind: ToolCall, ID: ev.ID, Name: ev.Name}
case KToolArgs:
if e.tool != nil {
e.args.WriteString(ev.Text)
}
case KError:
e.w.event("", map[string]any{"error": map[string]any{"code": 502, "message": ev.Text, "status": "UNAVAILABLE"}})
}
e.col.add(ev)
}
func (e *geminiEncoder) finish() {
if !e.started {
e.start(Event{})
}
e.flushTool()
res := e.col.finish()
e.chunk(nil, stopToGemini(res.Stop), res.Usage.gemini())
}
// renderGemini is the non-streaming reply.
func renderGemini(res Result, model string) []byte {
if res.Model != "" {
model = res.Model
}
id := res.ID
if id == "" {
id = newID()
}
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}},
"usageMetadata": res.Usage.gemini(), "modelVersion": model, "responseId": id,
})
return b
}
// 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",
"supportedGenerationMethods": []string{"generateContent", "streamGenerateContent", "countTokens"}}
}