diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7a1b91a8c..17b0b20bb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -105,7 +105,7 @@ recorded as a prediction failure (`noPrediction`). - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. -- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. +- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). - An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. - Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index a6c2cf4b3..d707b3f43 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -112,6 +112,73 @@ func geminiKin(actual provider.Protocol) bool { return actual == provider.Gemini || actual == provider.CodeAssist } +// saysItsEnd tells whether every whole reply of p in proto, serving model, +// says it ended, so a stream that stops short of that is a reply cut +// short: Anthropic's message_stop, Responses' response.completed, a +// Gemini candidate's finishReason (#1643, #1644), and a finish_reason from +// Gemini's OpenAI-compatible API (geminiCompat). That one sends a whole +// function call in one chunk and its finish_reason in the next; an +// upstream that hung up between the two ended the reply with no end, and +// a strict client (Pi: "Stream ended without finish_reason") threw the +// call away, while a lenient one took the turn as over (Linka on +// Discord). When the last chunk counted the reply's usage, which that API +// sends only once its generation is done, only the finish_reason was lost +// and it is filled in (chatTail); without it the cut is said as one. +// Other Chat APIs may end a whole reply with neither a finish_reason nor +// [DONE], so only a failed read is a cut there. +func saysItsEnd(p provider.Provider, proto provider.Protocol, model string) bool { + switch { + case proto == provider.Anthropic, proto == provider.Responses, geminiKin(proto): + return true + case proto == provider.Chat: + return geminiCompat(p.Host(), model) + } + return false +} + +// chatTail follows a Chat stream's chunks for a Gemini OpenAI-compatible +// reply that ended without its finish_reason (saysItsEnd): whether its +// last chunk counted the usage and whether it made calls. +type chatTail struct{ usage, calls bool } + +func (t *chatTail) see(data []byte) { + var v struct { + Choices []struct { + Delta struct { + ToolCalls []json.RawMessage `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + Usage *cUsage `json:"usage"` + } + if json.Unmarshal(data, &v) != nil { + return // [DONE], or nothing to read + } + t.usage = v.Usage != nil && (v.Usage.PromptTokens > 0 || v.Usage.CompletionTokens > 0) + for _, c := range v.Choices { + t.calls = t.calls || len(c.Delta.ToolCalls) > 0 + } +} + +// finish is the finish_reason a reply that ended without one is given: +// Gemini's OpenAI-compatible API counts the usage only on the +// generation's last chunks, so a last chunk with it says the generation +// was done and only the chunk with its finish_reason was lost (Linka on +// Discord). Without it, "": the reply was cut. +func (t chatTail) finish() string { + switch { + case !t.usage: + return "" + case t.calls: + return "tool_calls" + } + return "stop" +} + +// finishChunk is the Chat chunk that ends a reply with finish_reason fin. +func finishChunk(fin string) []byte { + return []byte(`{"choices":[{"delta":{},"finish_reason":"` + fin + `","index":0}],"object":"chat.completion.chunk"}`) +} + // groupTryKey marks a try of a routing group's member. A member whose // stream breaks with an error mid-reply is failed as it used to be — the // group answers the agent's retry with another of its members (#733) — @@ -463,7 +530,9 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov attemptSee, held = t.event, t.release } ended := false // the upstream said its reply ended + var tail chatTail serr = readSSEAlive(rd, func(_, data string) error { + tail.see([]byte(data)) st := upstreamStop([]byte(data)) u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st, Tier: upstreamTier([]byte(data))}) ended = ended || replyEnds(actual, data, st) @@ -480,7 +549,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov serr = nil } if serr == nil && failed == "" && !ended && !relooped && - (actual == provider.Anthropic || actual == provider.Responses || geminiKin(actual)) && r.Context().Err() == nil { + saysItsEnd(p, actual, model) && r.Context().Err() == nil { // an Anthropic stream that just stopped — no // stop_reason, no message_stop — or a Responses one // with no response.completed is a reply cut short, @@ -490,6 +559,12 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // whole would say completed it never said. A Gemini // one is told by its finishReason (geminiEnds, #1643) serr = errEndedShort + if fin := tail.finish(); actual == provider.Chat && fin != "" { + // Gemini's OpenAI-compatible API lost only the + // finish_reason after its generation was done + u.add(Usage{Stop: fin}) + serr = dec(string(finishChunk(fin)), attemptSee) + } } } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 42f329657..ee2804eef 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4493,20 +4493,35 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. status, msg := gather.finish(client, p, sse, cut, sniff.failed) return status, msg, true } - if sse && r.Context().Err() == nil && !sniff.whole() { + // a Chat stream of Gemini's OpenAI-compatible API is whole only with + // its finish_reason, [DONE] or not (saysItsEnd) + unfinished := proto == provider.Chat && sniff.failed == "" && sniff.u.Stop == "" && saysItsEnd(p, proto, upstream) + if fin := sniff.tail.finish(); sse && unfinished && fin != "" && (rerr == nil || rerr == io.EOF) && r.Context().Err() == nil { + // only the finish_reason was lost, after the generation was done + // (chatTail): the client gets it, and the reply is whole + w.Write([]byte("data: " + string(finishChunk(fin)) + "\n\n")) + if !sniff.ended { + w.Write([]byte("data: [DONE]\n\n")) + } + if f != nil { + f.Flush() + } + sniff.u.Stop, unfinished = fin, false + } + if sse && r.Context().Err() == nil && (!sniff.whole() || unfinished) { // the upstream died mid-reply, or ended it short of its last // event: say so in the stream rather than end it as if whole, // which a client reads as a reply cut off for no reason (#370: // dsh's "stream ended before message_stop", not retried). A Chat // stream may end without [DONE] and be whole, so only a read that - // failed counts there; a Gemini one ends on a candidate's - // finishReason (#1644). + // failed counts there, Gemini's own aside; a Gemini one ends on a + // candidate's finishReason (#1644). var failed string switch { case rerr != nil && rerr != io.EOF: failed = cutMidReply(p.Name, rerr) - case proto == provider.Anthropic || proto == provider.Responses || proto == provider.Gemini: - failed = p.Name + ": the reply ended before it was complete" + case proto == provider.Anthropic || proto == provider.Responses || proto == provider.Gemini || unfinished: + failed = p.Name + ": " + errEndedShort.Error() } if failed != "" { w.Write(streamFailure(proto, failed)) @@ -5416,12 +5431,19 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } var col collector ended := false // the upstream said its reply ended + var tail chatTail see, held := written(zenSee(zen, col.add)) err = readSSE(rd, func(_, data string) error { + tail.see([]byte(data)) u.add(Usage{Upstream: upstreamOf([]byte(data)), Tier: upstreamTier([]byte(data))}) ended = ended || replyEnds(actual, data, upstreamStop([]byte(data))) return dec(data, see) }) + if fin := tail.finish(); err == nil && !ended && actual == provider.Chat && fin != "" && saysItsEnd(p, actual, model) { + // Gemini's OpenAI-compatible API lost only the finish_reason + // after its generation was done (chatTail) + ended, err = true, dec(string(finishChunk(fin)), see) + } held() if err != nil { // a partial answer is not an answer @@ -5439,7 +5461,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr // the vendor failing return writeVendorError(w, from, cmp.Or(col.errStatus, 502), p.Name+": "+said, col.errSaid), said } - if col.err == "" && !ended && (actual == provider.Anthropic || actual == provider.Responses || geminiKin(actual)) && r.Context().Err() == nil { + if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil { // an Anthropic stream that just stopped — no stop_reason, no // message_stop — or a Responses one with no response.completed is // a reply cut short, not a finished one, as a streaming client is diff --git a/internal/gateway/gemini_compat_cut_test.go b/internal/gateway/gemini_compat_cut_test.go new file mode 100644 index 000000000..2da5a4aa2 --- /dev/null +++ b/internal/gateway/gemini_compat_cut_test.go @@ -0,0 +1,144 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Gemini's OpenAI-compatible API, in Linka's frames (Discord): a whole +// function call, its thought signature and the usage in one chunk, then +// the finish_reason in the next. +const ( + compatCall = `data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"extra_content":{"google":{"thought_signature":"c2ln"}},"function":{"arguments":"{\"code\":\"run()\"}","name":"codemode"},"id":"call_1","type":"function"}]},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n" + compatStop = `data: {"choices":[{"delta":{},"finish_reason":"stop","index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n" + compatDone = "data: [DONE]\n\n" +) + +// compatServer serves reply as a Chat upstream on this machine, where a +// Gemini model's is taken to be Gemini's OpenAI-compatible API +// (geminiCompat), and asks it for model at path with body. +func compatServer(t *testing.T, model, reply, path, body string) (int, string) { + t.Helper() + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, reply) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{model}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + return post(t, path, strings.ReplaceAll(body, "MODEL", "up/"+model)) +} + +// compatBare is compatCall without the usage: the generation wasn't +// counted as done. +var compatBare = strings.Replace(compatCall, `,"usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}`, "", 1) + +// The upstream hung up between the call and its finish_reason. Gemini's +// OpenAI-compatible API counts the usage only once the generation is +// done, so a call chunk carrying it lost only the finish_reason: the +// client relayed to gets it, "tool_calls", where Pi threw the call away +// as "Stream ended without finish_reason". Without the usage the reply +// was cut, and the client is told so, as a Gemini stream's is (#1644). +func TestGeminiCompatRelayEndedShort(t *testing.T) { + const ask = `{"model":"MODEL","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}` + const cut = `data: {"error":{"message":"UP: the reply ended before it was complete","type":"api_error"}}` + + code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/chat/completions", ask) + if code != 200 || !strings.Contains(body, `"codemode"`) || strings.Contains(body, "ended before") { + t.Fatalf("status %d: %s", code, body) + } + if !strings.Contains(body, `"finish_reason":"tool_calls"`) || !strings.HasSuffix(strings.TrimSpace(body), compatDone[:len(compatDone)-2]) { + t.Errorf("a done Gemini reply that lost its finish_reason didn't end with it: %s", body) + } + + // text alone, done, ends with "stop" + text := `data: {"choices":[{"delta":{"role":"assistant","content":"hi"},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1,"prompt_tokens":2049,"total_tokens":2050}}` + "\n\n" + if _, body := compatServer(t, "gemini-4-argon", text, "/v1/chat/completions", ask); !strings.Contains(body, `"finish_reason":"stop"`) || strings.Contains(body, "ended before") { + t.Errorf("done text: %s", body) + } + + code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/chat/completions", ask) + if code != 200 || !strings.Contains(body, `"codemode"`) { + t.Fatalf("status %d: %s", code, body) + } + if !strings.HasSuffix(strings.TrimSpace(body), cut) { + t.Errorf("a cut Gemini reply ended as if whole: %s", body) + } + if strings.Contains(body, `"finish_reason":"`) { + t.Errorf("a cut reply given a finish_reason: %s", body) + } + + // whole, with [DONE] or without it, it goes as it came + for what, reply := range map[string]string{ + "whole": compatCall + compatStop + compatDone, + "whole, no [DONE]": compatCall + compatStop, + } { + code, body := compatServer(t, "gemini-4-argon", reply, "/v1/chat/completions", ask) + if code != 200 || strings.Contains(body, "ended before") || strings.Count(body, `"finish_reason":"`) != 1 || !strings.Contains(body, `"finish_reason":"stop"`) { + t.Errorf("%s: %d %s", what, code, body) + } + } + + // another vendor's Chat stream may end whole with neither: it goes as + // it came, as it did + for _, reply := range []string{compatCall, compatBare} { + other := strings.ReplaceAll(reply, "models/gemini-4-argon", "kimi-k3") + code, body = compatServer(t, "kimi-k3", other, "/v1/chat/completions", ask) + if code != 200 || strings.Contains(body, "ended before") || strings.Contains(body, `"finish_reason":"`) { + t.Errorf("another vendor's stream: %d %s", code, body) + } + } +} + +// Translated, a call whose generation was done ends the turn with the +// call, for Claude Code to run; a cut one ends with the error, not with a +// turn that ended with the call never run. +func TestGeminiCompatTranslatedEndedShort(t *testing.T) { + const ask = `{"model":"MODEL","max_tokens":32000,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + _, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", ask) + if !strings.Contains(body, `"codemode"`) { + t.Fatalf("the call didn't reach the client: %s", body) + } + if _, stops, errs := messageStops(body); errs != 0 || stops != 1 || !strings.Contains(body, `"stop_reason":"tool_use"`) { + t.Errorf("a done Gemini call didn't end its turn as one (%d stops, %d errors): %s", stops, errs, body) + } + + _, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", ask) + if !strings.Contains(body, `"codemode"`) { + t.Fatalf("the call didn't reach the client: %s", body) + } + if _, stops, errs := messageStops(body); errs != 1 || stops != 0 { + t.Errorf("a cut Gemini reply ended as a turn (%d stops, %d errors): %s", stops, errs, body) + } + + _, body = compatServer(t, "gemini-4-argon", compatCall+compatStop+compatDone, "/v1/messages", ask) + if _, stops, errs := messageStops(body); errs != 0 || stops != 1 { + t.Errorf("a whole Gemini reply (%d stops, %d errors): %s", stops, errs, body) + } + + // another vendor's Chat stream ends as it did + other := strings.ReplaceAll(compatBare, "models/gemini-4-argon", "kimi-k3") + _, body = compatServer(t, "kimi-k3", other, "/v1/messages", ask) + if _, _, errs := messageStops(body); errs != 0 { + t.Errorf("another vendor's stream: %s", body) + } + + // unstreamed: a done call is the answer, a cut reply a 502 + unstreamed := strings.Replace(ask, `"stream":true`, `"stream":false`, 1) + code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", unstreamed) + if code != 200 || !strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"stop_reason":"tool_use"`) { + t.Errorf("unstreamed done call: %d %s", code, body) + } + code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", unstreamed) + if code != 502 || !strings.Contains(body, "ended before") { + t.Errorf("unstreamed cut: %d %s", code, body) + } +} diff --git a/internal/gateway/sniff.go b/internal/gateway/sniff.go index 4e6d62fe8..d618a3937 100644 --- a/internal/gateway/sniff.go +++ b/internal/gateway/sniff.go @@ -26,6 +26,8 @@ type usageSniffer struct { // failed: what an explicit error event said; a terminal event can end // the stream successfully or with a failure despite its HTTP 200. failed string + // tail: what a Chat stream's chunks say of its end (chatTail) + tail chatTail } func newSniffer(proto provider.Protocol, contentType string) *usageSniffer { @@ -161,6 +163,7 @@ func (s *usageSniffer) parse(b []byte) { } } case provider.Chat: + s.tail.see(b) var v struct { ID string `json:"id"` Error any `json:"error"`