From 82ff889338cf9861bd0b3b53e27f63deffff37dd Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 09:07:21 +0800 Subject: [PATCH] gateway: a Chat tool call naming no function is dropped, not sent for the client to refuse (#1475) AricRedemption on #1475: a long Qoder turn ended with an upstream tool call whose function.name was no string, and the AI SDK refused the whole reply ("Expected 'function.name' to be a string"), not retryable and with the call already in the history, so every "continue" died there while the gateway logged status=200 done=true. The parsers for calls a model writes into its text already refuse a nameless one, but calls an upstream made itself went out as they came. A call whose function names nothing in a JSON string (absent, null, another kind) is dropped on every path a relayed Chat reply leaves by: a stream (chatTidy.nameless, its later fragments with it, and the id mend no longer gives the dropped fragments an id back), a whole reply (wholeNameless in chatWhole) and a whole reply given as the stream the agent asked for (chatWholeEvents). A finish of tool_calls with no call left ends stop. An empty string name goes as it came. Translated routes are unchanged: their names are Go strings by construction. Changed from gua2100's patch (hunt61-a-1475-unnamed-call, d851d922f): - chatWholeEvents turned the finish to stop whenever any call was dropped, so a named call beside a nameless one went out with finish stop and the client ended its turn without running it; it now does so only when no call is left. The calls it keeps are numbered 0.. with no gap where a dropped one stood, and a call with no function object is dropped there too, as wholeNameless already did. - chatWhole turned any whole reply ending tool_calls with no named call into stop, a reply that came with no tool_calls at all included; it now does so only when wholeNameless dropped a call. New tests for both: TestNamelessCallBesideAGoodOneWholeAsStream, TestToolCallsFinishWithNoCallsStaysWhole. Run at this head (451c7e929 on 576b5dcbc), on mote: - go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok (528s). The first try at e53ba61f4 was red only on TestClaudeCallerEnvironmentInAMessageIsTheLastGiven, red 2 of 20 on origin/main too; fixed at its cause in 576b5dcbc, under this commit. - go test -tags nogui -count=1 -run '^(TestNameless|TestNameAbsent| TestToolCallsFinishWithNoCallsStaysWhole|TestChatCallsEndToolCalls| TestEmptyCallID|TestStreamedCallGivenAnID|TestTextWritten|TestDSML| TestQuietWholeReplyStreamed|TestPluginTextWrittenCall|TestChatTidy| TestGeminiCompat|TestWhole|TestRelayed)' ./internal/gateway: ok. - go vet -tags nogui ./internal/gateway on darwin, GOOS=linux and GOOS=windows: clean (at the review tree). gofmt -l: clean. - Not run: go test ./... across every package. Red on main: with chattidy.go, whole_stream.go and chat_call_ids.go from origin/main, 7 of the 8 new tests fail, e.g. TestNamelessCallStreamDropped "calls map[], finish \"tool_calls\"" and TestNamelessCallBesideAGoodOneWholeAsStream "[{Index:0 ID:call_bad ...} {Index:1 ID:call_up ...}]" (TestToolCallsFinishWithNoCallsStaysWhole guards unchanged behaviour and passes there). Broken by hand: - the patch's own chattidy.go and whole_stream.go: TestNamelessCallBesideAGoodOneWholeAsStream fails with "[{Index:1 ID:call_up ...}], finish \"stop\"" and TestToolCallsFinishWithNoCallsStaysWhole with finish "stop". - the `calls = nil` clearing removed: TestNamelessCallWithoutAnIDStaysDropped "the call dropped for naming no function came back with an id". - wholeNameless not called in chatWhole: TestNamelessCallWholeDropped "calls [{call_up ...}], finish \"tool_calls\"". Not tried: a real Qoder subscription or the reporter's exact reply (the report says replays came back well formed; fixtures are synthetic with the shape the client's error names), a real AI SDK client. Not covered: a relayed stream that keeps a named call beside a dropped one keeps the upstream's index numbers, so a gap is left where the dropped call stood; Responses and Anthropic relays (responsesWholeEvents, anthropicWholeEvents, passthrough) forwarding a nameless function_call or tool_use, which has no report. Co-authored-by: ggbdpq --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/chat_call_ids.go | 42 +++++ internal/gateway/chat_call_name_test.go | 204 ++++++++++++++++++++++++ internal/gateway/chattidy.go | 151 ++++++++++++++++-- internal/gateway/textcalls_test.go | 3 + internal/gateway/whole_stream.go | 38 ++++- 6 files changed, 424 insertions(+), 15 deletions(-) create mode 100644 internal/gateway/chat_call_name_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f12da3e62..fa2796b39 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -235,6 +235,7 @@ recorded as a prediction failure (`noPrediction`). - A relayed Chat stream's tool call fragment with no `index` (none, or null) is given its call's (`streamCallIndexes` in [`chattidy.go`](../../internal/gateway/chattidy.go), #3386). Gemini's OpenAI-compatible API sends its calls with none, where the OpenAI contract has one on every fragment: the AI SDK's OpenAI provider (Cursor's Private Inference) turned the chunk away ("expected number, received undefined" at `tool_calls[0].index`), and OpenAI's node SDK's stream helper kept no call at all. A fragment with an id other than the open call's, or after the first in its delta, is the next call; any other goes on with the open one. So two calls in chunks of their own are 0 and 1, never both 0, which that helper merges into one call. A fragment with an index keeps it. `TestChatTidyGivesCallsAnIndex` in [`chattidy_test.go`](../../internal/gateway/chattidy_test.go), `TestGeminiCompatRelayedCallsHaveAnIndex` in [`gemini_compat_cut_test.go`](../../internal/gateway/gemini_compat_cut_test.go). - A translated Chat stream's tool calls are read by `index`, not as one after another (`chatDecoder.toolCall` in [`chat.go`](../../internal/gateway/chat.go)). An upstream may send several calls' fragments by turns (index 0, 1, 0, 1…), the first of each with its id and name; read as a new call at each change of index, two calls reached Codex as six `function_call` items, the first two with `{}` and four with no name (mysterious_dove on Discord). The open call streams as it comes; a call that starts while the open one's arguments aren't yet whole JSON is held by its index and given whole, in index order, at `finish_reason` or `[DONE]`. Every translation from Chat (Responses, Messages, Gemini, a whole reply) reads the stream through it. `TestInterleavedToolCallsToResponses`, `TestInterleavedToolCallsToAnthropic`, `TestInterleavedToolCallsWhole`, `TestToolCallsNamedFirstThenArgued` in [`translate_stream_test.go`](../../internal/gateway/translate_stream_test.go). - A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go). +- A Chat reply's call whose function names nothing in a JSON string — no name, null, another kind — is dropped, its later fragments with it, and a finish of `tool_calls` with no call left after the drop ends `stop` (a reply that came with no calls keeps its finish), and a whole reply given as a stream numbers the calls it keeps with no gap: streamed (`chatTidy`), whole (`chatWhole`) and a whole reply given to the agent as the stream it asked for (`chatWholeEvents`), since a client that checks the shape of every frame refuses the whole reply for one — the turn not retryable, the call already in the history, the session dead, while the gateway's own log says the reply went (AricRedemption, #1475). A nameless call runs nowhere, so it is no call, as a written block naming no offered tool is; a name the client reads as a string, empty included, goes as it came. `TestNamelessCallStreamDropped`, `TestNameAbsentStreamDropped`, `TestNamelessCallBesideAGoodOne`, `TestNamelessCallWholeDropped`, `TestNamelessCallWholeAsStreamDropped`, `TestNamelessCallWithoutAnIDStaysDropped`, `TestNamelessCallBesideAGoodOneWholeAsStream`, `TestToolCallsFinishWithNoCallsStaysWhole` in [`chat_call_name_test.go`](../../internal/gateway/chat_call_name_test.go). - 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 stay in it when they are kept out of other agents' lists for routing groups, by the codex provider "Only through routing groups" (`Provider.Unlisted`) or a group that unlists its members (`Group.Unlists`): Codex's own catalog (`catalogOf("codex")`, behind `ListedFor`/`CatalogFor`) keeps `CodexOwn` entries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file and `spawnChoices` list them. #1602 dropped them here, and the picker then still offered them through the own-models switch while the Codex app had none (士奇 on Discord, 10-28). They are hidden from Codex through Codex's list (`provider.CodexNativeHidden`, `TestCodexModelListKeepsOwnForGroups`, `TestCodexOwnModelsListedOnlyThroughGroups`). Every agent keeps a signed-in subscription's own models (`provider.SubscriptionKept`: an account's, its provider not `Unlisted`) that a group listing alone would keep out: `catalogOf(agent)` keeps them for any agent, so the Agents page, the pickers, the files magpie writes and the agent's `/v1/models` (and `/v1/models/{id}`, Desktop's aliases through `provider.CatalogOf`) still have them with the group on. Only a client that is no agent (`CatalogFor("")`, `Catalog()`) is given the group alone (#1783). a3ee00c05 had kept them for Codex alone, and Hermes Agent and WorkBuddy lost the Codex section with the group on (士奇 on Discord, 10-30; `TestSubscriptionModelsStayInEveryAgentsListWithGroupOn`). A backend answer that says the sign-in itself is revoked (`provider.SignInRevoked`, a 401 `token_revoked`; jjt on Discord, #4308) isn't passed through: the list is Codex's cached one (`codexcat.CacheEntries`) and magpie's, so the picker keeps magpie's models; any other refusal, a 401 `token_expired` among them, still is. The desk file does the same while the live list says revoked (`provider.CodexListRevoked`, `codexDesk.revoked`) (`TestCodexModelListRevokedSignIn`, `TestCodexDesktopCatalogRevokedSignIn`). - The Codex app and its VS Code extension read only the first 100 of that list by priority, hidden entries counted: each asks its app-server for `model/list` with `limit: 100` and never for the next page (ChatGPT.app 26.1013, openai.chatgpt 26.51021; the CLI's `/model` lists every one). So `codexcat.FitOwn` ranks the list last of all: hidden entries after every listed one, and, with more than 100 listed (`codexcat.AppList`), Codex's own listed models (the backend's entries in `codexMerged`; a ChatGPT account's `codex/…` ones, `codexcat.ChatGPTOwn`, on the other two routes) and then the models Codex used in the last 30 days (`usage.CodexUsed`, most recent first, at most 100) brought into the first 100 in the order they stood, the rest kept in theirs. The user's own order (`codexcat.Order`, #855) goes first, so an order that names only magpie's models (set while Codex's list had no Codex section, or before OpenAI added a model) no longer puts every GPT model past the 100th (maiya on Discord); the user takes one out of the app by hiding it in Codex's list. The same holds for `/v1/codex/models` (with the models that key's Codex used alone, `usage.CodexUsedBy`, before the 1 MiB cut) and the `model_catalog_json` magpie writes (`codexcat.CatalogUsed`). `codexListTag` carries a tag of the used set (`codexcat.UsedTag`), so the ETag and `X-Models-Etag` change when Codex uses a model it hadn't; `usage.CodexUsed` is read again a minute on, or at once when `Append` writes a Codex call to a model it doesn't hold (`codexUsedNew`). `TestCodexModelListKeepsUsedModelsInTheAppsHundred`, `TestCodexCatalogKeepsTheKeysUsedModelsFirst`, `TestFitKeepsUsedModelsWhereTheCodexAppReads`, `TestCodexUsed`, `TestCodexModelListKeepsOwnModelsInTheAppsHundred`, `TestFitOwnKeepsCodexsOwnInTheAppsHundred` and `TestCatalogUsedKeepsChatGPTOwn` cover it (@ZhenLuoTTAWDTT on X). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Across APIs, only Claude's reasoning is carried to a Responses client, below. diff --git a/internal/gateway/chat_call_ids.go b/internal/gateway/chat_call_ids.go index a3d3cd954..6e4b2e431 100644 --- a/internal/gateway/chat_call_ids.go +++ b/internal/gateway/chat_call_ids.go @@ -137,3 +137,45 @@ func wholeCallIDs(msg map[string]json.RawMessage) bool { } return changed } + +// wholeNameless drops the tool calls of a whole reply's message whose +// function names nothing in a JSON string — no name, null, another kind +// (#1475) — and reports whether any was dropped. +func wholeNameless(msg map[string]json.RawMessage) bool { + var calls []map[string]json.RawMessage + if decodeJSON(msg["tool_calls"], &calls) != nil { + return false + } + var kept []map[string]json.RawMessage + for _, c := range calls { + var fn map[string]json.RawMessage + if decodeJSON(c["function"], &fn) == nil && aName(fn["name"]) { + kept = append(kept, c) + } + } + if len(kept) == len(calls) { + return false + } + if kept == nil { + delete(msg, "tool_calls") + return true + } + msg["tool_calls"], _ = marshalPlain(kept) + return true +} + +// wholeNamedCall says whether a whole reply's message still carries a +// tool call whose function names itself in a string. +func wholeNamedCall(msg map[string]json.RawMessage) bool { + var calls []map[string]json.RawMessage + if decodeJSON(msg["tool_calls"], &calls) != nil { + return false + } + for _, c := range calls { + var fn map[string]json.RawMessage + if decodeJSON(c["function"], &fn) == nil && aName(fn["name"]) { + return true + } + } + return false +} diff --git a/internal/gateway/chat_call_name_test.go b/internal/gateway/chat_call_name_test.go new file mode 100644 index 000000000..66fc68f70 --- /dev/null +++ b/internal/gateway/chat_call_name_test.go @@ -0,0 +1,204 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" +) + +// AricRedemption on #1475: a long Qoder turn ended with an upstream tool +// call whose function.name was no string, and the client that checks the +// shape of every frame (the AI SDK) refused the whole reply — "Expected +// 'function.name' to be a string" — the turn not retryable and the call +// already in the history, so the session was dead; magpie's own log said +// status=200, done=true. A call no client can read runs nowhere, so it is +// no call: it is dropped, its later fragments with it, and a finish of +// tool_calls with no call left ends stop — what textcalls' parser does +// with a written block that names no offered tool. A name the client +// reads as a string, empty included, goes as it came. + +// The first fragment of a streamed call naming no function in a string, +// its argument fragments dropped with it, a finish of tool_calls ended +// stop, the text before the call kept. +func TestNamelessCallStreamDropped(t *testing.T) { + first := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"name":null,"arguments":""}}]},"finish_reason":null}]}` + args := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"cmd\":\"ls -la\"}"}}]},"finish_reason":null}]}` + ended := strings.Replace(stopChunk, `"stop"`, `"tool_calls"`, 1) + text, calls, finish, raw := relayedChat(t, + `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + chunkOf("Running it."), first, args, ended) + if text != "Running it." || len(calls) != 0 || finish != "stop" { + t.Fatalf("text %q, calls %v, finish %q\n%s", text, calls, finish, raw) + } + if strings.Contains(raw, `"tool_calls":[`) { + t.Fatalf("a call naming no function reached the client:\n%s", raw) + } +} + +// The same with the name field absent, as the merged deltas leave it for +// a client to read. +func TestNameAbsentStreamDropped(t *testing.T) { + first := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"arguments":""}}]},"finish_reason":null}]}` + args := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"cmd\":\"ls\"}"}}]},"finish_reason":null}]}` + _, calls, finish, raw := relayedChat(t, + `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + first, args, stopChunk) + if len(calls) != 0 || finish != "stop" { + t.Fatalf("calls %v, finish %q\n%s", calls, finish, raw) + } + if strings.Contains(raw, `"tool_calls":[`) { + t.Fatalf("a call naming no function reached the client:\n%s", raw) + } +} + +// The same dropped call the upstream gave no id for: the call is dropped, +// yet it comes back — the drop takes it out of the delta, but the +// fragments themselves stay in the local calls, and the id mend that +// follows (#2611) gives the first one an id and writes them back. The +// frame the client refuses leaves after all, an id on it. +func TestNamelessCallWithoutAnIDStaysDropped(t *testing.T) { + first := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"type":"function","function":{"name":null,"arguments":""}}]},"finish_reason":null}]}` + args := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"cmd\":\"ls -la\"}"}}]},"finish_reason":null}]}` + ended := strings.Replace(stopChunk, `"stop"`, `"tool_calls"`, 1) + _, calls, finish, raw := relayedChat(t, + `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + chunkOf("Running it."), first, args, ended) + if len(calls) != 0 || finish != "stop" { + t.Fatalf("calls %v, finish %q\n%s", calls, finish, raw) + } + if strings.Contains(raw, `"tool_calls":[`) { + t.Fatalf("the call dropped for naming no function came back with an id:\n%s", raw) + } +} + +// A call with a name stands beside one without: the named one goes, the +// nameless one alone is dropped, and the finish stays tool_calls. +func TestNamelessCallBesideAGoodOne(t *testing.T) { + mixed := `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"ls\"}"}},{"index":1,"id":"call_bad","type":"function","function":{"name":null,"arguments":""}}]},"finish_reason":null}]}` + _, calls, finish, raw := relayedChat(t, + `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + mixed, stopChunk) + if len(calls) != 1 || calls["exec_command"] != `{"cmd":"ls"}` || finish != "tool_calls" { + t.Fatalf("calls %v, finish %q\n%s", calls, finish, raw) + } + if strings.Contains(raw, "call_bad") { + t.Fatalf("the nameless call reached the client:\n%s", raw) + } +} + +// A whole reply's call naming no function is dropped before it is +// relayed, and its finish of tool_calls ends stop; the text is kept. +func TestNamelessCallWholeDropped(t *testing.T) { + up := `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"Let me.","tool_calls":[{"id":"call_up","type":"function","function":{"name":null,"arguments":"{\"cmd\":\"ls\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + text, calls, finish, raw := wholeChat(t, + `{"model":"a/m","stream":false,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + "application/json", up) + if text == nil || *text != "Let me." || len(calls) != 0 || finish != "stop" { + t.Fatalf("text %v, calls %v, finish %q\n%s", text, calls, finish, raw) + } + if strings.Contains(raw, `"tool_calls"`) { + t.Fatalf("a call naming no function reached the client:\n%s", raw) + } +} + +// The whole reply a vendor gave after the agent was kept alive goes out +// as the stream the agent asked for (wholeAsStream): its call naming no +// function is dropped there too, and the finish with no call left ends +// stop. +func TestNamelessCallWholeAsStreamDropped(t *testing.T) { + up := `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"Let me.","tool_calls":[{"id":"call_up","type":"function","function":{"name":null,"arguments":"{\"cmd\":\"ls\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + var sawToolCalls, saidNull bool + var finish string + for _, e := range chatWholeEvents([]byte(up)) { + b, _ := json.Marshal(e.data) + s := string(b) + if strings.Contains(s, `"name":null`) || strings.Contains(s, `"name":`) && !strings.Contains(s, `"name":"`) { + saidNull = true + } + if strings.Contains(s, `"tool_calls"`) { + sawToolCalls = true + } + var ch struct { + Choices []struct { + FinishReason string `json:"finish_reason"` + } `json:"choices"` + } + if json.Unmarshal([]byte(s), &ch) == nil && len(ch.Choices) > 0 && ch.Choices[0].FinishReason != "" { + finish = ch.Choices[0].FinishReason + } + } + if sawToolCalls || saidNull { + t.Fatalf("the events carried a call naming no function (tool_calls %v, null name %v)", sawToolCalls, saidNull) + } + if finish != "stop" { + t.Fatalf("finish %q, want stop", finish) + } +} + +// A whole reply given as a stream with a named call beside a nameless +// one: the named call goes, numbered 0 with no gap where the dropped one +// stood, and the finish stays tool_calls, since a call is left. +func TestNamelessCallBesideAGoodOneWholeAsStream(t *testing.T) { + up := `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[{"id":"call_bad","type":"function","function":{"name":null,"arguments":""}},{"id":"call_up","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"ls\"}"}}]},"finish_reason":"tool_calls"}]}` + var finish string + var got []struct { + Index int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + } `json:"function"` + } + for _, e := range chatWholeEvents([]byte(up)) { + if _, done := e.data.(string); done { + continue // [DONE] + } + b, _ := json.Marshal(e.data) + var ch struct { + Choices []struct { + Delta struct { + ToolCalls []struct { + Index int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + FinishReason *string `json:"finish_reason"` + } `json:"choices"` + } + if err := json.Unmarshal(b, &ch); err != nil { + t.Fatalf("unreadable event %s: %v", b, err) + } + for _, c := range ch.Choices { + for _, tc := range c.Delta.ToolCalls { + got = append(got, struct { + Index int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + } `json:"function"` + }(tc)) + } + if c.FinishReason != nil { + finish = *c.FinishReason + } + } + } + if len(got) != 1 || got[0].ID != "call_up" || got[0].Index != 0 || got[0].Function.Name != "exec_command" || finish != "tool_calls" { + t.Fatalf("calls %+v, finish %q", got, finish) + } +} + +// A whole reply that ends tool_calls with no call in it at all keeps its +// finish as it came: only a reply whose calls were dropped for naming no +// function ends stop. +func TestToolCallsFinishWithNoCallsStaysWhole(t *testing.T) { + up := `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"Done."},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + text, _, finish, raw := wholeChat(t, + `{"model":"a/m","stream":false,"messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, + "application/json", up) + if text == nil || *text != "Done." || finish != "tool_calls" { + t.Fatalf("text %v, finish %q\n%s", text, finish, raw) + } +} diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index a0050ed4f..01406ee69 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -68,12 +68,26 @@ import ( // gateway counted the hit, but an agent on pi-ai (DeepSeek Harness), which // reads prompt_tokens_details.cached_tokens first, showed none. // +// And a call whose first fragment names no function in a JSON string — +// no name, null, another kind — is dropped, its later fragments with it, +// and a finish of tool_calls with no call left ends stop (#1475): a +// client that checks the shape of every frame refuses the chunk for it +// and the whole reply with it, the turn not retryable and the call +// already in the history, so the session is dead — while the gateway's +// own log says the reply went (AricRedemption). A nameless call runs +// nowhere, so it is no call, as a written block naming no offered tool +// is; a name of another kind on a later fragment is left out, the first +// one's kept. +// // Lines pass whole, as they came, unless one has any of them. type chatTidy struct { buf []byte ids streamCallIDs indexes streamCallIndexes - called map[int]bool // the choices that made a call + called map[int]bool // the choices that made a call + named map[int]bool // the choices with a call whose name a client reads + seen map[[2]int]bool // the streamed calls, to know a first fragment + bad map[[2]int]bool // the calls naming no function, with their later fragments } var ( @@ -273,29 +287,55 @@ func (t *chatTidy) line(line []byte) []byte { calls, delta["tool_calls"] = given, given inDelta = true } - if t.ids == nil { - t.ids = streamCallIDs{} - } if t.called == nil { t.called = map[int]bool{} } t.called[choice] = true - if mended, chg := t.ids.mend(choice, calls); chg { - calls, delta["tool_calls"] = mended, mended + if kept, chg := t.nameless(choice, calls); chg { + if kept == nil { + delete(delta, "tool_calls") + // the fragments went with the drop: none is left for the + // id mend to give an id to, or the dropped call would + // come back as one with a fresh id and no name (#1475) + calls = nil + } else { + calls, delta["tool_calls"] = kept, kept + } inDelta = true } - if mended, chg := withoutEmptyNames(calls); chg { - delta["tool_calls"] = mended - inDelta = true + if calls != nil { + if t.ids == nil { + t.ids = streamCallIDs{} + } + if mended, chg := t.ids.mend(choice, calls); chg { + calls, delta["tool_calls"] = mended, mended + inDelta = true + } + if mended, chg := withoutEmptyNames(calls); chg { + delta["tool_calls"] = mended + inDelta = true + } } } if inDelta { c["delta"], _ = json.Marshal(delta) changed = true } - if t.called[choice] && string(bytes.TrimSpace(c["finish_reason"])) == `"stop"` { - c["finish_reason"] = json.RawMessage(`"tool_calls"`) - changed = true + if t.called[choice] { + switch end := string(bytes.TrimSpace(c["finish_reason"])); end { + case `"stop"`: + if t.named[choice] { + c["finish_reason"] = json.RawMessage(`"tool_calls"`) + changed = true + } + case `"tool_calls"`: + if !t.named[choice] { + // the call the finish named named no function: it ends + // stop, as a reply that made no call (#1475) + c["finish_reason"] = json.RawMessage(`"stop"`) + changed = true + } + } } } if !changed && !usageMended { @@ -401,6 +441,83 @@ func (s streamCallIndexes) give(choice int, raw json.RawMessage) (json.RawMessag return out, true } +// nameless drops the fragments of a streamed call whose first one names +// no function in a JSON string — no name, null, another kind — with the +// later fragments of the same call (#1475): a client that checks the +// shape of every frame refuses the chunk for it and the whole reply with +// it, the turn not retryable and the call already in the history, so the +// session is dead. A nameless call runs nowhere, so it is no call, as a +// written block naming no offered tool is. A name of another kind on a +// later fragment only loses the field, the first one's kept. It reports +// the fragments kept, nil when none, and whether any was dropped. +func (t *chatTidy) nameless(choice int, raw json.RawMessage) (json.RawMessage, bool) { + var calls []map[string]json.RawMessage + if decodeJSON(raw, &calls) != nil { + return raw, false + } + var kept []map[string]json.RawMessage + changed := false + for _, call := range calls { + idx := 0 + decodeJSON(call["index"], &idx) + key := [2]int{choice, idx} + if t.bad[key] { + changed = true + continue + } + first := !t.seen[key] + if t.seen == nil { + t.seen = map[[2]int]bool{} + } + t.seen[key] = true + var fn map[string]json.RawMessage + var name json.RawMessage + var has bool + if decodeJSON(call["function"], &fn) == nil { + name, has = fn["name"] + } + switch { + case has && aName(name): + if t.named == nil { + t.named = map[int]bool{} + } + t.named[choice] = true + kept = append(kept, call) + case has && !first: + // it would write itself over the name the first fragment + // carried, as an empty one would + delete(fn, "name") + call["function"], _ = json.Marshal(fn) + kept = append(kept, call) + changed = true + default: + if !first { + // a later fragment: the name went with the first + kept = append(kept, call) + continue + } + // no name the client reads, and a call's name goes with its + // first fragment: no fragment of this call will name it + if t.bad == nil { + t.bad = map[[2]int]bool{} + } + t.bad[key] = true + changed = true + } + } + if !changed { + return raw, false + } + if kept == nil { + return nil, true + } + out, err := json.Marshal(kept) + if err != nil { + return raw, false + } + return out, true +} + // partsText reads a content that is an array of typed parts: its text, // and the text of its thinking parts. ok is false for any other content, // a string or null. @@ -513,6 +630,10 @@ func (t *chatWhole) flush() []byte { mended := parts && flattenContent(msg, true) // a call the upstream gave no id (#2611) mended = wholeCallIDs(msg) || mended + // a call naming no function runs nowhere and no client can read + // it (#1475) + dropped := wholeNameless(msg) + mended = dropped || mended if wrote, called := wholeTextCalls(msg, t.names); wrote { if called { c["finish_reason"] = json.RawMessage(`"tool_calls"`) @@ -525,6 +646,12 @@ func (t *chatWhole) flush() []byte { c["finish_reason"] = json.RawMessage(`"tool_calls"`) changed = true } + // the call the finish named naming no function, it ends stop, as a + // reply that made no call (#1475) + if dropped && string(bytes.TrimSpace(c["finish_reason"])) == `"tool_calls"` && !wholeNamedCall(msg) { + c["finish_reason"] = json.RawMessage(`"stop"`) + changed = true + } if !mended { continue } diff --git a/internal/gateway/textcalls_test.go b/internal/gateway/textcalls_test.go index 16dbad387..19e0bc31f 100644 --- a/internal/gateway/textcalls_test.go +++ b/internal/gateway/textcalls_test.go @@ -64,6 +64,9 @@ func relayedChat(t *testing.T, body string, up ...string) (text string, calls ma if tc.Function.Name != "" { names = append(names, tc.Function.Name) } + if len(names) == 0 { + continue // a fragment with no name before it + } calls[names[len(names)-1]] += tc.Function.Arguments } if c.FinishReason != nil { diff --git a/internal/gateway/whole_stream.go b/internal/gateway/whole_stream.go index 55ee03988..a7d585dea 100644 --- a/internal/gateway/whole_stream.go +++ b/internal/gateway/whole_stream.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "encoding/json" "maps" "net/http" @@ -60,6 +61,15 @@ func str(m obj, k string) string { return s } +// aName says whether raw is a JSON string: a call name a client's shape +// check takes, empty or not. No name, null and any other kind are not +// (#1475): a client that checks the shape of every frame refuses the +// whole reply for one. +func aName(r json.RawMessage) bool { + t := bytes.TrimSpace(r) + return len(t) > 0 && t[0] == '"' +} + // chatWholeEvents streams a chat.completion as its chunks: each choice's // message as one delta, its tool calls numbered as a stream numbers them, // then its finish reason with the usage, then [DONE]. @@ -101,12 +111,34 @@ func chatWholeEvents(b []byte) []wholeEvent { delta := maps.Clone(c.Message) var calls []obj if json.Unmarshal(delta["tool_calls"], &calls) == nil && len(calls) > 0 { - for n, call := range calls { - if _, ok := call["index"]; !ok { + var kept []obj + for _, call := range calls { + var fn obj + if json.Unmarshal(call["function"], &fn) != nil || !aName(fn["name"]) { + // a call naming no function in a string runs nowhere + // and no client can read (#1475): dropped, as a written + // block naming no offered tool is + continue + } + kept = append(kept, call) + } + for n, call := range kept { + // numbered as a stream numbers them, with no gap where a + // dropped call stood + if _, ok := call["index"]; !ok || len(kept) < len(calls) { call["index"] = raw(n) } } - delta["tool_calls"] = raw(calls) + if kept == nil { + delete(delta, "tool_calls") + } else { + delta["tool_calls"] = raw(kept) + } + if kept == nil && string(bytes.TrimSpace(c.FinishReason)) == `"tool_calls"` { + // the call the finish named named no function: it ends + // stop, as a reply that made no call + c.FinishReason = raw("stop") + } } d := obj{"index": index, "delta": raw(delta), "finish_reason": raw(nil)} if c.Logprobs != nil {