diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d2f1495e4..154ab606b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -124,7 +124,7 @@ recorded as a prediction failure (`noPrediction`). - A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`). - A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests. - Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). -- A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. +- A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`. - A request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated, and Zed's bridge) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go). - A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in `attempt`, before it is relayed or translated, plugins included ([`responses.go`](../../internal/gateway/responses.go)). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (`joinToolRuns`, #1752, Edward4226): Codex writes its `` right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a `call_id` never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (`orphanedToolOutputs`), and a call nothing answers gets a synthetic result at the end of its run (`pairToolItems`, #1341). `TestRelayedCodexImageBatchKeepsItsResultsTogether`, `TestJoinToolRunsOnlyMovesWhatBreaksARun`, `TestRelayedTextBetweenABatchsCallsIsAnswered`. - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`). diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index 5f7b02289..82a77969d 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -181,7 +181,7 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte { } names := map[string]string{} var contents []map[string]any - for _, m := range r.Messages { + for _, m := range dropSecondAnswers(r.Messages) { role := "user" if m.Role == "assistant" { role = "model" @@ -422,6 +422,56 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte { return b } +// 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 +// upstream. Google turns a call turn away when its functionResponse count +// differs from its functionCall count, so a client that answers one call +// twice (#2262) had every later turn refused. A call made again under the +// same id takes an answer of its own, and a result with no id is left as +// it is. msgs is not changed: a fallback builds from the same request. +func dropSecondAnswers(msgs []Message) []Message { + var out []Message + answered := map[string]bool{} + for i, m := range msgs { + var parts []Part + for j, p := range m.Parts { + switch { + case p.Kind == ToolCall && p.ID != "": + delete(answered, p.ID) + case p.Kind == ToolResult && p.CallID != "" && p.Standalone == nil: + if answered[p.CallID] { + if parts == nil { + parts = append(make([]Part, 0, len(m.Parts)), m.Parts[:j]...) + } + if out == nil { + out = append(make([]Message, 0, len(msgs)), msgs[:i]...) + } + continue + } + answered[p.CallID] = true + } + if parts != nil { + parts = append(parts, p) + } + } + if out == nil { + continue + } + if parts != nil { + if len(parts) == 0 { + continue + } + m.Parts = parts + } + out = append(out, m) + } + if out == nil { + return msgs + } + return out +} + // interruptedToolNote is the result a call left unanswered is answered // with, the words the chat build gives such a call (pairToolMessages). const interruptedToolNote = "[The result of this tool call is unavailable: the turn was interrupted.]" diff --git a/internal/gateway/gemini.go b/internal/gateway/gemini.go index c6474f4ef..b52fd9f44 100644 --- a/internal/gateway/gemini.go +++ b/internal/gateway/gemini.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "slices" "strings" ) @@ -242,8 +243,12 @@ func parseGemini(body []byte) (*Request, error) { } } // function results carry the call's id when the client kept it; older - // clients send only the name, matched to the latest call of that name + // 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" { @@ -276,6 +281,7 @@ func parseGemini(body []byte) (*Request, error) { 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: @@ -283,7 +289,11 @@ func parseGemini(body []byte) (*Request, error) { 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}) diff --git a/internal/gateway/gemini_pending_call_test.go b/internal/gateway/gemini_pending_call_test.go index 7433964af..0447d835e 100644 --- a/internal/gateway/gemini_pending_call_test.go +++ b/internal/gateway/gemini_pending_call_test.go @@ -335,3 +335,181 @@ func TestPairFunctionTurnsShapes(t *testing.T) { }) } } + +// geminiEqualCountUpstream answers like Google when a function-call turn is +// followed by a different number of functionResponse parts, and with SSE +// when the counts match. +func geminiEqualCountUpstream(t *testing.T) (*httptest.Server, func() []string) { + t.Helper() + var mu sync.Mutex + var bodies []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + if !strings.HasSuffix(r.URL.Path, ":streamGenerateContent") { + http.NotFound(w, r) + return + } + mu.Lock() + bodies = append(bodies, string(b)) + mu.Unlock() + if !geminiCallTurnCountsMatch(b) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":{"code":400,"message":"Please ensure that the number of function response parts is equal to the number of function call parts of the function call turn.","status":"INVALID_ARGUMENT"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"kept-"}]}}],"modelVersion":"gm"}`, + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"up"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":3,"totalTokenCount":10}}`, + )) + })) + t.Cleanup(up.Close) + return up, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), bodies...) + } +} + +// geminiCallTurnCountsMatch reports whether the turn right after every +// function-call turn holds exactly as many functionResponse parts as that +// turn holds functionCall parts. +func geminiCallTurnCountsMatch(body []byte) bool { + var q struct { + Contents []struct { + Parts []struct { + FunctionCall *struct{} `json:"functionCall"` + FunctionResponse *struct{} `json:"functionResponse"` + } `json:"parts"` + } `json:"contents"` + } + if json.Unmarshal(body, &q) != nil { + return false + } + pending := 0 + for _, c := range q.Contents { + nCall, nResp := 0, 0 + for _, p := range c.Parts { + if p.FunctionCall != nil { + nCall++ + } + if p.FunctionResponse != nil { + nResp++ + } + } + if pending > 0 { + if nResp != pending { + return false + } + pending = 0 + } + if nCall > 0 { + pending = nCall + } + } + return pending == 0 +} + +// A Chat client that answers one call twice is turned into Gemini with both +// functionResponse parts. Google refuses that history: the response count +// has to equal the call count. Chat and Messages builds drop the second +// answer; the Gemini build kept it (#2262). +func TestGeminiDropsASecondAnswer(t *testing.T) { + up, bodies := geminiEqualCountUpstream(t) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "gem", Name: "Gem", Key: "AIza-test", Gemini: up.URL + "/v1beta", Models: []string{"gemini-2.5-pro"}}); err != nil { + t.Fatal(err) + } + gw := httptest.NewServer(New().Handler()) + defer gw.Close() + res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader( + `{"model":"gem/gemini-2.5-pro","stream":true,"messages":[ + {"role":"user","content":"look into it"}, + {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"Bash","arguments":"{}"}}]}, + {"role":"tool","tool_call_id":"call_1","content":"alpha-result"}, + {"role":"tool","tool_call_id":"call_1","content":"beta-result"}]}`)) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + bs := bodies() + upBody := "" + if len(bs) > 0 { + upBody = bs[0] + } + if res.StatusCode != 200 || !strings.Contains(string(b), "kept-") { + t.Fatalf("status %d: %s\nupstream: %s", res.StatusCode, b, upBody) + } + raw := gjson.Get(upBody, "contents").Raw + if strings.Count(raw, "alpha-result") != 1 || strings.Contains(raw, "beta-result") { + t.Fatalf("second answer forwarded: %s", raw) + } +} + +// The second answer goes with the images it carried, and a call made again +// under the same id later in the conversation takes an answer of its own. +func TestSecondAnswerDroppedWithItsImages(t *testing.T) { + img := []Part{{Kind: Image, MediaType: "image/png", Data: "c2Vjb25k"}} + r := &Request{Messages: []Message{ + {Role: "user", Parts: []Part{{Kind: Text, Text: "look"}}}, + {Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_1", Name: "Read", Args: json.RawMessage(`{}`)}}}, + {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "call_1", Text: "alpha-result"}}}, + {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "call_1", Text: "beta-result", Images: img}}}, + {Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_1", Name: "Read", Args: json.RawMessage(`{}`)}}}, + {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "call_1", Text: "gamma-result"}}}, + }} + for _, c := range []struct { + name string + body []byte + }{ + {"gemini", buildCodeAssistSent(r, "gemini-2.5-pro", "")}, + {"responses", buildResponses(r, "gpt-5.4", "api.openai.com", false)}, + } { + s := string(c.body) + if strings.Count(s, "alpha-result") != 1 || strings.Contains(s, "beta-result") || strings.Contains(s, "c2Vjb25k") { + t.Errorf("%s: the second answer or its image went out: %s", c.name, s) + } + if strings.Count(s, "gamma-result") != 1 { + t.Errorf("%s: the answer to the call made again is gone: %s", c.name, s) + } + } + if n := len(r.Messages[3].Parts); n != 1 { + t.Fatalf("the request itself was changed: %d parts", n) + } +} + +// A Gemini client that keeps no ids answers two calls of one function by +// name, in the calls' order. Each answer goes to its own call: matching +// both to the latest call left the first unanswered, and Google turns the +// history away. +func TestGeminiClientUnnamedCallsAnsweredInOrder(t *testing.T) { + r, err := parseGemini([]byte(`{"contents":[ + {"role":"user","parts":[{"text":"read both"}]}, + {"role":"model","parts":[{"functionCall":{"name":"read_file","args":{"path":"a"}}},{"functionCall":{"name":"read_file","args":{"path":"b"}}}]}, + {"role":"user","parts":[{"functionResponse":{"name":"read_file","response":{"output":"file-a"}}},{"functionResponse":{"name":"read_file","response":{"output":"file-b"}}}]}]}`)) + if err != nil { + t.Fatal(err) + } + body := []byte(gjson.GetBytes(buildCodeAssistSent(r, "gemini-2.5-pro", ""), "request").Raw) + if !geminiCallTurnCountsMatch(body) { + t.Fatalf("call and response counts differ: %s", body) + } + contents := gjson.GetBytes(body, "contents").Array() + var calls, answers []string + for _, c := range contents { + for _, p := range c.Get("parts").Array() { + if id := p.Get("functionCall.id").String(); id != "" { + calls = append(calls, id) + } + if p.Get("functionResponse").Exists() { + answers = append(answers, p.Get("functionResponse.id").String()+"="+p.Get("functionResponse.response.output").String()) + } + } + } + if len(calls) != 2 || strings.Join(answers, ",") != calls[0]+"=file-a,"+calls[1]+"=file-b" { + t.Fatalf("calls %v answered %v", calls, answers) + } +} diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 13f021246..d42edbd53 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -1035,7 +1035,9 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { // sealed reasoning, and may refuse an item without it. replay := replaysReasoning(model, host) var input []any - for _, m := range r.Messages { + // a second answer to one call is left out, as the Chat and Messages + // builds leave it (dropSecondAnswers) + for _, m := range dropSecondAnswers(r.Messages) { var content []map[string]any flushMsg := func() { if len(content) == 0 {