gateway: a ToolSearch answer's definition goes to DeepSeek as the reference it takes (#5404)

Newer Claude Code builds put the loaded tool's definition itself in the
ToolSearch answer's tool_result.content[] ({"type":"tool_definition",
"definition":{...}}, the same block shape Claude Code's own bundle
handles beside tool_reference). DeepSeek's Anthropic endpoint refuses
it there: 422 "messages[1].content: unknown variant `tool_definition`,
expected `tool_reference`". withoutDeferredTools walked the messages'
top-level blocks only, so the nested definition survived every learned
retry, and a body with no top-level deferred block never learned the
refusal at all.

hasDeferredTools now sees a tool_definition in a tool_result's content,
and withoutDeferredTools hoists each such definition onto the request's
tools (once; one already listed wins) and sends the block as
{"type":"tool_reference","tool_name":...}, which the endpoint takes only
once the tool is declared. A result whose content isn't an array, or a
definition without a name, goes as it came. DeepSeek's own host
(isDeepSeekAnthropic, by host, not preset) now gets the deferred blocks
stripped up front like Kimi (#2042), since it takes a tool_addition at
no position (erlinerd's live check of 2026-11-05).

Review change on top of ggbdpq's patch: added
TestDeepSeekAnthropicIsStrippedUpFront, which drives a provider at
api.deepseek.com (dial redirected to httptest) through the server; the
patch had no test for the forwardOnce wiring.

Run (mote, -tags nogui, -count=1):
- TestToolResultDefinitionRefusedOnceBecomesReference,
  TestNestedToolResultDefinitionBecomesReference,
  TestDeepSeekAnthropicRecognized, TestDeepSeekAnthropicIsStrippedUpFront:
  PASS.
- -run 'Deferred|Kimi|DeepSeek|ToolSearch|ToolReference|RefsOnly|OpenCode|Shape'
  ./internal/gateway: ok 18.3s.
- gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet
  of ./internal/gateway: clean.

Broken by hand:
- anthropic_shapes.go at the parent: the refused-once test 422s to the
  client, the unit test fails "a nested tool_definition was not seen as
  a deferred tool", the up-front test 422s.
- gateway.go at the parent: TestDeepSeekAnthropicIsStrippedUpFront fails
  "DeepSeek was asked 2 times, want once".

Not tried: a live api.deepseek.com request (no DeepSeek key here); the
endpoint's answers are the reporter's live checks. Not run: the whole
gateway package or ./... suite.

#5404, erlinerd.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: erlinerd <10431861+erlinerd@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-06 09:55:19 +08:00
co-authored by ggbdpq erlinerd
parent d84f58fd2b
commit bfb0d92ca8
4 changed files with 326 additions and 14 deletions
+8
View File
@@ -815,6 +815,14 @@ var effortInOutputConfig = regexp.MustCompile(`(?i)glm-5\.[23](?:$|[-.:/\[])|min
// (api.deepseek.com/anthropic) takes the effort in output_config.
const deepseekHost = provider.DeepSeekHost
// isDeepSeekAnthropic is whether the request goes to DeepSeek's own
// Anthropic endpoint, whose shape is checked against the host, not the
// preset: a "deepseek" provider pointed at another host is that host's
// shape, and it learns from that endpoint's refusals as any other does.
func isDeepSeekAnthropic(p provider.Provider, to provider.Protocol) bool {
return provider.HostOf(p.Base(to)) == deepseekHost
}
// deepseekEfforts are the levels DeepSeek's models think at: its thinking
// guide maps minimal to low, medium and xhigh to high, and ultra to max.
// A budget a client sent is fitted to them when the model's own list is
+89 -12
View File
@@ -48,15 +48,23 @@ import (
// put blocks of their own in a message: {"type":"tool_addition","tool":
// {"type":"tool_reference","name":…}} (or a tool_definition) when a tool
// is loaded, a tool_removal when one goes, and a tool_reference. DeepSeek's
// Anthropic endpoint takes a tool_addition naming a tool, but not one
// defining it, nor a tool_removal or a message's tool_reference: 422
// "messages[1].content: unknown variant `tool_removal`". A provider that
// refuses one is sent none of them (withoutDeferredTools); Kimi, whose 400
// Anthropic endpoint took a tool_addition naming a tool once (10-14), but
// takes one at no position now: "`tool_addition` blocks can only be in
// `system` messages", and a system message's with "unknown variant
// `tool_addition`, expected `text`" (#5404, checked against
// api.deepseek.com on 2026-11-05), so its blocks come out before the
// first ask (isDeepSeekAnthropic). A provider that refuses one is sent
// none of them from then on (withoutDeferredTools); Kimi, whose 400
// names nothing, is never sent them (forwardOnce, #2042). OpenCode's
// DeepSeek route also names nothing: 422 "Endpoint is unavailable.".
//
// ToolSearch's answer is a tool_result whose content is tool_reference
// blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed
// blocks alone — or, in newer builds, the loaded tool's definition itself,
// which an endpoint that refuses the blocks refuses there too: DeepSeek's
// 422 "unknown variant `tool_definition`, expected `tool_reference`"
// (#5404). It goes as the reference, its definition on the request's tools
// list (withoutDeferredTools). OpenDesign's Anthropic endpoint can't read
// a references-only 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
@@ -318,16 +326,19 @@ func deferredBlock(typ string) bool {
}
// hasDeferredTools is a request with a deferred-tool block in a message's
// content. A tool_reference inside a tool_result (ToolSearch's answer) is
// not one.
// content, or with a tool_definition in a tool_result's — the ToolSearch
// answer of newer Claude Code builds, which an endpoint that refuses the
// blocks refuses there too (#5404). A tool_reference inside a tool_result
// (ToolSearch's older answer) is not one.
func hasDeferredTools(body []byte) bool {
if !bytes.Contains(body, []byte(`"tool_addition"`)) && !bytes.Contains(body, []byte(`"tool_removal"`)) && !bytes.Contains(body, []byte(`"tool_reference"`)) {
if !bytes.Contains(body, []byte(`"tool_addition"`)) && !bytes.Contains(body, []byte(`"tool_removal"`)) && !bytes.Contains(body, []byte(`"tool_reference"`)) && !bytes.Contains(body, []byte(`"tool_definition"`)) {
return false
}
found := false
getIn(body, "messages").ForEach(func(_, m gjson.Result) bool {
m.Get("content").ForEach(func(_, b gjson.Result) bool {
found = deferredBlock(b.Get("type").String())
found = deferredBlock(b.Get("type").String()) ||
b.Get("type").String() == "tool_result" && bytes.Contains([]byte(b.Get("content").Raw), []byte(`"tool_definition"`))
return !found
})
return !found
@@ -339,8 +350,10 @@ func hasDeferredTools(body []byte) bool {
// messages, and without a message they leave empty. Definitions carried
// only inline join the request's own tools list; a definition already on
// that list wins. A tool_result's tool_reference stays: it is
// the tool's answer, and Kimi and DeepSeek take it. A body with none is
// sent as it was.
// the tool's answer, and Kimi and DeepSeek take it. A tool_definition in
// a tool_result's content (a ToolSearch answer carrying the definition
// itself, #5404) joins the tools as its block goes as the reference a
// tool_result takes. A body with none is sent as it was.
func withoutDeferredTools(body []byte) []byte {
if !hasDeferredTools(body) {
return body
@@ -365,6 +378,7 @@ func withoutDeferredTools(body []byte) []byte {
continue
}
var kept []json.RawMessage
changed := false
for _, b := range c.Array() {
if b.Get("type").String() == "tool_addition" && b.Get("tool.type").String() == "tool_definition" {
def := b.Get("tool.definition")
@@ -373,11 +387,22 @@ func withoutDeferredTools(body []byte) []byte {
have[name.String()] = true
}
}
if b.Get("type").String() == "tool_result" && bytes.Contains([]byte(b.Get("content").Raw), []byte(`"tool_definition"`)) {
// a ToolSearch answer carrying the definition itself: the
// definition joins the tools and the block goes as the
// reference the result takes (#5404)
if fixed, added := resultDefinitionRef(b, have); fixed != nil {
tools = append(tools, added...)
kept = append(kept, fixed)
changed = true
continue
}
}
if !deferredBlock(b.Get("type").String()) {
kept = append(kept, json.RawMessage(b.Raw))
}
}
if len(kept) == len(c.Array()) {
if !changed && len(kept) == len(c.Array()) {
out = append(out, raw)
continue
}
@@ -406,6 +431,58 @@ func withoutDeferredTools(body []byte) []byte {
return withFields(body, fields)
}
// resultDefinitionRef is a tool_result whose content carries a
// tool_definition, the ToolSearch answer of newer Claude Code builds: each
// definition joins the request's tools (have dedupes by name) and the
// block goes back as the tool_reference a tool_result's content takes.
// DeepSeek's Anthropic endpoint refuses the definition there with
// "unknown variant `tool_definition`, expected `tool_reference`", and a
// reference only once the tool is on the tools list (#5404, a 2026-11-05
// check against api.deepseek.com). nil when the result can't be read, or
// a definition in it has no name: it goes as it came.
func resultDefinitionRef(b gjson.Result, have map[string]bool) (json.RawMessage, []json.RawMessage) {
var m map[string]json.RawMessage
if json.Unmarshal([]byte(b.Raw), &m) != nil {
return nil, nil
}
content := b.Get("content")
if !content.IsArray() {
return nil, nil
}
var added []json.RawMessage
items := make([]json.RawMessage, 0, len(content.Array()))
for _, item := range content.Array() {
if item.Get("type").String() != "tool_definition" {
items = append(items, json.RawMessage(item.Raw))
continue
}
def := item.Get("definition")
name := def.Get("name").String()
if name == "" {
return nil, nil // a definition without a name: the result goes as it came
}
if def.IsObject() && !have[name] {
added = append(added, json.RawMessage(def.Raw))
have[name] = true
}
ref, err := marshalPlain(map[string]string{"type": "tool_reference", "tool_name": name})
if err != nil {
return nil, nil
}
items = append(items, ref)
}
cb, err := marshalPlain(items)
if err != nil {
return nil, nil
}
m["content"] = cb
out, err := marshalPlain(m)
if err != nil {
return nil, nil
}
return out, added
}
// 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 {
+223
View File
@@ -1,8 +1,10 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
@@ -200,3 +202,224 @@ func TestDeferredToolBlocksRefusedOnceLeftOut(t *testing.T) {
t.Fatalf("a provider that takes tool_addition was sent %q", got)
}
}
// resultDefVendor answers as an Anthropic endpoint that takes Claude
// Code's deferred-tool blocks but refuses the definition a newer
// ToolSearch answer carries in its tool_result (#5404, api.deepseek.com's
// answer of 2026-11-05), and a tool_reference naming a tool the request's
// tools list lacks.
type resultDefVendor struct {
mu sync.Mutex
bodies []string
}
func (v *resultDefVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
v.mu.Lock()
v.bodies = append(v.bodies, string(b))
v.mu.Unlock()
var m struct {
Tools []struct {
Name string `json:"name"`
} `json:"tools"`
Messages []struct {
Content []struct {
Type string `json:"type"`
Content []struct {
Type string `json:"type"`
ToolName string `json:"tool_name"`
} `json:"content"`
} `json:"content"`
} `json:"messages"`
}
json.Unmarshal(b, &m)
declared := map[string]bool{}
for _, t := range m.Tools {
declared[t.Name] = true
}
refused := ""
for _, msg := range m.Messages {
for _, bl := range msg.Content {
if bl.Type != "tool_result" {
continue
}
for _, it := range bl.Content {
switch {
case it.Type == "tool_definition":
refused = "unknown variant `tool_definition`, expected `tool_reference`"
case it.Type == "tool_reference" && !declared[it.ToolName]:
refused = "tool reference not found in available tools"
}
}
}
}
w.Header().Set("Content-Type", "application/json")
if refused != "" {
w.WriteHeader(422)
io.WriteString(w, `{"error":{"message":"Failed to deserialize the JSON body into the target type: messages[1].content: `+refused+` at line 1 column 473","type":"invalid_request_error"}}`)
return
}
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}
func (v *resultDefVendor) sent() []string {
v.mu.Lock()
defer v.mu.Unlock()
return append([]string(nil), v.bodies...)
}
// nestedDefBody is a conversation whose ToolSearch answer carries the
// loaded tool's definition itself in its tool_result, as newer Claude Code
// builds send it (#5404), with no deferred-tool block at the top level of
// any message.
const nestedDefBody = `{"model":"relay/deepseek-chat","max_tokens":32,"stream":false,` +
`"tools":[{"name":"ToolSearch","description":"find tools","input_schema":{"type":"object"}}],` +
`"messages":[` +
`{"role":"user","content":"find a reader"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"ToolSearch","input":{"query":"read"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":[{"type":"tool_definition","definition":{"name":"Read","description":"read a file","input_schema":{"type":"object"}}}]}]},` +
`{"role":"user","content":"go"}` + `]}`
// #5404: a ToolSearch answer's tool_definition survives a learned retry.
// The endpoint refuses it with 422 "unknown variant `tool_definition`,
// expected `tool_reference`"; the learned retry stripped the top-level
// blocks alone (none here), so the same variant failed again. Now the
// definition joins the tools and the answer goes as the reference the
// endpoint takes — the reference only once the tool is declared, which is
// what the hoisting is for.
func TestToolResultDefinitionRefusedOnceBecomesReference(t *testing.T) {
fresh(t)
up := &resultDefVendor{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL,
Models: []string{"deepseek-chat"}}); err != nil {
t.Fatal(err)
}
h := New().Handler()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(nestedDefBody)))
if rec.Code != 200 {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
sent := up.sent()
if len(sent) != 2 {
t.Fatalf("the relay was asked %d times, want the refusal once and then a body it takes: %d", len(sent), len(sent))
}
if !strings.Contains(sent[0], `"tool_definition"`) {
t.Fatalf("the first ask came already reshaped: %s", sent[0])
}
if strings.Contains(sent[1], `"tool_definition"`) {
t.Fatalf("the retry still carried the definition: %s", sent[1])
}
if !strings.Contains(sent[1], `"tool_name":"Read"`) {
t.Fatalf("the retry lost the ToolSearch answer's reference: %s", sent[1])
}
if !strings.Contains(sent[1], `"name":"Read","description":"read a file"`) {
t.Fatalf("the definition did not join the retry's tools: %s", sent[1])
}
if !strings.Contains(sent[1], `"tool_use_id":"toolu_01"`) {
t.Fatalf("the retry lost the answer's pairing: %s", sent[1])
}
}
// The reshaping, on the bytes: a definition in a tool_result joins the
// tools once, the block goes as the named reference, the rest of the
// result (a reference already there, text) stays; a body with only the
// nested definition is still one that gets worked, and one whose result
// can't be read goes as it came.
func TestNestedToolResultDefinitionBecomesReference(t *testing.T) {
body := `{"model":"m","max_tokens":8,"stream":false,` +
`"tools":[{"name":"ToolSearch","description":"find tools","input_schema":{"type":"object"}},{"name":"Read","description":"read a file","input_schema":{"type":"object"}}],` +
`"messages":[` +
`{"role":"user","content":"find readers"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"ToolSearch","input":{"query":"read"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":[{"type":"tool_reference","tool_name":"Read"},{"type":"tool_definition","definition":{"name":"Grep","description":"search files","input_schema":{"type":"object"}}},{"type":"text","text":"2 tools found"}]}]},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_02","name":"ToolSearch","input":{"query":"grep"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_02","content":[{"type":"tool_definition","definition":{"name":"Grep","description":"search files","input_schema":{"type":"object"}}}]}]},` +
`{"role":"user","content":"go"}]}`
if !hasDeferredTools([]byte(body)) {
t.Fatal("a nested tool_definition was not seen as a deferred tool")
}
out := string(withoutDeferredTools([]byte(body)))
if strings.Contains(out, `"tool_definition"`) {
t.Fatalf("the body still carried a tool_definition: %s", out)
}
for _, want := range []string{`"tool_name":"Read"`, `"tool_name":"Grep"`, `"text":"2 tools found"`, `"tool_use_id":"toolu_01"`, `"tool_use_id":"toolu_02"`} {
if !strings.Contains(out, want) {
t.Fatalf("the reshaped body lost %s: %s", want, out)
}
}
if n := strings.Count(out, `"name":"Grep","description":"search files"`); n != 1 {
t.Fatalf("Grep's definition joined the tools %d times, want once: %s", n, out)
}
if n := strings.Count(out, `"name":"Read","description":"read a file"`); n != 1 {
t.Fatalf("Read's definition on the tools list %d times, want once: %s", n, out)
}
// a result whose content is no array of blocks goes as it came
unreadable := `{"model":"m","max_tokens":8,"stream":false,"tools":[{"name":"ToolSearch","description":"find tools","input_schema":{"type":"object"}}],"messages":[` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":{"type":"tool_definition","definition":{"name":"Read","description":"read a file","input_schema":{"type":"object"}}}}]}]}`
if !hasDeferredTools([]byte(unreadable)) {
t.Fatal("a result carrying a tool_definition was not seen as a deferred tool")
}
out = string(withoutDeferredTools([]byte(unreadable)))
if !strings.Contains(out, `"content":{"type":"tool_definition"`) {
t.Fatalf("the unreadable result was reworked: %s", out)
}
}
// isDeepSeekAnthropic is DeepSeek's own Anthropic endpoint alone, however
// the provider is built (#5404): a preset pointed elsewhere keeps the
// blocks until that endpoint refuses them.
func TestDeepSeekAnthropicRecognized(t *testing.T) {
ds := provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k",
Anthropic: "https://api.deepseek.com/anthropic", Models: []string{"deepseek-chat"}}
if !isDeepSeekAnthropic(ds, provider.Anthropic) {
t.Fatal("DeepSeek's own endpoint was not recognized")
}
relay := provider.Provider{ID: "relay", Name: "Relay", Preset: "deepseek", Key: "k",
Anthropic: "https://relay.example.invalid/anthropic", Models: []string{"deepseek-chat"}}
if isDeepSeekAnthropic(relay, provider.Anthropic) {
t.Fatal("another host was taken for DeepSeek's endpoint")
}
}
// #5404: DeepSeek's own endpoint takes a tool_addition at no position
// now, so a body to it goes without the deferred-tool blocks on the first
// ask, its ToolSearch answer's definition on the tools list and the
// answer as the reference, instead of a 422 to learn from first.
func TestDeepSeekAnthropicIsStrippedUpFront(t *testing.T) {
fresh(t)
up := &resultDefVendor{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Key: "k", Anthropic: "http://api.deepseek.com/anthropic",
Models: []string{"deepseek-chat"}}); err != nil {
t.Fatal(err)
}
s := New()
addr := strings.TrimPrefix(srv.URL, "http://")
s.client = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr)
}}}
body := strings.Replace(nestedDefBody, `"relay/deepseek-chat"`, `"deepseek/deepseek-chat"`, 1)
body = strings.Replace(body, `{"role":"user","content":"go"}`,
`{"role":"system","content":[{"type":"text","text":"t"},`+ccAddDef+`]},{"role":"user","content":"go"}`, 1)
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
sent := up.sent()
if len(sent) != 1 {
t.Fatalf("DeepSeek was asked %d times, want once: %q", len(sent), sent)
}
for _, b := range []string{`"tool_addition"`, `"tool_definition"`} {
if strings.Contains(sent[0], b) {
t.Errorf("DeepSeek was sent %s: %s", b, sent[0])
}
}
if !strings.Contains(sent[0], `"tool_name":"Read"`) || !strings.Contains(sent[0], `"name":"Read","description":"read a file"`) {
t.Errorf("the ToolSearch answer did not go as a declared reference: %s", sent[0])
}
}
+6 -2
View File
@@ -5490,10 +5490,14 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
body = s.withoutRefusedThinking(p, body)
// and those another vendor signed, to Claude (thinking_bound.go)
body = withoutForeignThinking(p, body)
if isKimi(p, to) || p.IsOpenCode() && strings.Contains(strings.ToLower(modelOf(body)), "deepseek") {
if isKimi(p, to) || isDeepSeekAnthropic(p, to) || p.IsOpenCode() && strings.Contains(strings.ToLower(modelOf(body)), "deepseek") {
// Claude Code's deferred-tool blocks, for which Kimi's
// Anthropic endpoint turns the whole request away with a 400
// that names nothing to learn from (#2042). OpenCode's
// that names nothing to learn from (#2042). DeepSeek's own
// Anthropic endpoint now takes a tool_addition at no position
// it can appear in (#5404, a 2026-11-05 check against
// api.deepseek.com), so its blocks come out up front too,
// not after a refusal taught it. OpenCode's
// DeepSeek route hides the refusal behind a 422 "Endpoint
// is unavailable."; other OpenCode models keep their blocks.
body = withoutDeferredTools(body)