gateway: an assistant turn cut off before it said anything is left out of what a Chat upstream is sent (#2599)

timonwong (#2599): after the user stops a reply while the model is still
thinking, the agent keeps a turn with no text and no calls and sends it
again on every later turn. Translated (buildChat) or relayed, it reached
the Chat upstream as {"role":"assistant","content":""} (reasoning_content
alone, on DeepSeek), and DeepSeek and Kimi turned every request of the
conversation away: "Invalid assistant message: content or tool_calls must
be set".

One rule, withoutSilentAssistants (chat.go), runs on both Chat routes:
buildChat before pairToolMessages (Claude Code, Codex and Gemini clients,
and the plugins fed by buildChat), and silentAssistantsOut in passthrough
next to developerAsSystem (a Chat client's own body). An assistant
message with no content or only blank text parts, and no tool_calls or
function_call, is left out; the user messages it stood between join into
one (texts with a blank line, else their parts in order), so no two user
messages stand in a row. A prefill (prefix, partial, a Resume), a legacy
function_call, a refusal and an audio reply stay. A relayed body without
such a turn goes byte for byte. TestChatThinkingOnlyAssistantKeptOutside-
Exchange pinned the old pass-through; it now expects the joined message.

Built on ggbdpq's patch (cb438ebb on their fork) and its fake upstream,
written again because the review found it missed shapes the issue names:
- after a tool result it kept the empty turn ("a strict template wants the
  reply behind its tool message"), so the interruption mid tool loop still
  sent content "" and still got the 400. tool then user is what any agent
  sends when the user writes after a tool result; it is now left out.
- the relay dropped an assistant with a legacy function_call or a refusal
  and empty content, and a client's own prefix/partial prefill;
  kept blank text-part arrays (still refused); joined only string users;
  re-marshalled with HTML escaping.
- its Resume check compared a joinSplitCalls turn index with
  len(r.Messages)-1.

Verified (sandbox HOME, pinned caches, go1.26.8 darwin/arm64, base
origin/main 72d6103e2):
- The fake upstream refuses with the issue's literal 400 body any
  assistant without content or tool_calls, plus DeepSeek's #1462/#1822
  reasoning rule. On main's product code 18 subtests of the new tests go
  red with that 400 (Claude Code: thinking, redacted, empty text,
  thinking+empty text, [], "", after a tool result; Codex: lone reasoning,
  empty output_text, no content; Gemini thought-only; relay: "", null, no
  content, blank parts, after a tool result; relay keeps-what-speaks), and
  TestChatThinkingOnlyAssistantLeftOutOutsideExchange. With ggbdpq's
  product files instead, after-a-tool-result (both routes), blank parts
  and TestChatRelaySilentAssistantsOnly are red. With this change all
  pass; TestChatResumeEmptyPrefillKept is a guard, green before and after.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows:
  ok. Full suite with both this and the #2575 test change in the tree,
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 66 packages
  ok, none failed (internal/gateway 825s, internal/provider 266s).
- Rebased onto origin/main ec6454395 (claude_subscription, ir.go):
  gofmt clean, vet darwin/linux/windows on internal/gateway and
  internal/settings ok; go test -tags nogui -timeout 45m
  ./internal/gateway ./internal/settings: ok (gateway 668s).
- Not tried against real DeepSeek or Kimi (the fake answers with the
  issue's bytes). Gemini and Responses upstreams are not changed; the
  Messages build already drops an empty turn and merges same-role
  neighbours (anthropicBody's push).

Co-authored-by: ggbdpq <67929842+ggbdpq@users.noreply.github.com>
This commit is contained in:
yetone
2026-10-17 05:15:16 +08:00
co-authored by ggbdpq
parent e903d87fbe
commit ed0335f75c
6 changed files with 444 additions and 9 deletions
+1
View File
@@ -144,6 +144,7 @@ recorded as a prediction failure (`noPrediction`).
- A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`.
- Every request to a key+URL provider goes with magpie's User-Agent (`magpie/<Version>`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set <id> user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's `<client> magpie-image/1`, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`.
- A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before.
- An assistant turn the user cut off before it said anything (only its thinking, an empty text, nothing; an isolated Codex reasoning item; a Gemini thought alone) stays in the agent's history and is sent on every later turn. DeepSeek and Kimi turn the whole request away over an assistant message with neither content nor tool calls, `reasoning_content` alone included ("Invalid assistant message: content or tool_calls must be set", #2599). Every Chat upstream gets such a turn left out, translated (`buildChat`, before `pairToolMessages`) or relayed (`silentAssistantsOut` in `passthrough`), by one rule (`withoutSilentAssistants` in [`chat.go`](../../internal/gateway/chat.go)): the two user messages it stood between join into one, and after a tool result the user's message follows the tool message. A prefill to go on from (`prefix`, `partial`, a Resume), a legacy `function_call`, a refusal and an audio reply stay, and a relayed body without such a turn goes byte for byte. `TestChatEmptyAssistantLeftOutFromAnthropic`, `…FromResponses`, `…FromGemini`, `TestChatRelayLeavesOutEmptyAssistant`, `TestChatRelaySilentAssistantsOnly`.
- Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`).
- Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put blocks of their own in a message: a `tool_addition` (`tool` a `tool_reference` naming the tool, or a `tool_definition`), a `tool_removal`, and a `tool_reference`. Kimi's Anthropic endpoint refuses any of them with a whole-request 400 "Invalid request Error" that names nothing, so once a session had loaded a tool every turn failed (#2042); DeepSeek's takes a `tool_addition` naming a tool but refuses one defining it, a `tool_removal` and a message's `tool_reference` with 422 "unknown variant `tool_removal`" (both checked against the real endpoints on 2026-10-14). OpenCode Go also rejects DeepSeek inline definitions with a generic 422 "Upstream request failed: Endpoint is unavailable." (checked on 2026-10-15). Kimi and DeepSeek models on OpenCode are never sent these blocks (`forwardOnce`); a provider that refuses one in those words is asked again at once without them and not sent them again while magpie runs (`refuseShapes`, `shapeDeferred`; the retry loop reads a 422 as well as a 400). `withoutDeferredTools` drops the blocks and a message they leave empty; definitions present only in a `tool_addition.tool.definition` join the request's `tools` once by name (an existing top-level definition wins), and a `tool_reference` inside a `tool_result` (ToolSearch's answer, which both take) stays. Any other provider is sent them as Claude Code wrote them ([`anthropic_shapes.go`](../../internal/gateway/anthropic_shapes.go), `TestKimiIsSentNoDeferredToolBlocks`, `TestDeferredToolBlocksRefusedOnceLeftOut`, `TestOpenCodeDeepSeekInlineTools`, `TestDeferredInlineDefinitionPreserved`).
- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).
+132 -3
View File
@@ -5,10 +5,12 @@ import (
"cmp"
"encoding/json"
"fmt"
"maps"
"mime"
"net"
"path"
"regexp"
"slices"
"sort"
"strings"
"time"
@@ -448,6 +450,7 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
flush()
}
showSeen()
msgs, _ = withoutSilentAssistants(msgs)
msgs = pairToolMessages(msgs)
out := map[string]any{"model": model, "messages": msgs, "stream": r.Stream}
if r.CacheKey != "" {
@@ -551,9 +554,10 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
// calls split over consecutive assistant messages were joined into
// one by joinSplitCalls before, so they are pending together (#1275);
// - an assistant message with nothing in it — no text, no calls, no
// reasoning, what a thinking-only turn becomes — is dropped inside a
// pending exchange, where it would sit between calls and their
// answers; outside an exchange it passes through, as on main.
// reasoning — is dropped inside a pending exchange, where it would
// sit between calls and their answers. One with neither text nor
// calls was taken out before, wherever it stood
// (withoutSilentAssistants, #2599).
func pairToolMessages(msgs []map[string]any) []map[string]any {
out := make([]map[string]any, 0, len(msgs))
var pending []string // calls of the last assistant message with tool_calls
@@ -663,6 +667,131 @@ func emptyAssistant(m map[string]any) bool {
return strings.TrimSpace(s) == ""
}
// silentAssistant reports whether a Chat message is an assistant turn
// that says nothing: no content or only blank text, and no tool_calls or
// function_call. It is what an agent keeps of a reply the user cut off
// before it said anything — only its thinking, an empty text, nothing —
// and DeepSeek, Kimi and the like turn the whole request away over it,
// "Invalid assistant message: content or tool_calls must be set", on
// every later turn of the conversation (#2599). reasoning_content is not
// content to them. A prefill to go on from (prefix, partial), a refusal
// and an audio reply say something and stay.
func silentAssistant(m map[string]any) bool {
if m["role"] != "assistant" {
return false
}
if m["prefix"] == true || m["partial"] == true || m["function_call"] != nil || m["audio"] != nil {
return false
}
if s, _ := m["refusal"].(string); s != "" {
return false
}
switch c := m["tool_calls"].(type) {
case []map[string]any:
if len(c) > 0 {
return false
}
case []any:
if len(c) > 0 {
return false
}
case nil:
default:
return false
}
switch c := m["content"].(type) {
case nil:
return true
case string:
return strings.TrimSpace(c) == ""
case []any:
for _, p := range c {
pm, _ := p.(map[string]any)
if t, _ := pm["text"].(string); pm == nil || pm["type"] != "text" || strings.TrimSpace(t) != "" {
return false
}
}
return true
case []map[string]any:
for _, pm := range c {
if t, _ := pm["text"].(string); pm["type"] != "text" || strings.TrimSpace(t) != "" {
return false
}
}
return true
}
return false
}
// withoutSilentAssistants leaves out of a Chat request's messages every
// assistant turn that says nothing (silentAssistant), and joins the user
// messages it stood between into one, as toolAsUser joins: some models'
// chat templates turn away two user messages in a row. Nothing of the cut
// turn reaches the model, as nothing of it reached the user. Every
// strict-template rule stays kept: a tool message still follows the turn
// with its call, and a tool message followed by the user's is what an
// agent sends whenever the user writes after a tool result. It reports
// whether it changed anything; the messages are edited in place.
func withoutSilentAssistants(msgs []map[string]any) ([]map[string]any, bool) {
if !slices.ContainsFunc(msgs, silentAssistant) {
return msgs, false
}
out := make([]map[string]any, 0, len(msgs))
dropped := false
for _, m := range msgs {
if silentAssistant(m) {
dropped = true
continue
}
if n := len(out); dropped && n > 0 && m["role"] == "user" && out[n-1]["role"] == "user" {
if joined, ok := joinedUserContent(out[n-1]["content"], m["content"]); ok {
prev := maps.Clone(out[n-1])
prev["content"] = joined
out[n-1] = prev
continue
}
}
dropped = false
out = append(out, m)
}
return out, true
}
// joinedUserContent is two user messages' content as one: two texts with a
// blank line between them, else the parts of the first and then the
// second's, a text becoming a text part.
func joinedUserContent(a, b any) (any, bool) {
as, aText := a.(string)
bs, bText := b.(string)
if aText && bText {
return as + "\n\n" + bs, true
}
parts := func(c any) ([]any, bool) {
switch c := c.(type) {
case string:
if strings.TrimSpace(c) == "" {
return nil, true
}
return []any{map[string]any{"type": "text", "text": c}}, true
case []any:
return c, true
case []map[string]any:
out := make([]any, len(c))
for i, p := range c {
out[i] = p
}
return out, true
}
return nil, false
}
ap, aok := parts(a)
bp, bok := parts(b)
if !aok || !bok {
return nil, false
}
return append(slices.Clip(ap), bp...), true
}
// aiStudioHost is Google AI Studio's Gemini API, whose OpenAI-compatible
// endpoint gives the model's thoughts only when asked for them.
const aiStudioHost = "generativelanguage.googleapis.com"
@@ -0,0 +1,266 @@
package gateway
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// dsRefuseEmptyAssistant answers as DeepSeek's and Kimi's Chat APIs do,
// in the bytes of #2599, for a turn the agent cut off before it said
// anything: an assistant message with neither content nor tool_calls is
// invalid however much reasoning_content it carries, and the whole request
// is turned away. DeepSeek's rule for a tool turn without its reasoning
// (#1462, #1822) holds as well.
func dsRefuseEmptyAssistant(body []byte) (int, string) {
var q struct {
Messages []map[string]json.RawMessage `json:"messages"`
}
json.Unmarshal(body, &q)
for _, m := range q.Messages {
if string(m["role"]) != `"assistant"` {
continue
}
var calls []json.RawMessage
if json.Unmarshal(m["tool_calls"], &calls) == nil && len(calls) > 0 {
continue
}
var s string
var parts []struct {
Text string `json:"text"`
}
empty := m["content"] == nil || string(m["content"]) == "null"
if json.Unmarshal(m["content"], &s) == nil {
empty = strings.TrimSpace(s) == ""
} else if json.Unmarshal(m["content"], &parts) == nil {
empty = true
for _, p := range parts {
empty = empty && strings.TrimSpace(p.Text) == ""
}
}
if empty {
return 400, `{"error":{"message":"Invalid assistant message: content or tool_calls must be set","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`
}
}
return deepseekRefuseToolTurns(body)
}
const emptyOKStream = `data: {"id":"c1","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"Yes."},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}` + "\n\ndata: [DONE]\n\n"
// dsUpstream is a DeepSeek-strict Chat upstream behind provider "ds".
func dsUpstream(t *testing.T) *fake {
f := &fake{t: t, reply: emptyOKStream, refuse: dsRefuseEmptyAssistant}
up := setup(t, provider.Chat, f)
chatProvider(t, up.URL, provider.Provider{ID: "ds", Models: []string{"deepseek-v4.1-flash", "glm-5.2"}})
return f
}
// sentRoles is the roles of the messages an upstream was sent, with the
// last one's content.
func sentRoles(t *testing.T, got []byte) (string, string) {
t.Helper()
var roles []string
var last string
for _, raw := range sentMessages(t, got) {
var m struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
json.Unmarshal(raw, &m)
roles = append(roles, m.Role)
last = string(m.Content)
}
return strings.Join(roles, " "), last
}
// A reply Claude Code's user cut off before it said anything — only its
// thinking, only an empty text, nothing at all — stays in its history and
// is sent again with every later turn. Translated to a Chat upstream it
// went out as an assistant message with "content": "", and DeepSeek and
// Kimi turned every request of the conversation away. It is left out, and
// the two user messages around it join into one. After a tool result the
// user's message follows the tool message, as when they write there.
func TestChatEmptyAssistantLeftOutFromAnthropic(t *testing.T) {
f := dsUpstream(t)
for name, turn := range map[string]string{
"thinking": `[{"type":"thinking","thinking":"mid-thought","signature":"sig"}]`,
"redacted": `[{"type":"redacted_thinking","data":"gAAAAABpZm9vYmFy"}]`,
"empty text": `[{"type":"text","text":""}]`,
"thinking + text": `[{"type":"thinking","thinking":"mid-thought","signature":"sig"},{"type":"text","text":""}]`,
"no blocks": `[]`,
"empty string": `""`,
} {
t.Run(name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/messages", `{"model":"ds/deepseek-v4.1-flash","max_tokens":32,"messages":[
{"role":"user","content":"hi"},
{"role":"assistant","content":`+turn+`},
{"role":"user","content":"continue"}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
})
}
t.Run("after a tool result", func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/messages", `{"model":"ds/deepseek-v4.1-flash","max_tokens":32,
"tools":[{"name":"get_time","input_schema":{"type":"object","properties":{}}}],"messages":[
{"role":"user","content":"what time is it?"},
{"role":"assistant","content":[{"type":"thinking","thinking":"Ask the clock.","signature":"sig"},{"type":"tool_use","id":"toolu_1","name":"get_time","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"12:00"}]},
{"role":"assistant","content":[{"type":"thinking","thinking":"It is noon, so","signature":"sig"}]},
{"role":"user","content":"continue"}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user assistant tool user" || last != `"continue"` {
t.Fatalf("sent %s", f.got)
}
})
}
// The same from Codex: a cut-off reply is an isolated reasoning item, or
// an assistant message with an empty output_text.
func TestChatEmptyAssistantLeftOutFromResponses(t *testing.T) {
f := dsUpstream(t)
for name, turn := range map[string]string{
"reasoning": `{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"mid-thought"}]}`,
"empty text": `{"type":"message","role":"assistant","content":[{"type":"output_text","text":""}]}`,
"no contents": `{"type":"message","role":"assistant","content":[]}`,
} {
t.Run(name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, New(), "/v1/responses", `{"model":"ds/deepseek-v4.1-flash","stream":false,"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]},
`+turn+`,
{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
})
}
}
// And from Gemini CLI: a model turn with only its thought.
func TestChatEmptyAssistantLeftOutFromGemini(t *testing.T) {
f := dsUpstream(t)
code, body := postTo(t, New(), "/v1beta/models/ds/deepseek-v4.1-flash:streamGenerateContent?alt=sse", `{"contents":[
{"role":"user","parts":[{"text":"hi"}]},
{"role":"model","parts":[{"text":"mid-thought","thought":true}]},
{"role":"user","parts":[{"text":"continue"}]}]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != "user" || last != `"hi\n\ncontinue"` {
t.Fatalf("sent %s", f.got)
}
}
// A Chat agent (OpenCode, Kimi Code) keeps the turn it cut off as it
// came, {"role":"assistant","content":""} or null with reasoning_content
// alone, and its request is relayed as it sent it: the turn is left out
// there too, whichever model, and the user messages around it join.
func TestChatRelayLeavesOutEmptyAssistant(t *testing.T) {
f := dsUpstream(t)
srv := New()
for _, c := range []struct{ name, model, turns, shape, last string }{
{"empty", "ds/deepseek-v4.1-flash", `{"role":"user","content":"hi"},{"role":"assistant","content":"","reasoning_content":"halfway"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"null", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant","content":null,"reasoning_content":"halfway"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"no content", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant"},{"role":"user","content":"continue"}`,
"user", `"hi\n\ncontinue"`},
{"blank parts", "ds/glm-5.2", `{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"text","text":""}]},{"role":"user","content":[{"type":"text","text":"continue"}]}`,
"user", `[{"text":"hi","type":"text"},{"text":"continue","type":"text"}]`},
{"after a tool result", "ds/deepseek-v4.1-flash", `{"role":"user","content":"what time is it?"},
{"role":"assistant","content":null,"reasoning_content":"Ask.","tool_calls":[` + timeCall + `]},
{"role":"tool","tool_call_id":"call_1","content":"12:00"},
{"role":"assistant","content":"","reasoning_content":"It is noon, so"},
{"role":"user","content":"continue"}`,
"user assistant tool user", `"continue"`},
} {
t.Run(c.name, func(t *testing.T) {
f.calls = 0
code, body := postTo(t, srv, "/v1/chat/completions", `{"model":"`+c.model+`","stream":true,"messages":[`+c.turns+`]}`)
if code != 200 || f.calls != 1 {
t.Fatalf("%d after %d calls, sent %s: %s", code, f.calls, f.got, body)
}
if shape, last := sentRoles(t, f.got); shape != c.shape || last != c.last {
t.Fatalf("sent %s", f.got)
}
})
}
}
// What says something stays as the client sent it: a body without a
// silent turn byte for byte, and in one with, a legacy function_call, a
// prefill to go on from, a refusal, and a turn of text.
func TestChatRelaySilentAssistantsOnly(t *testing.T) {
clean := []byte(`{"model":"m","messages":[{"role":"user","content":"a <b> & c"},{"role":"assistant","content":"x","n":1.50},{"role":"user","content":"go"}]}`)
if got := silentAssistantsOut(clean); !bytes.Equal(got, clean) {
t.Fatalf("a clean body was rewritten: %s", got)
}
body := []byte(`{"model":"m","temperature":0.70,"messages":[
{"role":"user","content":"a <b> & c"},
{"role":"assistant","content":null,"function_call":{"name":"f","arguments":"{}"}},
{"role":"function","name":"f","content":"1"},
{"role":"assistant","content":"","refusal":"I can't."},
{"role":"user","content":"then"},
{"role":"assistant","content":"","reasoning_content":"cut"},
{"role":"user","content":"go"},
{"role":"assistant","content":"","prefix":true}]}`)
got := silentAssistantsOut(body)
var q struct {
Temperature json.RawMessage `json:"temperature"`
Messages []json.RawMessage `json:"messages"`
}
if err := json.Unmarshal(got, &q); err != nil {
t.Fatal(err)
}
if string(q.Temperature) != "0.70" || !bytes.Contains(got, []byte(`"a <b> & c"`)) {
t.Errorf("the rest of the body changed: %s", got)
}
want := []string{
`{"role":"user","content":"a <b> & c"}`,
`{"role":"assistant","content":null,"function_call":{"name":"f","arguments":"{}"}}`,
`{"role":"function","name":"f","content":"1"}`,
`{"role":"assistant","content":"","refusal":"I can't."}`,
`{"role":"user","content":"then\n\ngo"}`,
`{"role":"assistant","content":"","prefix":true}`,
}
if len(q.Messages) != len(want) {
t.Fatalf("sent %s", got)
}
for i, w := range want {
sameJSON(t, q.Messages[i], w)
}
}
// A Resume's prefill, magpie's own ask to go on from a reply cut short,
// stays however little of the reply there was: without it the upstream
// would answer from the start instead of going on.
func TestChatResumeEmptyPrefillKept(t *testing.T) {
r := &Request{Resume: true, Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "go on"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "half"}}},
}}
var q struct {
Messages []map[string]any `json:"messages"`
}
if err := json.Unmarshal(buildChat(r, "deepseek-chat", "api.deepseek.com", false), &q); err != nil {
t.Fatal(err)
}
last := q.Messages[len(q.Messages)-1]
if last["role"] != "assistant" || last["prefix"] != true || last["reasoning_content"] != "half" {
t.Fatalf("prefill = %v, want it kept with its prefix and reasoning", last)
}
}
+11 -6
View File
@@ -272,20 +272,25 @@ func TestChatThinkingOnlyAssistantDroppedInsideExchange(t *testing.T) {
}
}
// Outside an exchange a thinking-only turn passes through, as on main:
// dropping it would leave two user messages in a row, which some models'
// chat templates refuse.
func TestChatThinkingOnlyAssistantKeptOutsideExchange(t *testing.T) {
// Outside an exchange a thinking-only turn, one the user cut off before
// it said anything, is left out too: DeepSeek and Kimi turn the request
// away over an assistant message with neither content nor tool_calls
// (#2599). The two user messages it stood between join into one, as some
// models' chat templates turn away two in a row.
func TestChatThinkingOnlyAssistantLeftOutOutsideExchange(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "hmm", Signature: "sig"}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "继续"}}},
}}
trace, _ := chatTrace(t, r)
want := "user assistant user"
trace, msgs := chatTrace(t, r)
want := "user"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if c, _ := msgs[0]["content"].(string); c != "hi\n\n继续" {
t.Fatalf("joined content = %q", c)
}
}
// The shape a real Claude Code session replays to (97 clean exchanges in
+31
View File
@@ -424,6 +424,37 @@ func withReasoningOnToolTurns(body []byte) []byte {
})
}
// silentAssistantsOut is withoutSilentAssistants for a Chat request
// relayed as the client sent it (#2599): an agent that speaks Chat keeps
// the turn it cut off as {"role":"assistant","content":""} (or null, with
// reasoning_content alone) and sends it again on every later turn. A body
// without such a turn comes back byte for byte.
func silentAssistantsOut(body []byte) []byte {
if !bytes.Contains(body, []byte(`"assistant"`)) {
return body
}
var q map[string]json.RawMessage
if decodeJSON(body, &q) != nil {
return body
}
dec := json.NewDecoder(bytes.NewReader(q["messages"]))
dec.UseNumber()
var msgs []map[string]any
if dec.Decode(&msgs) != nil {
return body
}
msgs, changed := withoutSilentAssistants(msgs)
if !changed {
return body
}
q["messages"], _ = marshalPlain(msgs)
nb, err := marshalPlain(q)
if err != nil {
return body
}
return nb
}
// reasoningDetailsAsContent leaves reasoning_details out of every message
// of a Chat request, its thinking kept in reasoning_content when the
// message has none: Kimi's API turns reasoning_details away in whatever
+3
View File
@@ -4026,6 +4026,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
}
case provider.Chat:
body = developerAsSystem(body)
// a turn the client cut off before it said anything, which
// DeepSeek and Kimi turn every later request away for (#2599)
body = silentAssistantsOut(body)
if mistral := p.Preset == "mistral" || p.Host() == "api.mistral.ai"; !mistral && (chatReplaysReasoning(buildHost(p), model) || chatReplaysReasoning(buildHost(p), upstream)) {
// a tool call the client kept no thinking for, which DeepSeek
// turns the whole request away for (#1462)