diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index bded4d738..b9c97bd1b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -122,6 +122,7 @@ recorded as a prediction failure (`noPrediction`). - 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. - 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). Kimi is never sent them (`forwardOnce`, `isKimi`); 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; the tools stay in the request's `tools`, 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`). +- 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 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`). - A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte. - A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. - A Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)). diff --git a/internal/gateway/anthropic_shapes.go b/internal/gateway/anthropic_shapes.go index 90ce471be..743284349 100644 --- a/internal/gateway/anthropic_shapes.go +++ b/internal/gateway/anthropic_shapes.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "regexp" + "strings" "github.com/tidwall/gjson" @@ -49,6 +50,15 @@ import ( // "messages[1].content: unknown variant `tool_removal`". A provider that // refuses one is sent none of them (withoutDeferredTools); Kimi, whose 400 // names nothing, is never sent them (forwardOnce, #2042). +// +// 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), while it takes the same result with a text block +// beside the references. A provider that refuses one is sent each such +// result with a text block first, saying which tools are loaded, in the +// words a translated route tells a model (stringOrText); the references and +// the tool_use/tool_result pairing stay. // The refusals, remembered in unfit under the provider's id as betas are. const ( @@ -58,6 +68,7 @@ const ( shapeTurnSystem = "shape:messages[].role=system" shapeSafeguards = "shape:safeguards" shapeDeferred = "shape:messages[].content[].tool_addition" + shapeRefsOnly = "shape:tool_result.content=tool_reference" ) var ( @@ -67,6 +78,7 @@ var ( turnRoleRefused = regexp.MustCompile(`messages\.(\d+)\.role\b`) safeguardsRefused = regexp.MustCompile(`\bsafeguards:? Extra inputs are not permitted`) deferredRefused = regexp.MustCompile("messages\\[\\d+\\]\\.content: unknown variant `(?:tool_addition|tool_removal|tool_definition|tool_reference)`") + refsOnlyRefused = regexp.MustCompile("missing field `content`") ) // knownDisplay is a thinking.display every Anthropic endpoint has taken. @@ -99,6 +111,9 @@ func (s *Server) refuseShapes(p provider.Provider, errBody, body []byte) bool { if deferredRefused.Match(errBody) && hasDeferredTools(body) { mark(shapeDeferred) } + if refsOnlyRefused.Match(errBody) && hasRefsOnlyResult(body) { + mark(shapeRefsOnly) + } // a role refused at a message that is a system one, counted in the // messages as they were sent; a refusal naming a user or assistant // message is over something else @@ -117,6 +132,9 @@ func (s *Server) withoutRefusedShapes(p provider.Provider, body []byte) []byte { if !s.fits(p.ID, shapeDeferred, provider.Anthropic) { body = withoutDeferredTools(body) } + if !s.fits(p.ID, shapeRefsOnly, provider.Anthropic) { + body = withRefsSaid(body) + } if !s.fits(p.ID, shapeTurnSystem, provider.Anthropic) { body = withSystemOnTop(body) } @@ -366,3 +384,114 @@ func withoutDeferredTools(body []byte) []byte { } return withFields(body, map[string]any{"messages": out}) } + +// toolLoadedText is what a model is told of a tool ToolSearch loaded, where +// the tool_reference that names it can't go as it is. +func toolLoadedText(name string) string { + return "Tool " + name + " is loaded and can be called now." +} + +// refsOnly is a tool_result's content that is tool_reference blocks and +// nothing else, as ToolSearch answers. +func refsOnly(c gjson.Result) bool { + if !c.IsArray() || len(c.Array()) == 0 { + return false + } + only := true + c.ForEach(func(_, b gjson.Result) bool { + only = b.Get("type").String() == "tool_reference" + return only + }) + return only +} + +// hasRefsOnlyResult is a request with a tool_result holding only +// tool_reference blocks. +func hasRefsOnlyResult(body []byte) bool { + if !bytes.Contains(body, []byte(`"tool_reference"`)) { + return false + } + found := false + gjson.GetBytes(body, "messages").ForEach(func(_, m gjson.Result) bool { + m.Get("content").ForEach(func(_, b gjson.Result) bool { + found = b.Get("type").String() == "tool_result" && refsOnly(b.Get("content")) + return !found + }) + return !found + }) + return found +} + +// withRefsSaid is body with a text block first in each tool_result that +// holds only tool_reference blocks, naming the tools they load; the +// references stay after it. A body with none is sent as it was. +func withRefsSaid(body []byte) []byte { + if !hasRefsOnlyResult(body) { + return body + } + var v struct { + Messages []json.RawMessage `json:"messages"` + } + if json.Unmarshal(body, &v) != nil { + return body + } + out := make([]json.RawMessage, 0, len(v.Messages)) + for _, raw := range v.Messages { + c := gjson.GetBytes(raw, "content") + if !c.IsArray() { + out = append(out, raw) + continue + } + changed := false + blocks := make([]json.RawMessage, 0, len(c.Array())) + for _, b := range c.Array() { + rc := b.Get("content") + if b.Get("type").String() != "tool_result" || !refsOnly(rc) { + blocks = append(blocks, json.RawMessage(b.Raw)) + continue + } + var said []string + for _, r := range rc.Array() { + said = append(said, toolLoadedText(r.Get("tool_name").String())) + } + content := []any{map[string]any{"type": "text", "text": strings.Join(said, "\n")}} + for _, r := range rc.Array() { + content = append(content, json.RawMessage(r.Raw)) + } + var m map[string]json.RawMessage + if json.Unmarshal([]byte(b.Raw), &m) != nil { + return body + } + cb, err := marshalPlain(content) + if err != nil { + return body + } + m["content"] = cb + nb, err := marshalPlain(m) + if err != nil { + return body + } + blocks = append(blocks, nb) + changed = true + } + if !changed { + out = append(out, raw) + continue + } + var m map[string]json.RawMessage + if json.Unmarshal(raw, &m) != nil { + return body + } + cb, err := marshalPlain(blocks) + if err != nil { + return body + } + m["content"] = cb + nb, err := marshalPlain(m) + if err != nil { + return body + } + out = append(out, nb) + } + return withFields(body, map[string]any{"messages": out}) +} diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 86fca8ca2..aa11456ee 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -627,7 +627,7 @@ func stringOrText(raw json.RawMessage) string { if b.Len() > 0 { b.WriteString("\n") } - b.WriteString("Tool " + x.ToolName + " is loaded and can be called now.") + b.WriteString(toolLoadedText(x.ToolName)) } } return b.String() diff --git a/internal/gateway/tool_reference_result_test.go b/internal/gateway/tool_reference_result_test.go new file mode 100644 index 000000000..8e3fddcc0 --- /dev/null +++ b/internal/gateway/tool_reference_result_test.go @@ -0,0 +1,236 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// openDesignVendor answers as OpenDesign's Anthropic endpoint answered +// #2124's reporter: a tool_result whose content is tool_reference blocks +// alone is a 422 "missing field `content`" (its index counting something +// other than the messages sent), and the same result with a text block +// beside the references is taken. takes is a vendor that reads either. +type openDesignVendor struct { + takes bool + mu sync.Mutex + paths []string + bodies []string +} + +func (v *openDesignVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + v.mu.Lock() + v.paths = append(v.paths, r.URL.Path) + v.bodies = append(v.bodies, string(b)) + v.mu.Unlock() + var m struct { + Messages []struct { + Content json.RawMessage `json:"content"` + } `json:"messages"` + } + json.Unmarshal(b, &m) + refused := false + for _, msg := range m.Messages { + var blocks []struct { + Type string `json:"type"` + Content []struct { + Type string `json:"type"` + } `json:"content"` + } + json.Unmarshal(msg.Content, &blocks) + for _, bl := range blocks { + if bl.Type != "tool_result" || len(bl.Content) == 0 { + continue + } + text := false + for _, c := range bl.Content { + text = text || c.Type == "text" + } + refused = refused || !text && !v.takes + } + } + w.Header().Set("Content-Type", "application/json") + switch { + case refused: + w.WriteHeader(422) + io.WriteString(w, "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content` at line 38 column 3") + case strings.HasSuffix(r.URL.Path, "/count_tokens"): + io.WriteString(w, `{"input_tokens":12}`) + default: + io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"deepseek-v4.1-flash","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`) + } +} + +func (v *openDesignVendor) sent() []string { + v.mu.Lock() + defer v.mu.Unlock() + return append([]string(nil), v.bodies...) +} + +// #2124's repro.json, as the reporter posted it, with magpie's model. +func reporterRefsOnly(model string) string { + return `{ + "model": "` + model + `", + "max_tokens": 64, + "thinking": {"type": "disabled"}, + "system": "This is a synthetic format test. Reply OK. Do not call any tool.", + "tools": [ + { + "name": "ToolSearch", + "description": "Find a test tool.", + "input_schema": { + "type": "object", + "properties": {"query": {"type": "string"}}, + "required": ["query"] + } + }, + { + "name": "check", + "description": "Return a fixed synthetic result.", + "input_schema": {"type": "object", "properties": {}} + } + ], + "messages": [ + {"role": "user", "content": "Reply with OK only."}, + { + "role": "assistant", + "content": [ + {"type": "text", "text": "I will find the check tool."}, + { + "type": "tool_use", + "id": "toolu_direct_probe", + "name": "ToolSearch", + "input": {"query": "check"} + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "toolu_direct_probe", + "content": [{"type": "tool_reference", "tool_name": "check"}] + } + ] + } + ] +}` +} + +// #2124 (liuyejinghong): OpenDesign, added as a custom Anthropic provider, +// refused every turn after ToolSearch answered with tool_reference blocks +// alone. It is asked again at once with a text block naming the loaded +// tools before the references, and from then on sent them that way, on +// /v1/messages, count_tokens and through a group. The references and the +// tool_use pairing stay. A provider that takes the bare references is sent +// them as Claude Code wrote them. +func TestRefsOnlyToolResultRefusedGetsText(t *testing.T) { + fresh(t) + od := &openDesignVendor{} + odSrv := httptest.NewServer(od) + t.Cleanup(odSrv.Close) + takes := &openDesignVendor{takes: true} + tkSrv := httptest.NewServer(takes) + t.Cleanup(tkSrv.Close) + if err := provider.Save(provider.Provider{ID: "opendesign", Name: "OpenDesign", Key: "k", Anthropic: odSrv.URL, + Models: []string{"deepseek-v4.1-flash"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Key: "k", Anthropic: tkSrv.URL, + Models: []string{"deepseek-v4.1-flash"}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"opendesign/deepseek-v4.1-flash"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + h := New().Handler() + post := func(path, body string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%s: status %d: %s", path, rec.Code, rec.Body) + } + } + said := func(t *testing.T, got string) { + t.Helper() + var m struct { + Messages []struct { + Content json.RawMessage `json:"content"` + } `json:"messages"` + } + if err := json.Unmarshal([]byte(got), &m); err != nil || len(m.Messages) != 3 { + t.Fatalf("sent %d messages (%v): %s", len(m.Messages), err, got) + } + var res []struct { + Type string `json:"type"` + ToolUseID string `json:"tool_use_id"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + ToolName string `json:"tool_name"` + } `json:"content"` + } + json.Unmarshal(m.Messages[2].Content, &res) + if len(res) != 1 || res[0].Type != "tool_result" || res[0].ToolUseID != "toolu_direct_probe" || len(res[0].Content) != 2 || + res[0].Content[0].Type != "text" || res[0].Content[0].Text != "Tool check is loaded and can be called now." || + res[0].Content[1].Type != "tool_reference" || res[0].Content[1].ToolName != "check" { + t.Fatalf("the ToolSearch answer went as %s", m.Messages[2].Content) + } + if !strings.Contains(string(m.Messages[1].Content), `"id": "toolu_direct_probe"`) && !strings.Contains(string(m.Messages[1].Content), `"id":"toolu_direct_probe"`) { + t.Fatalf("the tool_use was changed: %s", m.Messages[1].Content) + } + } + + post("/v1/messages", reporterRefsOnly("opendesign/deepseek-v4.1-flash:max")) + sent := od.sent() + if len(sent) != 2 || strings.Contains(sent[0], "is loaded and can be called") { + t.Fatalf("OpenDesign was asked %d times, want the bare references once and then with text: %q", len(sent), sent) + } + said(t, sent[1]) + + // learned: the group's member, and counting tokens, go with the text + // from the start + post("/v1/messages", reporterRefsOnly("group/g")) + post("/v1/messages/count_tokens", reporterRefsOnly("opendesign/deepseek-v4.1-flash")) + sent = od.sent() + if len(sent) != 4 { + t.Fatalf("after the refusal OpenDesign was asked %d times, want 4: %q", len(sent), sent) + } + said(t, sent[2]) + said(t, sent[3]) + + // a provider that reads the bare references keeps getting them + post("/v1/messages", reporterRefsOnly("other/deepseek-v4.1-flash")) + if got := takes.sent(); len(got) != 1 || strings.Contains(got[0], "is loaded and can be called") || !strings.Contains(got[0], `"tool_name": "check"`) && !strings.Contains(got[0], `"tool_name":"check"`) { + t.Fatalf("a provider that takes the references was sent %q", got) + } +} + +// A tool_result that already has text beside its references, or no +// references, is sent as it was, and so is a body without any. +func TestRefsSaidLeavesOtherResults(t *testing.T) { + for _, body := range []string{ + `{"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":[{"type":"text","text":"x"},{"type":"tool_reference","tool_name":"check"}]}]}]}`, + `{"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":"done"}]}]}`, + `{"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":[]}]}]}`, + `{"messages":[{"role":"user","content":"hi"}]}`, + } { + if got := string(withRefsSaid([]byte(body))); got != body { + t.Errorf("%s\nwent as %s", body, got) + } + } + two := `{"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"a","content":[{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebSearch"}]}]}]}` + if got := string(withRefsSaid([]byte(two))); !strings.Contains(got, `"text":"Tool WebFetch is loaded and can be called now.\nTool WebSearch is loaded and can be called now."`) || + !strings.Contains(got, `{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebSearch"}`) { + t.Errorf("two references went as %s", got) + } +}