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.
This commit is contained in:
yetone
2026-10-13 01:26:54 +08:00
parent 98b5a02d11
commit d0c587aeed
7 changed files with 353 additions and 10 deletions
+2
View File
@@ -81,6 +81,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- 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)).
- A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `<tool_call>{…}</tool_call>`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters), DeepSeek's half-Hermes `<parameter>` form (#917) and GLM's `<arg_key>`/`<arg_value>` (#906), read by `parseTextCalls`. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A reply whose model made a call itself is left alone. Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`.
- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before.
- Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
@@ -333,6 +334,7 @@ Covered by `TestAutoVisionPassesOverOneOut`,
```sh
go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard'
go test -tags nogui ./internal/gateway -run 'TestCreditsExhaustedIsOutOfCredit|TestOutOfCreditLeavesFreeModels'
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
+23 -8
View File
@@ -258,10 +258,14 @@ func flattenContent(m map[string]json.RawMessage, whole bool) bool {
// chatWhole mends a Chat Completions reply that came whole, not streamed:
// a message whose content is typed parts (Mistral's thinking, #483) goes
// on with a string content and its thinking in reasoning_content. It is
// held until it ends; any other reply passes byte for byte.
// on with a string content and its thinking in reasoning_content, and,
// when the request offered tools (names), calls the model wrote into its
// text are made the calls they are, as textCallTidy makes them in a
// stream (#1845). It is held until it ends; any other reply passes byte
// for byte.
type chatWhole struct {
buf []byte
names map[string]bool
buf []byte
}
func (t *chatWhole) write(b []byte) []byte {
@@ -272,7 +276,8 @@ func (t *chatWhole) write(b []byte) []byte {
func (t *chatWhole) flush() []byte {
b := t.buf
t.buf = nil
if !bytes.Contains(b, contentParts) && !bytes.Contains(b, contentPartsSpace) {
parts := bytes.Contains(b, contentParts) || bytes.Contains(b, contentPartsSpace)
if !parts && !mayWriteCalls(b, t.names) {
return b
}
var reply map[string]json.RawMessage
@@ -286,17 +291,27 @@ func (t *chatWhole) flush() []byte {
changed := false
for _, c := range choices {
var msg map[string]json.RawMessage
if decodeJSON(c["message"], &msg) != nil || !flattenContent(msg, true) {
if decodeJSON(c["message"], &msg) != nil {
continue
}
c["message"], _ = json.Marshal(msg)
mended := parts && flattenContent(msg, true)
if wrote, called := wholeTextCalls(msg, t.names); wrote {
if called {
c["finish_reason"] = json.RawMessage(`"tool_calls"`)
}
mended = true
}
if !mended {
continue
}
c["message"], _ = marshalPlain(msg)
changed = true
}
if !changed {
return b
}
reply["choices"], _ = json.Marshal(choices)
nb, err := json.Marshal(reply)
reply["choices"], _ = marshalPlain(choices)
nb, err := marshalPlain(reply)
if err != nil {
return b
}
+4 -2
View File
@@ -3794,9 +3794,11 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if names := chatToolNames(body); proto == provider.Chat && sse && names != nil {
written = &textCallTidy{names: names}
}
// a reply that came whole: JSON, or one under text/plain or no type
// that eventStream found isn't a stream
var whole *chatWhole
if proto == provider.Chat && !sse && strings.Contains(res.Header.Get("Content-Type"), "json") {
whole = &chatWhole{}
if ct := res.Header.Get("Content-Type"); proto == provider.Chat && !sse && (strings.Contains(ct, "json") || ct == "" || strings.HasPrefix(ct, "text/plain")) {
whole = &chatWhole{names: chatToolNames(body)}
}
var sigs *sigTidy
if proto == provider.Chat && geminiCompat(p.Host(), model) {
+27
View File
@@ -61,6 +61,33 @@ func TestPluginTextWrittenCall(t *testing.T) {
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")
+4
View File
@@ -40,6 +40,10 @@ func TestQuietWholeReplyStreamed(t *testing.T) {
}{
{"chat", "application/json", `{"id":"chatcmpl-9f2","object":"chat.completion","created":1791370000,"model":"m","system_fingerprint":"fp_1","choices":[{"index":0,"message":{"role":"assistant","content":"` + text + `","reasoning_content":"` + think + `","tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}]},"logprobs":null,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":12,"completion_tokens":9,"total_tokens":21}}`,
provider.Chat, "think:" + think + "|text:" + text + "|tool:get_weather " + args + "|stop:tool", 0},
// a call the model wrote into its text, made the call it is as a
// stream's would be (#1845)
{"chat with a call in its text", "application/json", `{"id":"chatcmpl-9f4","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"` + text + `\n<|DSML|tool_calls>\n<|DSML|invoke name=\"get_weather\">\n<|DSML|parameter name=\"city\" string=\"true\">Paris</|DSML|parameter>\n</|DSML|invoke>\n</|DSML|tool_calls>"},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":9,"total_tokens":21}}`,
provider.Chat, "text:" + text + "\n|tool:get_weather " + args + "|stop:tool", 0},
// a reply that isn't streamed, whatever its type says
{"chat as text/plain", "text/plain; charset=utf-8", `{"id":"chatcmpl-9f3","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"` + text + `"},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":2,"total_tokens":14}}`,
provider.Chat, "text:" + text + "|stop:stop", 0},
+54
View File
@@ -623,3 +623,57 @@ func (t *textCallTidy) line(line []byte) []byte {
}
return append(append(append(pre, "data: "...), nb...), line[len(body):]...)
}
// mayWriteCalls tells whether a whole Chat reply b could carry a call
// written into its text, for a request that offered names: one of
// textCallMarks' words is in it, however its JSON escapes the brackets.
func mayWriteCalls(b []byte, names map[string]bool) bool {
return names != nil && (bytes.Contains(b, []byte("tool_call")) || bytes.Contains(b, []byte("DSML")))
}
// wholeTextCalls reads the calls written into the content of a whole Chat
// reply's message, as textCallTidy reads a stream's: the text before the
// first is kept, the blocks become tool_calls and what is left of their
// tags goes. wrote is whether msg changed, called whether it now calls
// tools. A message that made a call itself, or whose written blocks
// aren't all calls of names with arguments that can be read, is left as
// it came.
func wholeTextCalls(msg map[string]json.RawMessage, names map[string]bool) (wrote, called bool) {
if names == nil {
return false, false
}
var native []json.RawMessage
if decodeJSON(msg["tool_calls"], &native) == nil && len(native) > 0 {
return false, false
}
var s string
if decodeJSON(msg["content"], &s) != nil {
return false, false
}
at, _ := textCallAt(s)
if at < 0 {
return false, false
}
calls, rest, ok := parseTextCalls(s[at:], names)
if !ok {
return false, false
}
text := s[:at] + rest
if len(calls) == 0 {
// tags and nothing else, dropped as a stream drops them
msg["content"], _ = marshalPlain(text)
return true, false
}
tcs := make([]map[string]any, len(calls))
for i, c := range calls {
tcs[i] = map[string]any{"id": textCallID(), "type": "function",
"function": map[string]any{"name": c.Name, "arguments": string(c.Args)}}
}
if text != "" {
msg["content"], _ = marshalPlain(text)
} else {
msg["content"] = json.RawMessage("null")
}
msg["tool_calls"], _ = marshalPlain(tcs)
return true, true
}
+239
View File
@@ -0,0 +1,239 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// issueDSML is #1845's reply: DeepSeek's DSML for a call of the request's
// Bash tool, as cline-pass/deepseek-v4.1-flash wrote it into the content
// of a reply asked for whole. The issue shows its brackets full-width
// (<|DSML|tool_calls>) to keep them from rendering; the same request
// streamed was rescued, so the bytes had DeepSeek's own <|DSML|.
const issueDSML = "<|DSML|tool_calls>\n<|DSML|invoke name=\"Bash\">\n<|DSML|parameter name=\"command\" string=\"true\">ls /tmp</|DSML|parameter>\n</|DSML|invoke>\n</|DSML|tool_calls>"
const issueTools = `"tools":[{"type":"function","function":{"name":"Bash","parameters":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}}]`
// wholeChatUp is a chat.completion whose message says content.
func wholeChatUp(content string) string {
c, _ := json.Marshal(content)
return `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":` + string(c) + `},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`
}
type wholeCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
// wholeChat sends a Chat client's request for one body (body) through
// the gateway to an upstream that answers up whole under ctype, and gives
// back the message's content (nil for null), its calls, the finish reason
// and the bytes the client read.
func wholeChat(t *testing.T, body, ctype, up string) (text *string, calls []wholeCall, finish, raw string) {
t.Helper()
fresh(t)
scriptedOn(t, "a", provider.Chat, &scripted{replies: []reply{{200, ctype, up}}})
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)))
raw = rec.Body.String()
var got struct {
Choices []struct {
Message struct {
Content *string `json:"content"`
ToolCalls []wholeCall `json:"tool_calls"`
} `json:"message"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &got) != nil || len(got.Choices) != 1 {
t.Fatalf("%d %s", rec.Code, raw)
}
m := got.Choices[0].Message
return m.Content, m.ToolCalls, got.Choices[0].FinishReason, raw
}
func strOr(s *string) string {
if s == nil {
return "<null>"
}
return *s
}
// #1845: a call a model wrote into the text of a Chat reply asked for
// whole (stream:false) reached the client as that text, finish_reason
// stop, and the agent ran nothing; the same request streamed was rescued.
// It is the call it is now, in every format the stream reads, the text
// before it kept and the markup gone.
func TestTextWrittenCallWhole(t *testing.T) {
ask := `{"model":"a/m","stream":false,"messages":[{"role":"system","content":"You are a coding agent. Use the Bash tool."},{"role":"user","content":"ls /tmp"}],` + issueTools + `}`
for _, c := range []struct {
name, ctype, up string
text string // "<null>" for none
args string
}{
{"the issue's DSML", "application/json", wholeChatUp(issueDSML), "<null>", `{"command":"ls /tmp"}`},
{"DSML after text", "application/json; charset=utf-8", wholeChatUp("看一下。\n\n" + issueDSML), "看一下。\n\n", `{"command":"ls /tmp"}`},
// a Go relay escapes < and > in its JSON
{"escaped brackets", "application/json", strings.NewReplacer("<", `<`, ">", `>`).Replace(wholeChatUp(issueDSML)), "<null>", `{"command":"ls /tmp"}`},
// a whole reply under text/plain, which eventStream found isn't
// a stream
{"text/plain", "text/plain; charset=utf-8", wholeChatUp(issueDSML), "<null>", `{"command":"ls /tmp"}`},
{"Hermes", "application/json", wholeChatUp("我先看看目录。\n\n<tool_call>{\"name\":\"Bash\",\"arguments\":{\"command\":\"ls -la\"}}</tool_call>"), "我先看看目录。\n\n", `{"command":"ls -la"}`},
// #823's: a raw newline in the JSON's string, DeepSeek's closes strewn after it
{"Hermes with junk", "application/json", wholeChatUp("<tool_call>{\"name\":\"Bash\",\"arguments\":{\"command\":\"cd /e && for s in a b; do\n\techo \\\"$s\\\"; done\"}}</|DSML|parameter>\n</|DSML|invoke"), "<null>", `{"command":"cd /e && for s in a b; do\n\techo \"$s\"; done"}`},
// #917's: half Hermes, half DeepSeek's template, cut at its end
{"param", "application/json", wholeChatUp("Let me run it.\n\n<tool_call>{\"name\":\"Bash\">\n<parameter name=\"command\">cd /e/Project/synara && node .review-tmp\n"), "Let me run it.\n\n", `{"command":"cd /e/Project/synara && node .review-tmp"}`},
// #906's: GLM's own
{"GLM", "application/json", wholeChatUp("Looking.<tool_call>Bash<arg_key>command</arg_key><arg_value>ls -la</arg_value></tool_call>"), "Looking.", `{"command":"ls -la"}`},
// #823's: a <tool_call> wrapping DeepSeek's own invoke
{"wrapped invoke", "application/json", wholeChatUp("看一下。<tool_call>\n<|DSML|invoke name=\"Bash\">\n<|DSML|parameter name=\"command\" string=\"true\">ls</|DSML|parameter>\n</|DSML|invoke>\n</tool_call>"), "看一下。", `{"command":"ls"}`},
} {
t.Run(c.name, func(t *testing.T) {
text, calls, finish, raw := wholeChat(t, ask, c.ctype, c.up)
var want, got any
json.Unmarshal([]byte(c.args), &want)
if len(calls) == 1 {
json.Unmarshal([]byte(calls[0].Function.Arguments), &got)
}
if strOr(text) != c.text || len(calls) != 1 || calls[0].Function.Name != "Bash" || calls[0].Type != "function" ||
calls[0].ID == "" || got == nil || !jsonEqual(got, want) || finish != "tool_calls" {
t.Fatalf("text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw)
}
if strings.Contains(raw, "DSML") || strings.Contains(raw, "tool_call>") || strings.Contains(raw, "arg_key") || strings.Contains(raw, "parameter") {
t.Fatalf("markup left: %s", raw)
}
if !strings.Contains(raw, `"total_tokens":5`) || !strings.Contains(raw, `"id":"c1"`) {
t.Fatalf("the reply's own fields lost: %s", raw)
}
})
}
t.Run("two calls", func(t *testing.T) {
two := issueDSML + "\n" + strings.ReplaceAll(issueDSML, "ls /tmp", "pwd")
text, calls, finish, raw := wholeChat(t, ask, "application/json", wholeChatUp(two))
if text != nil || len(calls) != 2 || calls[0].Function.Arguments != `{"command":"ls /tmp"}` || calls[1].Function.Arguments != `{"command":"pwd"}` ||
calls[0].ID == calls[1].ID || finish != "tool_calls" {
t.Fatalf("text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw)
}
})
// what a stream leaves as text, a whole reply leaves too
for _, c := range []struct{ name, body, content string }{
{"no tools offered", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`, issueDSML},
{"a tool not offered", ask, `Like this: <tool_call>{"name":"rm_rf","arguments":{}}</tool_call>`},
{"cut short", ask, `<tool_call>{"name":"Bash","arguments":{"command":"l`},
{"lookalike", ask, "a <tooltip> b </tool_call> c"},
{"empty", ask, ""},
{"plain", ask, "Nothing to run."},
} {
t.Run(c.name, func(t *testing.T) {
text, calls, finish, raw := wholeChat(t, c.body, "application/json", wholeChatUp(c.content))
if strOr(text) != c.content || len(calls) != 0 || finish != "stop" {
t.Fatalf("text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw)
}
})
}
// tags and nothing else go, as a stream drops them (#823)
t.Run("tags only", func(t *testing.T) {
text, calls, finish, raw := wholeChat(t, ask, "application/json", wholeChatUp("<tool_call>\n</|DSML|parameter>\n</|DSML|invoke>\n</"))
if strOr(text) != "" || len(calls) != 0 || finish != "stop" || strings.Contains(raw, "DSML") {
t.Fatalf("text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw)
}
})
// a call the model made itself keeps the reply as it came
t.Run("beside a native call", func(t *testing.T) {
c, _ := json.Marshal(issueDSML)
up := `{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":` + string(c) + `,"tool_calls":[{"id":"call_9","type":"function","function":{"name":"Bash","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}`
text, calls, finish, raw := wholeChat(t, ask, "application/json", up)
if strOr(text) != issueDSML || len(calls) != 1 || calls[0].ID != "call_9" || finish != "tool_calls" {
t.Fatalf("text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw)
}
})
// a body cut short, or none, goes on as it came: nothing is made up
t.Run("truncated body", func(t *testing.T) {
fresh(t)
up := wholeChatUp(issueDSML)
up = up[:strings.Index(up, "ls /tmp")+len("ls /tmp")]
scriptedOn(t, "a", provider.Chat, &scripted{replies: []reply{{200, "application/json", up}}})
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(ask)))
if rec.Code == 200 && rec.Body.String() != up || strings.Contains(rec.Body.String(), `"tool_calls"`) {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
})
t.Run("empty body", func(t *testing.T) {
fresh(t)
scriptedOn(t, "a", provider.Chat, &scripted{replies: []reply{{200, "application/json", ""}}})
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(ask)))
if rec.Code == 200 && rec.Body.Len() != 0 || strings.Contains(rec.Body.String(), `"tool_calls"`) {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
})
}
// The issue's DSML through each translation of a Chat upstream, which
// magpie always asks streamed: a Responses or Anthropic client, streamed
// or whole, and a Chat client's request for one body that is asked
// streamed (DashScope's thinking models), all get the call.
func TestTextWrittenCallWholeTranslated(t *testing.T) {
up := []string{chunkOf("Running it.\n\n" + issueDSML[:40]), chunkOf(issueDSML[40:]), stopChunk}
for _, stream := range []string{"true", "false"} {
items, raw := responsesItems(t, `{"model":"a/m","stream":`+stream+`,"input":"ls /tmp","tools":[{"type":"function","name":"Bash","parameters":{"type":"object"}}]}`, up...)
var call map[string]any
for _, it := range items {
if it["type"] == "function_call" {
call = it
}
}
if call == nil || call["name"] != "Bash" || call["arguments"] != `{"command":"ls /tmp"}` || strings.Contains(raw, "DSML") || !strings.Contains(raw, "Running it.") {
t.Fatalf("responses stream=%s: %v\n%s", stream, call, raw)
}
fresh(t)
scriptedOn(t, "a", provider.Chat, &scripted{replies: []reply{{200, "text/event-stream", sse(append(up, `data: [DONE]`)...)}}})
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(
`{"model":"a/m","max_tokens":100,"stream":`+stream+`,"messages":[{"role":"user","content":"ls /tmp"}],"tools":[{"name":"Bash","input_schema":{"type":"object"}}]}`)))
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, "DSML") || !strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"stop_reason":"tool_use"`) {
t.Fatalf("messages stream=%s: %d %s", stream, rec.Code, body)
}
}
f := &fake{t: t, refuse: dashScopeRefuse, reply: sse(append(up, `data: [DONE]`)...)}
srv := setup(t, provider.Chat, f)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Qwen Token Plan", Key: "k", Models: []string{"m1"},
Preset: "qwen-token-plan", Chat: srv.URL + "/compatible-mode/v1"}); err != nil {
t.Fatal(err)
}
code, body := postTo(t, New(), "/v1/chat/completions", `{"model":"m1","stream":false,"messages":[{"role":"user","content":"ls /tmp"}],`+issueTools+`}`)
var out struct {
Choices []struct {
Message struct {
Content *string `json:"content"`
ToolCalls []wholeCall `json:"tool_calls"`
} `json:"message"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
}
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || len(out.Choices) != 1 || !strings.Contains(string(f.got), `"stream":true`) {
t.Fatalf("%d %s (asked %s)", code, body, f.got)
}
m := out.Choices[0]
if len(m.Message.ToolCalls) != 1 || m.Message.ToolCalls[0].Function.Arguments != `{"command":"ls /tmp"}` || m.FinishReason != "tool_calls" ||
strings.Contains(body, "DSML") || !strings.Contains(strOr(m.Message.Content), "Running it.") {
t.Fatalf("asked streamed, given whole: %s", body)
}
}