gateway: a Chat body relayed to Gemini's OpenAI-compatible API goes without Ollama's options (#3097)

What changed: a client that takes the gateway for an Ollama server (its
/api/show is answered in Ollama's shape) sends Ollama's per-request
options beside its Chat fields. The google preset serves a model on
Gemini's OpenAI-compatible endpoint, so such a request is relayed as it
came, and that endpoint reads proto JSON: an unknown name turns the
whole request away with 400 "Invalid JSON payload received. Unknown
name \"options\": Cannot find field", every call, whatever the effort.
A body relayed to a Gemini OpenAI-compatible upstream (geminiCompat)
now goes without the top-level options, whose runner settings have no
place on a Chat API, as the Ollama route's own body builder already
leaves them out (ollamaChatBody). Another vendor's Chat upstream still
gets the body as the client sent it, and translated requests are
unchanged: they are built from the request's own fields, which never
carried options. geminiCompat is worked out once where the thought
signatures ask for it too.

Run: TestGeminiCompatRelayLeavesOutOllamaOptions fails on the old code
with "Ollama's options reached Gemini's OpenAI-compatible API" and
passes with the change; a request to another vendor's Chat upstream
still carries options there. go test ./internal/gateway/ ok (346.6s);
go test ./... -timeout 45m: 66 packages ok, internal/agent TestMothX
and internal/gui TestProxyCheckSaysAProxyPassedBy red, both red with
the change stashed on f5b01574 too (this machine's, not this change's);
gofmt -l clean; go vet ./... exits 0 (a cgo warning in internal/gui is
the baseline's); GOOS=linux GOARCH=amd64 go vet -tags nogui ./... and
GOOS=windows GOARCH=amd64 go vet ./... clean (GOOS=linux/darwin vet of
the gui fails in wails v3 beta on the baseline too); go build (darwin
arm64), GOOS=windows GOARCH=amd64 and GOOS=linux GOARCH=amd64
-tags nogui builds ok (a plain GOOS=linux/darwin build fails inside
wails v3 beta on the baseline too). Not tried against Google's real
endpoint: the reporter's 400 names the unknown field, and the fake
upstream checks what it is sent.

Generated-by: GLM-5.3-Flash (ZCode)
This commit is contained in:
ggbdpq
2026-11-01 16:43:20 +08:00
committed by yetone
parent 026d4423d0
commit 9a4eaab82a
3 changed files with 76 additions and 1 deletions
+1
View File
@@ -266,6 +266,7 @@ recorded as a prediction failure (`noPrediction`).
- Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`, with the message's `reasoning` left out once its text is there), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`).
- Vertex AI takes a function declaration's parameters as its own Schema object, whose `type` is required, and turns the whole request away over one schema without it, though the tool is never called: 400 "`mcp__cua-driver__drag` functionDeclaration `parameters.target` schema didn't specify the schema type field." (kthink on Discord: dsh with cua-driver's MCP tools, from before cua's own fix in its #4888, on Command Code's `google/gemini-3.8-flash`, which Command Code's gateway serves on Vertex; `target` was an anyOf of an untyped oneOf and null, `scope` a const). A body whose `model` names Gemini (`geminiNamed`: the id's last `/` segment starts with `gemini`, whoever serves it) has each untyped schema under its tools' `function.parameters`, `parameters` or `input_schema` given its type in place (`geminiToolTypes` in [`gemini_schema.go`](../../internal/gateway/gemini_schema.go), in `forwardOnce`, so a plugin's request too): from its enum or const values, its keywords or its branches, null left out (an object's or array's keywords, `properties` or `items`, before its values: a string enum beside `items` typed `"string"` sent items on a string, and Antigravity turned the turn away with "properties[display].items: field predicate failed: $type == Type.ARRAY", ferock on Discord; `TestGeminiToolTypesItemsBeforeEnum`), `{}` or a description alone a string, a tool's root an object. A node whose branches have more than one type, an unresolved `$ref` or union, and anything under `not` or `if` are left as they came, so such a schema can still be refused; every other model's tools go byte for byte. Google's own Gemini API and Code Assist are sent `parametersJsonSchema` and Antigravity `plainSchema`, so a Gemini-shaped body isn't walked (`TestGeminiToolTypesCuaDriverDrag`, with cua-driver's drag schema as its server listed it, `TestGeminiToolTypes`). `plainSchema` itself keeps an array's keywords (`items`, `minItems`, `maxItems`) on an array only and an object's (`properties`, `required` …) on an object only, and of a type list takes the type its `items` or `properties` are for, so a body a magpie from before sends is taken too (`TestAntigravityItemsOnlyOnArrays`). Google's Schema is an object with a fixed set of fields, so a boolean schema (`items: true`, a property's `true` or `false`) or an `x-` keyword such as MCP's `x-mcp-header` (2026-07-28 spec, SEP-2243) turns the whole request away ("Invalid value at '…items.items' (…aiplatform.master.Schema), true" and 'Unknown name "x-mcp-header" … Cannot find field', han_tiv on Discord). `plainSchema` is an allow-list, so `x-` keys never pass it; a boolean is `{}` for true and left out for false (a false property leaves `required` too, a false `items` is `items {}` with `maxItems 0`). Before typing, `geminiToolTypes` runs `geminiSchemaShapes`, which does the same for the relay's case: true is `{}`, false is left out, `x-` keywords go (a property named `x-…` stays), and `additionalProperties` and the `unevaluated…` keywords keep their booleans; a schema with neither goes byte for byte (`TestAntigravityBooleanSchemaAndXKeys`, `TestPlainSchemaBooleansAndXKeysEverywhere`, `TestGeminiToolTypesDropsBooleansAndXKeys`). What is left is still JSON Schema, so `parametersJsonSchema` (Gemini API, Code Assist, Vertex), which runs after it on a Gemini-named body, takes it as before.
- A Responses request's top-level `access_programs`, the Cyber program Codex asks the model under (`{"cyber":"standard"}` on a subagent it inherits, OpenAI's Daybreak programs, magpie-releases#18), goes only where Codex itself would send it: codex-rs sends it with a ChatGPT sign-in, or an API key on its provider named `openai`, and to no other provider (`cyber_access_program.rs`, `for_auth`, `for_provider`). In `forwardOnce`, relayed or built (from Chat too), it goes as it came to a ChatGPT (Codex) account, a host ending in `openai.com`, another magpie (`IsRemoteMagpie`, whose own upstream decides) and a relay set `codexAsSent` when Codex sent the request; every other Responses upstream is sent the request without it (`keepsAccessPrograms`, `withoutTopMember`, the rest byte for byte). OpenCode Go answered it, for DeepSeek and GLM, with 503 "Upstream request failed: Endpoint is unavailable." and 200 without it or with null; its Haiku took it (#3172, three reporters' real A/B runs). It is taken out before the user's extraBody is merged, so an `access_programs` written there still goes. Chat and Messages builds never carry it; a Chat request relayed as it came keeps whatever its client wrote. `TestAccessProgramsGoToOpenAIAlone`, `TestWithoutTopMember`, `TestCodexAccessProgramsReachBackend`.
- A client that took the gateway for an Ollama server (its `/api/show` is answered in Ollama's shape) sends Ollama's per-request `options` beside its Chat fields. Gemini's OpenAI-compatible API (`geminiCompat`: AI Studio's, or a local proxy in front of it) reads proto JSON and turns the whole request away over a name it doesn't know (#3097), so a body relayed to one goes without `options`, whose runner settings have no place on a Chat API, as the Ollama route's own body builder leaves them out (`ollamaChatBody`). Another vendor's Chat upstream gets `options` as the client sent it. `TestGeminiCompatRelayLeavesOutOllamaOptions`.
- Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put blocks of their own in a message: a `tool_addition` (`tool` a `tool_reference` naming the tool, or a `tool_definition`), a `tool_removal`, and a `tool_reference`. Kimi's Anthropic endpoint refuses any of them with a whole-request 400 "Invalid request Error" that names nothing, so once a session had loaded a tool every turn failed (#2042); DeepSeek's takes a `tool_addition` naming a tool but refuses one defining it, a `tool_removal` and a message's `tool_reference` with 422 "unknown variant `tool_removal`" (both checked against the real endpoints on 2026-10-14). OpenCode Go also rejects DeepSeek inline definitions with a generic 422 "Upstream request failed: Endpoint is unavailable." (checked on 2026-10-15). Kimi and DeepSeek models on OpenCode are never sent these blocks (`forwardOnce`); a provider that refuses one in those words is asked again at once without them and not sent them again while magpie runs (`refuseShapes`, `shapeDeferred`; the retry loop reads a 422 as well as a 400). `withoutDeferredTools` drops the blocks and a message they leave empty; definitions present only in a `tool_addition.tool.definition` join the request's `tools` once by name (an existing top-level definition wins), and a `tool_reference` inside a `tool_result` (ToolSearch's answer, which both take) stays. Any other provider is sent them as Claude Code wrote them ([`anthropic_shapes.go`](../../internal/gateway/anthropic_shapes.go), `TestKimiIsSentNoDeferredToolBlocks`, `TestDeferredToolBlocksRefusedOnceLeftOut`, `TestOpenCodeDeepSeekInlineTools`, `TestDeferredInlineDefinitionPreserved`).
- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).
- A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`), for a ChatGPT (Codex) account, and for a provider set `additionalTools` (`magpie provider set <id> additional-tools=on`); `additional-tools=off` (`additionalToolsOff`) turns it off even where it is the default, and `default` goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into `tools`, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`, `TestCodexAccountLoadsInPlace`.
+12 -1
View File
@@ -5197,10 +5197,21 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// turns the whole request away for (#1462)
body = withReasoningOnToolTurns(body)
}
compat := geminiCompat(p.Host(), model)
if compat {
// a client that took the gateway for an Ollama server (its
// /api/show is answered in Ollama's shape) sends Ollama's
// per-request options beside its Chat fields. Gemini's
// OpenAI-compatible API reads proto JSON and turns the whole
// request away over a name it doesn't know (#3097), and the
// runner settings in options have no place on a Chat API, as
// the Ollama route's own body builder judges (ollamaChatBody)
body = withoutFields(body, "options")
}
// Gemini's thought signatures, which came to the client in its
// calls' ids, go back where Gemini wants them; another upstream
// gets the calls' own ids (#687)
body = chatCallSignatures(body, geminiCompat(p.Host(), model))
body = chatCallSignatures(body, compat)
if p.Preset == "mistral" || p.Host() == "api.mistral.ai" {
// an earlier turn's reasoning_content, which Mistral turns
// away, as the thinking part it takes (#494)
@@ -1,6 +1,7 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@@ -209,3 +210,65 @@ func TestGeminiCompatRelayedCallsHaveAnIndex(t *testing.T) {
})
}
}
// A client that took the gateway for an Ollama server (its /api/show is
// answered in Ollama's shape) sends Ollama's per-request options beside
// its Chat fields. Gemini's OpenAI-compatible API reads proto JSON and
// turns the whole request away over a name it doesn't know (#3097), so a
// body relayed to one goes without options; another vendor's gets it as
// the client sent it.
func TestGeminiCompatRelayLeavesOutOllamaOptions(t *testing.T) {
// a whole text reply, as Gemini's OpenAI-compatible API streams one
hi := `data: {"choices":[{"index":0,"delta":{"role":"assistant","content":"hi there"}}],"model":"models/gemini-3.8-flash","object":"chat.completion.chunk"}` + "\n\n"
whole := hi + compatStop + compatDone
ask := func(model string) string {
return `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":8,"options":{"num_ctx":1048576}}`
}
// served saves the provider (Chat at base) and hands back what its
// upstream is sent, readable once the call has come back
served := func(t *testing.T, id, model, base string) func() []byte {
t.Helper()
fresh(t)
var got []byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, whole)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: id, Name: "UP", Key: "k", Models: []string{model}, Chat: up.URL + base}); err != nil {
t.Fatal(err)
}
return func() []byte { return got }
}
// as the google preset serves Gemini: an OpenAI-compatible Chat
// endpoint under generativelanguage.googleapis.com/v1beta/openai,
// stood in for by this machine's own address, where a Gemini model's
// Chat API is taken for Gemini's OpenAI-compatible one (geminiCompat)
read := served(t, "google", "models/gemini-3.8-flash", "/v1beta/openai")
code, body := post(t, "/v1/chat/completions", ask("google/models/gemini-3.8-flash"))
if code != 200 || !strings.Contains(body, `"content":"hi there"`) {
t.Fatalf("status %d: %s", code, body)
}
var sent map[string]json.RawMessage
if err := json.Unmarshal(read(), &sent); err != nil {
t.Fatalf("the upstream was sent %s", read())
}
if _, ok := sent["options"]; ok {
t.Errorf("Ollama's options reached Gemini's OpenAI-compatible API: %s", read())
}
if !strings.Contains(string(sent["messages"]), `"hi"`) || string(sent["max_tokens"]) != "8" {
t.Errorf("the rest of the request didn't go as asked: %s", read())
}
// another vendor's Chat upstream, no Gemini model there: the body goes
// as the client sent it
read = served(t, "km", "kimi-k3", "/v1")
if code, body := post(t, "/v1/chat/completions", ask("km/kimi-k3")); code != 200 || !strings.Contains(body, `"content":"hi there"`) {
t.Fatalf("another vendor: %d %s", code, body)
}
if !strings.Contains(string(read()), `"options":{"num_ctx":1048576}`) {
t.Errorf("another vendor's Chat upstream lost the client's options: %s", read())
}
}