Files
magpie/internal/gateway/custom_tool_test.go
T
yetone 5b12407e8e gateway: a custom tool a Responses upstream turns away is translated, not given back as a 400 (#2656)
DeepSeek's Responses API answers Codex's exec, a custom tool, with 400
"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported."
The relay (attempt -> passthrough) sent the tools as they came, so the
translation that offers a custom tool as a function and gives its call
back as a custom_tool_call never ran, and the 400 matched no word list,
so a group's next member wasn't asked either.

- passthrough: a 400/422 matching customToolRefusal, on a Responses
  body that offers a custom tool (tools, a namespace's, an input item's
  tools), marks the model (customToolRefused) and returns not done.
- attempt: then, and on a marked model's later requests with a custom
  tool, the request is translated on the client's own API (ownAPI), so
  exec keeps its name and comes back as custom_tool_call. A Codex
  compaction (keepsCompaction) isn't translated and gets the refusal.
- shapeRefused also takes customToolRefusal, so where the refusal does
  reach a group, the next member is asked and nobody rests.

Not scoped to DeepSeek: any Responses relay (key, plugin) that says its
custom tools are unsupported is handled the same; an upstream that never
refused them still gets them as sent (tested).

Tests: custom_tool_test.go, fixture from the reporter's literal error
text and request. TestCustomToolTranslatedWhereRefused (stream and
not), TestCustomToolRefusalInGroup (reporter's ordered group, next
member asked 0 times), TestCustomToolRefusalWordings. Broken by hand:
passthrough branch off -> both request tests 400 with the reporter's
exact message; attempt pre-skip off -> next turn asked 4 times, not 3;
shapeRefused addition off -> Wordings red.

Run:
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
  go vet -tags nogui ./... clean, at the pushed head.
- Full go test -tags nogui -timeout 45m ./... on e085d6e92 + this
  change: every package ok except internal/agent, timed out at 2706s
  (TestPortMovesEveryAgent running 30s at the deadline; load ~100-150;
  same as #2544, commented there). internal/agent alone -timeout 60m:
  ok 3031s.
- After rebasing onto cb05dc2d1 (3 commits, none in this path):
  internal/gateway -timeout 60m run twice. First: FAIL at 2559s; I
  piped it through tail and lost which test, so it is not named or
  filed here. Second, full log kept: ok 2509s (load ~150).
- Rebased again onto 9f9bfc160 (3 more commits: agent, provider's
  Codex window; none in this path): TestCustomTool*, TestCodexCustom*,
  TestToolStrict*, *Shape* ok; gofmt and vet (darwin, linux, windows)
  clean. Then onto 85eef5d87 (GUI quota refresh only): build and
  TestCustomTool* ok. The full suite was not rerun at this head.
- Not tried against the real DeepSeek API; the fake upstream refuses as
  the reporter's logs show.
2026-10-17 17:44:23 +08:00

224 lines
8.7 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// deepSeekCustomRefusal is DeepSeek's Responses API turning Codex's exec
// away, the message as #2656's reporter got it from api.deepseek.com.
const deepSeekCustomRefusal = `{"error":{"message":"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.","type":"invalid_request_error","param":null,"code":null}}`
// customExecRequest is #2656's request: Codex's exec offered as a custom
// tool, nothing called yet.
const customExecRequest = `{"model":%q,"stream":%t,"input":[{"role":"user","content":"Return ok."}],` +
`"tools":[{"type":"custom","name":"exec","description":"Execute source text.","format":{"type":"text"}}]}`
// customUpstream is a Responses API that, like DeepSeek's, takes no custom
// tool but apply_patch, and calls exec when it is offered as a function.
type customUpstream struct {
mu sync.Mutex
asked []map[string]any
paths []string
}
func (u *customUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var q map[string]any
json.Unmarshal(b, &q)
u.mu.Lock()
u.asked = append(u.asked, q)
u.paths = append(u.paths, r.URL.Path)
u.mu.Unlock()
tools, _ := q["tools"].([]any)
for _, t := range tools {
if tm, _ := t.(map[string]any); tm["type"] == "custom" && tm["name"] != "apply_patch" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, deepSeekCustomRefusal)
return
}
}
call := `{"type":"function_call","id":"fc_1","call_id":"call_1","name":"exec","arguments":"{\"input\":\"print(1)\"}","status":"completed"}`
if q["stream"] == true {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"exec","arguments":""}}`,
`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":"{\"input\":\"print(1)\"}"}`,
`data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`,
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[`+call+`],"usage":{"input_tokens":9,"output_tokens":3}}}`))
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"r1","object":"response","status":"completed","output":[`+call+`],"usage":{"input_tokens":9,"output_tokens":3}}`)
}
// A Responses API that takes no custom tool (DeepSeek's, #2656) turned
// every Codex turn offering exec away, and magpie gave the 400 back. The
// turn is now translated on the same API: exec offered as a function
// taking its input, the call back to Codex as the custom_tool_call it
// runs, exec's name kept. The next turn goes translated at once, and an
// upstream that takes custom tools still gets them as sent.
func TestCustomToolTranslatedWhereRefused(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("stream %t", stream), func(t *testing.T) {
fresh(t)
noRests()
t.Cleanup(noRests)
refusing := &customUpstream{}
ds := httptest.NewServer(refusing)
t.Cleanup(ds.Close)
var taking []map[string]any
var mu sync.Mutex
lax := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var q map[string]any
json.Unmarshal(b, &q)
mu.Lock()
taking = append(taking, q)
mu.Unlock()
answer(w, r)
}))
t.Cleanup(lax.Close)
for _, p := range []provider.Provider{
// Chat and Responses both, as DeepSeek's preset has them
{ID: "ds", Name: "DeepSeek", Key: "k", Models: []string{"deepseek-flash"}, Chat: ds.URL + "/v1", Responses: ds.URL + "/v1"},
{ID: "lax", Name: "Lax", Key: "k", Models: []string{"m1"}, Responses: lax.URL + "/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
ask := func(model string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(customExecRequest, model, stream))))
return rec
}
rec := ask("ds/deepseek-flash")
if rec.Code != 200 {
t.Fatalf("ds: %d %s", rec.Code, rec.Body)
}
if len(refusing.asked) != 2 || refusing.paths[1] != "/v1/responses" {
t.Fatalf("ds asked %d times, at %v", len(refusing.asked), refusing.paths)
}
tool, _ := refusing.asked[1]["tools"].([]any)[0].(map[string]any)
props, _ := tool["parameters"].(map[string]any)["properties"].(map[string]any)
if tool["type"] != "function" || tool["name"] != "exec" || props["input"] == nil {
t.Fatalf("asked again with %v", tool)
}
var call map[string]any
if stream {
for _, e := range events(rec.Body.String()) {
if e["type"] == "response.output_item.done" {
call, _ = e["item"].(map[string]any)
}
}
} else {
var out struct{ Output []map[string]any }
json.Unmarshal(rec.Body.Bytes(), &out)
for _, it := range out.Output {
if it["type"] != "reasoning" {
call = it
}
}
}
if call["type"] != "custom_tool_call" || call["name"] != "exec" || call["input"] != "print(1)" || call["call_id"] != "call_1" {
t.Fatalf("Codex got %v\n%s", call, rec.Body)
}
// the next turn goes translated at once
if rec = ask("ds/deepseek-flash"); rec.Code != 200 || len(refusing.asked) != 3 {
t.Fatalf("next turn: %d, asked %d times: %s", rec.Code, len(refusing.asked), rec.Body)
}
if tool, _ := refusing.asked[2]["tools"].([]any)[0].(map[string]any); tool["type"] != "function" {
t.Fatalf("next turn offered %v", tool)
}
// an upstream that takes them gets them as sent
if rec = ask("lax/m1"); rec.Code != 200 || len(taking) != 1 {
t.Fatalf("lax: %d, asked %d times", rec.Code, len(taking))
}
if tool, _ := taking[0]["tools"].([]any)[0].(map[string]any); tool["type"] != "custom" {
t.Fatalf("lax offered %v", tool)
}
})
}
}
// In a routing group the refusing member answers translated, and the
// next member isn't asked (#2656: the group gave the 400 back, its
// healthy member never asked).
func TestCustomToolRefusalInGroup(t *testing.T) {
fresh(t)
noRests()
t.Cleanup(noRests)
refusing := &customUpstream{}
ds := httptest.NewServer(refusing)
t.Cleanup(ds.Close)
asked := 0
next := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked++
answer(w, r)
}))
t.Cleanup(next.Close)
for _, p := range []provider.Provider{
{ID: "ds", Name: "DeepSeek", Key: "k", Models: []string{"deepseek-flash"}, Responses: ds.URL + "/v1"},
{ID: "next", Name: "Next", Key: "k", Models: []string{"m1"}, Responses: next.URL + "/v1"},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{ID: "repro", Name: "Reproduction", Routing: provider.Ordered, Members: []string{"ds/deepseek-flash", "next/m1"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(customExecRequest, "group/repro", false))))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"custom_tool_call"`) {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if len(refusing.asked) != 2 || asked != 0 {
t.Fatalf("ds asked %d times, next %d", len(refusing.asked), asked)
}
}
// The refusal is known as DeepSeek words it, decoded or not, and as a
// vendor may name the type; a 400 over something else about a tool is
// not taken for one. A group's next member is asked over it where it
// reaches the group untranslated.
func TestCustomToolRefusalWordings(t *testing.T) {
for _, b := range []string{
deepSeekCustomRefusal,
`{"error":{"message":"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported."}}`,
`{"error":{"message":"DeepSeek: Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.","type":"invalid_request_error"}}`,
`{"error":{"message":"Invalid tool type: 'custom'"}}`,
`{"error":{"message":"custom tools are not supported"}}`,
} {
if !customToolRefusal.Match(wordsOf([]byte(b))) {
t.Errorf("not known: %s", b)
}
if !shapeRefused(400, []byte(b)) {
t.Errorf("no next member over: %s", b)
}
}
for _, b := range []string{
`{"error":{"message":"Invalid schema for function 'exec': 'input' is required"}}`,
`{"error":{"message":"tools[0].function.strict is not supported"}}`,
`{"error":{"message":"Insufficient Balance"}}`,
} {
if customToolRefusal.Match([]byte(b)) {
t.Errorf("taken for one: %s", b)
}
}
}