gateway: a system message between a call and its result goes after the result (wizcheu on X)

Claude Code puts {role: "system"} messages into messages[]: a turn's
effort (output_config), a steer the user sent while a tool ran, a
deferred tool's tool_addition. One can stand between an assistant's
tool_use and the user message holding its tool_result. DeepSeek counts
it as the next message and refuses the request, 400 "messages.N:
`tool_use` ids were found without `tool_result` blocks immediately
after", and every later request of the conversation carries the same
history (Claude Code: "400 due to tool use concurrency issues").

The relay's mend made it worse. pairedMessages (toolBlocksPaired) read
the system message as the turn after the call: it gave the call a
synthetic result inside the system message, and the real result in the
user message after it became text. A system message can't hold a
tool_result, and withSystemOnTop or withoutTurnEffort then dropped it,
so the call stayed unanswered. pairToolMessages (Chat relays and
builds) did the same: synthetic tool results, then the real ones as
user text.

Now a system or developer message that stands between a call and its
results is held and goes after the results (after the synthetic ones
when none came). The real result stays a result. A body that already
pairs comes back byte for byte. The translated routes were already
safe: responseInstructions turns a mid-conversation system message into
user text, and mergeTurns joins it with the results' message.

Checked against api.deepseek.com/anthropic with a real key on
2026-11-18: a system message (text, empty effort, or string) between
the call and its result gives 400. Magpie's old output gives 400 too.
The same system message after the result gives 200.

Tests: TestSystemMessageBetweenCallAndResult sends the reporter's turn
(thinking, text, tool_use call_00_jdrDF4PKrnFwMUMBRQlr4516) with each
of five system-message shapes between the call and its result. It goes
through /v1/messages to a fake DeepSeek that enforces the same rule.
TestSystemMessageFollowsTheResults covers pairedMessages directly,
including byte for byte when already paired.
TestChatSystemMessageBetweenCallAndResult covers pairToolMessages and
toolPairsOut. All three fail on the old code (all 11 subtests red at
534b85bf9) and pass with the fix.

Run on mote:
- go test ./... -timeout 45m at 1d7f0b3a2 (this change on 534b85bf9):
  103 ok, no FAIL.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok.
- gofmt -l: clean.
- After rebasing onto bfddc9cfb (which touched internal/gateway),
  go test ./internal/gateway again: ok (964s) at 516f40c43.

Not changed: pairToolItems (Responses). DeepSeek serves no Responses
API.
This commit is contained in:
yetone
2026-11-18 18:40:49 +08:00
parent 8634c4ad08
commit d747549700
3 changed files with 272 additions and 1 deletions
+19 -1
View File
@@ -736,13 +736,20 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
// 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).
// (withoutSilentAssistants, #2599);
// - a system or developer message between the calls and their tool
// messages goes after them: DeepSeek takes it for the message after
// the calls and refuses the request ("tool_use ids were found
// without tool_result blocks immediately after"), and read as the
// turn after them it gave the calls synthetic results and the real
// ones went as user text.
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
order := map[string]int{} // a pending call's place among them
answered := map[string]bool{} // pending calls a tool message answered
var tools []map[string]any // answers to pending, held for sorting
var held []map[string]any // system messages after pending's calls
flushTools := func() {
if len(tools) == 0 {
@@ -763,6 +770,8 @@ func pairToolMessages(msgs []map[string]any) []map[string]any {
}
}
pending, order, answered = nil, map[string]int{}, map[string]bool{}
out = append(out, held...)
held = nil
}
// toolAsUser turns a tool message that answers no pending call into a
// user message carrying its result. A user message just emitted takes
@@ -818,6 +827,15 @@ func pairToolMessages(msgs []map[string]any) []map[string]any {
}
answered[id] = true
tools = append(tools, m)
case "system", "developer":
if len(pending) > 0 {
// between the calls and their tool messages, which must
// follow them at once (DeepSeek, Kimi): it goes after
// them, and the results it stood before stay results
held = append(held, m)
continue
}
out = append(out, m)
default:
flushPending()
out = append(out, m)
+26
View File
@@ -29,6 +29,17 @@ import (
// members and blocks as they came, with a missing call's synthetic error
// result first, an answer to no call as the text it said, and a second
// answer to one call left out.
//
// A message of another role between a call and its results (Claude Code's
// {role: "system"} messages: a turn's effort, a steer the user sent while
// a tool ran, a deferred tool's tool_addition) goes after the results.
// It answers nothing: read as the turn after the call, it took the
// call's synthetic result (which a system message can't hold, and which
// withSystemOnTop and withoutTurnEffort then dropped) while the real
// result after it turned into text, and DeepSeek, which counts it as the
// next message, refused the request either way, 400 "messages.N:
// `tool_use` ids were found without `tool_result` blocks immediately
// after" (wizcheu on X, deepseek-flash through Claude Code).
func toolBlocksPaired(body []byte) []byte {
if !bodyHas(body, `"tool_use"`) && !bodyHas(body, `"tool_result"`) {
return body
@@ -51,6 +62,11 @@ func pairedMessages(msgs []byte) ([]byte, bool) {
changed := false
var pending []string // the calls of the assistant message in hand
answered := map[string]bool{} // which of them a result answered
var held []json.RawMessage // other roles' messages after those calls
release := func() {
out = append(out, held...)
held = nil
}
open := func(id string) bool {
for _, p := range pending {
if p == id {
@@ -87,11 +103,18 @@ func pairedMessages(msgs []byte) ([]byte, bool) {
}
return true
})
if (role == "system" || role == "developer") && len(pending) > 0 {
// between the calls and their results: it follows them
held = append(held, el)
changed = true
return true
}
if role == "assistant" {
if blocks := unanswered(); len(blocks) > 0 {
out = append(out, resultsMessage(blocks))
changed = true
}
release()
pending, answered = nil, map[string]bool{}
if len(content) > 0 && content[0] == '[' {
eachElement(content, func(b []byte) bool {
@@ -143,6 +166,7 @@ func pairedMessages(msgs []byte) ([]byte, bool) {
pending, answered = nil, map[string]bool{}
if !touched {
out = append(out, el)
release()
return true
}
changed = true
@@ -158,6 +182,7 @@ func pairedMessages(msgs []byte) ([]byte, bool) {
} else {
out = append(out, withTopValue(el, "content", list))
}
release()
return true
})
if !valid {
@@ -167,6 +192,7 @@ func pairedMessages(msgs []byte) ([]byte, bool) {
out = append(out, resultsMessage(blocks))
changed = true
}
release()
if !changed {
return nil, false
}
+227
View File
@@ -0,0 +1,227 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The reporter's turn (wizcheu on X, deepseek-flash at max effort through
// Claude Code): a reply of thinking, text and a call, the call's block
// the third (messages.N.2), DeepSeek's own call id.
const (
steerCallID = "call_00_jdrDF4PKrnFwMUMBRQlr4516"
steerAsst = `{"role":"assistant","content":[{"type":"thinking","thinking":"I will list the files.","signature":""},{"type":"text","text":"Let me look."},{"type":"tool_use","id":"` + steerCallID + `","name":"Bash","input":{"command":"ls"}}]}`
steerResult = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + steerCallID + `","content":"a.go"}]}`
)
// steerBetween is each {role: "system"} message Claude Code puts in the
// conversation, as it stood between a call and its result.
var steerBetween = map[string]string{
"a steer": `{"role":"system","content":[{"type":"text","text":"The user sent a new message while you were working:\nhi"}]}`,
"a turn's effort": `{"role":"system","content":[],"output_config":{"effort":"max"}}`,
"an effort with no content": `{"role":"system","output_config":{"effort":"max"}}`,
"a deferred tool": `{"role":"system","content":[{"type":"tool_addition","tool":{"type":"tool_reference","name":"Read"}}]}`,
"words": `{"role":"system","content":"note"}`,
}
// deepseekPairing is what api.deepseek.com/anthropic holds a request to,
// checked against it on 2026-11-18 (a system message between a call and
// its result: 400; after the result: 200): the message right after a
// tool_use's is a user message whose results answer every call, and a
// system message holds no tool_result. "" when the request passes.
func deepseekPairing(body []byte) string {
var q struct {
Messages []struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
} `json:"messages"`
}
if json.Unmarshal(body, &q) != nil {
return "bad body"
}
blocks := func(c json.RawMessage) []map[string]any {
var bs []map[string]any
_ = json.Unmarshal(c, &bs)
return bs
}
for i, m := range q.Messages {
if m.Role == "system" {
for _, b := range blocks(m.Content) {
if b["type"] == "tool_result" {
return fmt.Sprintf("messages.%d: a system message holds text only", i)
}
}
}
if m.Role != "assistant" {
continue
}
var ids []string
for j, b := range blocks(m.Content) {
if b["type"] == "tool_use" {
ids = append(ids, fmt.Sprintf("%d:%v", j, b["id"]))
}
}
if len(ids) == 0 {
continue
}
answered := map[string]bool{}
if i+1 < len(q.Messages) && q.Messages[i+1].Role == "user" {
for _, b := range blocks(q.Messages[i+1].Content) {
if b["type"] == "tool_result" {
answered[fmt.Sprint(b["tool_use_id"])] = true
}
}
}
for _, id := range ids {
n, call, _ := strings.Cut(id, ":")
if !answered[call] {
return fmt.Sprintf("messages.%d.%s: `tool_use` ids were found without `tool_result` blocks immediately after: %s", i, n, call)
}
}
}
return ""
}
// strictDeepSeek is a DeepSeek Anthropic endpoint refusing as deepseekPairing
// does; it keeps each body it was sent.
func strictDeepSeek(t *testing.T) (*httptest.Server, func() []string) {
t.Helper()
var mu sync.Mutex
var got []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
got = append(got, string(b))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if why := deepseekPairing(b); why != "" {
w.WriteHeader(400)
msg, _ := json.Marshal(why)
fmt.Fprintf(w, `{"type":"error","error":{"type":"invalid_request_error","message":%s}}`, msg)
return
}
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"deepseek-flash","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}))
t.Cleanup(srv.Close)
return srv, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), got...)
}
}
// A Claude Code request whose {role: "system"} message stands between a
// call and its result reaches DeepSeek with the message after the result,
// the call answered by its real result, never a made-up one: magpie read
// the system message as the turn after the call, gave the call a
// synthetic result there and the real one as text, and DeepSeek refused
// every later request of the conversation, "400 due to tool use
// concurrency issues" (wizcheu on X).
func TestSystemMessageBetweenCallAndResult(t *testing.T) {
for name, between := range steerBetween {
t.Run(name, func(t *testing.T) {
fresh(t)
srv, sent := strictDeepSeek(t)
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Preset: "deepseek", Key: "k", Anthropic: srv.URL, Models: []string{"deepseek-flash"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"deepseek/deepseek-flash","max_tokens":32,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"messages":[{"role":"user","content":"list the files"},` +
steerAsst + `,` + between + `,` + steerResult + `,{"role":"user","content":"go on"}]}`
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
got := sent()
if len(got) != 1 {
t.Fatalf("sent %d requests, want 1", len(got))
}
if strings.Contains(got[0], interruptedTool) {
t.Fatalf("the call got a made-up result, though its own came:\n%s", got[0])
}
if !strings.Contains(got[0], `"tool_use_id":"`+steerCallID+`","content":"a.go"`) {
t.Fatalf("the call's own result is gone:\n%s", got[0])
}
})
}
}
// pairedMessages keeps the system message whole, after the results, and
// a body whose system message follows the results comes back as it was.
func TestSystemMessageFollowsTheResults(t *testing.T) {
for name, between := range steerBetween {
t.Run(name, func(t *testing.T) {
msgs := `[` + steerAsst + `,` + between + `,` + steerResult + `]`
got, changed := pairedMessages([]byte(msgs))
want := `[` + steerAsst + `,` + steerResult + `,` + between + `]`
if !changed || string(got) != want {
t.Fatalf("got %s\nwant %s", got, want)
}
after := `{"model":"m","messages":[` + steerAsst + `,` + steerResult + `,` + between + `]}`
if out := toolBlocksPaired([]byte(after)); string(out) != after {
t.Fatalf("a paired body changed:\n%s", out)
}
})
}
// no result came: the synthetic one goes in a user message of its
// own, the system message after it
msgs := `[` + steerAsst + `,` + steerBetween["a steer"] + `,{"role":"assistant","content":[{"type":"text","text":"done"}]}]`
got, _ := pairedMessages([]byte(msgs))
var out []map[string]any
if err := json.Unmarshal(got, &out); err != nil {
t.Fatal(err)
}
var roles []string
for _, m := range out {
roles = append(roles, fmt.Sprint(m["role"]))
}
if strings.Join(roles, ",") != "assistant,user,system,assistant" {
t.Fatalf("roles %v: %s", roles, got)
}
}
// A Chat request relayed to DeepSeek's Chat API with a system message
// between the calls and their tool messages: the system message goes
// after them, and the tool messages stay tool messages.
func TestChatSystemMessageBetweenCallAndResult(t *testing.T) {
msgs := []map[string]any{
{"role": "user", "content": "list the files"},
{"role": "assistant", "content": "", "tool_calls": []map[string]any{{"id": steerCallID, "type": "function", "function": map[string]any{"name": "Bash", "arguments": `{"command":"ls"}`}}}},
{"role": "system", "content": "The user sent a new message while you were working:\nhi"},
{"role": "tool", "tool_call_id": steerCallID, "content": "a.go"},
{"role": "user", "content": "go on"},
}
out := pairToolMessages(msgs)
var roles []string
for _, m := range out {
roles = append(roles, fmt.Sprint(m["role"]))
}
if strings.Join(roles, ",") != "user,assistant,tool,system,user" {
t.Fatalf("roles %v", roles)
}
if out[2]["content"] != "a.go" {
t.Fatalf("the call's own result is gone: %v", out[2])
}
body := `{"model":"deepseek-flash","messages":[{"role":"user","content":"list the files"},{"role":"assistant","content":"","tool_calls":[{"id":"` + steerCallID + `","type":"function","function":{"name":"Bash","arguments":"{}"}}]},{"role":"system","content":"note"},{"role":"tool","tool_call_id":"` + steerCallID + `","content":"a.go"}]}`
var q struct {
Messages []map[string]any `json:"messages"`
}
if err := json.Unmarshal(toolPairsOut([]byte(body)), &q); err != nil {
t.Fatal(err)
}
roles = nil
for _, m := range q.Messages {
roles = append(roles, fmt.Sprint(m["role"]))
}
if strings.Join(roles, ",") != "user,assistant,tool,system" || q.Messages[2]["content"] != "a.go" {
t.Fatalf("relayed %v", q.Messages)
}
}