gateway: Codex compacts on Gemini after a tool's output, no "Requests ending with a model turn" (#1533, yycsyu)
What the user saw: Codex on Google Vertex AI (gemini-3.8-flash) failed
every compaction that came right after a tool's output with
"Google Vertex AI: Requests ending with a model turn are not supported."
Why: codexInput turns compaction_trigger into a user message holding the
compaction prompt; mergeTurns and then buildCodeAssistSent merged it with
the function_call_output's user turn, so Gemini got one user content
holding a functionResponse and text. Vertex answers that with the
"ending with a model turn" 400 although the last role is user; #1533
showed the same history with the two as separate user contents gets 200.
What changed:
- buildCodeAssistSent (every Gemini-shaped request: Vertex AI, Factory's
Gemini, Gemini CLI's and Antigravity's Code Assist, Google sign-in)
puts what the user said after tools' responses in a user turn of its
own, and never merges text into a responses turn or the other way.
Tools' images stay with their response; parallel calls' responses stay
in one turn. A Claude model on Antigravity keeps its single tool_result
turn as before.
- It also never ends contents with the model's turn: a user turn goes
after it ("Continue.", or compactLastText when an agent compacts with
the ask in its system prompt). prefillRefusal knows Gemini's wording.
- docs/subsystems/gateway-routing.md says both.
Tests: gemini_model_last_test.go uses #1533's exact Responses request
(read_sample / call_diagnostic_1 / compaction_trigger) on /v1/responses
and Codex's path against a fake Vertex that refuses as the real one did;
with the split disabled it fails with the reporter's exact message, and
TestGeminiToolResponseTurnHoldsNoText fails for all four builders.
ump45nose's fork patch on #1533 (93a2afca) found the same cause and
split the turn on Vertex AI only; this does it for every Gemini builder,
and takes its Anthropic case (a tool_result beside text in one message)
into the end-to-end test, which fails on the old code too.
TestBuildCodeAssistForGemini, TestCodeAssistToolImagesAfterEveryResponse
and TestGeminiHistoryOpeningWithModel held the old one-turn merge (from
637b2458, a choice, not a fix for a report) and now expect the question
in a turn of its own.
Run: go test ./internal/gateway ./internal/provider, the full
go test -tags nogui ./... (queue lock), gofmt -l, go vet -tags nogui for
darwin, linux and windows.
Not tried against real Vertex AI: no Vertex credentials on this machine.
Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
This commit is contained in:
@@ -73,7 +73,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`); a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).
|
||||
- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is.
|
||||
- A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once.
|
||||
- A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal.
|
||||
- A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both.
|
||||
- A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`).
|
||||
|
||||
## Remote magpie APIs
|
||||
|
||||
@@ -162,6 +162,7 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
role = "model"
|
||||
}
|
||||
var parts, after []map[string]any // after: tools' images held back
|
||||
toolImage := map[int]bool{} // which of parts are a tool's images
|
||||
// signed: a step Gemini signed, whose later calls go without, as
|
||||
// Gemini signs the first (#1445, as chat's #687)
|
||||
signed := false
|
||||
@@ -244,7 +245,10 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
after = append(after, map[string]any{"text": label})
|
||||
after = append(after, ims...)
|
||||
} else {
|
||||
parts = append(parts, ims...)
|
||||
for _, im := range ims {
|
||||
toolImage[len(parts)] = true
|
||||
parts = append(parts, im)
|
||||
}
|
||||
}
|
||||
}
|
||||
// thinking isn't sent back: its signatures belong to whoever
|
||||
@@ -263,14 +267,34 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
}
|
||||
parts = append(append(lead, after...), rest...)
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
// what the user said goes in a turn of its own after the tools'
|
||||
// responses: Gemini answers a turn mixing a functionResponse with
|
||||
// text "Requests ending with a model turn are not supported" (#1533,
|
||||
// yycsyu: Codex's compaction prompt after a tool's output), and takes
|
||||
// the two as separate turns. A Claude model on Antigravity keeps them
|
||||
// in one, the tool_result turn Anthropic reads them as.
|
||||
var said []map[string]any
|
||||
if role == "user" && !(ag && claude) && hasResponse(parts) {
|
||||
var tools []map[string]any
|
||||
for i, part := range parts {
|
||||
if part["functionResponse"] != nil || toolImage[i] {
|
||||
tools = append(tools, part)
|
||||
} else {
|
||||
said = append(said, part)
|
||||
}
|
||||
}
|
||||
parts = tools
|
||||
}
|
||||
if n := len(contents); n > 0 && contents[n-1]["role"] == role {
|
||||
contents[n-1]["parts"] = append(contents[n-1]["parts"].([]map[string]any), parts...)
|
||||
continue
|
||||
for _, ps := range [][]map[string]any{parts, said} {
|
||||
if len(ps) == 0 {
|
||||
continue
|
||||
}
|
||||
if n := len(contents); n > 0 && contents[n-1]["role"] == role && (role != "user" || hasResponse(contents[n-1]["parts"].([]map[string]any)) == hasResponse(ps)) {
|
||||
contents[n-1]["parts"] = append(contents[n-1]["parts"].([]map[string]any), ps...)
|
||||
continue
|
||||
}
|
||||
contents = append(contents, map[string]any{"role": role, "parts": ps})
|
||||
}
|
||||
contents = append(contents, map[string]any{"role": role, "parts": parts})
|
||||
}
|
||||
if len(contents) > 0 && contents[0]["role"] == "model" {
|
||||
// Gemini turns away a history that opens with the model's turn
|
||||
@@ -279,6 +303,13 @@ func buildCodeAssistSent(r *Request, sent, agent string) []byte {
|
||||
// this user turn before it, and so does this.
|
||||
contents = append([]map[string]any{{"role": "user", "parts": []map[string]any{{"text": "[Continuing from previous AI thoughts...]"}}}}, contents...)
|
||||
}
|
||||
if n := len(contents); n > 0 && contents[n-1]["role"] == "model" {
|
||||
// nor one that ends with it: "Requests ending with a model turn
|
||||
// are not supported" on Vertex AI, Code Assist and Antigravity
|
||||
// alike (yycsyu: Codex compacting on gemini-3.8-flash). A user
|
||||
// turn goes after it, as Gemini CLI keeps its history ending
|
||||
contents = append(contents, map[string]any{"role": "user", "parts": []map[string]any{{"text": modelLastAsk(r)}}})
|
||||
}
|
||||
req := map[string]any{"contents": contents}
|
||||
if r.System != "" {
|
||||
req["systemInstruction"] = map[string]any{"role": "user", "parts": []map[string]any{{"text": r.System}}}
|
||||
@@ -993,3 +1024,13 @@ func stopFromGemini(s string) string {
|
||||
// SAFETY, RECITATION, BLOCKLIST, PROHIBITED_CONTENT, SPII, ...
|
||||
return "filter"
|
||||
}
|
||||
|
||||
// hasResponse says whether a Gemini turn's parts hold a tool's response.
|
||||
func hasResponse(parts []map[string]any) bool {
|
||||
for _, p := range parts {
|
||||
if p["functionResponse"] != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -59,10 +59,18 @@ func TestBuildCodeAssistForGemini(t *testing.T) {
|
||||
if strings.Contains(s, "sig-from-claude") || strings.Contains(s, `"hm"`) {
|
||||
t.Error("thinking was sent back")
|
||||
}
|
||||
// the tool result and the next question are one user turn
|
||||
// the tool result is a user turn, and the next question one of its own
|
||||
// after it: Gemini turns away the two in one (#1533)
|
||||
contents := req["contents"].([]any)
|
||||
if len(contents) != 3 || len(contents[2].(map[string]any)["parts"].([]any)) != 2 {
|
||||
t.Errorf("contents = %v", contents)
|
||||
if len(contents) != 4 {
|
||||
t.Fatalf("contents = %v", contents)
|
||||
}
|
||||
tools, asked := contents[2].(map[string]any), contents[3].(map[string]any)
|
||||
if tp := tools["parts"].([]any); tools["role"] != "user" || len(tp) != 1 || tp[0].(map[string]any)["functionResponse"] == nil {
|
||||
t.Errorf("the tool's turn = %v", tools)
|
||||
}
|
||||
if ap := asked["parts"].([]any); asked["role"] != "user" || len(ap) != 1 || ap[0].(map[string]any)["text"] != "and?" {
|
||||
t.Errorf("the question's turn = %v", asked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,9 +364,21 @@ func TestCodeAssistToolImagesAfterEveryResponse(t *testing.T) {
|
||||
if err := json.Unmarshal(buildCodeAssist(r, model, agent), &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// every part after the model's last turn, "|" between two turns
|
||||
cs := env.Request.Contents
|
||||
var out []string
|
||||
for _, p := range cs[len(cs)-1].Parts {
|
||||
var parts []map[string]json.RawMessage
|
||||
for _, c := range cs[2:] {
|
||||
if len(parts) > 0 {
|
||||
parts = append(parts, map[string]json.RawMessage{"turn": nil})
|
||||
}
|
||||
parts = append(parts, c.Parts...)
|
||||
}
|
||||
for _, p := range parts {
|
||||
if _, ok := p["turn"]; ok {
|
||||
out = append(out, "|")
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case p["functionResponse"] != nil:
|
||||
var fr struct{ ID string }
|
||||
@@ -391,7 +411,7 @@ func TestCodeAssistToolImagesAfterEveryResponse(t *testing.T) {
|
||||
gem := []string{
|
||||
"response toolu_bdrk_01AvFfWkjBwUMB97S9vUMAR7", "image QUFB",
|
||||
"response toolu_bdrk_01TJixAcopSp2JamBfnbfF4V", "image QkJC",
|
||||
"which is bigger?",
|
||||
"|", "which is bigger?", // in a turn of its own (#1533)
|
||||
}
|
||||
if got := shape("gemini-3-flash", "antigravity"); !reflect.DeepEqual(got, gem) {
|
||||
t.Errorf("Antigravity Gemini:\n got %q\nwant %q", got, gem)
|
||||
|
||||
@@ -70,8 +70,12 @@ func TestGeminiHistoryOpeningWithModel(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for route, cs := range geminiContents(t, r) {
|
||||
if got := geminiRoles(cs); got != "user,model,user" {
|
||||
t.Errorf("%s via %s: roles %s, want user,model,user", name, route, got)
|
||||
want := "user,model,user"
|
||||
if name == "model functionCall" {
|
||||
want += ",user" // the question after the tool's response (#1533)
|
||||
}
|
||||
if got := geminiRoles(cs); got != want {
|
||||
t.Errorf("%s via %s: roles %s, want %s", name, route, got, want)
|
||||
continue
|
||||
}
|
||||
lead, _ := json.Marshal(cs[0]["parts"])
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// vertexModelLast is Vertex AI's refusal of contents whose last turn is the
|
||||
// model's, as yycsyu was shown it (Codex compacting on gemini-3.8-flash),
|
||||
// in the shape of Vertex AI's other 400s (vertexBadSig).
|
||||
const vertexModelLast = "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Requests ending with a model turn are not supported.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n"
|
||||
|
||||
// lastTurn is the role and text of a Gemini request's last content.
|
||||
func lastTurn(t *testing.T, contents any) (role, text string) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(contents)
|
||||
var cs []struct {
|
||||
Role string `json:"role"`
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &cs); err != nil || len(cs) == 0 {
|
||||
t.Fatalf("contents %s", b)
|
||||
}
|
||||
last := cs[len(cs)-1]
|
||||
for _, p := range last.Parts {
|
||||
text += p.Text
|
||||
}
|
||||
return last.Role, text
|
||||
}
|
||||
|
||||
// Every builder of Gemini contents — Vertex AI, Gemini's own API (Factory),
|
||||
// Code Assist for Gemini CLI and Antigravity, a Claude model on
|
||||
// Antigravity too — ends a conversation that ends with the assistant's
|
||||
// message with a user turn: Gemini turns away contents ending with the
|
||||
// model's. An agent compacting with its ask in the system prompt is asked
|
||||
// for the summary, not told to go on with the task.
|
||||
func TestGeminiContentsNeverEndWithModel(t *testing.T) {
|
||||
said := []Message{
|
||||
{Role: "user", Parts: []Part{{Kind: Text, Text: "fix the bug"}}},
|
||||
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "looking"}, {Kind: Text, Text: "Fixed it in main.go."}}},
|
||||
}
|
||||
builders := map[string]func(r *Request) any{
|
||||
"vertex": func(r *Request) any {
|
||||
b, err := buildVertex(r, "gemini-3.8-flash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var q map[string]any
|
||||
json.Unmarshal(b, &q)
|
||||
return q["contents"]
|
||||
},
|
||||
"gemini": func(r *Request) any {
|
||||
b, err := buildGemini(r, "gemini-3.8-flash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var q map[string]any
|
||||
json.Unmarshal(b, &q)
|
||||
return q["contents"]
|
||||
},
|
||||
}
|
||||
for _, c := range []struct{ agent, model string }{{"gemini", "gemini-3.8-flash"}, {"antigravity", "gemini-3.8-flash"}, {"antigravity", "claude-sonnet-4-6"}} {
|
||||
builders["code assist "+c.agent+" "+c.model] = func(r *Request) any {
|
||||
var q struct {
|
||||
Request map[string]any `json:"request"`
|
||||
}
|
||||
json.Unmarshal(buildCodeAssist(r, c.model, c.agent), &q)
|
||||
return q.Request["contents"]
|
||||
}
|
||||
}
|
||||
for name, build := range builders {
|
||||
for _, c := range []struct {
|
||||
name, system, want string
|
||||
}{
|
||||
{"a turn", "You are Codex.", continueText},
|
||||
{"a compaction asked in the system prompt", "You are a helpful AI assistant tasked with summarizing conversations.", compactLastText},
|
||||
} {
|
||||
role, text := lastTurn(t, build(&Request{System: c.system, Messages: said}))
|
||||
if role != "user" || text != c.want {
|
||||
t.Errorf("%s, %s: ends with %s %q, want user %q", name, c.name, role, text, c.want)
|
||||
}
|
||||
}
|
||||
// a conversation that already ends with the user's turn is sent as it is
|
||||
asked := append(said[:2:2], Message{Role: "user", Parts: []Part{{Kind: Text, Text: "and the test?"}}})
|
||||
if role, text := lastTurn(t, build(&Request{Messages: asked})); role != "user" || text != "and the test?" {
|
||||
t.Errorf("%s: a user-ended conversation ends with %s %q", name, role, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End to end on Vertex AI, which answers 400 vertexModelLast to contents
|
||||
// ending with the model's turn: Codex's compaction (its compaction_trigger
|
||||
// after a reply, as compact_remote_v2_attempt.rs pushes it), a Codex turn
|
||||
// whose input ends with the assistant's message, and an Anthropic client
|
||||
// compacting with the ask in its system prompt all get an answer.
|
||||
func TestVertexNeverAskedEndingWithModel(t *testing.T) {
|
||||
v := &vertexUp{}
|
||||
v.reply = vertexTurnsAway
|
||||
s := vertexServe(t, v, vertexLevels)
|
||||
const history = `{"type":"message","role":"developer","content":[{"type":"input_text","text":"<permissions instructions>sandbox</permissions instructions>"}]},` +
|
||||
`{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the bug"}]},` +
|
||||
`{"type":"function_call","name":"shell","arguments":"{\"command\":[\"ls\"]}","call_id":"call_1"},` +
|
||||
`{"type":"function_call_output","call_id":"call_1","output":"main.go"},` +
|
||||
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Fixed it in main.go."}]}`
|
||||
for _, c := range []struct {
|
||||
name, path, body, want string
|
||||
}{
|
||||
{"codex compaction", CodexPath + "/responses",
|
||||
`{"model":"google-vertex/gemini-3.8-flash","instructions":"You are Codex.","stream":true,"tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{}}}],"input":[` + history + `,{"type":"compaction_trigger"}]}`,
|
||||
codexCompactPrompt},
|
||||
{"codex turn ending with the assistant's message", CodexPath + "/responses",
|
||||
`{"model":"google-vertex/gemini-3.8-flash","instructions":"You are Codex.","stream":true,"input":[` + history + `]}`,
|
||||
continueText},
|
||||
// #1533's own request, as zhhe17 posted it: the compaction_trigger
|
||||
// right after a tool's output, which went out as one user turn
|
||||
// holding the functionResponse and the compaction prompt
|
||||
{"#1533: codex compaction after a tool's output", "/v1/responses", issue1533, codexCompactPrompt},
|
||||
{"#1533 on codex's own path", CodexPath + "/responses", issue1533, codexCompactPrompt},
|
||||
// an Anthropic client's tool_result beside its words in one
|
||||
// message, which goes to Gemini the same way (ump45nose's case)
|
||||
{"anthropic tool result and words", "/v1/messages", `{"model":"google-vertex/gemini-3.8-flash","max_tokens":64,"stream":true,
|
||||
"tools":[{"name":"read_sample","input_schema":{"type":"object"}}],"messages":[
|
||||
{"role":"user","content":"Read a sample file."},
|
||||
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"read_sample","input":{"path":"sample.txt"}}]},
|
||||
{"role":"user","content":[
|
||||
{"type":"tool_result","tool_use_id":"toolu_1","content":"Sample file content: hello."},
|
||||
{"type":"text","text":"Summarize the sample conversation briefly."}]}]}`,
|
||||
"Summarize the sample conversation briefly."},
|
||||
{"anthropic compaction asked in the system prompt", "/v1/messages",
|
||||
`{"model":"google-vertex/gemini-3.8-flash","max_tokens":2000,"stream":true,"system":"You are a helpful AI assistant tasked with summarizing conversations.","messages":[{"role":"user","content":"fix the bug"},{"role":"assistant","content":"Fixed it in main.go."}]}`,
|
||||
compactLastText},
|
||||
} {
|
||||
rec := codexPostTo(s, c.body)
|
||||
if c.path != CodexPath+"/responses" {
|
||||
rec = vertexPost(s, c.path, c.body)
|
||||
}
|
||||
if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "model turn") {
|
||||
t.Errorf("%s: %d %s", c.name, rec.Code, rec.Body.String())
|
||||
continue
|
||||
}
|
||||
role, text := lastTurn(t, v.last(t).body["contents"])
|
||||
if role != "user" || !strings.Contains(text, c.want) {
|
||||
t.Errorf("%s: Vertex AI was asked ending with %s %q, want user %q", c.name, role, text, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func vertexPost(s *Server, path, body string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
// issue1533 is the Responses request #1533 reproduced the refusal with.
|
||||
const issue1533 = `{
|
||||
"model": "google-vertex/gemini-3.8-flash",
|
||||
"stream": true,
|
||||
"store": false,
|
||||
"max_output_tokens": 64,
|
||||
"reasoning": {"effort": "none"},
|
||||
"input": [
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{"type": "input_text", "text": "Read a sample file."}]
|
||||
},
|
||||
{
|
||||
"type": "function_call",
|
||||
"name": "read_sample",
|
||||
"call_id": "call_diagnostic_1",
|
||||
"arguments": "{\"path\":\"sample.txt\"}"
|
||||
},
|
||||
{
|
||||
"type": "function_call_output",
|
||||
"call_id": "call_diagnostic_1",
|
||||
"output": "Sample file content: hello."
|
||||
},
|
||||
{"type": "compaction_trigger"}
|
||||
]
|
||||
}`
|
||||
|
||||
// vertexTurnsAway answers as Vertex AI answered #1533: 400 vertexModelLast
|
||||
// to contents ending with the model's turn, and to a user turn mixing a
|
||||
// tool's functionResponse with text, which it takes as two turns.
|
||||
func vertexTurnsAway(_ int, body map[string]any) (int, string) {
|
||||
contents, _ := body["contents"].([]any)
|
||||
for i, c := range contents {
|
||||
turn, _ := c.(map[string]any)
|
||||
if i == len(contents)-1 && turn["role"] == "model" {
|
||||
return http.StatusBadRequest, vertexModelLast
|
||||
}
|
||||
parts, _ := turn["parts"].([]any)
|
||||
response, text := false, false
|
||||
for _, p := range parts {
|
||||
part, _ := p.(map[string]any)
|
||||
response = response || part["functionResponse"] != nil
|
||||
text = text || part["text"] != nil
|
||||
}
|
||||
if response && text {
|
||||
return http.StatusBadRequest, vertexModelLast
|
||||
}
|
||||
}
|
||||
return http.StatusOK, vertexPong
|
||||
}
|
||||
|
||||
// Every builder of Gemini contents but a Claude model's on Antigravity
|
||||
// (an Anthropic tool_result turn) puts what the user said after a tool's
|
||||
// response in a user turn of its own (#1533), and keeps parallel calls'
|
||||
// responses together in one.
|
||||
func TestGeminiToolResponseTurnHoldsNoText(t *testing.T) {
|
||||
r := &Request{Messages: []Message{
|
||||
{Role: "user", Parts: []Part{{Kind: Text, Text: "Read a sample file."}}},
|
||||
{Role: "assistant", Parts: []Part{
|
||||
{Kind: ToolCall, ID: "call_diagnostic_1", Name: "read_sample", Args: json.RawMessage(`{"path":"sample.txt"}`)},
|
||||
{Kind: ToolCall, ID: "call_2", Name: "read_sample", Args: json.RawMessage(`{"path":"other.txt"}`)},
|
||||
}},
|
||||
{Role: "user", Parts: []Part{
|
||||
{Kind: ToolResult, CallID: "call_diagnostic_1", Text: "Sample file content: hello.", Images: []Part{{Kind: Image, MediaType: "image/png", Data: "iVBORw0KGgo="}}},
|
||||
{Kind: ToolResult, CallID: "call_2", Text: "other"},
|
||||
{Kind: Text, Text: codexCompactPrompt},
|
||||
}},
|
||||
}}
|
||||
sent := map[string][]byte{}
|
||||
sent["vertex"], _ = buildVertex(r, "gemini-3.8-flash")
|
||||
sent["gemini"], _ = buildGemini(r, "gemini-3.8-flash")
|
||||
for _, agent := range []string{"gemini", "antigravity"} {
|
||||
var q struct {
|
||||
Request json.RawMessage `json:"request"`
|
||||
}
|
||||
json.Unmarshal(buildCodeAssist(r, "gemini-3.8-flash", agent), &q)
|
||||
sent["code assist "+agent] = q.Request
|
||||
}
|
||||
for name, b := range sent {
|
||||
var q struct {
|
||||
Contents []struct {
|
||||
Role string `json:"role"`
|
||||
Parts []map[string]any `json:"parts"`
|
||||
} `json:"contents"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &q); err != nil || len(q.Contents) != 4 {
|
||||
t.Errorf("%s: want 4 turns, got %s", name, b)
|
||||
continue
|
||||
}
|
||||
tools, said := q.Contents[2], q.Contents[3]
|
||||
if tools.Role != "user" || len(tools.Parts) != 3 || tools.Parts[0]["functionResponse"] == nil || tools.Parts[1]["inlineData"] == nil || tools.Parts[2]["functionResponse"] == nil {
|
||||
t.Errorf("%s: the tools' turn is %v", name, tools)
|
||||
}
|
||||
if said.Role != "user" || len(said.Parts) != 1 || said.Parts[0]["text"] != codexCompactPrompt {
|
||||
t.Errorf("%s: the user's turn after it is %v", name, said)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,9 @@ import (
|
||||
// "This model does not support assistant message prefill. The
|
||||
// conversation must end with a user message.", as Volcengine's Agent Plan
|
||||
// does, "The last message cannot be from the assistant for a model that
|
||||
// does not support prefill". The same providers' other models take it, so
|
||||
// does not support prefill", and Gemini on Vertex AI's, "Requests ending
|
||||
// with a model turn are not supported" (yycsyu; Gemini's own requests never
|
||||
// end so: buildCodeAssistSent). The same providers' other models take it, so
|
||||
// the refusal is remembered for that model on that provider and API, in
|
||||
// unfit, and nowhere else.
|
||||
//
|
||||
@@ -25,10 +27,13 @@ import (
|
||||
// assistant's message as an OpenAI upstream answers it. An Anthropic
|
||||
// client's prefill is the client's own ask, and gets the refusal as
|
||||
// Anthropic itself answers it.
|
||||
// A request built in Gemini's own shape is the exception: every upstream
|
||||
// of it turns the model's turn last away, so it never goes out so
|
||||
// (buildCodeAssistSent, modelLastAsk).
|
||||
|
||||
// prefillRefusal is an upstream's refusal of a conversation ending with
|
||||
// the assistant's message.
|
||||
var prefillRefusal = regexp.MustCompile(`(?i)does not support (?:assistant message )?prefill`)
|
||||
var prefillRefusal = regexp.MustCompile(`(?i)does not support (?:assistant message )?prefill|requests ending with a model turn are not supported`)
|
||||
|
||||
// prefillRefused is how unfit remembers a provider's model refusing a
|
||||
// conversation ending with the assistant's message.
|
||||
@@ -43,6 +48,20 @@ func refusesPrefill(status int, body []byte) bool {
|
||||
// ended with the assistant's message, for a model that takes no prefill.
|
||||
const continueText = "Continue."
|
||||
|
||||
// compactLastText is that user turn when the conversation is an agent
|
||||
// compacting it with the ask in the system prompt (compacting): "Continue."
|
||||
// there reads as going on with the task, and the summary isn't written.
|
||||
const compactLastText = "Write the summary of the conversation above that the system prompt asks for."
|
||||
|
||||
// modelLastAsk is the user turn put after a conversation ending with the
|
||||
// model's turn, for an upstream that takes none (buildCodeAssistSent).
|
||||
func modelLastAsk(r *Request) string {
|
||||
if compacting(r) {
|
||||
return compactLastText
|
||||
}
|
||||
return continueText
|
||||
}
|
||||
|
||||
// endsWithAssistant says whether r's conversation ends with the
|
||||
// assistant's message rather than a call it made: what a prefill is.
|
||||
func (r *Request) endsWithAssistant() bool {
|
||||
|
||||
Reference in New Issue
Block a user