Files
magpie/internal/gateway/plugin_textcalls_test.go
T
yetone d0c587aeed gateway: a tool call a model wrote into the text of a Chat reply asked for whole is made the call it is, as a streamed one is (#1845)
A request with stream:false relayed to a Chat upstream had its reply
mended by chatWhole, which only flattened typed content (#483). The
rescue of calls written into the text (textcalls.go, #823) ran only in
textCallTidy, on a stream. So a DeepSeek reply whose content was its
DSML <|DSML|invoke name="Bash">… reached the client as that text with
finish_reason stop, and the agent ran nothing; the same request
streamed got a real tool_call (#1845, cline-pass/deepseek-v4.1-flash).

chatWhole now gets the request's tool names and, for each choice,
wholeTextCalls reads the content with the streaming parser
(textCallAt + parseTextCalls), so the same formats are taken: Hermes'
<tool_call>, DSML, the half-Hermes <parameter> form (#917) and GLM's
(#906). The text before the first block is kept (null when none), the
tags go, the calls become tool_calls with call_text_ ids and
finish_reason becomes tool_calls. As in the stream: a reply that made
a call itself, a block naming a tool not offered, arguments that can't
be read, or no tools offered leave the reply as it came; tags and
nothing else are dropped. A cheap check (tool_call or DSML in the
bytes, escaped brackets included) keeps other replies byte for byte.
chatWhole is now also used for a whole reply under text/plain or no
type, which eventStream had found isn't a stream; before, only JSON
types were mended.

Routes checked: Chat relayed whole (fixed); a streamed request a vendor
answered whole goes through chatWhole before wholeAsStream (fixed by
the same, tested); Responses and Anthropic translations of a Chat
upstream, streamed and whole, a plugin's, and a Chat request for one
body asked streamed (DashScope) all go through textCallSee already
(tests added). A relayed Responses or Messages upstream's text isn't
read for calls, streamed or whole; unchanged.

Run (Go 1.26.8, sandbox HOME, private GOCACHE):
- New TestTextWrittenCallWhole (the issue's DSML, after text, Go-escaped
  brackets, text/plain, Hermes, #823's junk, #917's param, GLM, wrapped
  invoke, two calls; left as text: no tools, unknown tool, cut short,
  lookalike, empty content, plain; tags only; beside a native call;
  truncated body; empty body), TestTextWrittenCallWholeTranslated, a
  case in TestQuietWholeReplyStreamed and a chat-whole subtest in
  TestPluginTextWrittenCall.
- Broken by hand: chatWhole without names turns 11 subtests of
  TestTextWrittenCallWhole and the TestQuietWholeReplyStreamed case
  red; leaving finish_reason alone turns them red on "finish stop";
  the old JSON-only gate turns the text/plain case red; turning
  textCallSee's rescue off turns the translated and plugin tests red.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go test -tags nogui
  ./internal/gateway in full: ok (363s).
- Real: no ClinePass key here, so the reporter's request went through
  this branch's gateway in a sandbox to DeepSeek's own API
  (deepseek/deepseek-flash), 5 runs each way. One stream:false reply
  in DSML came back as tool_calls Bash {"command":"ls /tmp"},
  finish_reason tool_calls. Other runs the model wrote other markup
  (<|tool▁calls▁begin|>…, <|invoke name="Bash"|>) that neither the
  streamed nor the whole rescue reads, streamed or not; not changed here.

Not run: the full go test ./... (only internal/gateway), Windows and
Linux test runs, ClinePass itself.
2026-10-13 01:26:54 +08:00

102 lines
4.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// A plugin's model that writes its tool call into the text is answered as
// a built-in's is (#823, Dazzle-sys: Trae CN's DeepSeek V4.1 Flash in a
// group, in Pi): the plugin's text goes through the same reading, so the
// agent gets the call, whether it speaks Chat or Anthropic Messages.
func TestPluginTextWrittenCall(t *testing.T) {
// as the screenshot had it: Hermes' block, closed with DeepSeek's tags
text := "<tool_call>{\"name\":\"bash\",\"arguments\":{\"command\":\"cd /e/Project && echo \\\"### $spec\\\"; done\"}}</|DSML|parameter>\n</|DSML|invoke"
pid := besideFake(t, "trae-cn", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for _, part := range []string{text[:40], text[40:]} {
b, _ := json.Marshal(map[string]any{"id": "c1", "object": "chat.completion.chunk", "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": part}, "finish_reason": nil}}})
io.WriteString(w, "data: "+string(b)+"\n\n")
}
io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
h := New().Handler()
model := pid + "/fake-1"
tool := `{"type":"function","function":{"name":"bash","parameters":{"type":"object","properties":{"command":{"type":"string"}}}}}`
t.Run("chat", func(t *testing.T) {
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","stream":true,"tools":[`+tool+`],"messages":[{"role":"user","content":"go on"}]}`))
req.Header.Set("Authorization", "Bearer magpie")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, "DSML") || strings.Contains(body, "tool_call>") ||
!strings.Contains(body, `"tool_calls"`) || !strings.Contains(body, `"finish_reason":"tool_calls"`) {
t.Fatalf("%d %s", rec.Code, body)
}
var args string
for _, line := range strings.Split(body, "\n") {
var c struct {
Choices []struct {
Delta struct {
ToolCalls []struct {
Function struct{ Name, Arguments string }
} `json:"tool_calls"`
}
}
}
if json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &c) == nil && len(c.Choices) > 0 {
for _, tc := range c.Choices[0].Delta.ToolCalls {
args += tc.Function.Arguments
}
}
}
var a map[string]string
if json.Unmarshal([]byte(args), &a) != nil || a["command"] != `cd /e/Project && echo "### $spec"; done` {
t.Fatalf("arguments %q", args)
}
})
t.Run("chat whole", func(t *testing.T) {
// asked for one body (#1845): a plugin is asked streamed and the
// reply given whole, its text read the same way
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","stream":false,"tools":[`+tool+`],"messages":[{"role":"user","content":"go on"}]}`))
req.Header.Set("Authorization", "Bearer magpie")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
body := rec.Body.String()
var out struct {
Choices []struct {
Message struct {
ToolCalls []struct {
Function struct{ Name, Arguments string }
} `json:"tool_calls"`
}
FinishReason string `json:"finish_reason"`
}
}
if rec.Code != 200 || json.Unmarshal([]byte(body), &out) != nil || len(out.Choices) != 1 || strings.Contains(body, "DSML") || strings.Contains(body, "tool_call>") ||
len(out.Choices[0].Message.ToolCalls) != 1 || out.Choices[0].FinishReason != "tool_calls" {
t.Fatalf("%d %s", rec.Code, body)
}
var a map[string]string
if json.Unmarshal([]byte(out.Choices[0].Message.ToolCalls[0].Function.Arguments), &a) != nil || a["command"] != `cd /e/Project && echo "### $spec"; done` {
t.Fatalf("arguments %s", body)
}
})
t.Run("messages", func(t *testing.T) {
req := httptest.NewRequest("POST", "/v1/messages", bytes.NewReader([]byte(`{"model":"`+model+`","stream":true,"max_tokens":100,"tools":[{"name":"bash","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"go on"}]}`)))
req.Header.Set("x-api-key", "magpie")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, "DSML") || !strings.Contains(body, `"tool_use"`) {
t.Fatalf("%d %s", rec.Code, body)
}
})
}